Compare commits

..

1 Commits

Author SHA1 Message Date
Ralph Khreish
9435c19d47 fix: env variables and wrapper 2025-05-01 18:52:45 +02:00
161 changed files with 3256 additions and 9740 deletions

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
- Add support for Google Gemini models via Vercel AI SDK integration.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Add xAI provider and Grok models support

View File

@@ -0,0 +1,8 @@
---
'task-master-ai': minor
---
feat(expand): Enhance `expand` and `expand-all` commands
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
- Change default behavior to *append* new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.

View File

@@ -0,0 +1,7 @@
---
'task-master-ai': minor
---
Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs.
- IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Add integration for Roo Code

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': patch
---
Improve and adjust `init` command for robustness and updated dependencies.
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140

View File

@@ -0,0 +1,10 @@
---
'task-master-ai': patch
---
Improves next command to be subtask-aware
- The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'.
- The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority.
- If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.

View File

@@ -0,0 +1,11 @@
---
'task-master-ai': minor
---
Adds custom model ID support for Ollama and OpenRouter providers.
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
- Added warnings when setting custom/unvalidated models.
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Add `--status` flag to `show` command to filter displayed subtasks.

View File

@@ -0,0 +1,7 @@
---
'task-master-ai': minor
---
Integrate OpenAI as a new AI provider.
- Enhance `models` command/tool to display API key status.
- Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.

View File

@@ -0,0 +1,9 @@
---
'task-master-ai': minor
---
Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information
- Forces temp at 0.1 for highly deterministic output, no variations
- Adds a system prompt to further improve the output
- Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity
- Specificies to use a high degree of research across the web
- Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix --task to --num-tasks in ui + related tests - issue #324

View File

@@ -0,0 +1,9 @@
---
'task-master-ai': patch
---
Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models."
- In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup.
- In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both.
- Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information.
- Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.

View File

@@ -25,7 +25,6 @@ This document outlines the architecture and usage patterns for interacting with
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`). * Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`). * Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`. * Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
* Returns a structured object containing the primary AI result (`mainResult`) and telemetry data (`telemetryData`). See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for details on how this telemetry data is propagated and handled.
* **Provider Implementations (`src/ai-providers/*.js`):** * **Provider Implementations (`src/ai-providers/*.js`):**
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`). * Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).

View File

@@ -42,7 +42,6 @@ alwaysApply: false
- Resolves API keys (from `.env` or `session.env`). - Resolves API keys (from `.env` or `session.env`).
- Implements fallback and retry logic. - Implements fallback and retry logic.
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`). - Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations** - **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions. - **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
@@ -66,9 +65,8 @@ alwaysApply: false
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration** - **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
- **Purpose**: Provides MCP interface using FastMCP. - **Purpose**: Provides MCP interface using FastMCP.
- **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)): - **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)):
- Registers tools (`mcp-server/src/tools/*.js`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling. - Registers tools (`mcp-server/src/tools/*.js`).
- The HOF provides a normalized `args.projectRoot` to the `execute` method. - Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`).
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`), passing the normalized `projectRoot` and other args.
- Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session. - Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session.
- Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`. - Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`.
- Manages MCP caching and response formatting. - Manages MCP caching and response formatting.

View File

@@ -116,7 +116,7 @@ Taskmaster configuration is managed through two main mechanisms:
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`. * For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`). * Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool. **Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`. **If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project. **If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.

View File

@@ -3,6 +3,7 @@ description: Glossary of other Cursor rules
globs: **/* globs: **/*
alwaysApply: true alwaysApply: true
--- ---
# Glossary of Task Master Cursor Rules # Glossary of Task Master Cursor Rules
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory. This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
@@ -22,5 +23,4 @@ This file provides a quick reference to the purpose of each rule file located in
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI. - **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
- **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components. - **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions. - **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions.
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.

View File

@@ -188,70 +188,58 @@ execute: async (args, { log, session }) => {
- **args**: Validated parameters. - **args**: Validated parameters.
- **context**: Contains `{ log, session }` from FastMCP. (Removed `reportProgress`). - **context**: Contains `{ log, session }` from FastMCP. (Removed `reportProgress`).
### Standard Tool Execution Pattern with Path Normalization (Updated) ### Standard Tool Execution Pattern
To ensure consistent handling of project paths across different client environments (Windows, macOS, Linux, WSL) and input formats (e.g., `file:///...`, URI encoded paths), all MCP tool `execute` methods that require access to the project root **MUST** be wrapped with the `withNormalizedProjectRoot` Higher-Order Function (HOF). The `execute` method within each MCP tool (in `mcp-server/src/tools/*.js`) should follow this standard pattern:
This HOF, defined in [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js), performs the following before calling the tool's core logic: 1. **Log Entry**: Log the start of the tool execution with relevant arguments.
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
1. **Determines the Raw Root:** It prioritizes `args.projectRoot` if provided by the client, otherwise it calls `getRawProjectRootFromSession` to extract the path from the session. 3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`. Crucially, the third argument (context) passed to the direct function should **only include `{ log, session }`**. **Do NOT pass `reportProgress`**.
2. **Normalizes the Path:** It uses the `normalizeProjectRoot` helper to decode URIs, strip `file://` prefixes, fix potential Windows drive letter prefixes (e.g., `/C:/`), convert backslashes (`\`) to forward slashes (`/`), and resolve the path to an absolute path suitable for the server's OS. ```javascript
3. **Injects Normalized Path:** It updates the `args` object by replacing the original `projectRoot` (or adding it) with the normalized, absolute path. // Example call (applies to both AI and non-AI direct functions now)
4. **Executes Original Logic:** It calls the original `execute` function body, passing the updated `args` object. const result = await someDirectFunction(
{ ...args, projectRoot }, // Args including resolved root
**Implementation Example:** log, // MCP logger
{ session } // Context containing session
);
```
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
6. **Return**: Return the formatted response object provided by `handleApiResult`.
```javascript ```javascript
// In mcp-server/src/tools/your-tool.js // Example execute method structure for a tool calling an AI-based direct function
import { import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
handleApiResult, import { someAIDirectFunction } from '../core/task-master-core.js';
createErrorResponse,
withNormalizedProjectRoot // <<< Import HOF
} from './utils.js';
import { yourDirectFunction } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; // If needed
export function registerYourTool(server) { // ... inside server.addTool({...})
server.addTool({ execute: async (args, { log, session }) => { // Note: reportProgress is omitted here
name: "your_tool", try {
description: "...". log.info(`Starting AI tool execution with args: ${JSON.stringify(args)}`);
parameters: z.object({
// ... other parameters ...
projectRoot: z.string().optional().describe('...') // projectRoot is optional here, HOF handles fallback
}),
// Wrap the entire execute function
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
// args.projectRoot is now guaranteed to be normalized and absolute
const { /* other args */, projectRoot } = args;
try { // 1. Get Project Root
log.info(`Executing your_tool with normalized root: ${projectRoot}`); let rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder && args.projectRoot) { // Fallback if needed
rootFolder = args.projectRoot;
log.info(`Using project root from args as fallback: ${rootFolder}`);
}
// Resolve paths using the normalized projectRoot // 2. Call AI-Based Direct Function (passing only log and session in context)
let tasksPath = findTasksJsonPath({ projectRoot, file: args.file }, log); const result = await someAIDirectFunction({
...args,
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
}, log, { session }); // Pass session here, NO reportProgress
// Call direct function, passing normalized projectRoot if needed by direct func // 3. Handle and Format Response
const result = await yourDirectFunction( return handleApiResult(result, log);
{
/* other args */,
projectRoot // Pass it if direct function needs it
},
log,
{ session }
);
return handleApiResult(result, log); } catch (error) {
} catch (error) { log.error(`Error during AI tool execution: ${error.message}`);
log.error(`Error in your_tool: ${error.message}`); return createErrorResponse(error.message);
return createErrorResponse(error.message); }
}
}) // End HOF wrap
});
} }
``` ```
By using this HOF, the core logic within the `execute` method and any downstream functions (like `findTasksJsonPath` or direct functions) can reliably expect `args.projectRoot` to be a clean, absolute path suitable for the server environment.
### Project Initialization Tool ### Project Initialization Tool
The `initialize_project` tool allows integrated clients like Cursor to set up a new Task Master project: The `initialize_project` tool allows integrated clients like Cursor to set up a new Task Master project:
@@ -522,8 +510,3 @@ Follow these steps to add MCP support for an existing Task Master command (see [
// Add more functions as implemented // Add more functions as implemented
}; };
``` ```
## Telemetry Integration
- Direct functions calling core logic that involves AI should receive and pass through `telemetryData` within their successful `data` payload. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the standard pattern.
- MCP tools use `handleApiResult`, which ensures the `data` object (potentially including `telemetryData`) from the direct function is correctly included in the final response.

View File

@@ -3,6 +3,7 @@ description: Guidelines for integrating new features into the Task Master CLI
globs: scripts/modules/*.js globs: scripts/modules/*.js
alwaysApply: false alwaysApply: false
--- ---
# Task Master Feature Integration Guidelines # Task Master Feature Integration Guidelines
## Feature Placement Decision Process ## Feature Placement Decision Process
@@ -195,8 +196,6 @@ The standard pattern for adding a feature follows this workflow:
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause. - ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues. - ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
- **Telemetry Integration**: Ensure AI calls correctly handle and propagate `telemetryData` as described in [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc).
```javascript ```javascript
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js) // 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
/** /**
@@ -524,24 +523,14 @@ Integrating Task Master commands with the MCP server (for use by tools like Curs
4. **Create MCP Tool (`mcp-server/src/tools/`)**: 4. **Create MCP Tool (`mcp-server/src/tools/`)**:
- Create a new file (e.g., `your-command.js`) using **kebab-case**. - Create a new file (e.g., `your-command.js`) using **kebab-case**.
- Import `zod`, `handleApiResult`, **`withNormalizedProjectRoot` HOF**, and your `yourCommandDirect` function. - Import `zod`, `handleApiResult`, `createErrorResponse`, **`getProjectRootFromSession`**, and your `yourCommandDirect` function.
- Implement `registerYourCommandTool(server)`. - Implement `registerYourCommandTool(server)`.
- **Define parameters**: Make `projectRoot` optional (`z.string().optional().describe(...)`) as the HOF handles fallback. - Define the tool `name` using **snake_case** (e.g., `your_command`).
- Consider if this operation should run in the background using `AsyncOperationManager`. - Define the `parameters` using `zod`. **Crucially, define `projectRoot` as optional**: `projectRoot: z.string().optional().describe(...)`. Include `file` if applicable.
- Implement the standard `execute` method **wrapped with `withNormalizedProjectRoot`**: - Implement the standard `async execute(args, { log, reportProgress, session })` method:
```javascript - Get `rootFolder` using `getProjectRootFromSession` (with fallback to `args.projectRoot`).
execute: withNormalizedProjectRoot(async (args, { log, session }) => { - Call `yourCommandDirect({ ...args, projectRoot: rootFolder }, log)`.
// args.projectRoot is now normalized - Pass the result to `handleApiResult(result, log, 'Error Message')`.
const { projectRoot /*, other args */ } = args;
// ... resolve tasks path if needed using normalized projectRoot ...
const result = await yourCommandDirect(
{ /* other args */, projectRoot /* if needed by direct func */ },
log,
{ session }
);
return handleApiResult(result, log);
})
```
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`. 5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.
@@ -629,3 +618,8 @@ When implementing project initialization commands:
}); });
} }
``` ```
}
});
}
```

View File

@@ -79,7 +79,6 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`. * **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
* **Notes:** Configuration is stored in `.taskmasterconfig` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live. * **Notes:** Configuration is stored in `.taskmasterconfig` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live.
* **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them. * **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them.
* **Model costs:** The costs in supported models are expressed in dollars. An input/output value of 3 is $3.00. A value of 0.8 is $0.80.
* **Warning:** DO NOT MANUALLY EDIT THE .taskmasterconfig FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback. * **Warning:** DO NOT MANUALLY EDIT THE .taskmasterconfig FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback.
--- ---

View File

@@ -1,228 +0,0 @@
---
description: Guidelines for integrating AI usage telemetry across Task Master.
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
alwaysApply: true
---
# AI Usage Telemetry Integration
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
## Overview
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
- **`telemetryData` Object Structure**:
```json
{
"timestamp": "ISO_STRING_DATE",
"userId": "USER_ID_FROM_CONFIG",
"commandName": "invoking_command_or_tool_name",
"modelUsed": "ai_model_id",
"providerName": "ai_provider_name",
"inputTokens": NUMBER,
"outputTokens": NUMBER,
"totalTokens": NUMBER,
"totalCost": NUMBER, // e.g., 0.012414
"currency": "USD" // e.g., "USD"
}
```
## Integration Pattern by Layer
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- **Actions**:
1. Call the appropriate AI service function (e.g., `generateObjectService`).
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
3. Extract `aiServiceResponse.mainResult` for the core processing.
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
- **CLI Output Handling (If Applicable)**:
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
1. Check if `outputFormat === 'text'` (or `'cli'`).
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
- This ensures telemetry is displayed directly to CLI users after the main command output.
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
```javascript
import { generateObjectService } from '../ai-services-unified.js';
import { displayAiUsageSummary } from '../ui.js';
async function performAiRelatedAction(params, context, outputFormat = 'text') {
const { commandNameFromContext, /* other context vars */ } = context;
let aiServiceResponse = null;
try {
aiServiceResponse = await generateObjectService({
// ... other parameters for AI service ...
commandName: commandNameFromContext || 'default-action-name',
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
});
const usefulAiOutput = aiServiceResponse.mainResult.object;
// ... do work with usefulAiOutput ...
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
return {
actionData: /* results of processing */,
telemetryData: aiServiceResponse.telemetryData
};
} catch (error) {
// ... handle error ...
throw error;
}
}
```
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
These functions adapt core logic for the MCP server, ensuring structured responses.
- **Actions**:
1. Call the corresponding core logic function.
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
```javascript
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
export async function someAiActionDirect(args, log, context = {}) {
const { session } = context;
// ... prepare arguments for core function from args, including args.projectRoot ...
try {
const coreResult = await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
session,
mcpLog: createLogWrapper(log),
projectRoot: args.projectRoot,
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
outputType: 'mcp'
},
'json' // Request 'json' output format from core function
);
return {
success: true,
data: {
operationSpecificData: coreResult.actionData,
telemetryData: coreResult.telemetryData // Pass telemetry through
}
};
} catch (error) {
// ... error handling, return { success: false, error: ... } ...
}
}
```
### 3. MCP Tools (in `mcp-server/src/tools/`)
These are the exposed endpoints for MCP clients.
- **Actions**:
1. Call the corresponding direct function wrapper.
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
```javascript
import { someAiActionDirect } from '../core/task-master-core.js';
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
// ... zod for parameters ...
export function registerSomeAiActionTool(server) {
server.addTool({
name: "some_ai_action",
// ... description, parameters ...
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const resultFromDirectFunction = await someAiActionDirect(
{ /* args including projectRoot */ },
log,
{ session }
);
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
} catch (error) {
// ... error handling ...
}
})
});
}
```
### 4. CLI Commands (`scripts/modules/commands.js`)
These define the command-line interface.
- **Actions**:
1. Call the appropriate core logic function.
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
- **Example Snippet (CLI Command in `commands.js`)**:
```javascript
// In scripts/modules/commands.js
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
programInstance
.command('some-cli-ai-action')
// ... .option() ...
.action(async (options) => {
try {
const projectRoot = findProjectRoot() || '.'; // Example root finding
// ... prepare parameters for core function from command options ...
await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
projectRoot,
commandNameFromContext: 'some-cli-ai-action',
outputType: 'cli'
},
'text' // Explicitly request text output format for CLI
);
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
} catch (error) {
// ... error handling ...
}
});
```
## Summary Flow
The telemetry data flows as follows:
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
2. **Core Logic Function**:
* Receives `{ mainResult, telemetryData }`.
* Uses `mainResult`.
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
* Returns `{ operationSpecificData, telemetryData }`.
3. **Direct Function Wrapper**:
* Receives `{ operationSpecificData, telemetryData }` from core logic.
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
4. **MCP Tool**:
* Receives direct function response.
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
5. **CLI Command**:
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.

View File

@@ -428,69 +428,36 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
## MCP Server Tool Utilities (`mcp-server/src/tools/utils.js`) ## MCP Server Tool Utilities (`mcp-server/src/tools/utils.js`)
These utilities specifically support the implementation and execution of MCP tools. - **Purpose**: These utilities specifically support the MCP server tools ([`mcp-server/src/tools/*.js`](mdc:mcp-server/src/tools/*.js)), handling MCP communication patterns, response formatting, caching integration, and the CLI fallback mechanism.
- **Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)** for detailed usage patterns within the MCP tool `execute` methods and direct function wrappers.
- **`normalizeProjectRoot(rawPath, log)`**: - **`getProjectRootFromSession(session, log)`**:
- **Purpose**: Takes a raw project root path (potentially URI encoded, with `file://` prefix, Windows slashes) and returns a normalized, absolute path suitable for the server's OS. - ✅ **DO**: Call this utility **within the MCP tool's `execute` method** to extract the project root path from the `session` object.
- **Logic**: Decodes URI, strips `file://`, handles Windows drive prefix (`/C:/`), replaces `\` with `/`, uses `path.resolve()`. - Decodes the `file://` URI and handles potential errors.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF. - Returns the project path string or `null`.
- The returned path should then be passed in the `args` object when calling the corresponding `*Direct` function (e.g., `yourDirectFunction({ ...args, projectRoot: rootFolder }, log)`).
- **`getRawProjectRootFromSession(session, log)`**:
- **Purpose**: Extracts the *raw* project root URI string from the session object (`session.roots[0].uri` or `session.roots.roots[0].uri`) without performing normalization.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF as a fallback if `args.projectRoot` isn't provided.
- **`withNormalizedProjectRoot(executeFn)`**:
- **Purpose**: A Higher-Order Function (HOF) designed to wrap a tool's `execute` method.
- **Logic**:
1. Determines the raw project root (from `args.projectRoot` or `getRawProjectRootFromSession`).
2. Normalizes the raw path using `normalizeProjectRoot`.
3. Injects the normalized, absolute path back into the `args` object as `args.projectRoot`.
4. Calls the original `executeFn` with the updated `args`.
- **Usage**: Should wrap the `execute` function of *every* MCP tool that needs a reliable, normalized project root path.
- **Example**:
```javascript
// In mcp-server/src/tools/your-tool.js
import { withNormalizedProjectRoot } from './utils.js';
export function registerYourTool(server) {
server.addTool({
// ... name, description, parameters ...
execute: withNormalizedProjectRoot(async (args, context) => {
// args.projectRoot is now normalized here
const { projectRoot /*, other args */ } = args;
// ... rest of tool logic using normalized projectRoot ...
})
});
}
```
- **`handleApiResult(result, log, errorPrefix, processFunction)`**: - **`handleApiResult(result, log, errorPrefix, processFunction)`**:
- **Purpose**: Standardizes the formatting of responses returned by direct functions (`{ success, data/error, fromCache }`) into the MCP response format. - ✅ **DO**: Call this from the MCP tool's `execute` method after receiving the result from the `*Direct` function wrapper.
- **Usage**: Call this at the end of the tool's `execute` method, passing the result from the direct function call. - Takes the standard `{ success, data/error, fromCache }` object.
- Formats the standard MCP success or error response, including the `fromCache` flag.
- Uses `processMCPResponseData` by default to filter response data.
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**: - **`executeTaskMasterCommand(command, log, args, projectRootRaw)`**:
- **Purpose**: Helper functions to create the basic MCP response structure for success or error messages. - Executes a Task Master CLI command as a child process.
- **Usage**: Used internally by `handleApiResult` and potentially directly for simple responses. - Handles fallback between global `task-master` and local `node scripts/dev.js`.
- ❌ **DON'T**: Use this as the primary method for MCP tools. Prefer direct function calls via `*Direct` wrappers.
- **`createLogWrapper(log)`**:
- **Purpose**: Creates a logger object wrapper with standard methods (`info`, `warn`, `error`, `debug`, `success`) mapping to the passed MCP `log` object's methods. Ensures compatibility when passing loggers to core functions.
- **Usage**: Used within direct functions before passing the `log` object down to core logic that expects the standard method names.
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
- **Purpose**: Utility for implementing caching within direct functions. Checks cache for `cacheKey`; if miss, executes `actionFn`, caches successful result, and returns.
- **Usage**: Wrap the core logic execution within a direct function call.
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**: - **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
- **Purpose**: Utility to filter potentially sensitive or large fields (like `details`, `testStrategy`) from task objects before sending the response back via MCP. - Filters task data (e.g., removing `details`, `testStrategy`) before sending to the MCP client. Called by `handleApiResult`.
- **Usage**: Passed as the default `processFunction` to `handleApiResult`.
- **`getProjectRootFromSession(session, log)`**: - **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
- **Purpose**: Legacy function to extract *and normalize* the project root from the session. Replaced by the HOF pattern but potentially still used. - Formatters for standard MCP success/error responses.
- **Recommendation**: Prefer using the `withNormalizedProjectRoot` HOF in tools instead of calling this directly.
- **`executeTaskMasterCommand(...)`**: - **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
- **Purpose**: Executes `task-master` CLI command as a fallback. - ✅ **DO**: Use this utility *inside direct function wrappers* to implement caching.
- **Recommendation**: Deprecated for most uses; prefer direct function calls. - Checks cache, executes `actionFn` on miss, stores result.
- Returns standard `{ success, data/error, fromCache: boolean }`.
## Export Organization ## Export Organization

View File

@@ -1,62 +0,0 @@
name: Pre-Release (RC)
on:
workflow_dispatch: # Allows manual triggering from GitHub UI/API
concurrency: pre-release-${{ github.ref }}
jobs:
rc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
timeout-minutes: 2
- name: Enter RC mode
run: |
npx changeset pre exit || true
npx changeset pre enter rc
- name: Version RC packages
run: npx changeset version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Release Candidate Pull Request or Publish Release Candidate to npm
uses: changesets/action@v1
with:
publish: npm run release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Exit RC mode
run: npx changeset pre exit
- name: Commit & Push changes
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
message: 'chore: rc version bump'

View File

@@ -33,9 +33,6 @@ jobs:
run: npm ci run: npm ci
timeout-minutes: 2 timeout-minutes: 2
- name: Exit pre-release mode (safety check)
run: npx changeset pre exit || true
- name: Create Release Pull Request or Publish to npm - name: Create Release Pull Request or Publish to npm
uses: changesets/action@v1 uses: changesets/action@v1
with: with:

3
.gitignore vendored
View File

@@ -61,6 +61,3 @@ dist
*.debug *.debug
init-debug.log init-debug.log
dev-debug.log dev-debug.log
# NPMRC
.npmrc

View File

@@ -1,32 +1,31 @@
{ {
"models": { "models": {
"main": { "main": {
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219", "modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 100000, "maxTokens": 100000,
"temperature": 0.2 "temperature": 0.2
}, },
"research": { "research": {
"provider": "perplexity", "provider": "xai",
"modelId": "sonar-pro", "modelId": "grok-3",
"maxTokens": 8700, "maxTokens": 8700,
"temperature": 0.1 "temperature": 0.1
}, },
"fallback": { "fallback": {
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219", "modelId": "claude-3-5-sonnet-20241022",
"maxTokens": 8192, "maxTokens": 120000,
"temperature": 0.2 "temperature": 0.2
} }
}, },
"global": { "global": {
"logLevel": "info", "logLevel": "info",
"debug": false, "debug": false,
"defaultSubtasks": 5, "defaultSubtasks": 5,
"defaultPriority": "medium", "defaultPriority": "medium",
"projectName": "Taskmaster", "projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api", "ollamaBaseUrl": "http://localhost:11434/api",
"userId": "1234567890", "azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/" }
} }
}

View File

@@ -1,197 +1,5 @@
# task-master-ai # task-master-ai
## 0.14.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.14.0-rc.1
### Minor Changes
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
### Patch Changes
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
## 0.14.0-rc.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.13.1
### Patch Changes
- [#399](https://github.com/eyaltoledano/claude-task-master/pull/399) [`734a4fd`](https://github.com/eyaltoledano/claude-task-master/commit/734a4fdcfc89c2e089255618cf940561ad13a3c8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
## 0.13.0
### Minor Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ef782ff`](https://github.com/eyaltoledano/claude-task-master/commit/ef782ff5bd4ceb3ed0dc9ea82087aae5f79ac933) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - feat(expand): Enhance `expand` and `expand-all` commands
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
- Change default behavior to _append_ new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`87d97bb`](https://github.com/eyaltoledano/claude-task-master/commit/87d97bba00d84e905756d46ef96b2d5b984e0f38) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs. - IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`1ab836f`](https://github.com/eyaltoledano/claude-task-master/commit/1ab836f191cb8969153593a9a0bd47fc9aa4a831) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`c8722b0`](https://github.com/eyaltoledano/claude-task-master/commit/c8722b0a7a443a73b95d1bcd4a0b68e0fce2a1cd) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds custom model ID support for Ollama and OpenRouter providers.
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
- Added warnings when setting custom/unvalidated models.
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`2517bc1`](https://github.com/eyaltoledano/claude-task-master/commit/2517bc112c9a497110f3286ca4bfb4130c9addcb) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Integrate OpenAI as a new AI provider. - Enhance `models` command/tool to display API key status. - Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`9a48278`](https://github.com/eyaltoledano/claude-task-master/commit/9a482789f7894f57f655fb8d30ba68542bd0df63) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information - Forces temp at 0.1 for highly deterministic output, no variations - Adds a system prompt to further improve the output - Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity - Specificies to use a high degree of research across the web - Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥
### Patch Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`842eaf7`](https://github.com/eyaltoledano/claude-task-master/commit/842eaf722498ddf7307800b4cdcef4ac4fd7e5b0) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - - Add support for Google Gemini models via Vercel AI SDK integration.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ed79d4f`](https://github.com/eyaltoledano/claude-task-master/commit/ed79d4f4735dfab4124fa189214c0bd5e23a6860) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add xAI provider and Grok models support
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`ad89253`](https://github.com/eyaltoledano/claude-task-master/commit/ad89253e313a395637aa48b9f92cc39b1ef94ad8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Better support for file paths on Windows, Linux & WSL.
- Standardizes handling of different path formats (URI encoded, Windows, Linux, WSL).
- Ensures tools receive a clean, absolute path suitable for the server OS.
- Simplifies tool implementation by centralizing normalization logic.
- [#285](https://github.com/eyaltoledano/claude-task-master/pull/285) [`2acba94`](https://github.com/eyaltoledano/claude-task-master/commit/2acba945c0afee9460d8af18814c87e80f747e9f) Thanks [@neno-is-ooo](https://github.com/neno-is-ooo)! - Add integration for Roo Code
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`d63964a`](https://github.com/eyaltoledano/claude-task-master/commit/d63964a10eed9be17856757661ff817ad6bacfdc) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improved update-subtask - Now it has context about the parent task details - It also has context about the subtask before it and the subtask after it (if they exist) - Not passing all subtasks to stay token efficient
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5f504fa`](https://github.com/eyaltoledano/claude-task-master/commit/5f504fafb8bdaa0043c2d20dee8bbb8ec2040d85) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improve and adjust `init` command for robustness and updated dependencies.
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`96aeeff`](https://github.com/eyaltoledano/claude-task-master/commit/96aeeffc195372722c6a07370540e235bfe0e4d8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5aea93d`](https://github.com/eyaltoledano/claude-task-master/commit/5aea93d4c0490c242d7d7042a210611977848e0a) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`66ac9ab`](https://github.com/eyaltoledano/claude-task-master/commit/66ac9ab9f66d006da518d6e8a3244e708af2764d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improves next command to be subtask-aware - The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'. - The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority. - If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ca7b045`](https://github.com/eyaltoledano/claude-task-master/commit/ca7b0457f1dc65fd9484e92527d9fd6d69db758d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--status` flag to `show` command to filter displayed subtasks.
- [#328](https://github.com/eyaltoledano/claude-task-master/pull/328) [`5a2371b`](https://github.com/eyaltoledano/claude-task-master/commit/5a2371b7cc0c76f5e95d43921c1e8cc8081bf14e) Thanks [@knoxgraeme](https://github.com/knoxgraeme)! - Fix --task to --num-tasks in ui + related tests - issue #324
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`6cb213e`](https://github.com/eyaltoledano/claude-task-master/commit/6cb213ebbd51116ae0688e35b575d09443d17c3b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models." - In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup. - In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both. - Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information. - Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.
## 0.12.1 ## 0.12.1
### Patch Changes ### Patch Changes

View File

@@ -47,7 +47,7 @@ npm install task-master-ai
task-master init task-master init
# If installed locally # If installed locally
npx task-master init npx task-master-init
``` ```
This will prompt you for project details and set up a new project with the necessary files and structure. This will prompt you for project details and set up a new project with the necessary files and structure.

View File

@@ -11,20 +11,8 @@ A task management system for AI-driven development with Claude, designed to work
## Requirements ## Requirements
Taskmaster utilizes AI across several commands, and those require a separate API key. You can use a variety of models from different AI providers provided you add your API keys. For example, if you want to use Claude 3.7, you'll need an Anthropic API key.
You can define 3 types of models to be used: the main model, the research model, and the fallback model (in case either the main or research fail). Whatever model you use, its provider API key must be present in either mcp.json or .env.
At least one (1) of the following is required:
- Anthropic API key (Claude API) - Anthropic API key (Claude API)
- OpenAI API key - OpenAI SDK (for Perplexity API integration, optional)
- Google Gemini API key
- Perplexity API key (for research model)
- xAI API Key (for research or main model)
- OpenRouter API Key (for research or main model)
Using the research model is optional but highly recommended. You will need at least ONE API key. Adding all API keys enables you to seamlessly switch between model providers at will.
## Quick Start ## Quick Start
@@ -48,8 +36,7 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE", "MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE", "OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE", "XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE", "AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
} }
} }
} }

View File

@@ -14,8 +14,8 @@
}, },
"fallback": { "fallback": {
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-5-sonnet-20240620", "modelId": "claude-3.5-sonnet-20240620",
"maxTokens": 8192, "maxTokens": 120000,
"temperature": 0.1 "temperature": 0.1
} }
}, },

View File

@@ -198,7 +198,7 @@ alwaysApply: true
- **MAX_TOKENS** (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`) - **MAX_TOKENS** (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
- **TEMPERATURE** (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`) - **TEMPERATURE** (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
- **DEBUG** (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`) - **DEBUG** (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
- **TASKMASTER_LOG_LEVEL** (Default: `"info"`): Console output level (Example: `TASKMASTER_LOG_LEVEL=debug`) - **LOG_LEVEL** (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
- **DEFAULT_SUBTASKS** (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`) - **DEFAULT_SUBTASKS** (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
- **DEFAULT_PRIORITY** (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`) - **DEFAULT_PRIORITY** (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
- **PROJECT_NAME** (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`) - **PROJECT_NAME** (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)

View File

@@ -1,9 +1,8 @@
# API Keys (Required to enable respective provider) # API Keys (Required to enable respective provider)
ANTHROPIC_API_KEY="your_anthropic_api_key_here" # Required: Format: sk-ant-api03-... ANTHROPIC_API_KEY=your_anthropic_api_key_here # Required: Format: sk-ant-api03-...
PERPLEXITY_API_KEY="your_perplexity_api_key_here" # Optional: Format: pplx-... PERPLEXITY_API_KEY=your_perplexity_api_key_here # Optional: Format: pplx-...
OPENAI_API_KEY="your_openai_api_key_here" # Optional, for OpenAI/OpenRouter models. Format: sk-proj-... OPENAI_API_KEY=your_openai_api_key_here # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gemini models. GOOGLE_API_KEY=your_google_api_key_here # Optional, for Google Gemini models.
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models. MISTRAL_API_KEY=your_mistral_key_here # Optional, for Mistral AI models.
XAI_API_KEY="YOUR_XAI_KEY_HERE" # Optional, for xAI AI models. XAI_API_KEY=YOUR_XAI_KEY_HERE # Optional, for xAI AI models.
AZURE_OPENAI_API_KEY="your_azure_key_here" # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig). AZURE_OPENAI_API_KEY=your_azure_key_here # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
OLLAMA_API_KEY="your_ollama_api_key_here" # Optional: For remote Ollama servers that require authentication.

View File

@@ -39,7 +39,7 @@
{ {
"slug": "debug", "slug": "debug",
"name": "Debug", "name": "Debug",
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.", "roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.", "customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
"groups": [ "groups": [
"read", "read",

View File

@@ -31,7 +31,7 @@ Task Master configuration is now managed through two primary methods:
- Create a `.env` file in your project root for CLI usage. - Create a `.env` file in your project root for CLI usage.
- See `assets/env.example` for required key names. - See `assets/env.example` for required key names.
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `TASKMASTER_LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead. **Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
## How It Works ## How It Works
@@ -42,7 +42,7 @@ Task Master configuration is now managed through two primary methods:
- Tasks can have `subtasks` for more detailed implementation steps. - Tasks can have `subtasks` for more detailed implementation steps.
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress. - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **CLI Commands** 2. **CLI Commands**
You can run the commands via: You can run the commands via:
```bash ```bash
@@ -200,7 +200,7 @@ Notes:
## Logging ## Logging
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable: The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting - `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default) - `info`: Confirmation that things are working as expected (default)

View File

@@ -1,368 +0,0 @@
We want to refine how Task Master handles AI model token limits to be more precise, by:
1. Distinguishing between `maxInputTokens` and `maxOutputTokens` in the configuration.
2. Dynamically adjusting the `maxOutputTokens` for an API call based on the actual prompt length to stay within the model's total context window (or respecting separate input/output limits if the API and model support that).
3. Ensuring that `ai-services-unified.js` uses these more granular limits.
This is a good improvement for both cost control and preventing errors.
Here's a plan:
**Phase 1: Configuration and Core Logic Updates**
1. **Update `.taskmasterconfig` Structure:**
- I'll modify the `models` section in your `.taskmasterconfig`. For each role (`main`, `research`, `fallback`), `maxTokens` will be replaced with `maxInputTokens` and `maxOutputTokens`.
- We'll need to decide on reasonable default values for these new fields. We can look at the current `maxTokens` and the model's known limits to make an initial guess.
2. **Update `MODEL_MAP` in `ai-services-unified.js`:**
- This array already stores cost data. We need to ensure it also stores the _absolute_ maximum input and output tokens for each model listed (e.g., `model_max_input_tokens`, `model_max_output_tokens`). If these fields are not present, they will need to be added. The values in `.taskmasterconfig` will then represent user-defined operational limits, which should ideally be validated against these absolute maximums.
3. **Update `config-manager.js`:**
- Getter functions like `getParametersForRole` will be updated to fetch `maxInputTokens` and `maxOutputTokens` instead of the singular `maxTokens`.
- New getters might be needed if we want to access the model's absolute limits directly from `MODEL_MAP` via `config-manager.js`.
4. **Update `ai-services-unified.js` (`_unifiedServiceRunner`):**
- **Token Counting:** This is a crucial step. Before an API call, we need to estimate the token count of the combined `systemPrompt` and `userPrompt`.
- The Vercel AI SDK or the individual provider SDKs might offer utilities for this. For example, some SDKs expose a `tokenizer` or a way to count tokens for a given string.
- If a direct utility isn't available through the Vercel SDK for the specific provider, we might need to use a library like `tiktoken` for OpenAI/Anthropic models or investigate provider-specific tokenization. This could be complex as tokenization varies between models.
- For now, let's assume we can get a reasonable estimate.
- **Dynamic Output Token Calculation & Validation:**
- Retrieve `configured_max_input_tokens` and `configured_max_output_tokens` from `config-manager.js` for the current role.
- Retrieve `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
- Let `prompt_tokens = countTokens(systemPrompt + userPrompt)`.
- **Input Validation:** If `prompt_tokens > configured_max_input_tokens` OR `prompt_tokens > model_absolute_max_input_tokens`, throw an error. (We might also consider auto-truncation strategies in the future, but an error is safer to start).
- **Output Calculation:** The `max_tokens` parameter sent to the API (which typically refers to the _max number of tokens to generate_) should be `configured_max_output_tokens`. We also need to ensure this doesn't violate the model's absolute output limit.
- Some models have a _total_ context window (input + output). If this is the case for a model, the `max_tokens` parameter for the API call might need to be `min(configured_max_output_tokens, model_absolute_total_tokens - prompt_tokens)`. However, many modern APIs handle separate input and output limits, simplifying this. We'll aim to pass `configured_max_output_tokens` as the API's `max_tokens` parameter, assuming the input validation has passed.
- **API Call Parameter:** Update the `callParams` to use the correctly determined `max_tokens` for generation (which will be our `configured_max_output_tokens`).
**Phase 2: Error Handling and Refinements**
1. **Enhanced Error Handling:** Provide clear error messages if prompt tokens exceed input limits, or if API calls fail due to token issues despite our calculations.
2. **Validation:** Add validation (perhaps in `config-manager.js` or when `task-master models --setup` is run) to ensure `configured_max_input_tokens` and `configured_max_output_tokens` in `.taskmasterconfig` do not exceed the `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
Let's start by inspecting `scripts/modules/config-manager.js` to see how parameters and `MODEL_MAP` are currently handled. This will inform the changes needed for `.taskmasterconfig` and `ai-services-unified.js`.
I will now read `scripts/modules/config-manager.js`.
Okay, I've reviewed `scripts/modules/config-manager.js`. Here's what I've gathered and how it impacts the plan:
- **`MODEL_MAP` Source:** `MODEL_MAP` is loaded from `supported-models.json`. This is excellent, as it means we can update the model capabilities (including new token limits) in a structured JSON file.
- **Configuration Loading:** `_loadAndValidateConfig` handles loading `.taskmasterconfig` and merging it with `DEFAULTS`.
- **Getters:** There are specific getters for `maxTokens` for each role (e.g., `getMainMaxTokens`). We will need to update these.
- **`getParametersForRole`:** This function already exists and is a good candidate for returning the new `maxInputTokens` and `maxOutputTokens`.
Here's the refined plan:
**Phase 1: Configuration and Data Structures**
1. **Update `supported-models.json`:**
- For each model entry in `supported-models.json`, we need to add `maxInputTokens` and `maxOutputTokens` fields. These should reflect the _absolute maximums_ for that specific model.
- Example entry change:
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
- I will need to find the official input/output token limits for the models currently in your `MODEL_MAP`. If you have this information handy, it would speed things up. Otherwise, I can make educated guesses or search for them.
2. **Update `.taskmasterconfig` (Defaults and User File):**
- In `scripts/modules/config-manager.js`, modify the `DEFAULTS` object. For each role (`main`, `research`, `fallback`), replace `maxTokens` with:
- `maxInputTokens`: A sensible default (e.g., a large portion of the model's capability, but user-configurable).
- `maxOutputTokens`: A sensible default for generation (e.g., 4096 or 8192).
- You will then need to manually update your existing `.taskmasterconfig` file to reflect this new structure. I can provide the snippet for you to paste.
3. **Update `config-manager.js`:**
- Modify `getParametersForRole(role, explicitRoot = null)`:
- It currently fetches `maxTokens` and `temperature`.
- Update it to fetch `maxInputTokens`, `maxOutputTokens`, and `temperature` from the loaded config for the given role.
- Remove the role-specific `getMaxTokens` functions (e.g., `getMainMaxTokens`, `getResearchMaxTokens`, `getFallbackMaxTokens`). The `getParametersForRole` will be the central way to get these.
- (Optional, for later validation) Consider adding a new function `getModelCapabilities(providerName, modelId)` that reads from `MODEL_MAP` to return the absolute `maxInputTokens` and `maxOutputTokens` for a given model. This would be useful for validating the user's settings in `.taskmasterconfig`.
**Phase 2: Core Logic in `ai-services-unified.js`**
1. **Token Counting (`_unifiedServiceRunner`):**
- This is the most complex part. We need a reliable way to count tokens for the prompts.
- **Strategy 1 (Ideal):** Leverage Vercel AI SDK. The SDK might provide a way to get a tokenizer for the active model or a utility function. We'll need to investigate its capabilities.
- **Strategy 2 (Fallback):** Use a library like `tiktoken` for models compatible with OpenAI's tokenization (many are, including some Anthropic models). For other models, we might need provider-specific tokenizers or make estimations (less ideal).
- **Initial Approach:** Let's try to find a Vercel AI SDK utility first. If not, we'll start with `tiktoken` as a common case and acknowledge that other models might need specific handling later.
- The function `_unifiedServiceRunner` will call this token counting utility:
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
2. **Dynamic Output Token Calculation & Validation (`_unifiedServiceRunner`):**
- Fetch parameters using the updated `getParametersForRole` from `config-manager.js`:
```javascript
const roleParams = getParametersForRole(
currentRole,
effectiveProjectRoot
);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
- Fetch model's absolute limits from `MODEL_MAP` (we'll need a helper in `config-manager.js` or do it directly in `ai-services-unified.js` for now):
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
- **Input Validation:**
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
- **API Call Parameter (`max_tokens` for generation):**
The `max_tokens` parameter passed to the provider's API call should be `roleParams.maxOutputTokens`. We must also ensure this doesn't exceed the model's absolute output capability.
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
3. **Update `logAiUsage`:**
- The cost calculation in `logAiUsage` seems correct as it already uses `inputCost` and `outputCost` per 1M tokens. This part should remain compatible.
**Next Steps:**
1. **Modify `supported-models.json`:** I need the content of this file to propose the new `maxInputTokens` and `maxOutputTokens` fields. Please provide it.
2. **Decide on Tokenizer Strategy:** What are your thoughts on the token counting? Are you aware of any utilities within Vercel AI SDK for this, or should we plan to integrate `tiktoken` initially?
Once I have the content of `supported-models.json`, I can draft the changes for it and then proceed to `config-manager.js` and `.taskmasterconfig`.
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
```javascript
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
Okay, I have the contents of `supported-models.json`.
It seems many models have a `max_tokens` field, which I assume is the _total context window_. Some don't have it, and for others (like OpenAI `gpt-4o`), the listed `max_tokens` (16384) is known to be its _output_ token limit when using the Chat Completions API, while the context window is much larger (128k). This highlights the complexity: `max_tokens` in `supported-models.json` is used inconsistently.
**Revised Plan for `supported-models.json` and Token Definitions:**
To bring clarity, we'll introduce two new fields and ensure their meaning is consistent:
- `contextWindowTokens`: The total number of tokens the model can process (input + output). This would replace the current ambiguous `max_tokens`.
- `maxOutputTokens`: The maximum number of tokens the model can _generate_ in a single response. This is often smaller than the total context window, especially for larger models.
If a model _only_ specifies a total context window, we'll have to make a reasonable assumption for `maxOutputTokens` (e.g., 4096 or 8192, or a fraction of the total context window). If it only specifies an output token limit (like some OpenAI models in certain API modes), we'll need to find its total context window.
**Updated `supported-models.json` Structure (Example):**
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
I will proceed to generate the updated `supported-models.json` content. This will be a significant change. I will make my best effort to find the correct `contextWindowTokens` and `maxOutputTokens` for each model. If official numbers are ambiguous or not readily available, I'll use sensible defaults and add a comment.
**Regarding Tokenizer Strategy:**
- **Vercel AI SDK:** The `ai` package (Vercel AI SDK) itself is a lightweight wrapper. Tokenization is usually handled by the underlying provider-specific SDKs (e.g., `@anthropic-ai/sdk`, `openai`). The Vercel SDK doesn't provide a universal tokenizer.
- **Provider SDKs:**
- `@anthropic-ai/sdk`: Does not expose a public tokenizer directly. Anthropic recommends counting based on their guidelines (roughly 3.5 chars/token for English).
- `openai` (for Node.js): The `gpt-3-encoder` or `tiktoken` libraries are commonly used. `tiktoken` is more current.
- **`tiktoken`:** This is a good general-purpose library for OpenAI models and those that use compatible tokenization (many models fine-tuned from Llama, etc., might be close). It supports various encodings.
- **Recommendation:**
1. Start by integrating `tiktoken`. We can select the encoding based on the provider or even specific model if needed (e.g., `cl100k_base` for gpt-4, gpt-3.5-turbo, DALL-E models).
2. For providers where `tiktoken` is not accurate (e.g., Google's Gemini, Perplexity if they have proprietary tokenizers), we might have to rely on character-based estimations (e.g., `length / N`) as a rougher guide or investigate if their specific SDKs offer token counting.
3. The Vercel AI SDK's `experimental_streamObject` and other functions _might_ internally handle some aspects of token counting for request preparation, but we need explicit counting for our logic _before_ the call.
For now, let's assume we'll add a `countTokens` utility that uses `tiktoken` for OpenAI and Anthropic (as Anthropic's guidance is character-based but `cl100k_base` is often a decent proxy for their tokenization for rough estimates, though not perfect), and a character-based fallback for others.
I will now generate the proposed changes for `scripts/modules/supported-models.json`. This will be a large diff.
After this, we'll move to:
1. Updating `.taskmasterconfig` defaults in `config-manager.js` and providing you the snippet for your user file.
2. Updating `config-manager.js` getters.
3. Implementing the logic in `ai-services-unified.js`.
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```

View File

@@ -15,15 +15,13 @@ Taskmaster uses two primary methods for configuration:
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219", "modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 64000, "maxTokens": 64000,
"temperature": 0.2, "temperature": 0.2
"baseUrl": "https://api.anthropic.com/v1"
}, },
"research": { "research": {
"provider": "perplexity", "provider": "perplexity",
"modelId": "sonar-pro", "modelId": "sonar-pro",
"maxTokens": 8700, "maxTokens": 8700,
"temperature": 0.1, "temperature": 0.1
"baseUrl": "https://api.perplexity.ai/v1"
}, },
"fallback": { "fallback": {
"provider": "anthropic", "provider": "anthropic",
@@ -58,9 +56,8 @@ Taskmaster uses two primary methods for configuration:
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`). - `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
- `OPENROUTER_API_KEY`: Your OpenRouter API key. - `OPENROUTER_API_KEY`: Your OpenRouter API key.
- `XAI_API_KEY`: Your X-AI API key. - `XAI_API_KEY`: Your X-AI API key.
- **Optional Endpoint Overrides:** - **Optional Endpoint Overrides (in .taskmasterconfig):**
- **Per-role `baseUrl` in `.taskmasterconfig`:** You can add a `baseUrl` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used. - `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key.
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseUrl` for the Azure model role).
- `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`). - `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`).
**Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables. **Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables.

View File

@@ -89,7 +89,7 @@ Initialize a new project:
task-master init task-master init
# If installed locally # If installed locally
npx task-master init npx task-master-init
``` ```
This will prompt you for project details and set up a new project with the necessary files and structure. This will prompt you for project details and set up a new project with the necessary files and structure.

View File

@@ -23,21 +23,13 @@ import { createLogWrapper } from '../../tools/utils.js';
* @param {string} [args.priority='medium'] - Task priority (high, medium, low) * @param {string} [args.priority='medium'] - Task priority (high, medium, low)
* @param {string} [args.tasksJsonPath] - Path to the tasks.json file (resolved by tool) * @param {string} [args.tasksJsonPath] - Path to the tasks.json file (resolved by tool)
* @param {boolean} [args.research=false] - Whether to use research capabilities for task creation * @param {boolean} [args.research=false] - Whether to use research capabilities for task creation
* @param {string} [args.projectRoot] - Project root path
* @param {Object} log - Logger object * @param {Object} log - Logger object
* @param {Object} context - Additional context (session) * @param {Object} context - Additional context (session)
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } } * @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
*/ */
export async function addTaskDirect(args, log, context = {}) { export async function addTaskDirect(args, log, context = {}) {
// Destructure expected args (including research and projectRoot) // Destructure expected args (including research)
const { const { tasksJsonPath, prompt, dependencies, priority, research } = args;
tasksJsonPath,
prompt,
dependencies,
priority,
research,
projectRoot
} = args;
const { session } = context; // Destructure session from context const { session } = context; // Destructure session from context
// Enable silent mode to prevent console logs from interfering with JSON response // Enable silent mode to prevent console logs from interfering with JSON response
@@ -94,7 +86,6 @@ export async function addTaskDirect(args, log, context = {}) {
let manualTaskData = null; let manualTaskData = null;
let newTaskId; let newTaskId;
let telemetryData;
if (isManualCreation) { if (isManualCreation) {
// Create manual task data object // Create manual task data object
@@ -110,25 +101,19 @@ export async function addTaskDirect(args, log, context = {}) {
); );
// Call the addTask function with manual task data // Call the addTask function with manual task data
const result = await addTask( newTaskId = await addTask(
tasksPath, tasksPath,
null, // prompt is null for manual creation null, // prompt is null for manual creation
taskDependencies, taskDependencies,
taskPriority, taskPriority,
{ {
session, session,
mcpLog, mcpLog
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
}, },
'json', // outputFormat 'json', // outputFormat
manualTaskData, // Pass the manual task data manualTaskData, // Pass the manual task data
false, // research flag is false for manual creation false // research flag is false for manual creation
projectRoot // Pass projectRoot
); );
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
} else { } else {
// AI-driven task creation // AI-driven task creation
log.info( log.info(
@@ -136,24 +121,19 @@ export async function addTaskDirect(args, log, context = {}) {
); );
// Call the addTask function, passing the research flag // Call the addTask function, passing the research flag
const result = await addTask( newTaskId = await addTask(
tasksPath, tasksPath,
prompt, // Use the prompt for AI creation prompt, // Use the prompt for AI creation
taskDependencies, taskDependencies,
taskPriority, taskPriority,
{ {
session, session,
mcpLog, mcpLog
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
}, },
'json', // outputFormat 'json', // outputFormat
null, // manualTaskData is null for AI creation null, // manualTaskData is null for AI creation
research // Pass the research flag research // Pass the research flag
); );
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
} }
// Restore normal logging // Restore normal logging
@@ -163,8 +143,7 @@ export async function addTaskDirect(args, log, context = {}) {
success: true, success: true,
data: { data: {
taskId: newTaskId, taskId: newTaskId,
message: `Successfully added new task #${newTaskId}`, message: `Successfully added new task #${newTaskId}`
telemetryData: telemetryData
} }
}; };
} catch (error) { } catch (error) {

View File

@@ -18,17 +18,15 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
* @param {string} args.outputPath - Explicit absolute path to save the report. * @param {string} args.outputPath - Explicit absolute path to save the report.
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10) * @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis * @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object * @param {Object} log - Logger object
* @param {Object} [context={}] - Context object containing session data * @param {Object} [context={}] - Context object containing session data
* @param {Object} [context.session] - MCP session object * @param {Object} [context.session] - MCP session object
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>} * @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
*/ */
export async function analyzeTaskComplexityDirect(args, log, context = {}) { export async function analyzeTaskComplexityDirect(args, log, context = {}) {
const { session } = context; const { session } = context; // Extract session
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args; // Destructure expected args
const { tasksJsonPath, outputPath, model, threshold, research } = args; // Model is ignored by core function now
const logWrapper = createLogWrapper(log);
// --- Initial Checks (remain the same) --- // --- Initial Checks (remain the same) ---
try { try {
@@ -62,36 +60,35 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
log.info('Using research role for complexity analysis'); log.info('Using research role for complexity analysis');
} }
// Prepare options for the core function - REMOVED mcpLog and session here // Prepare options for the core function
const coreOptions = { const options = {
file: tasksJsonPath, file: tasksPath,
output: outputPath, output: resolvedOutputPath,
// model: model, // No longer needed
threshold: threshold, threshold: threshold,
research: research === true, // Ensure boolean research: research === true // Ensure boolean
projectRoot: projectRoot // Pass projectRoot here
}; };
// --- End Initial Checks --- // --- End Initial Checks ---
// --- Silent Mode and Logger Wrapper --- // --- Silent Mode and Logger Wrapper (remain the same) ---
const wasSilent = isSilentMode(); const wasSilent = isSilentMode();
if (!wasSilent) { if (!wasSilent) {
enableSilentMode(); // Still enable silent mode as a backup enableSilentMode();
} }
let report; // Create logger wrapper using the utility
let coreResult; const mcpLog = createLogWrapper(log);
let report; // To store the result from the core function
try { try {
// --- Call Core Function (Pass context separately) --- // --- Call Core Function (Updated Context Passing) ---
// Pass coreOptions as the first argument // Call the core function, passing options and the context object { session, mcpLog }
// Pass context object { session, mcpLog } as the second argument report = await analyzeTaskComplexity(options, {
coreResult = await analyzeTaskComplexity(coreOptions, { session, // Pass the session object
session, mcpLog // Pass the logger wrapper
mcpLog: logWrapper,
commandName: 'analyze-complexity',
outputType: 'mcp'
}); });
report = coreResult.report; // --- End Core Function Call ---
} catch (error) { } catch (error) {
log.error( log.error(
`Error in analyzeTaskComplexity core function: ${error.message}` `Error in analyzeTaskComplexity core function: ${error.message}`
@@ -103,7 +100,7 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
return { return {
success: false, success: false,
error: { error: {
code: 'ANALYZE_CORE_ERROR', code: 'ANALYZE_CORE_ERROR', // More specific error code
message: `Error running core complexity analysis: ${error.message}` message: `Error running core complexity analysis: ${error.message}`
} }
}; };
@@ -127,13 +124,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
}; };
} }
if ( // The core function now returns the report object directly
!coreResult || if (!report || !report.complexityAnalysis) {
!coreResult.report ||
typeof coreResult.report !== 'object'
) {
log.error( log.error(
'Core analysis function returned an invalid or undefined response.' 'Core analyzeTaskComplexity function did not return a valid report object.'
); );
return { return {
success: false, success: false,
@@ -145,10 +139,7 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
} }
try { try {
// Ensure complexityAnalysis exists and is an array const analysisArray = report.complexityAnalysis; // Already an array
const analysisArray = Array.isArray(coreResult.report.complexityAnalysis)
? coreResult.report.complexityAnalysis
: [];
// Count tasks by complexity (remains the same) // Count tasks by complexity (remains the same)
const highComplexityTasks = analysisArray.filter( const highComplexityTasks = analysisArray.filter(
@@ -164,16 +155,16 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
return { return {
success: true, success: true,
data: { data: {
message: `Task complexity analysis complete. Report saved to ${outputPath}`, message: `Task complexity analysis complete. Report saved to ${resolvedOutputPath}`,
reportPath: outputPath, reportPath: resolvedOutputPath,
reportSummary: { reportSummary: {
taskCount: analysisArray.length, taskCount: analysisArray.length,
highComplexityTasks, highComplexityTasks,
mediumComplexityTasks, mediumComplexityTasks,
lowComplexityTasks lowComplexityTasks
}, }
fullReport: coreResult.report, // Include the full report data if needed by the client
telemetryData: coreResult.telemetryData // fullReport: report
} }
}; };
} catch (parseError) { } catch (parseError) {

View File

@@ -8,6 +8,7 @@ import {
enableSilentMode, enableSilentMode,
disableSilentMode disableSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { getCachedOrExecute } from '../../tools/utils.js';
/** /**
* Direct function wrapper for displaying the complexity report with error handling and caching. * Direct function wrapper for displaying the complexity report with error handling and caching.
@@ -85,20 +86,30 @@ export async function complexityReportDirect(args, log) {
// Use the caching utility // Use the caching utility
try { try {
const result = await coreActionFn(); const result = await getCachedOrExecute({
log.info('complexityReportDirect completed'); cacheKey,
return result; actionFn: coreActionFn,
log
});
log.info(
`complexityReportDirect completed. From cache: ${result.fromCache}`
);
return result; // Returns { success, data/error, fromCache }
} catch (error) { } catch (error) {
// Catch unexpected errors from getCachedOrExecute itself
// Ensure silent mode is disabled // Ensure silent mode is disabled
disableSilentMode(); disableSilentMode();
log.error(`Unexpected error during complexityReport: ${error.message}`); log.error(
`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`
);
return { return {
success: false, success: false,
error: { error: {
code: 'UNEXPECTED_ERROR', code: 'UNEXPECTED_ERROR',
message: error.message message: error.message
} },
fromCache: false
}; };
} }
} catch (error) { } catch (error) {

View File

@@ -17,15 +17,14 @@ import { createLogWrapper } from '../../tools/utils.js';
* @param {boolean} [args.research] - Enable research-backed subtask generation * @param {boolean} [args.research] - Enable research-backed subtask generation
* @param {string} [args.prompt] - Additional context to guide subtask generation * @param {string} [args.prompt] - Additional context to guide subtask generation
* @param {boolean} [args.force] - Force regeneration of subtasks for tasks that already have them * @param {boolean} [args.force] - Force regeneration of subtasks for tasks that already have them
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object from FastMCP * @param {Object} log - Logger object from FastMCP
* @param {Object} context - Context object containing session * @param {Object} context - Context object containing session
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>} * @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
*/ */
export async function expandAllTasksDirect(args, log, context = {}) { export async function expandAllTasksDirect(args, log, context = {}) {
const { session } = context; // Extract session const { session } = context; // Extract session
// Destructure expected args, including projectRoot // Destructure expected args
const { tasksJsonPath, num, research, prompt, force, projectRoot } = args; const { tasksJsonPath, num, research, prompt, force } = args;
// Create logger wrapper using the utility // Create logger wrapper using the utility
const mcpLog = createLogWrapper(log); const mcpLog = createLogWrapper(log);
@@ -44,7 +43,7 @@ export async function expandAllTasksDirect(args, log, context = {}) {
enableSilentMode(); // Enable silent mode for the core function call enableSilentMode(); // Enable silent mode for the core function call
try { try {
log.info( log.info(
`Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force, projectRoot })}` `Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force })}`
); );
// Parse parameters (ensure correct types) // Parse parameters (ensure correct types)
@@ -53,28 +52,22 @@ export async function expandAllTasksDirect(args, log, context = {}) {
const additionalContext = prompt || ''; const additionalContext = prompt || '';
const forceFlag = force === true; const forceFlag = force === true;
// Call the core function, passing options and the context object { session, mcpLog, projectRoot } // Call the core function, passing options and the context object { session, mcpLog }
const result = await expandAllTasks( const result = await expandAllTasks(
tasksJsonPath, tasksJsonPath,
numSubtasks, numSubtasks,
useResearch, useResearch,
additionalContext, additionalContext,
forceFlag, forceFlag,
{ session, mcpLog, projectRoot } { session, mcpLog }
); );
// Core function now returns a summary object including the *aggregated* telemetryData // Core function now returns a summary object
return { return {
success: true, success: true,
data: { data: {
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`, message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
details: { details: result // Include the full result details
expandedCount: result.expandedCount,
failedCount: result.failedCount,
skippedCount: result.skippedCount,
tasksToExpand: result.tasksToExpand
},
telemetryData: result.telemetryData // Pass the aggregated object
} }
}; };
} catch (error) { } catch (error) {

View File

@@ -25,7 +25,6 @@ import { createLogWrapper } from '../../tools/utils.js';
* @param {boolean} [args.research] - Enable research role for subtask generation. * @param {boolean} [args.research] - Enable research role for subtask generation.
* @param {string} [args.prompt] - Additional context to guide subtask generation. * @param {string} [args.prompt] - Additional context to guide subtask generation.
* @param {boolean} [args.force] - Force expansion even if subtasks exist. * @param {boolean} [args.force] - Force expansion even if subtasks exist.
* @param {string} [args.projectRoot] - Project root directory.
* @param {Object} log - Logger object * @param {Object} log - Logger object
* @param {Object} context - Context object containing session * @param {Object} context - Context object containing session
* @param {Object} [context.session] - MCP Session object * @param {Object} [context.session] - MCP Session object
@@ -33,8 +32,8 @@ import { createLogWrapper } from '../../tools/utils.js';
*/ */
export async function expandTaskDirect(args, log, context = {}) { export async function expandTaskDirect(args, log, context = {}) {
const { session } = context; // Extract session const { session } = context; // Extract session
// Destructure expected args, including projectRoot // Destructure expected args
const { tasksJsonPath, id, num, research, prompt, force, projectRoot } = args; const { tasksJsonPath, id, num, research, prompt, force } = args;
// Log session root data for debugging // Log session root data for debugging
log.info( log.info(
@@ -185,28 +184,20 @@ export async function expandTaskDirect(args, log, context = {}) {
// Create logger wrapper using the utility // Create logger wrapper using the utility
const mcpLog = createLogWrapper(log); const mcpLog = createLogWrapper(log);
let wasSilent; // Declare wasSilent outside the try block
// Process the request // Process the request
try { try {
// Enable silent mode to prevent console logs from interfering with JSON response // Enable silent mode to prevent console logs from interfering with JSON response
wasSilent = isSilentMode(); // Assign inside the try block const wasSilent = isSilentMode();
if (!wasSilent) enableSilentMode(); if (!wasSilent) enableSilentMode();
// Call the core expandTask function with the wrapped logger and projectRoot // Call the core expandTask function with the wrapped logger
const coreResult = await expandTask( const result = await expandTask(
tasksPath, tasksPath,
taskId, taskId,
numSubtasks, numSubtasks,
useResearch, useResearch,
additionalContext, additionalContext,
{ { mcpLog, session }
mcpLog,
session,
projectRoot,
commandName: 'expand-task',
outputType: 'mcp'
},
forceFlag
); );
// Restore normal logging // Restore normal logging
@@ -221,17 +212,16 @@ export async function expandTaskDirect(args, log, context = {}) {
? updatedTask.subtasks.length - subtasksCountBefore ? updatedTask.subtasks.length - subtasksCountBefore
: 0; : 0;
// Return the result, including telemetryData // Return the result
log.info( log.info(
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks` `Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
); );
return { return {
success: true, success: true,
data: { data: {
task: coreResult.task, task: updatedTask,
subtasksAdded, subtasksAdded,
hasExistingSubtasks, hasExistingSubtasks
telemetryData: coreResult.telemetryData
}, },
fromCache: false fromCache: false
}; };

View File

@@ -4,6 +4,7 @@ import {
disableSilentMode disableSilentMode
// isSilentMode // Not used directly here // isSilentMode // Not used directly here
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { getProjectRootFromSession } from '../../tools/utils.js'; // Adjust path if necessary
import os from 'os'; // Import os module for home directory check import os from 'os'; // Import os module for home directory check
/** /**
@@ -15,32 +16,60 @@ import os from 'os'; // Import os module for home directory check
* @returns {Promise<{success: boolean, data?: any, error?: {code: string, message: string}}>} - Standard result object. * @returns {Promise<{success: boolean, data?: any, error?: {code: string, message: string}}>} - Standard result object.
*/ */
export async function initializeProjectDirect(args, log, context = {}) { export async function initializeProjectDirect(args, log, context = {}) {
const { session } = context; // Keep session if core logic needs it const { session } = context;
const homeDir = os.homedir(); const homeDir = os.homedir();
let targetDirectory = null;
log.info(
`CONTEXT received in direct function: ${context ? JSON.stringify(Object.keys(context)) : 'MISSING or Falsy'}`
);
log.info(
`SESSION extracted in direct function: ${session ? 'Exists' : 'MISSING or Falsy'}`
);
log.info(`Args received in direct function: ${JSON.stringify(args)}`); log.info(`Args received in direct function: ${JSON.stringify(args)}`);
// --- Determine Target Directory --- // --- Determine Target Directory ---
// TRUST the projectRoot passed from the tool layer via args // 1. Prioritize projectRoot passed directly in args
// The HOF in the tool layer already normalized and validated it came from a reliable source (args or session) // Ensure it's not null, '/', or the home directory
const targetDirectory = args.projectRoot;
// --- Validate the targetDirectory (basic sanity checks) ---
if ( if (
!targetDirectory || args.projectRoot &&
typeof targetDirectory !== 'string' || // Ensure it's a string args.projectRoot !== '/' &&
targetDirectory === '/' || args.projectRoot !== homeDir
targetDirectory === homeDir
) { ) {
log.error( log.info(`Using projectRoot directly from args: ${args.projectRoot}`);
`Invalid target directory received from tool layer: '${targetDirectory}'` targetDirectory = args.projectRoot;
} else {
// 2. If args.projectRoot is missing or invalid, THEN try session (as a fallback)
log.warn(
`args.projectRoot ('${args.projectRoot}') is missing or invalid. Attempting to derive from session.`
); );
const sessionDerivedPath = getProjectRootFromSession(session, log);
// Validate the session-derived path as well
if (
sessionDerivedPath &&
sessionDerivedPath !== '/' &&
sessionDerivedPath !== homeDir
) {
log.info(
`Using project root derived from session: ${sessionDerivedPath}`
);
targetDirectory = sessionDerivedPath;
} else {
log.error(
`Could not determine a valid project root. args.projectRoot='${args.projectRoot}', sessionDerivedPath='${sessionDerivedPath}'`
);
}
}
// 3. Validate the final targetDirectory
if (!targetDirectory) {
// This error now covers cases where neither args.projectRoot nor session provided a valid path
return { return {
success: false, success: false,
error: { error: {
code: 'INVALID_TARGET_DIRECTORY', code: 'INVALID_TARGET_DIRECTORY',
message: `Cannot initialize project: Invalid target directory '${targetDirectory}' received. Please ensure a valid workspace/folder is open or specified.`, message: `Cannot initialize project: Could not determine a valid target directory. Please ensure a workspace/folder is open or specify projectRoot.`,
details: `Received args.projectRoot: ${args.projectRoot}` // Show what was received details: `Attempted args.projectRoot: ${args.projectRoot}`
}, },
fromCache: false fromCache: false
}; };
@@ -57,12 +86,11 @@ export async function initializeProjectDirect(args, log, context = {}) {
log.info( log.info(
`Temporarily changing CWD to ${targetDirectory} for initialization.` `Temporarily changing CWD to ${targetDirectory} for initialization.`
); );
process.chdir(targetDirectory); // Change CWD to the HOF-provided root process.chdir(targetDirectory); // Change CWD to the *validated* targetDirectory
enableSilentMode(); enableSilentMode(); // Enable silent mode BEFORE calling the core function
try { try {
// Construct options ONLY from the relevant flags in args // Always force yes: true when called via MCP to avoid interactive prompts
// The core initializeProject operates in the current CWD, which we just set
const options = { const options = {
aliases: args.addAliases, aliases: args.addAliases,
skipInstall: args.skipInstall, skipInstall: args.skipInstall,
@@ -72,11 +100,12 @@ export async function initializeProjectDirect(args, log, context = {}) {
log.info(`Initializing project with options: ${JSON.stringify(options)}`); log.info(`Initializing project with options: ${JSON.stringify(options)}`);
const result = await initializeProject(options); // Call core logic const result = await initializeProject(options); // Call core logic
// Format success result for handleApiResult
resultData = { resultData = {
message: 'Project initialized successfully.', message: 'Project initialized successfully.',
next_step: next_step:
'Now that the project is initialized, the next step is to create the tasks by parsing a PRD. This will create the tasks folder and the initial task files (tasks folder will be created when parse-prd is run). The parse-prd tool will require a prd.txt file as input (typically found in the project root directory, scripts/ directory). You can create a prd.txt file by asking the user about their idea, and then using the scripts/example_prd.txt file as a template to genrate a prd.txt file in scripts/. You may skip all of this if the user already has a prd.txt file. You can THEN use the parse-prd tool to create the tasks. So: step 1 after initialization is to create a prd.txt file in scripts/prd.txt or confirm the user already has one. Step 2 is to use the parse-prd tool to create the tasks. Do not bother looking for tasks after initialization, just use the parse-prd tool to create the tasks after creating a prd.txt from which to parse the tasks. You do NOT need to reinitialize the project to parse-prd.', 'Now that the project is initialized, the next step is to create the tasks by parsing a PRD. This will create the tasks folder and the initial task files (tasks folder will be created when parse-prd is run). The parse-prd tool will require a prd.txt file as input (typically found in the project root directory, scripts/ directory). You can create a prd.txt file by asking the user about their idea, and then using the scripts/example_prd.txt file as a template to genrate a prd.txt file in scripts/. You may skip all of this if the user already has a prd.txt file. You can THEN use the parse-prd tool to create the tasks. So: step 1 after initialization is to create a prd.txt file in scripts/prd.txt or confirm the user already has one. Step 2 is to use the parse-prd tool to create the tasks. Do not bother looking for tasks after initialization, just use the parse-prd tool to create the tasks after creating a prd.txt from which to parse the tasks. You do NOT need to reinitialize the project to parse-prd.',
...result ...result // Include details returned by initializeProject
}; };
success = true; success = true;
log.info( log.info(
@@ -91,11 +120,12 @@ export async function initializeProjectDirect(args, log, context = {}) {
}; };
success = false; success = false;
} finally { } finally {
disableSilentMode(); disableSilentMode(); // ALWAYS disable silent mode in finally
log.info(`Restoring original CWD: ${originalCwd}`); log.info(`Restoring original CWD: ${originalCwd}`);
process.chdir(originalCwd); process.chdir(originalCwd); // Change back to original CWD
} }
// Return in format expected by handleApiResult
if (success) { if (success) {
return { success: true, data: resultData, fromCache: false }; return { success: true, data: resultData, fromCache: false };
} else { } else {

View File

@@ -4,6 +4,7 @@
*/ */
import { listTasks } from '../../../../scripts/modules/task-manager.js'; import { listTasks } from '../../../../scripts/modules/task-manager.js';
import { getCachedOrExecute } from '../../tools/utils.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode disableSilentMode
@@ -18,7 +19,7 @@ import {
*/ */
export async function listTasksDirect(args, log) { export async function listTasksDirect(args, log) {
// Destructure the explicit tasksJsonPath from args // Destructure the explicit tasksJsonPath from args
const { tasksJsonPath, reportPath, status, withSubtasks } = args; const { tasksJsonPath, status, withSubtasks } = args;
if (!tasksJsonPath) { if (!tasksJsonPath) {
log.error('listTasksDirect called without tasksJsonPath'); log.error('listTasksDirect called without tasksJsonPath');
@@ -35,6 +36,7 @@ export async function listTasksDirect(args, log) {
// Use the explicit tasksJsonPath for cache key // Use the explicit tasksJsonPath for cache key
const statusFilter = status || 'all'; const statusFilter = status || 'all';
const withSubtasksFilter = withSubtasks || false; const withSubtasksFilter = withSubtasks || false;
const cacheKey = `listTasks:${tasksJsonPath}:${statusFilter}:${withSubtasksFilter}`;
// Define the action function to be executed on cache miss // Define the action function to be executed on cache miss
const coreListTasksAction = async () => { const coreListTasksAction = async () => {
@@ -49,7 +51,6 @@ export async function listTasksDirect(args, log) {
const resultData = listTasks( const resultData = listTasks(
tasksJsonPath, tasksJsonPath,
statusFilter, statusFilter,
reportPath,
withSubtasksFilter, withSubtasksFilter,
'json' 'json'
); );
@@ -64,7 +65,6 @@ export async function listTasksDirect(args, log) {
} }
}; };
} }
log.info( log.info(
`Core listTasks function retrieved ${resultData.tasks.length} tasks` `Core listTasks function retrieved ${resultData.tasks.length} tasks`
); );
@@ -88,19 +88,25 @@ export async function listTasksDirect(args, log) {
} }
}; };
// Use the caching utility
try { try {
const result = await coreListTasksAction(); const result = await getCachedOrExecute({
log.info('listTasksDirect completed'); cacheKey,
return result; actionFn: coreListTasksAction,
log
});
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
return result; // Returns { success, data/error, fromCache }
} catch (error) { } catch (error) {
log.error(`Unexpected error during listTasks: ${error.message}`); // Catch unexpected errors from getCachedOrExecute itself (though unlikely)
log.error(
`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`
);
console.error(error.stack); console.error(error.stack);
return { return {
success: false, success: false,
error: { error: { code: 'CACHE_UTIL_ERROR', message: error.message },
code: 'UNEXPECTED_ERROR', fromCache: false
message: error.message
}
}; };
} }
} }

View File

@@ -4,10 +4,8 @@
*/ */
import { findNextTask } from '../../../../scripts/modules/task-manager.js'; import { findNextTask } from '../../../../scripts/modules/task-manager.js';
import { import { readJSON } from '../../../../scripts/modules/utils.js';
readJSON, import { getCachedOrExecute } from '../../tools/utils.js';
readComplexityReport
} from '../../../../scripts/modules/utils.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode disableSilentMode
@@ -23,7 +21,7 @@ import {
*/ */
export async function nextTaskDirect(args, log) { export async function nextTaskDirect(args, log) {
// Destructure expected args // Destructure expected args
const { tasksJsonPath, reportPath } = args; const { tasksJsonPath } = args;
if (!tasksJsonPath) { if (!tasksJsonPath) {
log.error('nextTaskDirect called without tasksJsonPath'); log.error('nextTaskDirect called without tasksJsonPath');
@@ -37,6 +35,9 @@ export async function nextTaskDirect(args, log) {
}; };
} }
// Generate cache key using the provided task path
const cacheKey = `nextTask:${tasksJsonPath}`;
// Define the action function to be executed on cache miss // Define the action function to be executed on cache miss
const coreNextTaskAction = async () => { const coreNextTaskAction = async () => {
try { try {
@@ -58,11 +59,8 @@ export async function nextTaskDirect(args, log) {
}; };
} }
// Read the complexity report
const complexityReport = readComplexityReport(reportPath);
// Find the next task // Find the next task
const nextTask = findNextTask(data.tasks, complexityReport); const nextTask = findNextTask(data.tasks);
if (!nextTask) { if (!nextTask) {
log.info( log.info(
@@ -73,34 +71,24 @@ export async function nextTaskDirect(args, log) {
data: { data: {
message: message:
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies', 'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
nextTask: null nextTask: null,
allTasks: data.tasks
} }
}; };
} }
// Check if it's a subtask
const isSubtask =
typeof nextTask.id === 'string' && nextTask.id.includes('.');
const taskOrSubtask = isSubtask ? 'subtask' : 'task';
const additionalAdvice = isSubtask
? 'Subtasks can be updated with timestamped details as you implement them. This is useful for tracking progress, marking milestones and insights (of successful or successive falures in attempting to implement the subtask). Research can be used when updating the subtask to collect up-to-date information, and can be helpful to solve a repeating problem the agent is unable to solve. It is a good idea to get-task the parent task to collect the overall context of the task, and to get-task the subtask to collect the specific details of the subtask.'
: 'Tasks can be updated to reflect a change in the direction of the task, or to reformulate the task per your prompt. Research can be used when updating the task to collect up-to-date information. It is best to update subtasks as you work on them, and to update the task for more high-level changes that may affect pending subtasks or the general direction of the task.';
// Restore normal logging // Restore normal logging
disableSilentMode(); disableSilentMode();
// Return the next task data with the full tasks array for reference // Return the next task data with the full tasks array for reference
log.info( log.info(
`Successfully found next task ${nextTask.id}: ${nextTask.title}. Is subtask: ${isSubtask}` `Successfully found next task ${nextTask.id}: ${nextTask.title}`
); );
return { return {
success: true, success: true,
data: { data: {
nextTask, nextTask,
isSubtask, allTasks: data.tasks
nextSteps: `When ready to work on the ${taskOrSubtask}, use set-status to set the status to "in progress" ${additionalAdvice}`
} }
}; };
} catch (error) { } catch (error) {
@@ -120,11 +108,18 @@ export async function nextTaskDirect(args, log) {
// Use the caching utility // Use the caching utility
try { try {
const result = await coreNextTaskAction(); const result = await getCachedOrExecute({
log.info(`nextTaskDirect completed.`); cacheKey,
return result; actionFn: coreNextTaskAction,
log
});
log.info(`nextTaskDirect completed. From cache: ${result.fromCache}`);
return result; // Returns { success, data/error, fromCache }
} catch (error) { } catch (error) {
log.error(`Unexpected error during nextTask: ${error.message}`); // Catch unexpected errors from getCachedOrExecute itself
log.error(
`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`
);
return { return {
success: false, success: false,
error: { error: {

View File

@@ -8,11 +8,9 @@ import fs from 'fs';
import { parsePRD } from '../../../../scripts/modules/task-manager.js'; import { parsePRD } from '../../../../scripts/modules/task-manager.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode, disableSilentMode
isSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js'; import { createLogWrapper } from '../../tools/utils.js';
import { getDefaultNumTasks } from '../../../../scripts/modules/config-manager.js';
/** /**
* Direct function wrapper for parsing PRD documents and generating tasks. * Direct function wrapper for parsing PRD documents and generating tasks.
@@ -23,163 +21,177 @@ import { getDefaultNumTasks } from '../../../../scripts/modules/config-manager.j
* @returns {Promise<Object>} - Result object with success status and data/error information. * @returns {Promise<Object>} - Result object with success status and data/error information.
*/ */
export async function parsePRDDirect(args, log, context = {}) { export async function parsePRDDirect(args, log, context = {}) {
const { session } = context; const { session } = context; // Only extract session
// Extract projectRoot from args
const {
input: inputArg,
output: outputArg,
numTasks: numTasksArg,
force,
append,
projectRoot
} = args;
// Create the standard logger wrapper
const logWrapper = createLogWrapper(log);
// --- Input Validation and Path Resolution ---
if (!projectRoot) {
logWrapper.error('parsePRDDirect requires a projectRoot argument.');
return {
success: false,
error: {
code: 'MISSING_ARGUMENT',
message: 'projectRoot is required.'
}
};
}
if (!inputArg) {
logWrapper.error('parsePRDDirect called without input path');
return {
success: false,
error: { code: 'MISSING_ARGUMENT', message: 'Input path is required' }
};
}
// Resolve input and output paths relative to projectRoot
const inputPath = path.resolve(projectRoot, inputArg);
const outputPath = outputArg
? path.resolve(projectRoot, outputArg)
: path.resolve(projectRoot, 'tasks', 'tasks.json'); // Default output path
// Check if input file exists
if (!fs.existsSync(inputPath)) {
const errorMsg = `Input PRD file not found at resolved path: ${inputPath}`;
logWrapper.error(errorMsg);
return {
success: false,
error: { code: 'FILE_NOT_FOUND', message: errorMsg }
};
}
const outputDir = path.dirname(outputPath);
try {
if (!fs.existsSync(outputDir)) {
logWrapper.info(`Creating output directory: ${outputDir}`);
fs.mkdirSync(outputDir, { recursive: true });
}
} catch (dirError) {
logWrapper.error(
`Failed to create output directory ${outputDir}: ${dirError.message}`
);
// Return an error response immediately if dir creation fails
return {
success: false,
error: {
code: 'DIRECTORY_CREATION_ERROR',
message: `Failed to create output directory: ${dirError.message}`
}
};
}
let numTasks = getDefaultNumTasks(projectRoot);
if (numTasksArg) {
numTasks =
typeof numTasksArg === 'string' ? parseInt(numTasksArg, 10) : numTasksArg;
if (isNaN(numTasks) || numTasks <= 0) {
// Ensure positive number
numTasks = getDefaultNumTasks(projectRoot); // Fallback to default if parsing fails or invalid
logWrapper.warn(
`Invalid numTasks value: ${numTasksArg}. Using default: ${numTasks}`
);
}
}
if (append) {
logWrapper.info('Append mode enabled.');
if (force) {
logWrapper.warn(
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
);
}
}
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, ProjectRoot: ${projectRoot}`
);
const wasSilent = isSilentMode();
if (!wasSilent) {
enableSilentMode();
}
try { try {
// Call the core parsePRD function log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
const result = await parsePRD(
inputPath,
outputPath,
numTasks,
{
session,
mcpLog: logWrapper,
projectRoot,
force,
append,
commandName: 'parse-prd',
outputType: 'mcp'
},
'json'
);
// Adjust check for the new return structure // Validate required parameters
if (result && result.success) { if (!args.projectRoot) {
const successMsg = `Successfully parsed PRD and generated tasks in ${result.tasksPath}`; const errorMessage = 'Project root is required for parsePRDDirect';
logWrapper.success(successMsg); log.error(errorMessage);
return { return {
success: true, success: false,
data: { error: { code: 'MISSING_PROJECT_ROOT', message: errorMessage },
message: successMsg, fromCache: false
outputPath: result.tasksPath,
telemetryData: result.telemetryData
}
}; };
} else { }
// Handle case where core function didn't return expected success structure if (!args.input) {
logWrapper.error( const errorMessage = 'Input file path is required for parsePRDDirect';
'Core parsePRD function did not return a successful structure.' log.error(errorMessage);
); return {
success: false,
error: { code: 'MISSING_INPUT_PATH', message: errorMessage },
fromCache: false
};
}
if (!args.output) {
const errorMessage = 'Output file path is required for parsePRDDirect';
log.error(errorMessage);
return {
success: false,
error: { code: 'MISSING_OUTPUT_PATH', message: errorMessage },
fromCache: false
};
}
// Resolve input path (expecting absolute path or path relative to project root)
const projectRoot = args.projectRoot;
const inputPath = path.isAbsolute(args.input)
? args.input
: path.resolve(projectRoot, args.input);
// Verify input file exists
if (!fs.existsSync(inputPath)) {
const errorMessage = `Input file not found: ${inputPath}`;
log.error(errorMessage);
return { return {
success: false, success: false,
error: { error: {
code: 'CORE_FUNCTION_ERROR', code: 'INPUT_FILE_NOT_FOUND',
message: message: errorMessage,
result?.message || details: `Checked path: ${inputPath}\nProject root: ${projectRoot}\nInput argument: ${args.input}`
'Core function failed to parse PRD or returned unexpected result.' },
} fromCache: false
}; };
} }
// Resolve output path (expecting absolute path or path relative to project root)
const outputPath = path.isAbsolute(args.output)
? args.output
: path.resolve(projectRoot, args.output);
// Ensure output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
log.info(`Creating output directory: ${outputDir}`);
fs.mkdirSync(outputDir, { recursive: true });
}
// Parse number of tasks - handle both string and number values
let numTasks = 10; // Default
if (args.numTasks) {
numTasks =
typeof args.numTasks === 'string'
? parseInt(args.numTasks, 10)
: args.numTasks;
if (isNaN(numTasks)) {
numTasks = 10; // Fallback to default if parsing fails
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
}
}
// Extract the append flag from args
const append = Boolean(args.append) === true;
// Log key parameters including append flag
log.info(
`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks, append mode: ${append}`
);
// --- Logger Wrapper ---
const mcpLog = createLogWrapper(log);
// Prepare options for the core function
const options = {
mcpLog,
session
};
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
try {
// Make sure the output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
log.info(`Creating output directory: ${outputDir}`);
fs.mkdirSync(outputDir, { recursive: true });
}
// Execute core parsePRD function with AI client
const tasksDataResult = await parsePRD(
inputPath,
outputPath,
numTasks,
{
mcpLog: logWrapper,
session,
append
},
aiClient,
modelConfig
);
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
// to return it to the caller
if (fs.existsSync(outputPath)) {
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
const actionVerb = append ? 'appended' : 'generated';
const message = `Successfully ${actionVerb} ${tasksData.tasks?.length || 0} tasks from PRD`;
if (!tasksDataResult || !tasksDataResult.tasks || !tasksData) {
throw new Error(
'Core parsePRD function did not return valid task data.'
);
}
log.info(message);
return {
success: true,
data: {
message,
taskCount: tasksDataResult.tasks?.length || 0,
outputPath,
appended: append
},
fromCache: false // This operation always modifies state and should never be cached
};
} else {
const errorMessage = `Tasks file was not created at ${outputPath}`;
log.error(errorMessage);
return {
success: false,
error: { code: 'OUTPUT_FILE_NOT_CREATED', message: errorMessage },
fromCache: false
};
}
} finally {
// Always restore normal logging
disableSilentMode();
}
} catch (error) { } catch (error) {
logWrapper.error(`Error executing core parsePRD: ${error.message}`); // Make sure to restore normal logging even if there's an error
disableSilentMode();
log.error(`Error parsing PRD: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'PARSE_PRD_CORE_ERROR', code: error.code || 'PARSE_PRD_ERROR', // Use error code if available
message: error.message || 'Unknown error parsing PRD' message: error.message || 'Unknown error parsing PRD'
} },
fromCache: false
}; };
} finally {
if (!wasSilent && isSilentMode()) {
disableSilentMode();
}
} }
} }

View File

@@ -3,103 +3,151 @@
* Direct function implementation for showing task details * Direct function implementation for showing task details
*/ */
import { findTaskById } from '../../../../scripts/modules/utils.js';
import { readJSON } from '../../../../scripts/modules/utils.js';
import { getCachedOrExecute } from '../../tools/utils.js';
import { import {
findTaskById, enableSilentMode,
readComplexityReport, disableSilentMode
readJSON
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { findTasksJsonPath } from '../utils/path-utils.js';
/** /**
* Direct function wrapper for getting task details. * Direct function wrapper for showing task details with error handling and caching.
* *
* @param {Object} args - Command arguments. * @param {Object} args - Command arguments
* @param {string} args.id - Task ID to show. * @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
* @param {string} [args.file] - Optional path to the tasks file (passed to findTasksJsonPath). * @param {string} args.id - The ID of the task or subtask to show.
* @param {string} args.reportPath - Explicit path to the complexity report file.
* @param {string} [args.status] - Optional status to filter subtasks by. * @param {string} [args.status] - Optional status to filter subtasks by.
* @param {string} args.projectRoot - Absolute path to the project root directory (already normalized by tool). * @param {Object} log - Logger object
* @param {Object} log - Logger object. * @returns {Promise<Object>} - Task details result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
* @param {Object} context - Context object containing session data.
* @returns {Promise<Object>} - Result object with success status and data/error information.
*/ */
export async function showTaskDirect(args, log) { export async function showTaskDirect(args, log) {
// Destructure session from context if needed later, otherwise ignore // Destructure expected args
// const { session } = context; const { tasksJsonPath, id, status } = args;
// Destructure projectRoot and other args. projectRoot is assumed normalized.
const { id, file, reportPath, status, projectRoot } = args;
log.info( if (!tasksJsonPath) {
`Showing task direct function. ID: ${id}, File: ${file}, Status Filter: ${status}, ProjectRoot: ${projectRoot}` log.error('showTaskDirect called without tasksJsonPath');
);
// --- Path Resolution using the passed (already normalized) projectRoot ---
let tasksJsonPath;
try {
// Use the projectRoot passed directly from args
tasksJsonPath = findTasksJsonPath(
{ projectRoot: projectRoot, file: file },
log
);
log.info(`Resolved tasks path: ${tasksJsonPath}`);
} catch (error) {
log.error(`Error finding tasks.json: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'TASKS_FILE_NOT_FOUND', code: 'MISSING_ARGUMENT',
message: `Failed to find tasks.json: ${error.message}` message: 'tasksJsonPath is required'
} },
fromCache: false
}; };
} }
// --- End Path Resolution ---
// --- Rest of the function remains the same, using tasksJsonPath --- // Validate task ID
try { const taskId = id;
const tasksData = readJSON(tasksJsonPath); if (!taskId) {
if (!tasksData || !tasksData.tasks) { log.error('Task ID is required');
return {
success: false,
error: {
code: 'INPUT_VALIDATION_ERROR',
message: 'Task ID is required'
},
fromCache: false
};
}
// Generate cache key using the provided task path, ID, and status filter
const cacheKey = `showTask:${tasksJsonPath}:${taskId}:${status || 'all'}`;
// Define the action function to be executed on cache miss
const coreShowTaskAction = async () => {
try {
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
log.info(
`Retrieving task details for ID: ${taskId} from ${tasksJsonPath}${status ? ` (filtering by status: ${status})` : ''}`
);
// Read tasks data using the provided path
const data = readJSON(tasksJsonPath);
if (!data || !data.tasks) {
disableSilentMode(); // Disable before returning
return {
success: false,
error: {
code: 'INVALID_TASKS_FILE',
message: `No valid tasks found in ${tasksJsonPath}`
}
};
}
// Find the specific task, passing the status filter
const { task, originalSubtaskCount } = findTaskById(
data.tasks,
taskId,
status
);
if (!task) {
disableSilentMode(); // Disable before returning
return {
success: false,
error: {
code: 'TASK_NOT_FOUND',
message: `Task with ID ${taskId} not found${status ? ` or no subtasks match status '${status}'` : ''}`
}
};
}
// Restore normal logging
disableSilentMode();
// Return the task data, the original subtask count (if applicable),
// and the full tasks array for reference (needed for formatDependenciesWithStatus function in UI)
log.info(
`Successfully found task ${taskId}${status ? ` (with status filter: ${status})` : ''}`
);
return { return {
success: false, success: true,
error: { code: 'INVALID_TASKS_DATA', message: 'Invalid tasks data' } data: {
task,
originalSubtaskCount,
allTasks: data.tasks
}
}; };
} } catch (error) {
// Make sure to restore normal logging even if there's an error
disableSilentMode();
const complexityReport = readComplexityReport(reportPath); log.error(`Error showing task: ${error.message}`);
const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks,
id,
complexityReport,
status
);
if (!task) {
return { return {
success: false, success: false,
error: { error: {
code: 'TASK_NOT_FOUND', code: 'CORE_FUNCTION_ERROR',
message: `Task or subtask with ID ${id} not found` message: error.message || 'Failed to show task details'
} }
}; };
} }
};
log.info(`Successfully retrieved task ${id}.`); // Use the caching utility
try {
const returnData = { ...task }; const result = await getCachedOrExecute({
if (originalSubtaskCount !== null) { cacheKey,
returnData._originalSubtaskCount = originalSubtaskCount; actionFn: coreShowTaskAction,
returnData._subtaskFilter = status; log
} });
log.info(`showTaskDirect completed. From cache: ${result.fromCache}`);
return { success: true, data: returnData }; return result; // Returns { success, data/error, fromCache }
} catch (error) { } catch (error) {
log.error(`Error showing task ${id}: ${error.message}`); // Catch unexpected errors from getCachedOrExecute itself
disableSilentMode();
log.error(
`Unexpected error during getCachedOrExecute for showTask: ${error.message}`
);
return { return {
success: false, success: false,
error: { error: {
code: 'TASK_OPERATION_ERROR', code: 'UNEXPECTED_ERROR',
message: error.message message: error.message
} },
fromCache: false
}; };
} }
} }

View File

@@ -6,40 +6,29 @@
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js'; import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode, disableSilentMode
isSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js'; import { createLogWrapper } from '../../tools/utils.js';
/** /**
* Direct function wrapper for updateSubtaskById with error handling. * Direct function wrapper for updateSubtaskById with error handling.
* *
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot. * @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
* @param {string} args.id - Subtask ID in format "parent.sub".
* @param {string} args.prompt - Information to append to the subtask.
* @param {boolean} [args.research] - Whether to use research role.
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object. * @param {Object} log - Logger object.
* @param {Object} context - Context object containing session data. * @param {Object} context - Context object containing session data.
* @returns {Promise<Object>} - Result object with success status and data/error information. * @returns {Promise<Object>} - Result object with success status and data/error information.
*/ */
export async function updateSubtaskByIdDirect(args, log, context = {}) { export async function updateSubtaskByIdDirect(args, log, context = {}) {
const { session } = context; const { session } = context; // Only extract session, not reportProgress
// Destructure expected args, including projectRoot const { tasksJsonPath, id, prompt, research } = args;
const { tasksJsonPath, id, prompt, research, projectRoot } = args;
const logWrapper = createLogWrapper(log);
try { try {
logWrapper.info( log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
`Updating subtask by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
);
// Check if tasksJsonPath was provided // Check if tasksJsonPath was provided
if (!tasksJsonPath) { if (!tasksJsonPath) {
const errorMessage = 'tasksJsonPath is required but was not provided.'; const errorMessage = 'tasksJsonPath is required but was not provided.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'MISSING_ARGUMENT', message: errorMessage }, error: { code: 'MISSING_ARGUMENT', message: errorMessage },
@@ -47,22 +36,22 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
}; };
} }
// Basic validation for ID format (e.g., '5.2') // Check required parameters (id and prompt)
if (!id || typeof id !== 'string' || !id.includes('.')) { if (!id) {
const errorMessage = const errorMessage =
'Invalid subtask ID format. Must be in format "parentId.subtaskId" (e.g., "5.2").'; 'No subtask ID specified. Please provide a subtask ID to update.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'INVALID_SUBTASK_ID', message: errorMessage }, error: { code: 'MISSING_SUBTASK_ID', message: errorMessage },
fromCache: false fromCache: false
}; };
} }
if (!prompt) { if (!prompt) {
const errorMessage = const errorMessage =
'No prompt specified. Please provide the information to append.'; 'No prompt specified. Please provide a prompt with information to add to the subtask.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'MISSING_PROMPT', message: errorMessage }, error: { code: 'MISSING_PROMPT', message: errorMessage },
@@ -95,85 +84,78 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
// Use the provided path // Use the provided path
const tasksPath = tasksJsonPath; const tasksPath = tasksJsonPath;
// Get research flag
const useResearch = research === true; const useResearch = research === true;
log.info( log.info(
`Updating subtask with ID ${subtaskIdStr} with prompt "${prompt}" and research: ${useResearch}` `Updating subtask with ID ${subtaskIdStr} with prompt "${prompt}" and research: ${useResearch}`
); );
const wasSilent = isSilentMode();
if (!wasSilent) {
enableSilentMode();
}
try { try {
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
// Create the logger wrapper using the utility function
const mcpLog = createLogWrapper(log);
// Execute core updateSubtaskById function // Execute core updateSubtaskById function
const coreResult = await updateSubtaskById( // Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
const updatedSubtask = await updateSubtaskById(
tasksPath, tasksPath,
subtaskIdStr, subtaskIdStr,
prompt, prompt,
useResearch, useResearch,
{ {
mcpLog: logWrapper,
session, session,
projectRoot, mcpLog
commandName: 'update-subtask', }
outputType: 'mcp'
},
'json'
); );
if (!coreResult || coreResult.updatedSubtask === null) { // Restore normal logging
const message = `Subtask ${id} or its parent task not found.`; disableSilentMode();
logWrapper.error(message);
// Handle the case where the subtask couldn't be updated (e.g., already marked as done)
if (!updatedSubtask) {
return { return {
success: false, success: false,
error: { code: 'SUBTASK_NOT_FOUND', message: message }, error: {
code: 'SUBTASK_UPDATE_FAILED',
message:
'Failed to update subtask. It may be marked as completed, or another error occurred.'
},
fromCache: false fromCache: false
}; };
} }
// Subtask updated successfully // Return the updated subtask information
const successMessage = `Successfully updated subtask with ID ${subtaskIdStr}`;
logWrapper.success(successMessage);
return { return {
success: true, success: true,
data: { data: {
message: `Successfully updated subtask with ID ${subtaskIdStr}`, message: `Successfully updated subtask with ID ${subtaskIdStr}`,
subtaskId: subtaskIdStr, subtaskId: subtaskIdStr,
parentId: subtaskIdStr.split('.')[0], parentId: subtaskIdStr.split('.')[0],
subtask: coreResult.updatedSubtask, subtask: updatedSubtask,
tasksPath, tasksPath,
useResearch, useResearch
telemetryData: coreResult.telemetryData
}, },
fromCache: false fromCache: false // This operation always modifies state and should never be cached
}; };
} catch (error) { } catch (error) {
logWrapper.error(`Error updating subtask by ID: ${error.message}`); // Make sure to restore normal logging even if there's an error
return { disableSilentMode();
success: false, throw error; // Rethrow to be caught by outer catch block
error: {
code: 'UPDATE_SUBTASK_CORE_ERROR',
message: error.message || 'Unknown error updating subtask'
},
fromCache: false
};
} finally {
if (!wasSilent && isSilentMode()) {
disableSilentMode();
}
} }
} catch (error) { } catch (error) {
logWrapper.error( // Ensure silent mode is disabled
`Setup error in updateSubtaskByIdDirect: ${error.message}` disableSilentMode();
);
if (isSilentMode()) disableSilentMode(); log.error(`Error updating subtask by ID: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'DIRECT_FUNCTION_SETUP_ERROR', code: 'UPDATE_SUBTASK_ERROR',
message: error.message || 'Unknown setup error' message: error.message || 'Unknown error updating subtask'
}, },
fromCache: false fromCache: false
}; };

View File

@@ -6,40 +6,30 @@
import { updateTaskById } from '../../../../scripts/modules/task-manager.js'; import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode, disableSilentMode
isSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js'; import { createLogWrapper } from '../../tools/utils.js';
/** /**
* Direct function wrapper for updateTaskById with error handling. * Direct function wrapper for updateTaskById with error handling.
* *
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot. * @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
* @param {string} args.id - Task ID (or subtask ID like "1.2").
* @param {string} args.prompt - New information/context prompt.
* @param {boolean} [args.research] - Whether to use research role.
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object. * @param {Object} log - Logger object.
* @param {Object} context - Context object containing session data. * @param {Object} context - Context object containing session data.
* @returns {Promise<Object>} - Result object with success status and data/error information. * @returns {Promise<Object>} - Result object with success status and data/error information.
*/ */
export async function updateTaskByIdDirect(args, log, context = {}) { export async function updateTaskByIdDirect(args, log, context = {}) {
const { session } = context; const { session } = context; // Only extract session, not reportProgress
// Destructure expected args, including projectRoot // Destructure expected args, including the resolved tasksJsonPath
const { tasksJsonPath, id, prompt, research, projectRoot } = args; const { tasksJsonPath, id, prompt, research } = args;
const logWrapper = createLogWrapper(log);
try { try {
logWrapper.info( log.info(`Updating task with args: ${JSON.stringify(args)}`);
`Updating task by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
);
// Check if tasksJsonPath was provided // Check if tasksJsonPath was provided
if (!tasksJsonPath) { if (!tasksJsonPath) {
const errorMessage = 'tasksJsonPath is required but was not provided.'; const errorMessage = 'tasksJsonPath is required but was not provided.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'MISSING_ARGUMENT', message: errorMessage }, error: { code: 'MISSING_ARGUMENT', message: errorMessage },
@@ -51,7 +41,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
if (!id) { if (!id) {
const errorMessage = const errorMessage =
'No task ID specified. Please provide a task ID to update.'; 'No task ID specified. Please provide a task ID to update.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'MISSING_TASK_ID', message: errorMessage }, error: { code: 'MISSING_TASK_ID', message: errorMessage },
@@ -62,7 +52,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
if (!prompt) { if (!prompt) {
const errorMessage = const errorMessage =
'No prompt specified. Please provide a prompt with new information for the task update.'; 'No prompt specified. Please provide a prompt with new information for the task update.';
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'MISSING_PROMPT', message: errorMessage }, error: { code: 'MISSING_PROMPT', message: errorMessage },
@@ -81,7 +71,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
taskId = parseInt(id, 10); taskId = parseInt(id, 10);
if (isNaN(taskId)) { if (isNaN(taskId)) {
const errorMessage = `Invalid task ID: ${id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`; const errorMessage = `Invalid task ID: ${id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`;
logWrapper.error(errorMessage); log.error(errorMessage);
return { return {
success: false, success: false,
error: { code: 'INVALID_TASK_ID', message: errorMessage }, error: { code: 'INVALID_TASK_ID', message: errorMessage },
@@ -99,88 +89,66 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
// Get research flag // Get research flag
const useResearch = research === true; const useResearch = research === true;
logWrapper.info( log.info(
`Updating task with ID ${taskId} with prompt "${prompt}" and research: ${useResearch}` `Updating task with ID ${taskId} with prompt "${prompt}" and research: ${useResearch}`
); );
const wasSilent = isSilentMode();
if (!wasSilent) {
enableSilentMode();
}
try { try {
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
// Create the logger wrapper using the utility function
const mcpLog = createLogWrapper(log);
// Execute core updateTaskById function with proper parameters // Execute core updateTaskById function with proper parameters
const coreResult = await updateTaskById( await updateTaskById(
tasksPath, tasksPath,
taskId, taskId,
prompt, prompt,
useResearch, useResearch,
{ {
mcpLog: logWrapper, mcpLog, // Pass the wrapped logger
session, session
projectRoot,
commandName: 'update-task',
outputType: 'mcp'
}, },
'json' 'json'
); );
// Check if the core function returned null or an object without success // Since updateTaskById doesn't return a value but modifies the tasks file,
if (!coreResult || coreResult.updatedTask === null) { // we'll return a success message
// Core function logs the reason, just return success with info
const message = `Task ${taskId} was not updated (likely already completed).`;
logWrapper.info(message);
return {
success: true,
data: {
message: message,
taskId: taskId,
updated: false,
telemetryData: coreResult?.telemetryData
},
fromCache: false
};
}
// Task was updated successfully
const successMessage = `Successfully updated task with ID ${taskId} based on the prompt`;
logWrapper.success(successMessage);
return { return {
success: true, success: true,
data: { data: {
message: successMessage, message: `Successfully updated task with ID ${taskId} based on the prompt`,
taskId: taskId, taskId,
tasksPath: tasksPath, tasksPath: tasksPath, // Return the used path
useResearch: useResearch, useResearch
updated: true,
updatedTask: coreResult.updatedTask,
telemetryData: coreResult.telemetryData
}, },
fromCache: false fromCache: false // This operation always modifies state and should never be cached
}; };
} catch (error) { } catch (error) {
logWrapper.error(`Error updating task by ID: ${error.message}`); log.error(`Error updating task by ID: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'UPDATE_TASK_CORE_ERROR', code: 'UPDATE_TASK_ERROR',
message: error.message || 'Unknown error updating task' message: error.message || 'Unknown error updating task'
}, },
fromCache: false fromCache: false
}; };
} finally { } finally {
if (!wasSilent && isSilentMode()) { // Make sure to restore normal logging even if there's an error
disableSilentMode(); disableSilentMode();
}
} }
} catch (error) { } catch (error) {
logWrapper.error(`Setup error in updateTaskByIdDirect: ${error.message}`); // Ensure silent mode is disabled
if (isSilentMode()) disableSilentMode(); disableSilentMode();
log.error(`Error updating task by ID: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'DIRECT_FUNCTION_SETUP_ERROR', code: 'UPDATE_TASK_ERROR',
message: error.message || 'Unknown setup error' message: error.message || 'Unknown error updating task'
}, },
fromCache: false fromCache: false
}; };

View File

@@ -1,126 +1,128 @@
/** /**
* update-tasks.js * update-tasks.js
* Direct function implementation for updating tasks based on new context * Direct function implementation for updating tasks based on new context/prompt
*/ */
import path from 'path';
import { updateTasks } from '../../../../scripts/modules/task-manager.js'; import { updateTasks } from '../../../../scripts/modules/task-manager.js';
import { createLogWrapper } from '../../tools/utils.js';
import { import {
enableSilentMode, enableSilentMode,
disableSilentMode disableSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js';
/** /**
* Direct function wrapper for updating tasks based on new context. * Direct function wrapper for updating tasks based on new context/prompt.
* *
* @param {Object} args - Command arguments containing projectRoot, from, prompt, research options. * @param {Object} args - Command arguments containing from, prompt, research and tasksJsonPath.
* @param {Object} log - Logger object. * @param {Object} log - Logger object.
* @param {Object} context - Context object containing session data. * @param {Object} context - Context object containing session data.
* @returns {Promise<Object>} - Result object with success status and data/error information. * @returns {Promise<Object>} - Result object with success status and data/error information.
*/ */
export async function updateTasksDirect(args, log, context = {}) { export async function updateTasksDirect(args, log, context = {}) {
const { session } = context; const { session } = context; // Extract session
const { from, prompt, research, file: fileArg, projectRoot } = args; const { tasksJsonPath, from, prompt, research } = args;
// Create the standard logger wrapper // Create the standard logger wrapper
const logWrapper = createLogWrapper(log); const logWrapper = {
info: (message, ...args) => log.info(message, ...args),
warn: (message, ...args) => log.warn(message, ...args),
error: (message, ...args) => log.error(message, ...args),
debug: (message, ...args) => log.debug && log.debug(message, ...args),
success: (message, ...args) => log.info(message, ...args)
};
// --- Input Validation --- // --- Input Validation (Keep existing checks) ---
if (!projectRoot) { if (!tasksJsonPath) {
logWrapper.error('updateTasksDirect requires a projectRoot argument.'); log.error('updateTasksDirect called without tasksJsonPath');
return { return {
success: false, success: false,
error: { error: { code: 'MISSING_ARGUMENT', message: 'tasksJsonPath is required' },
code: 'MISSING_ARGUMENT', fromCache: false
message: 'projectRoot is required.' };
} }
if (args.id !== undefined && from === undefined) {
// Keep 'from' vs 'id' check
const errorMessage =
"Use 'from' parameter, not 'id', or use 'update_task' tool.";
log.error(errorMessage);
return {
success: false,
error: { code: 'PARAMETER_MISMATCH', message: errorMessage },
fromCache: false
}; };
} }
if (!from) { if (!from) {
logWrapper.error('updateTasksDirect called without from ID'); log.error('Missing from ID.');
return { return {
success: false, success: false,
error: { error: { code: 'MISSING_FROM_ID', message: 'No from ID specified.' },
code: 'MISSING_ARGUMENT', fromCache: false
message: 'Starting task ID (from) is required'
}
}; };
} }
if (!prompt) { if (!prompt) {
logWrapper.error('updateTasksDirect called without prompt'); log.error('Missing prompt.');
return {
success: false,
error: { code: 'MISSING_PROMPT', message: 'No prompt specified.' },
fromCache: false
};
}
let fromId;
try {
fromId = parseInt(from, 10);
if (isNaN(fromId) || fromId <= 0) throw new Error();
} catch {
log.error(`Invalid from ID: ${from}`);
return { return {
success: false, success: false,
error: { error: {
code: 'MISSING_ARGUMENT', code: 'INVALID_FROM_ID',
message: 'Update prompt is required' message: `Invalid from ID: ${from}. Must be a positive integer.`
} },
fromCache: false
}; };
} }
const useResearch = research === true;
// --- End Input Validation ---
// Resolve tasks file path log.info(`Updating tasks from ID ${fromId}. Research: ${useResearch}`);
const tasksFile = fileArg
? path.resolve(projectRoot, fileArg)
: path.resolve(projectRoot, 'tasks', 'tasks.json');
logWrapper.info(
`Updating tasks via direct function. From: ${from}, Research: ${research}, File: ${tasksFile}, ProjectRoot: ${projectRoot}`
);
enableSilentMode(); // Enable silent mode enableSilentMode(); // Enable silent mode
try { try {
// Call the core updateTasks function // Create logger wrapper using the utility
const result = await updateTasks( const mcpLog = createLogWrapper(log);
tasksFile,
from, // Execute core updateTasks function, passing session context
await updateTasks(
tasksJsonPath,
fromId,
prompt, prompt,
research, useResearch,
{ // Pass context with logger wrapper and session
session, { mcpLog, session },
mcpLog: logWrapper, 'json' // Explicitly request JSON format for MCP
projectRoot
},
'json'
); );
if (result && result.success && Array.isArray(result.updatedTasks)) { // Since updateTasks modifies file and doesn't return data, create success message
logWrapper.success( return {
`Successfully updated ${result.updatedTasks.length} tasks.` success: true,
); data: {
return { message: `Successfully initiated update for tasks from ID ${fromId} based on the prompt.`,
success: true, fromId,
data: { tasksPath: tasksJsonPath,
message: `Successfully updated ${result.updatedTasks.length} tasks.`, useResearch
tasksFile, },
updatedCount: result.updatedTasks.length, fromCache: false // Modifies state
telemetryData: result.telemetryData };
}
};
} else {
// Handle case where core function didn't return expected success structure
logWrapper.error(
'Core updateTasks function did not return a successful structure.'
);
return {
success: false,
error: {
code: 'CORE_FUNCTION_ERROR',
message:
result?.message ||
'Core function failed to update tasks or returned unexpected result.'
}
};
}
} catch (error) { } catch (error) {
logWrapper.error(`Error executing core updateTasks: ${error.message}`); log.error(`Error executing core updateTasks: ${error.message}`);
return { return {
success: false, success: false,
error: { error: {
code: 'UPDATE_TASKS_CORE_ERROR', code: 'UPDATE_TASKS_CORE_ERROR',
message: error.message || 'Unknown error updating tasks' message: error.message || 'Unknown error updating tasks'
} },
fromCache: false
}; };
} finally { } finally {
disableSilentMode(); // Ensure silent mode is disabled disableSilentMode(); // Ensure silent mode is disabled

View File

@@ -28,7 +28,7 @@ import { fixDependenciesDirect } from './direct-functions/fix-dependencies.js';
import { complexityReportDirect } from './direct-functions/complexity-report.js'; import { complexityReportDirect } from './direct-functions/complexity-report.js';
import { addDependencyDirect } from './direct-functions/add-dependency.js'; import { addDependencyDirect } from './direct-functions/add-dependency.js';
import { removeTaskDirect } from './direct-functions/remove-task.js'; import { removeTaskDirect } from './direct-functions/remove-task.js';
import { initializeProjectDirect } from './direct-functions/initialize-project.js'; import { initializeProjectDirect } from './direct-functions/initialize-project-direct.js';
import { modelsDirect } from './direct-functions/models.js'; import { modelsDirect } from './direct-functions/models.js';
// Re-export utility functions // Re-export utility functions

View File

@@ -339,49 +339,6 @@ export function findPRDDocumentPath(projectRoot, explicitPath, log) {
return null; return null;
} }
export function findComplexityReportPath(projectRoot, explicitPath, log) {
// If explicit path is provided, check if it exists
if (explicitPath) {
const fullPath = path.isAbsolute(explicitPath)
? explicitPath
: path.resolve(projectRoot, explicitPath);
if (fs.existsSync(fullPath)) {
log.info(`Using provided PRD document path: ${fullPath}`);
return fullPath;
} else {
log.warn(
`Provided PRD document path not found: ${fullPath}, will search for alternatives`
);
}
}
// Common locations and file patterns for PRD documents
const commonLocations = [
'', // Project root
'scripts/'
];
const commonFileNames = [
'complexity-report.json',
'task-complexity-report.json'
];
// Check all possible combinations
for (const location of commonLocations) {
for (const fileName of commonFileNames) {
const potentialPath = path.join(projectRoot, location, fileName);
if (fs.existsSync(potentialPath)) {
log.info(`Found PRD document at: ${potentialPath}`);
return potentialPath;
}
}
}
log.warn(`No PRD document found in common locations within ${projectRoot}`);
return null;
}
/** /**
* Resolves the tasks output directory path * Resolves the tasks output directory path
* @param {string} projectRoot - The project root directory * @param {string} projectRoot - The project root directory

View File

@@ -7,8 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
getProjectRootFromSession, getProjectRootFromSession
withNormalizedProjectRoot
} from './utils.js'; } from './utils.js';
import { addDependencyDirect } from '../core/task-master-core.js'; import { addDependencyDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -36,16 +35,28 @@ export function registerAddDependencyTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info( log.info(
`Adding dependency for task ${args.id} to depend on ${args.dependsOn}` `Adding dependency for task ${args.id} to depend on ${args.dependsOn}`
); );
// Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -81,6 +92,6 @@ export function registerAddDependencyTool(server) {
log.error(`Error in addDependency tool: ${error.message}`); log.error(`Error in addDependency tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { addSubtaskDirect } from '../core/task-master-core.js'; import { addSubtaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -60,15 +60,24 @@ export function registerAddSubtaskTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Adding subtask with args: ${JSON.stringify(args)}`); log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -104,6 +113,6 @@ export function registerAddSubtaskTool(server) {
log.error(`Error in addSubtask tool: ${error.message}`); log.error(`Error in addSubtask tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -6,8 +6,8 @@
import { z } from 'zod'; import { z } from 'zod';
import { import {
createErrorResponse, createErrorResponse,
handleApiResult, withProjectContext,
withNormalizedProjectRoot handleApiResult
} from './utils.js'; } from './utils.js';
import { addTaskDirect } from '../core/task-master-core.js'; import { addTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -63,11 +63,13 @@ export function registerAddTaskTool(server) {
.optional() .optional()
.describe('Whether to use research capabilities for task creation') .describe('Whether to use research capabilities for task creation')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: withProjectContext(async (args, { log, session }) => {
try { try {
log.info(`Starting add-task with args: ${JSON.stringify(args)}`); log.info(`Starting add-task with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Note: projectRoot is now guaranteed to be normalized by withProjectContext
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
@@ -81,10 +83,12 @@ export function registerAddTaskTool(server) {
); );
} }
// Call the direct functionP // Call the direct function
const result = await addTaskDirect( const result = await addTaskDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
prompt: args.prompt, prompt: args.prompt,
title: args.title, title: args.title,
description: args.description, description: args.description,
@@ -92,13 +96,13 @@ export function registerAddTaskTool(server) {
testStrategy: args.testStrategy, testStrategy: args.testStrategy,
dependencies: args.dependencies, dependencies: args.dependencies,
priority: args.priority, priority: args.priority,
research: args.research, research: args.research
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
); );
// Return the result
return handleApiResult(result, log); return handleApiResult(result, log);
} catch (error) { } catch (error) {
log.error(`Error in add-task tool: ${error.message}`); log.error(`Error in add-task tool: ${error.message}`);

View File

@@ -4,128 +4,121 @@
*/ */
import { z } from 'zod'; import { z } from 'zod';
import path from 'path'; import { handleApiResult, createErrorResponse } from './utils.js';
import fs from 'fs'; // Import fs for directory check/creation import { analyzeTaskComplexityDirect } from '../core/direct-functions/analyze-task-complexity.js';
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { analyzeTaskComplexityDirect } from '../core/task-master-core.js'; // Assuming core functions are exported via task-master-core.js
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
import path from 'path';
import fs from 'fs';
/** /**
* Register the analyze_project_complexity tool * Register the analyze tool with the MCP server
* @param {Object} server - FastMCP server instance * @param {Object} server - FastMCP server instance
*/ */
export function registerAnalyzeProjectComplexityTool(server) { export function registerAnalyzeTool(server) {
server.addTool({ server.addTool({
name: 'analyze_project_complexity', name: 'analyze_project_complexity',
description: description:
'Analyze task complexity and generate expansion recommendations.', 'Analyze task complexity and generate expansion recommendations',
parameters: z.object({ parameters: z.object({
threshold: z.coerce // Use coerce for number conversion from string if needed
.number()
.int()
.min(1)
.max(10)
.optional()
.default(5) // Default threshold
.describe('Complexity score threshold (1-10) to recommend expansion.'),
research: z
.boolean()
.optional()
.default(false)
.describe('Use Perplexity AI for research-backed analysis.'),
output: z output: z
.string() .string()
.optional() .optional()
.describe( .describe(
'Output file path relative to project root (default: scripts/task-complexity-report.json).' 'Output file path relative to project root (default: scripts/task-complexity-report.json)'
),
threshold: z.coerce
.number()
.min(1)
.max(10)
.optional()
.describe(
'Minimum complexity score to recommend expansion (1-10) (default: 5)'
), ),
file: z file: z
.string() .string()
.optional() .optional()
.describe( .describe(
'Path to the tasks file relative to project root (default: tasks/tasks.json).' 'Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)'
), ),
research: z
.boolean()
.optional()
.default(false)
.describe('Use research role for complexity analysis'),
projectRoot: z projectRoot: z
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
const toolName = 'analyze_project_complexity'; // Define tool name for logging
try { try {
log.info( log.info(
`Executing ${toolName} tool with args: ${JSON.stringify(args)}` `Executing analyze_project_complexity tool with args: ${JSON.stringify(args)}`
); );
const rootFolder = args.projectRoot;
if (!rootFolder) {
return createErrorResponse('projectRoot is required.');
}
if (!path.isAbsolute(rootFolder)) {
return createErrorResponse('projectRoot must be an absolute path.');
}
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
} catch (error) { } catch (error) {
log.error(`${toolName}: Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
return createErrorResponse( return createErrorResponse(
`Failed to find tasks.json within project root '${args.projectRoot}': ${error.message}` `Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
); );
} }
const outputPath = args.output const outputPath = args.output
? path.resolve(args.projectRoot, args.output) ? path.resolve(rootFolder, args.output)
: path.resolve( : path.resolve(rootFolder, 'scripts', 'task-complexity-report.json');
args.projectRoot,
'scripts',
'task-complexity-report.json'
);
log.info(`${toolName}: Report output path: ${outputPath}`);
// Ensure output directory exists
const outputDir = path.dirname(outputPath); const outputDir = path.dirname(outputPath);
try { try {
if (!fs.existsSync(outputDir)) { if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true }); fs.mkdirSync(outputDir, { recursive: true });
log.info(`${toolName}: Created output directory: ${outputDir}`); log.info(`Created output directory: ${outputDir}`);
} }
} catch (dirError) { } catch (dirError) {
log.error( log.error(
`${toolName}: Failed to create output directory ${outputDir}: ${dirError.message}` `Failed to create output directory ${outputDir}: ${dirError.message}`
); );
return createErrorResponse( return createErrorResponse(
`Failed to create output directory: ${dirError.message}` `Failed to create output directory: ${dirError.message}`
); );
} }
// 3. Call Direct Function - Pass projectRoot in first arg object
const result = await analyzeTaskComplexityDirect( const result = await analyzeTaskComplexityDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
outputPath: outputPath, outputPath: outputPath,
threshold: args.threshold, threshold: args.threshold,
research: args.research, research: args.research
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
); );
// 4. Handle Result if (result.success) {
log.info( log.info(`Tool analyze_project_complexity finished successfully.`);
`${toolName}: Direct function result: success=${result.success}` } else {
); log.error(
`Tool analyze_project_complexity failed: ${result.error?.message || 'Unknown error'}`
);
}
return handleApiResult(result, log, 'Error analyzing task complexity'); return handleApiResult(result, log, 'Error analyzing task complexity');
} catch (error) { } catch (error) {
log.error( log.error(`Critical error in analyze tool execute: ${error.message}`);
`Critical error in ${toolName} tool execute: ${error.message}` return createErrorResponse(`Internal tool error: ${error.message}`);
);
return createErrorResponse(
`Internal tool error (${toolName}): ${error.message}`
);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { clearSubtasksDirect } from '../core/task-master-core.js'; import { clearSubtasksDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -41,15 +41,26 @@ export function registerClearSubtasksTool(server) {
message: "Either 'id' or 'all' parameter must be provided", message: "Either 'id' or 'all' parameter must be provided",
path: ['id', 'all'] path: ['id', 'all']
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`); log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -61,11 +72,14 @@ export function registerClearSubtasksTool(server) {
const result = await clearSubtasksDirect( const result = await clearSubtasksDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
all: args.all all: args.all
}, },
log log
// Remove context object as clearSubtasksDirect likely doesn't need session/reportProgress
); );
if (result.success) { if (result.success) {
@@ -79,6 +93,6 @@ export function registerClearSubtasksTool(server) {
log.error(`Error in clearSubtasks tool: ${error.message}`); log.error(`Error in clearSubtasks tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { complexityReportDirect } from '../core/task-master-core.js'; import { complexityReportDirect } from '../core/task-master-core.js';
import path from 'path'; import path from 'path';
@@ -31,24 +31,34 @@ export function registerComplexityReportTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info( log.info(
`Getting complexity report with args: ${JSON.stringify(args)}` `Getting complexity report with args: ${JSON.stringify(args)}`
); );
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to the complexity report file
// Default to scripts/task-complexity-report.json relative to root
const reportPath = args.file const reportPath = args.file
? path.resolve(args.projectRoot, args.file) ? path.resolve(rootFolder, args.file)
: path.resolve( : path.resolve(rootFolder, 'scripts', 'task-complexity-report.json');
args.projectRoot,
'scripts',
'task-complexity-report.json'
);
const result = await complexityReportDirect( const result = await complexityReportDirect(
{ {
// Pass the explicitly resolved path
reportPath: reportPath reportPath: reportPath
// No other args specific to this tool
}, },
log log
); );
@@ -74,6 +84,6 @@ export function registerComplexityReportTool(server) {
`Failed to retrieve complexity report: ${error.message}` `Failed to retrieve complexity report: ${error.message}`
); );
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { expandAllTasksDirect } from '../core/task-master-core.js'; import { expandAllTasksDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -59,16 +59,25 @@ export function registerExpandAllTool(server) {
'Absolute path to the project root directory (derived from session if possible)' 'Absolute path to the project root directory (derived from session if possible)'
) )
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info( log.info(
`Tool expand_all execution started with args: ${JSON.stringify(args)}` `Tool expand_all execution started with args: ${JSON.stringify(args)}`
); );
const rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder) {
log.error('Could not determine project root from session.');
return createErrorResponse(
'Could not determine project root from session.'
);
}
log.info(`Project root determined: ${rootFolder}`);
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
log.info(`Resolved tasks.json path: ${tasksJsonPath}`); log.info(`Resolved tasks.json path: ${tasksJsonPath}`);
@@ -85,8 +94,7 @@ export function registerExpandAllTool(server) {
num: args.num, num: args.num,
research: args.research, research: args.research,
prompt: args.prompt, prompt: args.prompt,
force: args.force, force: args.force
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
@@ -104,6 +112,6 @@ export function registerExpandAllTool(server) {
`An unexpected error occurred: ${error.message}` `An unexpected error occurred: ${error.message}`
); );
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { expandTaskDirect } from '../core/task-master-core.js'; import { expandTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -47,15 +47,28 @@ export function registerExpandTaskTool(server) {
.default(false) .default(false)
.describe('Force expansion even if subtasks exist') .describe('Force expansion even if subtasks exist')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`); log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
log.info(`Project root resolved to: ${rootFolder}`);
// Resolve the path to tasks.json using the utility
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -65,25 +78,29 @@ export function registerExpandTaskTool(server) {
); );
} }
// Call direct function with only session in the context, not reportProgress
// Use the pattern recommended in the MCP guidelines
const result = await expandTaskDirect( const result = await expandTaskDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
num: args.num, num: args.num,
research: args.research, research: args.research,
prompt: args.prompt, prompt: args.prompt,
force: args.force, force: args.force // Need to add force to parameters
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
); ); // Only pass session, NOT reportProgress
// Return the result
return handleApiResult(result, log, 'Error expanding task'); return handleApiResult(result, log, 'Error expanding task');
} catch (error) { } catch (error) {
log.error(`Error in expand-task tool: ${error.message}`); log.error(`Error in expand task tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { fixDependenciesDirect } from '../core/task-master-core.js'; import { fixDependenciesDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -26,15 +26,24 @@ export function registerFixDependenciesTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Fixing dependencies with args: ${JSON.stringify(args)}`); log.info(`Fixing dependencies with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -62,6 +71,6 @@ export function registerFixDependenciesTool(server) {
log.error(`Error in fixDependencies tool: ${error.message}`); log.error(`Error in fixDependencies tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { generateTaskFilesDirect } from '../core/task-master-core.js'; import { generateTaskFilesDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -32,15 +32,26 @@ export function registerGenerateTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Generating task files with args: ${JSON.stringify(args)}`); log.info(`Generating task files with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -50,14 +61,17 @@ export function registerGenerateTool(server) {
); );
} }
// Determine output directory: use explicit arg or default to tasks.json directory
const outputDir = args.output const outputDir = args.output
? path.resolve(args.projectRoot, args.output) ? path.resolve(rootFolder, args.output) // Resolve relative to root if needed
: path.dirname(tasksJsonPath); : path.dirname(tasksJsonPath);
const result = await generateTaskFilesDirect( const result = await generateTaskFilesDirect(
{ {
// Pass the explicitly resolved paths
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
outputDir: outputDir outputDir: outputDir
// No other args specific to this tool
}, },
log log
); );
@@ -75,6 +89,6 @@ export function registerGenerateTool(server) {
log.error(`Error in generate tool: ${error.message}`); log.error(`Error in generate tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,13 +7,10 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { showTaskDirect } from '../core/task-master-core.js'; import { showTaskDirect } from '../core/task-master-core.js';
import { import { findTasksJsonPath } from '../core/utils/path-utils.js';
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/** /**
* Custom processor function that removes allTasks from the response * Custom processor function that removes allTasks from the response
@@ -24,10 +21,8 @@ function processTaskResponse(data) {
if (!data) return data; if (!data) return data;
// If we have the expected structure with task and allTasks // If we have the expected structure with task and allTasks
if (typeof data === 'object' && data !== null && data.id && data.title) { if (data.task) {
// If the data itself looks like the task object, return it // Return only the task object, removing the allTasks array
return data;
} else if (data.task) {
return data.task; return data.task;
} }
@@ -49,39 +44,44 @@ export function registerShowTaskTool(server) {
.string() .string()
.optional() .optional()
.describe("Filter subtasks by status (e.g., 'pending', 'done')"), .describe("Filter subtasks by status (e.g., 'pending', 'done')"),
file: z file: z.string().optional().describe('Absolute path to the tasks file'),
.string()
.optional()
.describe('Path to the tasks file relative to project root'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z projectRoot: z
.string() .string()
.optional() .describe('The directory of the project. Must be an absolute path.')
.describe(
'Absolute path to the project root directory (Optional, usually from session)'
)
}), }),
execute: withNormalizedProjectRoot(async (args, { log }) => { execute: async (args, { log, session }) => {
const { id, file, status, projectRoot } = args; // Log the session right at the start of execute
log.info(
`Session object received in execute: ${JSON.stringify(session)}`
); // Use JSON.stringify for better visibility
try { try {
log.info( log.info(
`Getting task details for ID: ${id}${status ? ` (filtering subtasks by status: ${status})` : ''} in root: ${projectRoot}` `Getting task details for ID: ${args.id}${args.status ? ` (filtering subtasks by status: ${args.status})` : ''}`
); );
// Resolve the path to tasks.json using the NORMALIZED projectRoot from args // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: projectRoot, file: file }, { projectRoot: rootFolder, file: args.file },
log log
); );
log.info(`Resolved tasks path: ${tasksJsonPath}`);
} catch (error) { } catch (error) {
log.error(`Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
return createErrorResponse( return createErrorResponse(
@@ -89,26 +89,13 @@ export function registerShowTaskTool(server) {
); );
} }
// Call the direct function, passing the normalized projectRoot log.info(`Attempting to use tasks file path: ${tasksJsonPath}`);
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await showTaskDirect( const result = await showTaskDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath, id: args.id,
// Pass other relevant args status: args.status
id: id,
status: status,
projectRoot: projectRoot
}, },
log log
); );
@@ -121,7 +108,7 @@ export function registerShowTaskTool(server) {
log.error(`Failed to get task: ${result.error.message}`); log.error(`Failed to get task: ${result.error.message}`);
} }
// Use our custom processor function // Use our custom processor function to remove allTasks from the response
return handleApiResult( return handleApiResult(
result, result,
log, log,
@@ -129,9 +116,9 @@ export function registerShowTaskTool(server) {
processTaskResponse processTaskResponse
); );
} catch (error) { } catch (error) {
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
return createErrorResponse(`Failed to get task: ${error.message}`); return createErrorResponse(`Failed to get task: ${error.message}`);
} }
}) }
}); });
} }

View File

@@ -7,13 +7,10 @@ import { z } from 'zod';
import { import {
createErrorResponse, createErrorResponse,
handleApiResult, handleApiResult,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { listTasksDirect } from '../core/task-master-core.js'; import { listTasksDirect } from '../core/task-master-core.js';
import { import { findTasksJsonPath } from '../core/utils/path-utils.js';
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/** /**
* Register the getTasks tool with the MCP server * Register the getTasks tool with the MCP server
@@ -41,51 +38,45 @@ export function registerListTasksTool(server) {
.describe( .describe(
'Path to the tasks file (relative to project root or absolute)' 'Path to the tasks file (relative to project root or absolute)'
), ),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z projectRoot: z
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Getting tasks with filters: ${JSON.stringify(args)}`); log.info(`Getting tasks with filters: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
log.error(`Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
// Use the error message from findTasksJsonPath for better context
return createErrorResponse( return createErrorResponse(
`Failed to find tasks.json: ${error.message}` `Failed to find tasks.json: ${error.message}`
); );
} }
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await listTasksDirect( const result = await listTasksDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
status: args.status, status: args.status,
withSubtasks: args.withSubtasks, withSubtasks: args.withSubtasks
reportPath: complexityReportPath
}, },
log log
); );
@@ -98,7 +89,7 @@ export function registerListTasksTool(server) {
log.error(`Error getting tasks: ${error.message}`); log.error(`Error getting tasks: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -17,7 +17,7 @@ import { registerExpandTaskTool } from './expand-task.js';
import { registerAddTaskTool } from './add-task.js'; import { registerAddTaskTool } from './add-task.js';
import { registerAddSubtaskTool } from './add-subtask.js'; import { registerAddSubtaskTool } from './add-subtask.js';
import { registerRemoveSubtaskTool } from './remove-subtask.js'; import { registerRemoveSubtaskTool } from './remove-subtask.js';
import { registerAnalyzeProjectComplexityTool } from './analyze.js'; import { registerAnalyzeTool } from './analyze.js';
import { registerClearSubtasksTool } from './clear-subtasks.js'; import { registerClearSubtasksTool } from './clear-subtasks.js';
import { registerExpandAllTool } from './expand-all.js'; import { registerExpandAllTool } from './expand-all.js';
import { registerRemoveDependencyTool } from './remove-dependency.js'; import { registerRemoveDependencyTool } from './remove-dependency.js';
@@ -63,7 +63,7 @@ export function registerTaskMasterTools(server) {
registerClearSubtasksTool(server); registerClearSubtasksTool(server);
// Group 5: Task Analysis & Expansion // Group 5: Task Analysis & Expansion
registerAnalyzeProjectComplexityTool(server); registerAnalyzeTool(server);
registerExpandTaskTool(server); registerExpandTaskTool(server);
registerExpandAllTool(server); registerExpandAllTool(server);

View File

@@ -1,9 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { import { createErrorResponse, handleApiResult } from './utils.js';
createErrorResponse,
handleApiResult,
withNormalizedProjectRoot
} from './utils.js';
import { initializeProjectDirect } from '../core/task-master-core.js'; import { initializeProjectDirect } from '../core/task-master-core.js';
export function registerInitializeProjectTool(server) { export function registerInitializeProjectTool(server) {
@@ -37,10 +33,19 @@ export function registerInitializeProjectTool(server) {
'The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.' 'The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.'
) )
}), }),
execute: withNormalizedProjectRoot(async (args, context) => { execute: async (args, context) => {
const { log } = context; const { log } = context;
const session = context.session; const session = context.session;
log.info(
'>>> Full Context Received by Tool:',
JSON.stringify(context, null, 2)
);
log.info(`Context received in tool function: ${context}`);
log.info(
`Session received in tool function: ${session ? session : 'undefined'}`
);
try { try {
log.info( log.info(
`Executing initialize_project tool with args: ${JSON.stringify(args)}` `Executing initialize_project tool with args: ${JSON.stringify(args)}`
@@ -54,6 +59,6 @@ export function registerInitializeProjectTool(server) {
log.error(errorMessage, error); log.error(errorMessage, error);
return createErrorResponse(errorMessage, { details: error.stack }); return createErrorResponse(errorMessage, { details: error.stack });
} }
}) }
}); });
} }

View File

@@ -5,9 +5,9 @@
import { z } from 'zod'; import { z } from 'zod';
import { import {
getProjectRootFromSession,
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse
withNormalizedProjectRoot
} from './utils.js'; } from './utils.js';
import { modelsDirect } from '../core/task-master-core.js'; import { modelsDirect } from '../core/task-master-core.js';
@@ -42,9 +42,7 @@ export function registerModelsTool(server) {
listAvailableModels: z listAvailableModels: z
.boolean() .boolean()
.optional() .optional()
.describe( .describe('List all available models not currently in use.'),
'List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).'
),
projectRoot: z projectRoot: z
.string() .string()
.optional() .optional()
@@ -58,22 +56,34 @@ export function registerModelsTool(server) {
.optional() .optional()
.describe('Indicates the set model ID is a custom Ollama model.') .describe('Indicates the set model ID is a custom Ollama model.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Starting models tool with args: ${JSON.stringify(args)}`); log.info(`Starting models tool with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Call the direct function
const result = await modelsDirect( const result = await modelsDirect(
{ ...args, projectRoot: args.projectRoot }, { ...args, projectRoot: rootFolder },
log, log,
{ session } { session }
); );
// Handle and return the result
return handleApiResult(result, log); return handleApiResult(result, log);
} catch (error) { } catch (error) {
log.error(`Error in models tool: ${error.message}`); log.error(`Error in models tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,13 +7,10 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { nextTaskDirect } from '../core/task-master-core.js'; import { nextTaskDirect } from '../core/task-master-core.js';
import { import { findTasksJsonPath } from '../core/utils/path-utils.js';
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/** /**
* Register the next-task tool with the MCP server * Register the next-task tool with the MCP server
@@ -26,25 +23,30 @@ export function registerNextTaskTool(server) {
'Find the next task to work on based on dependencies and status', 'Find the next task to work on based on dependencies and status',
parameters: z.object({ parameters: z.object({
file: z.string().optional().describe('Absolute path to the tasks file'), file: z.string().optional().describe('Absolute path to the tasks file'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z projectRoot: z
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Finding next task with args: ${JSON.stringify(args)}`); log.info(`Finding next task with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -54,21 +56,11 @@ export function registerNextTaskTool(server) {
); );
} }
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await nextTaskDirect( const result = await nextTaskDirect(
{ {
tasksJsonPath: tasksJsonPath, // Pass the explicitly resolved path
reportPath: complexityReportPath tasksJsonPath: tasksJsonPath
// No other args specific to this tool
}, },
log log
); );
@@ -88,6 +80,6 @@ export function registerNextTaskTool(server) {
log.error(`Error in nextTask tool: ${error.message}`); log.error(`Error in nextTask tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -4,16 +4,16 @@
*/ */
import { z } from 'zod'; import { z } from 'zod';
import path from 'path';
import { import {
getProjectRootFromSession,
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse
withNormalizedProjectRoot
} from './utils.js'; } from './utils.js';
import { parsePRDDirect } from '../core/task-master-core.js'; import { parsePRDDirect } from '../core/task-master-core.js';
import { resolveProjectPaths } from '../core/utils/path-utils.js';
/** /**
* Register the parse_prd tool * Register the parsePRD tool with the MCP server
* @param {Object} server - FastMCP server instance * @param {Object} server - FastMCP server instance
*/ */
export function registerParsePRDTool(server) { export function registerParsePRDTool(server) {
@@ -42,50 +42,72 @@ export function registerParsePRDTool(server) {
force: z force: z
.boolean() .boolean()
.optional() .optional()
.default(false) .describe('Allow overwriting an existing tasks.json file.'),
.describe('Overwrite existing output file without prompting.'),
append: z append: z
.boolean() .boolean()
.optional() .optional()
.default(false) .describe(
.describe('Append generated tasks to existing file.'), 'Append new tasks to existing tasks.json instead of overwriting'
),
projectRoot: z projectRoot: z
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
const toolName = 'parse_prd';
try { try {
log.info( log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
// Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve input (PRD) and output (tasks.json) paths using the utility
const { projectRoot, prdPath, tasksJsonPath } = resolveProjectPaths(
rootFolder,
args,
log
); );
// Call Direct Function - Pass relevant args including projectRoot // Check if PRD path was found (resolveProjectPaths returns null if not found and not provided)
if (!prdPath) {
return createErrorResponse(
'No PRD document found or provided. Please ensure a PRD file exists (e.g., PRD.md) or provide a valid input file path.'
);
}
// Call the direct function with fully resolved paths
const result = await parsePRDDirect( const result = await parsePRDDirect(
{ {
input: args.input, projectRoot: projectRoot,
output: args.output, input: prdPath,
output: tasksJsonPath,
numTasks: args.numTasks, numTasks: args.numTasks,
force: args.force, force: args.force,
append: args.append, append: args.append
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
); );
log.info( if (result.success) {
`${toolName}: Direct function result: success=${result.success}` log.info(`Successfully parsed PRD: ${result.data.message}`);
); } else {
log.error(
`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`
);
}
return handleApiResult(result, log, 'Error parsing PRD'); return handleApiResult(result, log, 'Error parsing PRD');
} catch (error) { } catch (error) {
log.error( log.error(`Error in parse-prd tool: ${error.message}`);
`Critical error in ${toolName} tool execute: ${error.message}` return createErrorResponse(error.message);
);
return createErrorResponse(
`Internal tool error (${toolName}): ${error.message}`
);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { removeDependencyDirect } from '../core/task-master-core.js'; import { removeDependencyDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -33,17 +33,28 @@ export function registerRemoveDependencyTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info( log.info(
`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}` `Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`
); );
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -55,7 +66,9 @@ export function registerRemoveDependencyTool(server) {
const result = await removeDependencyDirect( const result = await removeDependencyDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
dependsOn: args.dependsOn dependsOn: args.dependsOn
}, },
@@ -73,6 +86,6 @@ export function registerRemoveDependencyTool(server) {
log.error(`Error in removeDependency tool: ${error.message}`); log.error(`Error in removeDependency tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { removeSubtaskDirect } from '../core/task-master-core.js'; import { removeSubtaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -46,15 +46,26 @@ export function registerRemoveSubtaskTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Removing subtask with args: ${JSON.stringify(args)}`); log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -66,7 +77,9 @@ export function registerRemoveSubtaskTool(server) {
const result = await removeSubtaskDirect( const result = await removeSubtaskDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
convert: args.convert, convert: args.convert,
skipGenerate: args.skipGenerate skipGenerate: args.skipGenerate
@@ -85,6 +98,6 @@ export function registerRemoveSubtaskTool(server) {
log.error(`Error in removeSubtask tool: ${error.message}`); log.error(`Error in removeSubtask tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { removeTaskDirect } from '../core/task-master-core.js'; import { removeTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -35,15 +35,28 @@ export function registerRemoveTaskTool(server) {
.optional() .optional()
.describe('Whether to skip confirmation prompt (default: false)') .describe('Whether to skip confirmation prompt (default: false)')
}), }),
execute: withNormalizedProjectRoot(async (args, { log }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Removing task(s) with ID(s): ${args.id}`); log.info(`Removing task(s) with ID(s): ${args.id}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
log.info(`Using project root: ${rootFolder}`);
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -55,6 +68,7 @@ export function registerRemoveTaskTool(server) {
log.info(`Using tasks file path: ${tasksJsonPath}`); log.info(`Using tasks file path: ${tasksJsonPath}`);
// Assume client has already handled confirmation if needed
const result = await removeTaskDirect( const result = await removeTaskDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
@@ -74,6 +88,6 @@ export function registerRemoveTaskTool(server) {
log.error(`Error in remove-task tool: ${error.message}`); log.error(`Error in remove-task tool: ${error.message}`);
return createErrorResponse(`Failed to remove task: ${error.message}`); return createErrorResponse(`Failed to remove task: ${error.message}`);
} }
}) }
}); });
} }

View File

@@ -7,11 +7,10 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { setTaskStatusDirect } from '../core/task-master-core.js'; import { setTaskStatusDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
/** /**
* Register the setTaskStatus tool with the MCP server * Register the setTaskStatus tool with the MCP server
@@ -28,7 +27,7 @@ export function registerSetTaskStatusTool(server) {
"Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated to update multiple tasks/subtasks at once." "Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated to update multiple tasks/subtasks at once."
), ),
status: z status: z
.enum(TASK_STATUS_OPTIONS) .string()
.describe( .describe(
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'." "New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
), ),
@@ -37,15 +36,26 @@ export function registerSetTaskStatusTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`); log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -55,15 +65,19 @@ export function registerSetTaskStatusTool(server) {
); );
} }
// Call the direct function with the resolved path
const result = await setTaskStatusDirect( const result = await setTaskStatusDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
status: args.status status: args.status
}, },
log log
); );
// Log the result
if (result.success) { if (result.success) {
log.info( log.info(
`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}` `Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`
@@ -74,6 +88,7 @@ export function registerSetTaskStatusTool(server) {
); );
} }
// Format and return the result
return handleApiResult(result, log, 'Error setting task status'); return handleApiResult(result, log, 'Error setting task status');
} catch (error) { } catch (error) {
log.error(`Error in setTaskStatus tool: ${error.message}`); log.error(`Error in setTaskStatus tool: ${error.message}`);
@@ -81,6 +96,6 @@ export function registerSetTaskStatusTool(server) {
`Error setting task status: ${error.message}` `Error setting task status: ${error.message}`
); );
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { updateSubtaskByIdDirect } from '../core/task-master-core.js'; import { updateSubtaskByIdDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -37,19 +37,30 @@ export function registerUpdateSubtaskTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
const toolName = 'update_subtask';
try { try {
log.info(`Updating subtask with args: ${JSON.stringify(args)}`); log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
// Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
log.error(`${toolName}: Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
return createErrorResponse( return createErrorResponse(
`Failed to find tasks.json: ${error.message}` `Failed to find tasks.json: ${error.message}`
); );
@@ -57,11 +68,12 @@ export function registerUpdateSubtaskTool(server) {
const result = await updateSubtaskByIdDirect( const result = await updateSubtaskByIdDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
prompt: args.prompt, prompt: args.prompt,
research: args.research, research: args.research
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
@@ -77,13 +89,9 @@ export function registerUpdateSubtaskTool(server) {
return handleApiResult(result, log, 'Error updating subtask'); return handleApiResult(result, log, 'Error updating subtask');
} catch (error) { } catch (error) {
log.error( log.error(`Error in update_subtask tool: ${error.message}`);
`Critical error in ${toolName} tool execute: ${error.message}` return createErrorResponse(error.message);
);
return createErrorResponse(
`Internal tool error (${toolName}): ${error.message}`
);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { updateTaskByIdDirect } from '../core/task-master-core.js'; import { updateTaskByIdDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -23,7 +23,7 @@ export function registerUpdateTaskTool(server) {
'Updates a single task by ID with new information or context provided in the prompt.', 'Updates a single task by ID with new information or context provided in the prompt.',
parameters: z.object({ parameters: z.object({
id: z id: z
.string() // ID can be number or string like "1.2" .string()
.describe( .describe(
"ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool." "ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool."
), ),
@@ -39,53 +39,61 @@ export function registerUpdateTaskTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
const toolName = 'update_task';
try { try {
log.info( log.info(`Updating task with args: ${JSON.stringify(args)}`);
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
);
// Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
// Ensure project root was determined
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
// Resolve the path to tasks.json
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
} catch (error) { } catch (error) {
log.error(`${toolName}: Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
return createErrorResponse( return createErrorResponse(
`Failed to find tasks.json: ${error.message}` `Failed to find tasks.json: ${error.message}`
); );
} }
// 3. Call Direct Function - Include projectRoot
const result = await updateTaskByIdDirect( const result = await updateTaskByIdDirect(
{ {
// Pass the explicitly resolved path
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
// Pass other relevant args
id: args.id, id: args.id,
prompt: args.prompt, prompt: args.prompt,
research: args.research, research: args.research
projectRoot: args.projectRoot
}, },
log, log,
{ session } { session }
); );
// 4. Handle Result if (result.success) {
log.info( log.info(`Successfully updated task with ID ${args.id}`);
`${toolName}: Direct function result: success=${result.success}` } else {
); log.error(
`Failed to update task: ${result.error?.message || 'Unknown error'}`
);
}
return handleApiResult(result, log, 'Error updating task'); return handleApiResult(result, log, 'Error updating task');
} catch (error) { } catch (error) {
log.error( log.error(`Error in update_task tool: ${error.message}`);
`Critical error in ${toolName} tool execute: ${error.message}` return createErrorResponse(error.message);
);
return createErrorResponse(
`Internal tool error (${toolName}): ${error.message}`
);
} }
}) }
}); });
} }

View File

@@ -4,13 +4,10 @@
*/ */
import { z } from 'zod'; import { z } from 'zod';
import { import { handleApiResult, createErrorResponse } from './utils.js';
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { updateTasksDirect } from '../core/task-master-core.js'; import { updateTasksDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
import path from 'path';
/** /**
* Register the update tool with the MCP server * Register the update tool with the MCP server
@@ -34,61 +31,58 @@ export function registerUpdateTool(server) {
.boolean() .boolean()
.optional() .optional()
.describe('Use Perplexity AI for research-backed updates'), .describe('Use Perplexity AI for research-backed updates'),
file: z file: z.string().optional().describe('Absolute path to the tasks file'),
.string()
.optional()
.describe('Path to the tasks file relative to project root'),
projectRoot: z projectRoot: z
.string() .string()
.optional() .describe('The directory of the project. Must be an absolute path.')
.describe(
'The directory of the project. (Optional, usually from session)'
)
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
const toolName = 'update';
const { from, prompt, research, file, projectRoot } = args;
try { try {
log.info( log.info(`Executing update tool with args: ${JSON.stringify(args)}`);
`Executing ${toolName} tool with normalized root: ${projectRoot}`
);
// 1. Get Project Root
const rootFolder = args.projectRoot;
if (!rootFolder || !path.isAbsolute(rootFolder)) {
return createErrorResponse(
'projectRoot is required and must be absolute.'
);
}
log.info(`Project root: ${rootFolder}`);
// 2. Resolve Path
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath({ projectRoot, file }, log); tasksJsonPath = findTasksJsonPath(
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`); { projectRoot: rootFolder, file: args.file },
log
);
log.info(`Resolved tasks path: ${tasksJsonPath}`);
} catch (error) { } catch (error) {
log.error(`${toolName}: Error finding tasks.json: ${error.message}`); log.error(`Error finding tasks.json: ${error.message}`);
return createErrorResponse( return createErrorResponse(
`Failed to find tasks.json within project root '${projectRoot}': ${error.message}` `Failed to find tasks.json: ${error.message}`
); );
} }
// 3. Call Direct Function
const result = await updateTasksDirect( const result = await updateTasksDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
from: from, from: args.from,
prompt: prompt, prompt: args.prompt,
research: research, research: args.research
projectRoot: projectRoot
}, },
log, log,
{ session } { session }
); );
log.info( // 4. Handle Result
`${toolName}: Direct function result: success=${result.success}` log.info(`updateTasksDirect result: success=${result.success}`);
);
return handleApiResult(result, log, 'Error updating tasks'); return handleApiResult(result, log, 'Error updating tasks');
} catch (error) { } catch (error) {
log.error( log.error(`Critical error in update tool execute: ${error.message}`);
`Critical error in ${toolName} tool execute: ${error.message}` return createErrorResponse(`Internal tool error: ${error.message}`);
);
return createErrorResponse(
`Internal tool error (${toolName}): ${error.message}`
);
} }
}) }
}); });
} }

View File

@@ -7,7 +7,7 @@ import { spawnSync } from 'child_process';
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import { contextManager } from '../core/context-manager.js'; // Import the singleton import { contextManager } from '../core/context-manager.js'; // Import the singleton
import { withSessionEnv } from '../core/utils/env-utils.js';
// Import path utilities to ensure consistent path resolution // Import path utilities to ensure consistent path resolution
import { import {
lastFoundProjectRoot, lastFoundProjectRoot,
@@ -83,10 +83,10 @@ function getProjectRoot(projectRootRaw, log) {
} }
/** /**
* Extracts and normalizes the project root path from the MCP session object. * Extracts the project root path from the FastMCP session object.
* @param {Object} session - The MCP session object. * @param {Object} session - The FastMCP session object.
* @param {Object} log - The MCP logger object. * @param {Object} log - Logger object.
* @returns {string|null} - The normalized absolute project root path or null if not found/invalid. * @returns {string|null} - The absolute path to the project root, or null if not found.
*/ */
function getProjectRootFromSession(session, log) { function getProjectRootFromSession(session, log) {
try { try {
@@ -107,87 +107,68 @@ function getProjectRootFromSession(session, log) {
})}` })}`
); );
let rawRootPath = null; // ALWAYS ensure we return a valid path for project root
let decodedPath = null;
let finalPath = null;
// Check primary location
if (session?.roots?.[0]?.uri) {
rawRootPath = session.roots[0].uri;
log.info(`Found raw root URI in session.roots[0].uri: ${rawRootPath}`);
}
// Check alternate location
else if (session?.roots?.roots?.[0]?.uri) {
rawRootPath = session.roots.roots[0].uri;
log.info(
`Found raw root URI in session.roots.roots[0].uri: ${rawRootPath}`
);
}
if (rawRootPath) {
// Decode URI and strip file:// protocol
decodedPath = rawRootPath.startsWith('file://')
? decodeURIComponent(rawRootPath.slice(7))
: rawRootPath; // Assume non-file URI is already decoded? Or decode anyway? Let's decode.
if (!rawRootPath.startsWith('file://')) {
decodedPath = decodeURIComponent(rawRootPath); // Decode even if no file://
}
// Handle potential Windows drive prefix after stripping protocol (e.g., /C:/...)
if (
decodedPath.startsWith('/') &&
/[A-Za-z]:/.test(decodedPath.substring(1, 3))
) {
decodedPath = decodedPath.substring(1); // Remove leading slash if it's like /C:/...
}
log.info(`Decoded path: ${decodedPath}`);
// Normalize slashes and resolve
const normalizedSlashes = decodedPath.replace(/\\/g, '/');
finalPath = path.resolve(normalizedSlashes); // Resolve to absolute path for current OS
log.info(`Normalized and resolved session path: ${finalPath}`);
return finalPath;
}
// Fallback Logic (remains the same)
log.warn('No project root URI found in session. Attempting fallbacks...');
const cwd = process.cwd(); const cwd = process.cwd();
// Fallback 1: Use server path deduction (Cursor IDE) // If we have a session with roots array
const serverPath = process.argv[1]; if (session?.roots?.[0]?.uri) {
const rootUri = session.roots[0].uri;
log.info(`Found rootUri in session.roots[0].uri: ${rootUri}`);
const rootPath = rootUri.startsWith('file://')
? decodeURIComponent(rootUri.slice(7))
: rootUri;
log.info(`Decoded rootPath: ${rootPath}`);
return rootPath;
}
// If we have a session with roots.roots array (different structure)
if (session?.roots?.roots?.[0]?.uri) {
const rootUri = session.roots.roots[0].uri;
log.info(`Found rootUri in session.roots.roots[0].uri: ${rootUri}`);
const rootPath = rootUri.startsWith('file://')
? decodeURIComponent(rootUri.slice(7))
: rootUri;
log.info(`Decoded rootPath: ${rootPath}`);
return rootPath;
}
// Get the server's location and try to find project root -- this is a fallback necessary in Cursor IDE
const serverPath = process.argv[1]; // This should be the path to server.js, which is in mcp-server/
if (serverPath && serverPath.includes('mcp-server')) { if (serverPath && serverPath.includes('mcp-server')) {
// Find the mcp-server directory first
const mcpServerIndex = serverPath.indexOf('mcp-server'); const mcpServerIndex = serverPath.indexOf('mcp-server');
if (mcpServerIndex !== -1) { if (mcpServerIndex !== -1) {
const projectRoot = path.dirname( // Get the path up to mcp-server, which should be the project root
serverPath.substring(0, mcpServerIndex) const projectRoot = serverPath.substring(0, mcpServerIndex - 1); // -1 to remove trailing slash
); // Go up one level
// Verify this looks like our project root by checking for key files/directories
if ( if (
fs.existsSync(path.join(projectRoot, '.cursor')) || fs.existsSync(path.join(projectRoot, '.cursor')) ||
fs.existsSync(path.join(projectRoot, 'mcp-server')) || fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
fs.existsSync(path.join(projectRoot, 'package.json')) fs.existsSync(path.join(projectRoot, 'package.json'))
) { ) {
log.info( log.info(`Found project root from server path: ${projectRoot}`);
`Using project root derived from server path: ${projectRoot}` return projectRoot;
);
return projectRoot; // Already absolute
} }
} }
} }
// Fallback 2: Use CWD // ALWAYS ensure we return a valid path as a last resort
log.info(`Using current working directory as ultimate fallback: ${cwd}`); log.info(`Using current working directory as ultimate fallback: ${cwd}`);
return cwd; // Already absolute
} catch (e) {
log.error(`Error in getProjectRootFromSession: ${e.message}`);
// Attempt final fallback to CWD on error
const cwd = process.cwd();
log.warn(
`Returning CWD (${cwd}) due to error during session root processing.`
);
return cwd; return cwd;
} catch (e) {
// If we have a server path, use it as a basis for project root
const serverPath = process.argv[1];
if (serverPath && serverPath.includes('mcp-server')) {
const mcpServerIndex = serverPath.indexOf('mcp-server');
return mcpServerIndex !== -1
? serverPath.substring(0, mcpServerIndex - 1)
: process.cwd();
}
// Only use cwd if it's not "/"
const cwd = process.cwd();
return cwd !== '/' ? cwd : '/';
} }
} }
@@ -494,143 +475,80 @@ function createLogWrapper(log) {
} }
/** /**
* Resolves and normalizes a project root path from various formats. * Resolves and normalizes a project root path
* Handles URI encoding, Windows paths, and file protocols. * @param {string} rawPath - The raw project root path that might be URI encoded
* @param {string | undefined | null} rawPath - The raw project root path. * @returns {string} Normalized absolute path
* @param {object} [log] - Optional logger object.
* @returns {string | null} Normalized absolute path or null if input is invalid/empty.
*/ */
function normalizeProjectRoot(rawPath, log) { function normalizeProjectRoot(rawPath) {
if (!rawPath) return null; if (!rawPath) return null;
try { try {
let pathString = Array.isArray(rawPath) ? rawPath[0] : String(rawPath); // Handle URI encoded paths (e.g. /c%20/path/with%20spaces)
if (!pathString) return null; const decoded = decodeURIComponent(rawPath);
// 1. Decode URI Encoding // Convert Windows-style paths if needed
// Use try-catch for decoding as malformed URIs can throw const normalized = decoded.replace(/\\/g, '/');
try {
pathString = decodeURIComponent(pathString);
} catch (decodeError) {
if (log)
log.warn(
`Could not decode URI component for path "${rawPath}": ${decodeError.message}. Proceeding with raw string.`
);
// Proceed with the original string if decoding fails
pathString = Array.isArray(rawPath) ? rawPath[0] : String(rawPath);
}
// 2. Strip file:// prefix (handle 2 or 3 slashes) // Remove any file:// prefix
if (pathString.startsWith('file:///')) { const withoutProtocol = normalized.replace(/^file:\/\//, '');
pathString = pathString.slice(7); // Slice 7 for file:///, may leave leading / on Windows
} else if (pathString.startsWith('file://')) {
pathString = pathString.slice(7); // Slice 7 for file://
}
// 3. Handle potential Windows leading slash after stripping prefix (e.g., /C:/...) // Ensure absolute path
// This checks if it starts with / followed by a drive letter C: D: etc. return path.resolve(withoutProtocol);
if (
pathString.startsWith('/') &&
/[A-Za-z]:/.test(pathString.substring(1, 3))
) {
pathString = pathString.substring(1); // Remove the leading slash
}
// 4. Normalize backslashes to forward slashes
pathString = pathString.replace(/\\/g, '/');
// 5. Resolve to absolute path using server's OS convention
const resolvedPath = path.resolve(pathString);
return resolvedPath;
} catch (error) { } catch (error) {
if (log) {
log.error(
`Error normalizing project root path "${rawPath}": ${error.message}`
);
}
return null; // Return null on error
}
}
/**
* Extracts the raw project root path from the session (without normalization).
* Used as a fallback within the HOF.
* @param {Object} session - The MCP session object.
* @param {Object} log - The MCP logger object.
* @returns {string|null} The raw path string or null.
*/
function getRawProjectRootFromSession(session, log) {
try {
// Check primary location
if (session?.roots?.[0]?.uri) {
return session.roots[0].uri;
}
// Check alternate location
else if (session?.roots?.roots?.[0]?.uri) {
return session.roots.roots[0].uri;
}
return null; // Not found in expected session locations
} catch (e) {
log.error(`Error accessing session roots: ${e.message}`);
return null; return null;
} }
} }
/** /**
* Higher-order function to wrap MCP tool execute methods. * Higher-order function that wraps an MCP tool's execute method to provide:
* Ensures args.projectRoot is present and normalized before execution. * 1. Normalized project root resolution
* @param {Function} executeFn - The original async execute(args, context) function. * 2. Environment variable setup from both .env and session
* @returns {Function} The wrapped async execute function. * 3. Error handling
*
* @param {Function} executeFn - The original execute function to wrap
* @returns {Function} Wrapped execute function with project context
*/ */
function withNormalizedProjectRoot(executeFn) { export function withProjectContext(executeFn) {
return async (args, context) => { return async (args, context) => {
const { log, session } = context; const { log, session } = context;
let normalizedRoot = null;
let rootSource = 'unknown';
try { try {
// Determine raw root: prioritize args, then session // 1. Resolve and normalize project root
let rawRoot = args.projectRoot; const rawRoot =
if (!rawRoot) { args.projectRoot || getProjectRootFromSession(session, log);
rawRoot = getRawProjectRootFromSession(session, log); const projectRoot = normalizeProjectRoot(rawRoot);
rootSource = 'session';
} else {
rootSource = 'args';
}
if (!rawRoot) { if (!projectRoot) {
log.error('Could not determine project root from args or session.');
return createErrorResponse( return createErrorResponse(
'Could not determine project root. Please provide projectRoot argument or ensure session contains root info.' 'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
); );
} }
// Normalize the determined raw root // 2. Load .env from project root if it exists
normalizedRoot = normalizeProjectRoot(rawRoot, log); const envPath = path.join(projectRoot, '.env');
let localEnv = {};
if (!normalizedRoot) { if (fs.existsSync(envPath)) {
log.error( try {
`Failed to normalize project root obtained from ${rootSource}: ${rawRoot}` localEnv = require('dotenv').config({ path: envPath }).parsed || {};
); } catch (error) {
return createErrorResponse( log.warn(`Failed to load .env from ${envPath}: ${error.message}`);
`Invalid project root provided or derived from ${rootSource}: ${rawRoot}` }
);
} }
// Inject the normalized root back into args // 3. Combine with session env and execute
const updatedArgs = { ...args, projectRoot: normalizedRoot }; const combinedEnv = {
...localEnv,
...(session?.env || {})
};
// Execute the original function with normalized root in args return await withSessionEnv(combinedEnv, async () => {
return await executeFn(updatedArgs, context); // Pass normalized projectRoot to the execute function
return await executeFn({ ...args, projectRoot }, context);
});
} catch (error) { } catch (error) {
log.error( log.error(`Error in project context: ${error.message}`);
`Error within withNormalizedProjectRoot HOF (Normalized Root: ${normalizedRoot}): ${error.message}` return createErrorResponse(error.message);
);
// Add stack trace if available and debug enabled
if (error.stack && log.debug) {
log.debug(error.stack);
}
// Return a generic error or re-throw depending on desired behavior
return createErrorResponse(`Operation failed: ${error.message}`);
} }
}; };
} }
@@ -645,8 +563,5 @@ export {
processMCPResponseData, processMCPResponseData,
createContentResponse, createContentResponse,
createErrorResponse, createErrorResponse,
createLogWrapper, createLogWrapper
normalizeProjectRoot,
getRawProjectRootFromSession,
withNormalizedProjectRoot
}; };

View File

@@ -7,7 +7,7 @@ import { z } from 'zod';
import { import {
handleApiResult, handleApiResult,
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot getProjectRootFromSession
} from './utils.js'; } from './utils.js';
import { validateDependenciesDirect } from '../core/task-master-core.js'; import { validateDependenciesDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; import { findTasksJsonPath } from '../core/utils/path-utils.js';
@@ -27,15 +27,24 @@ export function registerValidateDependenciesTool(server) {
.string() .string()
.describe('The directory of the project. Must be an absolute path.') .describe('The directory of the project. Must be an absolute path.')
}), }),
execute: withNormalizedProjectRoot(async (args, { log, session }) => { execute: async (args, { log, session }) => {
try { try {
log.info(`Validating dependencies with args: ${JSON.stringify(args)}`); log.info(`Validating dependencies with args: ${JSON.stringify(args)}`);
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot) // Get project root from args or session
const rootFolder =
args.projectRoot || getProjectRootFromSession(session, log);
if (!rootFolder) {
return createErrorResponse(
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
);
}
let tasksJsonPath; let tasksJsonPath;
try { try {
tasksJsonPath = findTasksJsonPath( tasksJsonPath = findTasksJsonPath(
{ projectRoot: args.projectRoot, file: args.file }, { projectRoot: rootFolder, file: args.file },
log log
); );
} catch (error) { } catch (error) {
@@ -65,6 +74,6 @@ export function registerValidateDependenciesTool(server) {
log.error(`Error in validateDependencies tool: ${error.message}`); log.error(`Error in validateDependencies tool: ${error.message}`);
return createErrorResponse(error.message); return createErrorResponse(error.message);
} }
}) }
}); });
} }

34
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "task-master-ai", "name": "task-master-ai",
"version": "0.13.2", "version": "0.12.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "task-master-ai", "name": "task-master-ai",
"version": "0.13.2", "version": "0.12.1",
"license": "MIT WITH Commons-Clause", "license": "MIT WITH Commons-Clause",
"dependencies": { "dependencies": {
"@ai-sdk/anthropic": "^1.2.10", "@ai-sdk/anthropic": "^1.2.10",
@@ -19,9 +19,6 @@
"@anthropic-ai/sdk": "^0.39.0", "@anthropic-ai/sdk": "^0.39.0",
"@openrouter/ai-sdk-provider": "^0.4.5", "@openrouter/ai-sdk-provider": "^0.4.5",
"ai": "^4.3.10", "ai": "^4.3.10",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"commander": "^11.1.0", "commander": "^11.1.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
@@ -37,8 +34,7 @@
"ollama-ai-provider": "^1.2.0", "ollama-ai-provider": "^1.2.0",
"openai": "^4.89.0", "openai": "^4.89.0",
"ora": "^8.2.0", "ora": "^8.2.0",
"uuid": "^11.1.0", "uuid": "^11.1.0"
"zod": "^3.23.8"
}, },
"bin": { "bin": {
"task-master": "bin/task-master.js", "task-master": "bin/task-master.js",
@@ -49,6 +45,9 @@
"@changesets/changelog-github": "^0.5.1", "@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.28.1", "@changesets/cli": "^2.28.1",
"@types/jest": "^29.5.14", "@types/jest": "^29.5.14",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"execa": "^8.0.1", "execa": "^8.0.1",
"ink": "^5.0.1", "ink": "^5.0.1",
"jest": "^29.7.0", "jest": "^29.7.0",
@@ -58,7 +57,8 @@
"prettier": "^3.5.3", "prettier": "^3.5.3",
"react": "^18.3.1", "react": "^18.3.1",
"supertest": "^7.1.0", "supertest": "^7.1.0",
"tsx": "^4.16.2" "tsx": "^4.16.2",
"zod": "^3.23.8"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -1238,6 +1238,7 @@
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
"integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"engines": { "engines": {
@@ -3306,6 +3307,7 @@
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz", "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz",
"integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==", "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==",
"dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"string-width": "^4.1.0" "string-width": "^4.1.0"
@@ -3315,6 +3317,7 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@@ -3324,12 +3327,14 @@
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/ansi-align/node_modules/string-width": { "node_modules/ansi-align/node_modules/string-width": {
"version": "4.2.3", "version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"emoji-regex": "^8.0.0", "emoji-regex": "^8.0.0",
@@ -3344,6 +3349,7 @@
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-regex": "^5.0.1" "ansi-regex": "^5.0.1"
@@ -3693,6 +3699,7 @@
"version": "8.0.1", "version": "8.0.1",
"resolved": "https://registry.npmjs.org/boxen/-/boxen-8.0.1.tgz", "resolved": "https://registry.npmjs.org/boxen/-/boxen-8.0.1.tgz",
"integrity": "sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw==", "integrity": "sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-align": "^3.0.1", "ansi-align": "^3.0.1",
@@ -3843,6 +3850,7 @@
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-8.0.0.tgz", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-8.0.0.tgz",
"integrity": "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==", "integrity": "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=16" "node": ">=16"
@@ -3927,6 +3935,7 @@
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz",
"integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=10" "node": ">=10"
@@ -3966,6 +3975,7 @@
"version": "0.6.5", "version": "0.6.5",
"resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
"integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"string-width": "^4.2.0" "string-width": "^4.2.0"
@@ -3981,6 +3991,7 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@@ -3990,12 +4001,14 @@
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/cli-table3/node_modules/string-width": { "node_modules/cli-table3/node_modules/string-width": {
"version": "4.2.3", "version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"emoji-regex": "^8.0.0", "emoji-regex": "^8.0.0",
@@ -4010,6 +4023,7 @@
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-regex": "^5.0.1" "ansi-regex": "^5.0.1"
@@ -9474,6 +9488,7 @@
"version": "4.37.0", "version": "4.37.0",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.37.0.tgz", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.37.0.tgz",
"integrity": "sha512-S/5/0kFftkq27FPNye0XM1e2NsnoD/3FS+pBmbjmmtLT6I+i344KoOf7pvXreaFsDamWeaJX55nczA1m5PsBDg==", "integrity": "sha512-S/5/0kFftkq27FPNye0XM1e2NsnoD/3FS+pBmbjmmtLT6I+i344KoOf7pvXreaFsDamWeaJX55nczA1m5PsBDg==",
"dev": true,
"license": "(MIT OR CC0-1.0)", "license": "(MIT OR CC0-1.0)",
"engines": { "engines": {
"node": ">=16" "node": ">=16"
@@ -9683,6 +9698,7 @@
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz", "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz",
"integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==", "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"string-width": "^7.0.0" "string-width": "^7.0.0"
@@ -9698,6 +9714,7 @@
"version": "9.0.0", "version": "9.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz",
"integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-styles": "^6.2.1", "ansi-styles": "^6.2.1",
@@ -9715,6 +9732,7 @@
"version": "6.2.1", "version": "6.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz",
"integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=12" "node": ">=12"

View File

@@ -1,6 +1,6 @@
{ {
"name": "task-master-ai", "name": "task-master-ai",
"version": "0.14.0", "version": "0.12.1",
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.", "description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",
@@ -49,9 +49,6 @@
"@anthropic-ai/sdk": "^0.39.0", "@anthropic-ai/sdk": "^0.39.0",
"@openrouter/ai-sdk-provider": "^0.4.5", "@openrouter/ai-sdk-provider": "^0.4.5",
"ai": "^4.3.10", "ai": "^4.3.10",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"commander": "^11.1.0", "commander": "^11.1.0",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
@@ -67,8 +64,7 @@
"ollama-ai-provider": "^1.2.0", "ollama-ai-provider": "^1.2.0",
"openai": "^4.89.0", "openai": "^4.89.0",
"ora": "^8.2.0", "ora": "^8.2.0",
"uuid": "^11.1.0", "uuid": "^11.1.0"
"zod": "^3.23.8"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -82,14 +78,15 @@
"url": "https://github.com/eyaltoledano/claude-task-master/issues" "url": "https://github.com/eyaltoledano/claude-task-master/issues"
}, },
"files": [ "files": [
"scripts/**", "scripts/init.js",
"scripts/dev.js",
"scripts/modules/**",
"assets/**", "assets/**",
".cursor/**", ".cursor/**",
"README-task-master.md", "README-task-master.md",
"index.js", "index.js",
"bin/**", "bin/**",
"mcp-server/**", "mcp-server/**"
"src/**"
], ],
"overrides": { "overrides": {
"node-fetch": "^3.3.2", "node-fetch": "^3.3.2",
@@ -99,6 +96,9 @@
"@changesets/changelog-github": "^0.5.1", "@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.28.1", "@changesets/cli": "^2.28.1",
"@types/jest": "^29.5.14", "@types/jest": "^29.5.14",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"execa": "^8.0.1", "execa": "^8.0.1",
"ink": "^5.0.1", "ink": "^5.0.1",
"jest": "^29.7.0", "jest": "^29.7.0",
@@ -108,6 +108,7 @@
"prettier": "^3.5.3", "prettier": "^3.5.3",
"react": "^18.3.1", "react": "^18.3.1",
"supertest": "^7.1.0", "supertest": "^7.1.0",
"tsx": "^4.16.2" "tsx": "^4.16.2",
"zod": "^3.23.8"
} }
} }

View File

@@ -32,7 +32,7 @@ The script can be configured through environment variables in a `.env` file at t
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation - `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online") - `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false) - `DEBUG`: Enable debug logging (default: false)
- `TASKMASTER_LOG_LEVEL`: Log level - debug, info, warn, error (default: info) - `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3) - `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium) - `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
- `PROJECT_NAME`: Override default project name in tasks.json - `PROJECT_NAME`: Override default project name in tasks.json
@@ -47,7 +47,7 @@ The script can be configured through environment variables in a `.env` file at t
- Tasks can have `subtasks` for more detailed implementation steps. - Tasks can have `subtasks` for more detailed implementation steps.
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress. - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **Script Commands** 2. **Script Commands**
You can run the script via: You can run the script via:
```bash ```bash
@@ -225,7 +225,7 @@ To use the Perplexity integration:
## Logging ## Logging
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable: The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting - `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default) - `info`: Confirmation that things are working as expected (default)

View File

@@ -38,10 +38,10 @@ const LOG_LEVELS = {
success: 4 success: 4
}; };
// Determine log level from environment variable or default to 'info' // Get log level from environment or default to info
const LOG_LEVEL = process.env.TASKMASTER_LOG_LEVEL const LOG_LEVEL = process.env.LOG_LEVEL
? LOG_LEVELS[process.env.TASKMASTER_LOG_LEVEL.toLowerCase()] ? LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()]
: LOG_LEVELS.info; // Default to info : LOG_LEVELS.info;
// Create a color gradient for the banner // Create a color gradient for the banner
const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']); const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']);
@@ -180,9 +180,9 @@ function copyTemplateFile(templateName, targetPath, replacements = {}) {
// Map template names to their actual source paths // Map template names to their actual source paths
switch (templateName) { switch (templateName) {
// case 'scripts_README.md': case 'scripts_README.md':
// sourcePath = path.join(__dirname, '..', 'assets', 'scripts_README.md'); sourcePath = path.join(__dirname, '..', 'assets', 'scripts_README.md');
// break; break;
case 'dev_workflow.mdc': case 'dev_workflow.mdc':
sourcePath = path.join( sourcePath = path.join(
__dirname, __dirname,
@@ -219,8 +219,8 @@ function copyTemplateFile(templateName, targetPath, replacements = {}) {
'self_improve.mdc' 'self_improve.mdc'
); );
break; break;
// case 'README-task-master.md': case 'README-task-master.md':
// sourcePath = path.join(__dirname, '..', 'README-task-master.md'); sourcePath = path.join(__dirname, '..', 'README-task-master.md');
break; break;
case 'windsurfrules': case 'windsurfrules':
sourcePath = path.join(__dirname, '..', 'assets', '.windsurfrules'); sourcePath = path.join(__dirname, '..', 'assets', '.windsurfrules');
@@ -351,18 +351,18 @@ async function initializeProject(options = {}) {
} }
// Debug logging only if not in silent mode // Debug logging only if not in silent mode
// if (!isSilentMode()) { if (!isSilentMode()) {
// console.log('===== DEBUG: INITIALIZE PROJECT OPTIONS RECEIVED ====='); console.log('===== DEBUG: INITIALIZE PROJECT OPTIONS RECEIVED =====');
// console.log('Full options object:', JSON.stringify(options)); console.log('Full options object:', JSON.stringify(options));
// console.log('options.yes:', options.yes); console.log('options.yes:', options.yes);
// console.log('=================================================='); console.log('==================================================');
// } }
const skipPrompts = options.yes || (options.name && options.description); const skipPrompts = options.yes || (options.name && options.description);
// if (!isSilentMode()) { if (!isSilentMode()) {
// console.log('Skip prompts determined:', skipPrompts); console.log('Skip prompts determined:', skipPrompts);
// } }
if (skipPrompts) { if (skipPrompts) {
if (!isSilentMode()) { if (!isSilentMode()) {
@@ -565,12 +565,12 @@ function createProjectStructure(addAliases, dryRun) {
path.join(targetDir, 'scripts', 'example_prd.txt') path.join(targetDir, 'scripts', 'example_prd.txt')
); );
// // Create main README.md // Create main README.md
// copyTemplateFile( copyTemplateFile(
// 'README-task-master.md', 'README-task-master.md',
// path.join(targetDir, 'README-task-master.md'), path.join(targetDir, 'README-task-master.md'),
// replacements replacements
// ); );
// Initialize git repository if git is available // Initialize git repository if git is available
try { try {
@@ -761,22 +761,21 @@ function setupMCPConfiguration(targetDir) {
const newMCPServer = { const newMCPServer = {
'task-master-ai': { 'task-master-ai': {
command: 'npx', command: 'npx',
args: ['-y', '--package=task-master-ai', 'task-master-ai'], args: ['-y', 'task-master-mcp'],
env: { env: {
ANTHROPIC_API_KEY: 'ANTHROPIC_API_KEY_HERE', ANTHROPIC_API_KEY: 'YOUR_ANTHROPIC_API_KEY',
PERPLEXITY_API_KEY: 'PERPLEXITY_API_KEY_HERE', PERPLEXITY_API_KEY: 'YOUR_PERPLEXITY_API_KEY',
OPENAI_API_KEY: 'OPENAI_API_KEY_HERE', MODEL: 'claude-3-7-sonnet-20250219',
GOOGLE_API_KEY: 'GOOGLE_API_KEY_HERE', PERPLEXITY_MODEL: 'sonar-pro',
XAI_API_KEY: 'XAI_API_KEY_HERE', MAX_TOKENS: '64000',
OPENROUTER_API_KEY: 'OPENROUTER_API_KEY_HERE', TEMPERATURE: '0.2',
MISTRAL_API_KEY: 'MISTRAL_API_KEY_HERE', DEFAULT_SUBTASKS: '5',
AZURE_OPENAI_API_KEY: 'AZURE_OPENAI_API_KEY_HERE', DEFAULT_PRIORITY: 'medium'
OLLAMA_API_KEY: 'OLLAMA_API_KEY_HERE'
} }
} }
}; };
// Check if mcp.json already existsimage.png // Check if mcp.json already exists
if (fs.existsSync(mcpJsonPath)) { if (fs.existsSync(mcpJsonPath)) {
log( log(
'info', 'info',
@@ -796,14 +795,14 @@ function setupMCPConfiguration(targetDir) {
(server) => (server) =>
server.args && server.args &&
server.args.some( server.args.some(
(arg) => typeof arg === 'string' && arg.includes('task-master-ai') (arg) => typeof arg === 'string' && arg.includes('task-master-mcp')
) )
); );
if (hasMCPString) { if (hasMCPString) {
log( log(
'info', 'info',
'Found existing task-master-ai MCP configuration in mcp.json, leaving untouched' 'Found existing task-master-mcp configuration in mcp.json, leaving untouched'
); );
return; // Exit early, don't modify the existing configuration return; // Exit early, don't modify the existing configuration
} }

View File

@@ -14,13 +14,9 @@ import {
getResearchModelId, getResearchModelId,
getFallbackProvider, getFallbackProvider,
getFallbackModelId, getFallbackModelId,
getParametersForRole, getParametersForRole
getUserId,
MODEL_MAP,
getDebugFlag,
getBaseUrlForRole
} from './config-manager.js'; } from './config-manager.js';
import { log, resolveEnvVariable, isSilentMode } from './utils.js'; import { log, resolveEnvVariable } from './utils.js';
import * as anthropic from '../../src/ai-providers/anthropic.js'; import * as anthropic from '../../src/ai-providers/anthropic.js';
import * as perplexity from '../../src/ai-providers/perplexity.js'; import * as perplexity from '../../src/ai-providers/perplexity.js';
@@ -28,39 +24,8 @@ import * as google from '../../src/ai-providers/google.js';
import * as openai from '../../src/ai-providers/openai.js'; import * as openai from '../../src/ai-providers/openai.js';
import * as xai from '../../src/ai-providers/xai.js'; import * as xai from '../../src/ai-providers/xai.js';
import * as openrouter from '../../src/ai-providers/openrouter.js'; import * as openrouter from '../../src/ai-providers/openrouter.js';
import * as ollama from '../../src/ai-providers/ollama.js';
// TODO: Import other provider modules when implemented (ollama, etc.) // TODO: Import other provider modules when implemented (ollama, etc.)
// Helper function to get cost for a specific model
function _getCostForModel(providerName, modelId) {
if (!MODEL_MAP || !MODEL_MAP[providerName]) {
log(
'warn',
`Provider "${providerName}" not found in MODEL_MAP. Cannot determine cost for model ${modelId}.`
);
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
}
const modelData = MODEL_MAP[providerName].find((m) => m.id === modelId);
if (!modelData || !modelData.cost_per_1m_tokens) {
log(
'debug',
`Cost data not found for model "${modelId}" under provider "${providerName}". Assuming zero cost.`
);
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
}
// Ensure currency is part of the returned object, defaulting if not present
const currency = modelData.cost_per_1m_tokens.currency || 'USD';
return {
inputCost: modelData.cost_per_1m_tokens.input || 0,
outputCost: modelData.cost_per_1m_tokens.output || 0,
currency: currency
};
}
// --- Provider Function Map --- // --- Provider Function Map ---
// Maps provider names (lowercase) to their respective service functions // Maps provider names (lowercase) to their respective service functions
const PROVIDER_FUNCTIONS = { const PROVIDER_FUNCTIONS = {
@@ -97,11 +62,6 @@ const PROVIDER_FUNCTIONS = {
generateText: openrouter.generateOpenRouterText, generateText: openrouter.generateOpenRouterText,
streamText: openrouter.streamOpenRouterText, streamText: openrouter.streamOpenRouterText,
generateObject: openrouter.generateOpenRouterObject generateObject: openrouter.generateOpenRouterObject
},
ollama: {
generateText: ollama.generateOllamaText,
streamText: ollama.streamOllamaText,
generateObject: ollama.generateOllamaObject
} }
// TODO: Add entries for ollama, etc. when implemented // TODO: Add entries for ollama, etc. when implemented
}; };
@@ -176,11 +136,10 @@ function _extractErrorMessage(error) {
* Internal helper to resolve the API key for a given provider. * Internal helper to resolve the API key for a given provider.
* @param {string} providerName - The name of the provider (lowercase). * @param {string} providerName - The name of the provider (lowercase).
* @param {object|null} session - Optional MCP session object. * @param {object|null} session - Optional MCP session object.
* @param {string|null} projectRoot - Optional project root path for .env fallback.
* @returns {string|null} The API key or null if not found/needed. * @returns {string|null} The API key or null if not found/needed.
* @throws {Error} If a required API key is missing. * @throws {Error} If a required API key is missing.
*/ */
function _resolveApiKey(providerName, session, projectRoot = null) { function _resolveApiKey(providerName, session) {
const keyMap = { const keyMap = {
openai: 'OPENAI_API_KEY', openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY', anthropic: 'ANTHROPIC_API_KEY',
@@ -189,10 +148,14 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
mistral: 'MISTRAL_API_KEY', mistral: 'MISTRAL_API_KEY',
azure: 'AZURE_OPENAI_API_KEY', azure: 'AZURE_OPENAI_API_KEY',
openrouter: 'OPENROUTER_API_KEY', openrouter: 'OPENROUTER_API_KEY',
xai: 'XAI_API_KEY', xai: 'XAI_API_KEY'
ollama: 'OLLAMA_API_KEY'
}; };
// Double check this -- I have had to use an api key for ollama in the past
// if (providerName === 'ollama') {
// return null; // Ollama typically doesn't require an API key for basic setup
// }
const envVarName = keyMap[providerName]; const envVarName = keyMap[providerName];
if (!envVarName) { if (!envVarName) {
throw new Error( throw new Error(
@@ -200,17 +163,10 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
); );
} }
const apiKey = resolveEnvVariable(envVarName, session, projectRoot); const apiKey = resolveEnvVariable(envVarName, session);
// Special handling for Ollama - API key is optional
if (providerName === 'ollama') {
return apiKey || null;
}
// For all other providers, API key is required
if (!apiKey) { if (!apiKey) {
throw new Error( throw new Error(
`Required API key ${envVarName} for provider '${providerName}' is not set in environment, session, or .env file.` `Required API key ${envVarName} for provider '${providerName}' is not set in environment or session.`
); );
} }
return apiKey; return apiKey;
@@ -239,22 +195,18 @@ async function _attemptProviderCallWithRetries(
while (retries <= MAX_RETRIES) { while (retries <= MAX_RETRIES) {
try { try {
if (getDebugFlag()) { log(
log( 'info',
'info', `Attempt ${retries + 1}/${MAX_RETRIES + 1} calling ${fnName} (Provider: ${providerName}, Model: ${modelId}, Role: ${attemptRole})`
`Attempt ${retries + 1}/${MAX_RETRIES + 1} calling ${fnName} (Provider: ${providerName}, Model: ${modelId}, Role: ${attemptRole})` );
);
}
// Call the specific provider function directly // Call the specific provider function directly
const result = await providerApiFn(callParams); const result = await providerApiFn(callParams);
if (getDebugFlag()) { log(
log( 'info',
'info', `${fnName} succeeded for role ${attemptRole} (Provider: ${providerName}) on attempt ${retries + 1}`
`${fnName} succeeded for role ${attemptRole} (Provider: ${providerName}) on attempt ${retries + 1}` );
);
}
return result; return result;
} catch (error) { } catch (error) {
log( log(
@@ -267,13 +219,13 @@ async function _attemptProviderCallWithRetries(
const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retries - 1); const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retries - 1);
log( log(
'info', 'info',
`Something went wrong on the provider side. Retrying in ${delay / 1000}s...` `Retryable error detected. Retrying in ${delay / 1000}s...`
); );
await new Promise((resolve) => setTimeout(resolve, delay)); await new Promise((resolve) => setTimeout(resolve, delay));
} else { } else {
log( log(
'error', 'error',
`Something went wrong on the provider side. Max retries reached for role ${attemptRole} (${fnName} / ${providerName}).` `Non-retryable error or max retries reached for role ${attemptRole} (${fnName} / ${providerName}).`
); );
throw error; throw error;
} }
@@ -289,53 +241,27 @@ async function _attemptProviderCallWithRetries(
* Base logic for unified service functions. * Base logic for unified service functions.
* @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject'). * @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject').
* @param {object} params - Original parameters passed to the service function. * @param {object} params - Original parameters passed to the service function.
* @param {string} params.role - The initial client role.
* @param {object} [params.session=null] - Optional MCP session object.
* @param {string} [params.projectRoot] - Optional project root path.
* @param {string} params.commandName - Name of the command invoking the service.
* @param {string} params.outputType - 'cli' or 'mcp'.
* @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} [params.prompt] - The prompt for the AI.
* @param {string} [params.schema] - The Zod schema for the expected object.
* @param {string} [params.objectName] - Name for object/tool.
* @returns {Promise<any>} Result from the underlying provider call. * @returns {Promise<any>} Result from the underlying provider call.
*/ */
async function _unifiedServiceRunner(serviceType, params) { async function _unifiedServiceRunner(serviceType, params) {
const { const {
role: initialRole, role: initialRole,
session, session,
projectRoot,
systemPrompt, systemPrompt,
prompt, prompt,
schema, schema,
objectName, objectName,
commandName,
outputType,
...restApiParams ...restApiParams
} = params; } = params;
if (getDebugFlag()) { log('info', `${serviceType}Service called`, { role: initialRole });
log('info', `${serviceType}Service called`, {
role: initialRole,
commandName,
outputType,
projectRoot
});
}
// Determine the effective project root (passed in or detected if needed by config getters)
const { findProjectRoot: detectProjectRoot } = await import('./utils.js'); // Dynamically import if needed
const effectiveProjectRoot = projectRoot || detectProjectRoot();
// Get userId from config - ensure effectiveProjectRoot is passed
const userId = getUserId(effectiveProjectRoot);
let sequence; let sequence;
if (initialRole === 'main') { if (initialRole === 'main') {
sequence = ['main', 'fallback', 'research']; sequence = ['main', 'fallback', 'research'];
} else if (initialRole === 'research') {
sequence = ['research', 'fallback', 'main'];
} else if (initialRole === 'fallback') { } else if (initialRole === 'fallback') {
sequence = ['fallback', 'main', 'research']; sequence = ['fallback', 'research'];
} else if (initialRole === 'research') {
sequence = ['research', 'fallback'];
} else { } else {
log( log(
'warn', 'warn',
@@ -349,30 +275,22 @@ async function _unifiedServiceRunner(serviceType, params) {
'AI service call failed for all configured roles.'; 'AI service call failed for all configured roles.';
for (const currentRole of sequence) { for (const currentRole of sequence) {
let providerName, let providerName, modelId, apiKey, roleParams, providerFnSet, providerApiFn;
modelId,
apiKey,
roleParams,
providerFnSet,
providerApiFn,
baseUrl,
providerResponse,
telemetryData = null;
try { try {
log('info', `New AI service call with role: ${currentRole}`); log('info', `New AI service call with role: ${currentRole}`);
// 1. Get Config: Provider, Model, Parameters for the current role // 1. Get Config: Provider, Model, Parameters for the current role
// Pass effectiveProjectRoot to config getters // Call individual getters based on the current role
if (currentRole === 'main') { if (currentRole === 'main') {
providerName = getMainProvider(effectiveProjectRoot); providerName = getMainProvider();
modelId = getMainModelId(effectiveProjectRoot); modelId = getMainModelId();
} else if (currentRole === 'research') { } else if (currentRole === 'research') {
providerName = getResearchProvider(effectiveProjectRoot); providerName = getResearchProvider();
modelId = getResearchModelId(effectiveProjectRoot); modelId = getResearchModelId();
} else if (currentRole === 'fallback') { } else if (currentRole === 'fallback') {
providerName = getFallbackProvider(effectiveProjectRoot); providerName = getFallbackProvider();
modelId = getFallbackModelId(effectiveProjectRoot); modelId = getFallbackModelId();
} else { } else {
log( log(
'error', 'error',
@@ -396,9 +314,7 @@ async function _unifiedServiceRunner(serviceType, params) {
continue; continue;
} }
// Pass effectiveProjectRoot to getParametersForRole roleParams = getParametersForRole(currentRole);
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
baseUrl = getBaseUrlForRole(currentRole, effectiveProjectRoot);
// 2. Get Provider Function Set // 2. Get Provider Function Set
providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()]; providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()];
@@ -429,12 +345,7 @@ async function _unifiedServiceRunner(serviceType, params) {
} }
// 3. Resolve API Key (will throw if required and missing) // 3. Resolve API Key (will throw if required and missing)
// Pass effectiveProjectRoot to _resolveApiKey apiKey = _resolveApiKey(providerName?.toLowerCase(), session);
apiKey = _resolveApiKey(
providerName?.toLowerCase(),
session,
effectiveProjectRoot
);
// 4. Construct Messages Array // 4. Construct Messages Array
const messages = []; const messages = [];
@@ -475,13 +386,12 @@ async function _unifiedServiceRunner(serviceType, params) {
maxTokens: roleParams.maxTokens, maxTokens: roleParams.maxTokens,
temperature: roleParams.temperature, temperature: roleParams.temperature,
messages, messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }), ...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams ...restApiParams
}; };
// 6. Attempt the call with retries // 6. Attempt the call with retries
providerResponse = await _attemptProviderCallWithRetries( const result = await _attemptProviderCallWithRetries(
providerApiFn, providerApiFn,
callParams, callParams,
providerName, providerName,
@@ -489,53 +399,9 @@ async function _unifiedServiceRunner(serviceType, params) {
currentRole currentRole
); );
// --- Log Telemetry & Capture Data --- log('info', `${serviceType}Service succeeded using role: ${currentRole}`);
// Use providerResponse which contains the usage data directly for text/object
if (userId && providerResponse && providerResponse.usage) {
try {
telemetryData = await logAiUsage({
userId,
commandName,
providerName,
modelId,
inputTokens: providerResponse.usage.inputTokens,
outputTokens: providerResponse.usage.outputTokens,
outputType
});
} catch (telemetryError) {
// logAiUsage already logs its own errors and returns null on failure
// No need to log again here, telemetryData will remain null
}
} else if (userId && providerResponse && !providerResponse.usage) {
log(
'warn',
`Cannot log telemetry for ${commandName} (${providerName}/${modelId}): AI result missing 'usage' data. (May be expected for streams)`
);
}
// --- End Log Telemetry ---
// --- Extract the correct main result based on serviceType --- return result;
let finalMainResult;
if (serviceType === 'generateText') {
finalMainResult = providerResponse.text;
} else if (serviceType === 'generateObject') {
finalMainResult = providerResponse.object;
} else if (serviceType === 'streamText') {
finalMainResult = providerResponse; // Return the whole stream object
} else {
log(
'error',
`Unknown serviceType in _unifiedServiceRunner: ${serviceType}`
);
finalMainResult = providerResponse; // Default to returning the whole object as fallback
}
// --- End Main Result Extraction ---
// Return a composite object including the extracted main result and telemetry data
return {
mainResult: finalMainResult,
telemetryData: telemetryData
};
} catch (error) { } catch (error) {
const cleanMessage = _extractErrorMessage(error); const cleanMessage = _extractErrorMessage(error);
log( log(
@@ -577,19 +443,13 @@ async function _unifiedServiceRunner(serviceType, params) {
* @param {object} params - Parameters for the service call. * @param {object} params - Parameters for the service call.
* @param {string} params.role - The initial client role ('main', 'research', 'fallback'). * @param {string} params.role - The initial client role ('main', 'research', 'fallback').
* @param {object} [params.session=null] - Optional MCP session object. * @param {object} [params.session=null] - Optional MCP session object.
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
* @param {string} params.prompt - The prompt for the AI. * @param {string} params.prompt - The prompt for the AI.
* @param {string} [params.systemPrompt] - Optional system prompt. * @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} params.commandName - Name of the command invoking the service. * // Other specific generateText params can be included here.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'. * @returns {Promise<string>} The generated text content.
* @returns {Promise<object>} Result object containing generated text and usage data.
*/ */
async function generateTextService(params) { async function generateTextService(params) {
// Ensure default outputType if not provided return _unifiedServiceRunner('generateText', params);
const defaults = { outputType: 'cli' };
const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
return _unifiedServiceRunner('generateText', combinedParams);
} }
/** /**
@@ -599,21 +459,13 @@ async function generateTextService(params) {
* @param {object} params - Parameters for the service call. * @param {object} params - Parameters for the service call.
* @param {string} params.role - The initial client role ('main', 'research', 'fallback'). * @param {string} params.role - The initial client role ('main', 'research', 'fallback').
* @param {object} [params.session=null] - Optional MCP session object. * @param {object} [params.session=null] - Optional MCP session object.
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
* @param {string} params.prompt - The prompt for the AI. * @param {string} params.prompt - The prompt for the AI.
* @param {string} [params.systemPrompt] - Optional system prompt. * @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} params.commandName - Name of the command invoking the service. * // Other specific streamText params can be included here.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'. * @returns {Promise<ReadableStream<string>>} A readable stream of text deltas.
* @returns {Promise<object>} Result object containing the stream and usage data.
*/ */
async function streamTextService(params) { async function streamTextService(params) {
const defaults = { outputType: 'cli' }; return _unifiedServiceRunner('streamText', params);
const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
// NOTE: Telemetry for streaming might be tricky as usage data often comes at the end.
// The current implementation logs *after* the stream is returned.
// We might need to adjust how usage is captured/logged for streams.
return _unifiedServiceRunner('streamText', combinedParams);
} }
/** /**
@@ -623,95 +475,20 @@ async function streamTextService(params) {
* @param {object} params - Parameters for the service call. * @param {object} params - Parameters for the service call.
* @param {string} params.role - The initial client role ('main', 'research', 'fallback'). * @param {string} params.role - The initial client role ('main', 'research', 'fallback').
* @param {object} [params.session=null] - Optional MCP session object. * @param {object} [params.session=null] - Optional MCP session object.
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the expected object. * @param {import('zod').ZodSchema} params.schema - The Zod schema for the expected object.
* @param {string} params.prompt - The prompt for the AI. * @param {string} params.prompt - The prompt for the AI.
* @param {string} [params.systemPrompt] - Optional system prompt. * @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} [params.objectName='generated_object'] - Name for object/tool. * @param {string} [params.objectName='generated_object'] - Name for object/tool.
* @param {number} [params.maxRetries=3] - Max retries for object generation. * @param {number} [params.maxRetries=3] - Max retries for object generation.
* @param {string} params.commandName - Name of the command invoking the service. * @returns {Promise<object>} The generated object matching the schema.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
* @returns {Promise<object>} Result object containing the generated object and usage data.
*/ */
async function generateObjectService(params) { async function generateObjectService(params) {
const defaults = { const defaults = {
objectName: 'generated_object', objectName: 'generated_object',
maxRetries: 3, maxRetries: 3
outputType: 'cli'
}; };
const combinedParams = { ...defaults, ...params }; const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
return _unifiedServiceRunner('generateObject', combinedParams); return _unifiedServiceRunner('generateObject', combinedParams);
} }
// --- Telemetry Function --- export { generateTextService, streamTextService, generateObjectService };
/**
* Logs AI usage telemetry data.
* For now, it just logs to the console. Sending will be implemented later.
* @param {object} params - Telemetry parameters.
* @param {string} params.userId - Unique user identifier.
* @param {string} params.commandName - The command that triggered the AI call.
* @param {string} params.providerName - The AI provider used (e.g., 'openai').
* @param {string} params.modelId - The specific AI model ID used.
* @param {number} params.inputTokens - Number of input tokens.
* @param {number} params.outputTokens - Number of output tokens.
*/
async function logAiUsage({
userId,
commandName,
providerName,
modelId,
inputTokens,
outputTokens,
outputType
}) {
try {
const isMCP = outputType === 'mcp';
const timestamp = new Date().toISOString();
const totalTokens = (inputTokens || 0) + (outputTokens || 0);
// Destructure currency along with costs
const { inputCost, outputCost, currency } = _getCostForModel(
providerName,
modelId
);
const totalCost =
((inputTokens || 0) / 1_000_000) * inputCost +
((outputTokens || 0) / 1_000_000) * outputCost;
const telemetryData = {
timestamp,
userId,
commandName,
modelUsed: modelId, // Consistent field name from requirements
providerName, // Keep provider name for context
inputTokens: inputTokens || 0,
outputTokens: outputTokens || 0,
totalTokens,
totalCost: parseFloat(totalCost.toFixed(6)),
currency // Add currency to the telemetry data
};
if (getDebugFlag()) {
log('info', 'AI Usage Telemetry:', telemetryData);
}
// TODO (Subtask 77.2): Send telemetryData securely to the external endpoint.
return telemetryData;
} catch (error) {
log('error', `Failed to log AI usage telemetry: ${error.message}`, {
error
});
// Don't re-throw; telemetry failure shouldn't block core functionality.
return null;
}
}
export {
generateTextService,
streamTextService,
generateObjectService,
logAiUsage
};

View File

@@ -10,7 +10,6 @@ import boxen from 'boxen';
import fs from 'fs'; import fs from 'fs';
import https from 'https'; import https from 'https';
import inquirer from 'inquirer'; import inquirer from 'inquirer';
import ora from 'ora'; // Import ora
import { log, readJSON } from './utils.js'; import { log, readJSON } from './utils.js';
import { import {
@@ -62,8 +61,7 @@ import {
stopLoadingIndicator, stopLoadingIndicator,
displayModelConfiguration, displayModelConfiguration,
displayAvailableModels, displayAvailableModels,
displayApiKeyStatus, displayApiKeyStatus
displayAiUsageSummary
} from './ui.js'; } from './ui.js';
import { initializeProject } from '../init.js'; import { initializeProject } from '../init.js';
@@ -74,11 +72,7 @@ import {
getApiKeyStatusReport getApiKeyStatusReport
} from './task-manager/models.js'; } from './task-manager/models.js';
import { findProjectRoot } from './utils.js'; import { findProjectRoot } from './utils.js';
import {
isValidTaskStatus,
TASK_STATUS_OPTIONS
} from '../../src/constants/task-status.js';
import { getTaskMasterVersion } from '../../src/utils/getVersion.js';
/** /**
* Runs the interactive setup process for model configuration. * Runs the interactive setup process for model configuration.
* @param {string|null} projectRoot - The resolved project root directory. * @param {string|null} projectRoot - The resolved project root directory.
@@ -491,6 +485,11 @@ function registerCommands(programInstance) {
process.exit(1); process.exit(1);
}); });
// Default help
programInstance.on('--help', function () {
displayHelp();
});
// parse-prd command // parse-prd command
programInstance programInstance
.command('parse-prd') .command('parse-prd')
@@ -515,111 +514,80 @@ function registerCommands(programInstance) {
const outputPath = options.output; const outputPath = options.output;
const force = options.force || false; const force = options.force || false;
const append = options.append || false; const append = options.append || false;
let useForce = force;
let useAppend = append;
// Helper function to check if tasks.json exists and confirm overwrite // Helper function to check if tasks.json exists and confirm overwrite
async function confirmOverwriteIfNeeded() { async function confirmOverwriteIfNeeded() {
if (fs.existsSync(outputPath) && !useForce && !useAppend) { if (fs.existsSync(outputPath) && !force && !append) {
const overwrite = await confirmTaskOverwrite(outputPath); const shouldContinue = await confirmTaskOverwrite(outputPath);
if (!overwrite) { if (!shouldContinue) {
log('info', 'Operation cancelled.'); console.log(chalk.yellow('Operation cancelled by user.'));
return false; return false;
} }
// If user confirms 'y', we should set useForce = true for the parsePRD call
// Only overwrite if not appending
useForce = true;
} }
return true; return true;
} }
let spinner; // If no input file specified, check for default PRD location
if (!inputFile) {
if (fs.existsSync(defaultPrdPath)) {
console.log(chalk.blue(`Using default PRD file: ${defaultPrdPath}`));
try { // Check for existing tasks.json before proceeding
if (!inputFile) { if (!(await confirmOverwriteIfNeeded())) return;
if (fs.existsSync(defaultPrdPath)) {
console.log(
chalk.blue(`Using default PRD file path: ${defaultPrdPath}`)
);
if (!(await confirmOverwriteIfNeeded())) return;
console.log(chalk.blue(`Generating ${numTasks} tasks...`)); console.log(chalk.blue(`Generating ${numTasks} tasks...`));
spinner = ora('Parsing PRD and generating tasks...\n').start(); await parsePRD(defaultPrdPath, outputPath, numTasks, { append });
await parsePRD(defaultPrdPath, outputPath, numTasks, {
append: useAppend, // Changed key from useAppend to append
force: useForce // Changed key from useForce to force
});
spinner.succeed('Tasks generated successfully!');
return;
}
console.log(
chalk.yellow(
'No PRD file specified and default PRD file not found at scripts/prd.txt.'
)
);
console.log(
boxen(
chalk.white.bold('Parse PRD Help') +
'\n\n' +
chalk.cyan('Usage:') +
'\n' +
` task-master parse-prd <prd-file.txt> [options]\n\n` +
chalk.cyan('Options:') +
'\n' +
' -i, --input <file> Path to the PRD file (alternative to positional argument)\n' +
' -o, --output <file> Output file path (default: "tasks/tasks.json")\n' +
' -n, --num-tasks <number> Number of tasks to generate (default: 10)\n' +
' -f, --force Skip confirmation when overwriting existing tasks\n' +
' --append Append new tasks to existing tasks.json instead of overwriting\n\n' +
chalk.cyan('Example:') +
'\n' +
' task-master parse-prd requirements.txt --num-tasks 15\n' +
' task-master parse-prd --input=requirements.txt\n' +
' task-master parse-prd --force\n' +
' task-master parse-prd requirements_v2.txt --append\n\n' +
chalk.yellow('Note: This command will:') +
'\n' +
' 1. Look for a PRD file at scripts/prd.txt by default\n' +
' 2. Use the file specified by --input or positional argument if provided\n' +
' 3. Generate tasks from the PRD and either:\n' +
' - Overwrite any existing tasks.json file (default)\n' +
' - Append to existing tasks.json if --append is used',
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
)
);
return; return;
} }
if (!fs.existsSync(inputFile)) { console.log(
console.error( chalk.yellow(
chalk.red(`Error: Input PRD file not found: ${inputFile}`) 'No PRD file specified and default PRD file not found at scripts/prd.txt.'
); )
process.exit(1); );
} console.log(
boxen(
if (!(await confirmOverwriteIfNeeded())) return; chalk.white.bold('Parse PRD Help') +
'\n\n' +
console.log(chalk.blue(`Parsing PRD file: ${inputFile}`)); chalk.cyan('Usage:') +
console.log(chalk.blue(`Generating ${numTasks} tasks...`)); '\n' +
if (append) { ` task-master parse-prd <prd-file.txt> [options]\n\n` +
console.log(chalk.blue('Appending to existing tasks...')); chalk.cyan('Options:') +
} '\n' +
' -i, --input <file> Path to the PRD file (alternative to positional argument)\n' +
spinner = ora('Parsing PRD and generating tasks...\n').start(); ' -o, --output <file> Output file path (default: "tasks/tasks.json")\n' +
await parsePRD(inputFile, outputPath, numTasks, { ' -n, --num-tasks <number> Number of tasks to generate (default: 10)\n' +
useAppend: useAppend, ' -f, --force Skip confirmation when overwriting existing tasks\n' +
useForce: useForce ' --append Append new tasks to existing tasks.json instead of overwriting\n\n' +
}); chalk.cyan('Example:') +
spinner.succeed('Tasks generated successfully!'); '\n' +
} catch (error) { ' task-master parse-prd requirements.txt --num-tasks 15\n' +
if (spinner) { ' task-master parse-prd --input=requirements.txt\n' +
spinner.fail(`Error parsing PRD: ${error.message}`); ' task-master parse-prd --force\n' +
} else { ' task-master parse-prd requirements_v2.txt --append\n\n' +
console.error(chalk.red(`Error parsing PRD: ${error.message}`)); chalk.yellow('Note: This command will:') +
} '\n' +
process.exit(1); ' 1. Look for a PRD file at scripts/prd.txt by default\n' +
' 2. Use the file specified by --input or positional argument if provided\n' +
' 3. Generate tasks from the PRD and either:\n' +
' - Overwrite any existing tasks.json file (default)\n' +
' - Append to existing tasks.json if --append is used',
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
)
);
return;
} }
// Check for existing tasks.json before proceeding with specified input file
if (!(await confirmOverwriteIfNeeded())) return;
console.log(chalk.blue(`Parsing PRD file: ${inputFile}`));
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
if (append) {
console.log(chalk.blue('Appending to existing tasks...'));
}
await parsePRD(inputFile, outputPath, numTasks, { append });
}); });
// update command // update command
@@ -1038,7 +1006,7 @@ function registerCommands(programInstance) {
) )
.option( .option(
'-s, --status <status>', '-s, --status <status>',
`New status (one of: ${TASK_STATUS_OPTIONS.join(', ')})` 'New status (todo, in-progress, review, done)'
) )
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json') .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => { .action(async (options) => {
@@ -1051,16 +1019,6 @@ function registerCommands(programInstance) {
process.exit(1); process.exit(1);
} }
if (!isValidTaskStatus(status)) {
console.error(
chalk.red(
`Error: Invalid status value: ${status}. Use one of: ${TASK_STATUS_OPTIONS.join(', ')}`
)
);
process.exit(1);
}
console.log( console.log(
chalk.blue(`Setting status of task(s) ${taskId} to: ${status}`) chalk.blue(`Setting status of task(s) ${taskId} to: ${status}`)
); );
@@ -1073,16 +1031,10 @@ function registerCommands(programInstance) {
.command('list') .command('list')
.description('List all tasks') .description('List all tasks')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json') .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.option('-s, --status <status>', 'Filter by status') .option('-s, --status <status>', 'Filter by status')
.option('--with-subtasks', 'Show subtasks for each task') .option('--with-subtasks', 'Show subtasks for each task')
.action(async (options) => { .action(async (options) => {
const tasksPath = options.file; const tasksPath = options.file;
const reportPath = options.report;
const statusFilter = options.status; const statusFilter = options.status;
const withSubtasks = options.withSubtasks || false; const withSubtasks = options.withSubtasks || false;
@@ -1094,7 +1046,7 @@ function registerCommands(programInstance) {
console.log(chalk.blue('Including subtasks in listing')); console.log(chalk.blue('Including subtasks in listing'));
} }
await listTasks(tasksPath, statusFilter, reportPath, withSubtasks); await listTasks(tasksPath, statusFilter, withSubtasks);
}); });
// expand command // expand command
@@ -1144,6 +1096,12 @@ function registerCommands(programInstance) {
{} // Pass empty context for CLI calls {} // Pass empty context for CLI calls
// outputFormat defaults to 'text' in expandAllTasks for CLI // outputFormat defaults to 'text' in expandAllTasks for CLI
); );
// Optional: Display summary from result
console.log(chalk.green(`Expansion Summary:`));
console.log(chalk.green(` - Attempted: ${result.tasksToExpand}`));
console.log(chalk.green(` - Expanded: ${result.expandedCount}`));
console.log(chalk.yellow(` - Skipped: ${result.skippedCount}`));
console.log(chalk.red(` - Failed: ${result.failedCount}`));
} catch (error) { } catch (error) {
console.error( console.error(
chalk.red(`Error expanding all tasks: ${error.message}`) chalk.red(`Error expanding all tasks: ${error.message}`)
@@ -1273,7 +1231,7 @@ function registerCommands(programInstance) {
// add-task command // add-task command
programInstance programInstance
.command('add-task') .command('add-task')
.description('Add a new task using AI, optionally providing manual details') .description('Add a new task using AI or manual input')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json') .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option( .option(
'-p, --prompt <prompt>', '-p, --prompt <prompt>',
@@ -1288,6 +1246,10 @@ function registerCommands(programInstance) {
'--details <details>', '--details <details>',
'Implementation details (for manual task creation)' 'Implementation details (for manual task creation)'
) )
.option(
'--test-strategy <testStrategy>',
'Test strategy (for manual task creation)'
)
.option( .option(
'--dependencies <dependencies>', '--dependencies <dependencies>',
'Comma-separated list of task IDs this task depends on' 'Comma-separated list of task IDs this task depends on'
@@ -1314,70 +1276,74 @@ function registerCommands(programInstance) {
process.exit(1); process.exit(1);
} }
const tasksPath =
options.file ||
path.join(findProjectRoot() || '.', 'tasks', 'tasks.json') || // Ensure tasksPath is also relative to a found root or current dir
'tasks/tasks.json';
// Correctly determine projectRoot
const projectRoot = findProjectRoot();
let manualTaskData = null;
if (isManualCreation) {
manualTaskData = {
title: options.title,
description: options.description,
details: options.details || '',
testStrategy: options.testStrategy || ''
};
// Restore specific logging for manual creation
console.log(
chalk.blue(`Creating task manually with title: "${options.title}"`)
);
} else {
// Restore specific logging for AI creation
console.log(
chalk.blue(`Creating task with AI using prompt: "${options.prompt}"`)
);
}
// Log dependencies and priority if provided (restored)
const dependenciesArray = options.dependencies
? options.dependencies.split(',').map((id) => id.trim())
: [];
if (dependenciesArray.length > 0) {
console.log(
chalk.blue(`Dependencies: [${dependenciesArray.join(', ')}]`)
);
}
if (options.priority) {
console.log(chalk.blue(`Priority: ${options.priority}`));
}
const context = {
projectRoot,
commandName: 'add-task',
outputType: 'cli'
};
try { try {
const { newTaskId, telemetryData } = await addTask( // Prepare dependencies if provided
tasksPath, let dependencies = [];
options.prompt, if (options.dependencies) {
dependenciesArray, dependencies = options.dependencies
.split(',')
.map((id) => parseInt(id.trim(), 10));
}
// Create manual task data if title and description are provided
let manualTaskData = null;
if (isManualCreation) {
manualTaskData = {
title: options.title,
description: options.description,
details: options.details || '',
testStrategy: options.testStrategy || ''
};
console.log(
chalk.blue(`Creating task manually with title: "${options.title}"`)
);
if (dependencies.length > 0) {
console.log(
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
);
}
if (options.priority) {
console.log(chalk.blue(`Priority: ${options.priority}`));
}
} else {
console.log(
chalk.blue(
`Creating task with AI using prompt: "${options.prompt}"`
)
);
if (dependencies.length > 0) {
console.log(
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
);
}
if (options.priority) {
console.log(chalk.blue(`Priority: ${options.priority}`));
}
}
// Pass mcpLog and session for MCP mode
const newTaskId = await addTask(
options.file,
options.prompt, // Pass prompt (will be null/undefined if not provided)
dependencies,
options.priority, options.priority,
context, {
'text', // For CLI, session context isn't directly available like MCP
manualTaskData, // We don't need to pass session here for CLI API key resolution
options.research // as dotenv loads .env, and utils.resolveEnvVariable checks process.env
},
'text', // outputFormat
manualTaskData, // Pass the potentially created manualTaskData object
options.research || false // Pass the research flag value
); );
// addTask handles detailed CLI success logging AND telemetry display when outputFormat is 'text' console.log(chalk.green(`✓ Added new task #${newTaskId}`));
// No need to call displayAiUsageSummary here anymore. console.log(chalk.gray('Next: Complete this task or add more tasks'));
} catch (error) { } catch (error) {
console.error(chalk.red(`Error adding task: ${error.message}`)); console.error(chalk.red(`Error adding task: ${error.message}`));
if (error.details) { if (error.stack && getDebugFlag()) {
console.error(chalk.red(error.details)); console.error(error.stack);
} }
process.exit(1); process.exit(1);
} }
@@ -1390,15 +1356,9 @@ function registerCommands(programInstance) {
`Show the next task to work on based on dependencies and status${chalk.reset('')}` `Show the next task to work on based on dependencies and status${chalk.reset('')}`
) )
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json') .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.action(async (options) => { .action(async (options) => {
const tasksPath = options.file; const tasksPath = options.file;
const reportPath = options.report; await displayNextTask(tasksPath);
await displayNextTask(tasksPath, reportPath);
}); });
// show command // show command
@@ -1411,11 +1371,6 @@ function registerCommands(programInstance) {
.option('-i, --id <id>', 'Task ID to show') .option('-i, --id <id>', 'Task ID to show')
.option('-s, --status <status>', 'Filter subtasks by status') // ADDED status option .option('-s, --status <status>', 'Filter subtasks by status') // ADDED status option
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json') .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.action(async (taskId, options) => { .action(async (taskId, options) => {
const idArg = taskId || options.id; const idArg = taskId || options.id;
const statusFilter = options.status; // ADDED: Capture status filter const statusFilter = options.status; // ADDED: Capture status filter
@@ -1426,9 +1381,8 @@ function registerCommands(programInstance) {
} }
const tasksPath = options.file; const tasksPath = options.file;
const reportPath = options.report;
// PASS statusFilter to the display function // PASS statusFilter to the display function
await displayTaskById(tasksPath, idArg, reportPath, statusFilter); await displayTaskById(tasksPath, idArg, statusFilter);
}); });
// add-dependency command // add-dependency command
@@ -1677,7 +1631,6 @@ function registerCommands(programInstance) {
} }
} catch (error) { } catch (error) {
console.error(chalk.red(`Error: ${error.message}`)); console.error(chalk.red(`Error: ${error.message}`));
showAddSubtaskHelp();
process.exit(1); process.exit(1);
} }
}) })
@@ -2084,7 +2037,7 @@ function registerCommands(programInstance) {
); );
// Exit with error if any removals failed // Exit with error if any removals failed
if (result.removedTasks.length === 0) { if (successfulRemovals.length === 0) {
process.exit(1); process.exit(1);
} }
} }
@@ -2381,7 +2334,14 @@ function setupCLI() {
return 'unknown'; // Default fallback if package.json fails return 'unknown'; // Default fallback if package.json fails
}) })
.helpOption('-h, --help', 'Display help') .helpOption('-h, --help', 'Display help')
.addHelpCommand(false); // Disable default help command .addHelpCommand(false) // Disable default help command
.on('--help', () => {
displayHelp(); // Use your custom help display instead
})
.on('-h', () => {
displayHelp();
process.exit(0);
});
// Modify the help option to use your custom display // Modify the help option to use your custom display
programInstance.helpInformation = () => { programInstance.helpInformation = () => {
@@ -2401,7 +2361,28 @@ function setupCLI() {
*/ */
async function checkForUpdate() { async function checkForUpdate() {
// Get current version from package.json ONLY // Get current version from package.json ONLY
const currentVersion = getTaskMasterVersion(); let currentVersion = 'unknown'; // Initialize with a default
try {
// Try to get the version from the installed package (if applicable) or current dir
let packageJsonPath = path.join(
process.cwd(),
'node_modules',
'task-master-ai',
'package.json'
);
// Fallback to current directory package.json if not found in node_modules
if (!fs.existsSync(packageJsonPath)) {
packageJsonPath = path.join(process.cwd(), 'package.json');
}
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
currentVersion = packageJson.version;
}
} catch (error) {
// Silently fail and use default
log('debug', `Error reading current package version: ${error.message}`);
}
return new Promise((resolve) => { return new Promise((resolve) => {
// Get the latest version from npm registry // Get the latest version from npm registry

View File

@@ -345,12 +345,6 @@ function getDefaultSubtasks(explicitRoot = null) {
return isNaN(parsedVal) ? DEFAULTS.global.defaultSubtasks : parsedVal; return isNaN(parsedVal) ? DEFAULTS.global.defaultSubtasks : parsedVal;
} }
function getDefaultNumTasks(explicitRoot = null) {
const val = getGlobalConfig(explicitRoot).defaultNumTasks;
const parsedVal = parseInt(val, 10);
return isNaN(parsedVal) ? DEFAULTS.global.defaultNumTasks : parsedVal;
}
function getDefaultPriority(explicitRoot = null) { function getDefaultPriority(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getGlobalConfig(explicitRoot).defaultPriority; return getGlobalConfig(explicitRoot).defaultPriority;
@@ -430,13 +424,12 @@ function getParametersForRole(role, explicitRoot = null) {
/** /**
* Checks if the API key for a given provider is set in the environment. * Checks if the API key for a given provider is set in the environment.
* Checks process.env first, then session.env if session is provided, then .env file if projectRoot provided. * Checks process.env first, then session.env if session is provided.
* @param {string} providerName - The name of the provider (e.g., 'openai', 'anthropic'). * @param {string} providerName - The name of the provider (e.g., 'openai', 'anthropic').
* @param {object|null} [session=null] - The MCP session object (optional). * @param {object|null} [session=null] - The MCP session object (optional).
* @param {string|null} [projectRoot=null] - The project root directory (optional, for .env file check).
* @returns {boolean} True if the API key is set, false otherwise. * @returns {boolean} True if the API key is set, false otherwise.
*/ */
function isApiKeySet(providerName, session = null, projectRoot = null) { function isApiKeySet(providerName, session = null) {
// Define the expected environment variable name for each provider // Define the expected environment variable name for each provider
if (providerName?.toLowerCase() === 'ollama') { if (providerName?.toLowerCase() === 'ollama') {
return true; // Indicate key status is effectively "OK" return true; // Indicate key status is effectively "OK"
@@ -461,7 +454,7 @@ function isApiKeySet(providerName, session = null, projectRoot = null) {
} }
const envVarName = keyMap[providerKey]; const envVarName = keyMap[providerKey];
const apiKeyValue = resolveEnvVariable(envVarName, session, projectRoot); const apiKeyValue = resolveEnvVariable(envVarName, session);
// Check if the key exists, is not empty, and is not a placeholder // Check if the key exists, is not empty, and is not a placeholder
return ( return (
@@ -669,34 +662,6 @@ function isConfigFilePresent(explicitRoot = null) {
return fs.existsSync(configPath); return fs.existsSync(configPath);
} }
/**
* Gets the user ID from the configuration.
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The user ID or null if not found.
*/
function getUserId(explicitRoot = null) {
const config = getConfig(explicitRoot);
if (!config.global) {
config.global = {}; // Ensure global object exists
}
if (!config.global.userId) {
config.global.userId = '1234567890';
// Attempt to write the updated config.
// It's important that writeConfig correctly resolves the path
// using explicitRoot, similar to how getConfig does.
const success = writeConfig(config, explicitRoot);
if (!success) {
// Log an error or handle the failure to write,
// though for now, we'll proceed with the in-memory default.
log(
'warning',
'Failed to write updated configuration with new userId. Please let the developers know.'
);
}
}
return config.global.userId;
}
/** /**
* Gets a list of all provider names defined in the MODEL_MAP. * Gets a list of all provider names defined in the MODEL_MAP.
* @returns {string[]} An array of provider names. * @returns {string[]} An array of provider names.
@@ -705,19 +670,12 @@ function getAllProviders() {
return Object.keys(MODEL_MAP || {}); return Object.keys(MODEL_MAP || {});
} }
function getBaseUrlForRole(role, explicitRoot = null) {
const roleConfig = getModelConfigForRole(role, explicitRoot);
return roleConfig && typeof roleConfig.baseUrl === 'string'
? roleConfig.baseUrl
: undefined;
}
export { export {
// Core config access // Core config access
getConfig, getConfig,
writeConfig, writeConfig,
ConfigurationError, ConfigurationError, // Export custom error type
isConfigFilePresent, isConfigFilePresent, // Add the new function export
// Validation // Validation
validateProvider, validateProvider,
@@ -739,18 +697,16 @@ export {
getFallbackModelId, getFallbackModelId,
getFallbackMaxTokens, getFallbackMaxTokens,
getFallbackTemperature, getFallbackTemperature,
getBaseUrlForRole,
// Global setting getters (No env var overrides) // Global setting getters (No env var overrides)
getLogLevel, getLogLevel,
getDebugFlag, getDebugFlag,
getDefaultNumTasks,
getDefaultSubtasks, getDefaultSubtasks,
getDefaultPriority, getDefaultPriority,
getProjectName, getProjectName,
getOllamaBaseUrl, getOllamaBaseUrl,
getParametersForRole, getParametersForRole,
getUserId,
// API Key Checkers (still relevant) // API Key Checkers (still relevant)
isApiKeySet, isApiKeySet,
getMcpApiKeyStatus, getMcpApiKeyStatus,

View File

@@ -195,7 +195,7 @@ async function addDependency(tasksPath, taskId, dependencyId) {
} }
// Generate updated task files // Generate updated task files
await generateTaskFiles(tasksPath, path.dirname(tasksPath)); await generateTaskFiles(tasksPath, 'tasks');
log('info', 'Task files regenerated with updated dependencies.'); log('info', 'Task files regenerated with updated dependencies.');
} else { } else {
@@ -334,7 +334,7 @@ async function removeDependency(tasksPath, taskId, dependencyId) {
} }
// Regenerate task files // Regenerate task files
await generateTaskFiles(tasksPath, path.dirname(tasksPath)); await generateTaskFiles(tasksPath, 'tasks');
} }
/** /**

View File

@@ -13,6 +13,20 @@
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 }, "cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 64000 "max_tokens": 64000
},
{
"id": "claude-3-5-haiku-20241022",
"swe_score": 0.406,
"cost_per_1m_tokens": { "input": 0.8, "output": 4.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000
},
{
"id": "claude-3-opus-20240229",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 15, "output": 75 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000
} }
], ],
"openai": [ "openai": [
@@ -27,7 +41,7 @@
"id": "o1", "id": "o1",
"swe_score": 0.489, "swe_score": 0.489,
"cost_per_1m_tokens": { "input": 15.0, "output": 60.0 }, "cost_per_1m_tokens": { "input": 15.0, "output": 60.0 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "o3", "id": "o3",
@@ -39,7 +53,7 @@
"id": "o3-mini", "id": "o3-mini",
"swe_score": 0.493, "swe_score": 0.493,
"cost_per_1m_tokens": { "input": 1.1, "output": 4.4 }, "cost_per_1m_tokens": { "input": 1.1, "output": 4.4 },
"allowed_roles": ["main"], "allowed_roles": ["main", "fallback"],
"max_tokens": 100000 "max_tokens": 100000
}, },
{ {
@@ -52,86 +66,81 @@
"id": "o1-mini", "id": "o1-mini",
"swe_score": 0.4, "swe_score": 0.4,
"cost_per_1m_tokens": { "input": 1.1, "output": 4.4 }, "cost_per_1m_tokens": { "input": 1.1, "output": 4.4 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "o1-pro", "id": "o1-pro",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 150.0, "output": 600.0 }, "cost_per_1m_tokens": { "input": 150.0, "output": 600.0 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gpt-4-5-preview", "id": "gpt-4-5-preview",
"swe_score": 0.38, "swe_score": 0.38,
"cost_per_1m_tokens": { "input": 75.0, "output": 150.0 }, "cost_per_1m_tokens": { "input": 75.0, "output": 150.0 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gpt-4-1-mini", "id": "gpt-4-1-mini",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.4, "output": 1.6 }, "cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gpt-4-1-nano", "id": "gpt-4-1-nano",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 }, "cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gpt-4o-mini", "id": "gpt-4o-mini",
"swe_score": 0.3, "swe_score": 0.3,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 }, "cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gpt-4o-search-preview", "id": "gpt-4o-search-preview",
"swe_score": 0.33, "swe_score": 0.33,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 }, "cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["research"] "allowed_roles": ["main", "fallback", "research"]
}, },
{ {
"id": "gpt-4o-mini-search-preview", "id": "gpt-4o-mini-search-preview",
"swe_score": 0.3, "swe_score": 0.3,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 }, "cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["research"] "allowed_roles": ["main", "fallback", "research"]
} }
], ],
"google": [ "google": [
{ {
"id": "gemini-2.5-pro-preview-05-06", "id": "gemini-2.5-pro-exp-03-25",
"swe_score": 0.638, "swe_score": 0.638,
"cost_per_1m_tokens": null, "cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"]
"max_tokens": 1048000
},
{
"id": "gemini-2.5-pro-preview-03-25",
"swe_score": 0.638,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
}, },
{ {
"id": "gemini-2.5-flash-preview-04-17", "id": "gemini-2.5-flash-preview-04-17",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": null, "cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"]
"max_tokens": 1048000
}, },
{ {
"id": "gemini-2.0-flash", "id": "gemini-2.0-flash",
"swe_score": 0.754, "swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 }, "cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"]
"max_tokens": 1048000
}, },
{ {
"id": "gemini-2.0-flash-lite", "id": "gemini-2.0-flash-thinking-experimental",
"swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "gemini-2.0-pro",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": null, "cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"]
"max_tokens": 1048000
} }
], ],
"perplexity": [ "perplexity": [
@@ -180,6 +189,14 @@
"allowed_roles": ["main", "fallback", "research"], "allowed_roles": ["main", "fallback", "research"],
"max_tokens": 131072 "max_tokens": 131072
}, },
{
"id": "grok-3-mini",
"name": "Grok 3 Mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.3, "output": 0.5 },
"allowed_roles": ["main", "fallback", "research"],
"max_tokens": 131072
},
{ {
"id": "grok-3-fast", "id": "grok-3-fast",
"name": "Grok 3 Fast", "name": "Grok 3 Fast",
@@ -187,6 +204,13 @@
"cost_per_1m_tokens": { "input": 5, "output": 25 }, "cost_per_1m_tokens": { "input": 5, "output": 25 },
"allowed_roles": ["main", "fallback", "research"], "allowed_roles": ["main", "fallback", "research"],
"max_tokens": 131072 "max_tokens": 131072
},
{
"id": "grok-3-mini-fast",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.6, "output": 4 },
"allowed_roles": ["main", "fallback", "research"],
"max_tokens": 131072
} }
], ],
"ollama": [ "ollama": [
@@ -259,7 +283,7 @@
"id": "deepseek/deepseek-chat-v3-0324", "id": "deepseek/deepseek-chat-v3-0324",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.27, "output": 1.1 }, "cost_per_1m_tokens": { "input": 0.27, "output": 1.1 },
"allowed_roles": ["main"], "allowed_roles": ["main", "fallback"],
"max_tokens": 64000 "max_tokens": 64000
}, },
{ {
@@ -288,14 +312,14 @@
"id": "google/gemini-2.5-flash-preview", "id": "google/gemini-2.5-flash-preview",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 }, "cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main"], "allowed_roles": ["main", "fallback"],
"max_tokens": 65535 "max_tokens": 65535
}, },
{ {
"id": "google/gemini-2.5-flash-preview:thinking", "id": "google/gemini-2.5-flash-preview:thinking",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 }, "cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main"], "allowed_roles": ["main", "fallback"],
"max_tokens": 65535 "max_tokens": 65535
}, },
{ {

View File

@@ -23,7 +23,7 @@ import updateSubtaskById from './task-manager/update-subtask-by-id.js';
import removeTask from './task-manager/remove-task.js'; import removeTask from './task-manager/remove-task.js';
import taskExists from './task-manager/task-exists.js'; import taskExists from './task-manager/task-exists.js';
import isTaskDependentOn from './task-manager/is-task-dependent.js'; import isTaskDependentOn from './task-manager/is-task-dependent.js';
import { readComplexityReport } from './utils.js';
// Export task manager functions // Export task manager functions
export { export {
parsePRD, parsePRD,
@@ -45,6 +45,5 @@ export {
removeTask, removeTask,
findTaskById, findTaskById,
taskExists, taskExists,
isTaskDependentOn, isTaskDependentOn
readComplexityReport
}; };

View File

@@ -8,10 +8,9 @@ import {
displayBanner, displayBanner,
getStatusWithColor, getStatusWithColor,
startLoadingIndicator, startLoadingIndicator,
stopLoadingIndicator, stopLoadingIndicator
displayAiUsageSummary
} from '../ui.js'; } from '../ui.js';
import { readJSON, writeJSON, log as consoleLog, truncate } from '../utils.js'; import { log, readJSON, writeJSON, truncate } from '../utils.js';
import { generateObjectService } from '../ai-services-unified.js'; import { generateObjectService } from '../ai-services-unified.js';
import { getDefaultPriority } from '../config-manager.js'; import { getDefaultPriority } from '../config-manager.js';
import generateTaskFiles from './generate-task-files.js'; import generateTaskFiles from './generate-task-files.js';
@@ -43,56 +42,45 @@ const AiTaskDataSchema = z.object({
* @param {Object} customEnv - Custom environment variables (optional) - Note: AI params override deprecated * @param {Object} customEnv - Custom environment variables (optional) - Note: AI params override deprecated
* @param {Object} manualTaskData - Manual task data (optional, for direct task creation without AI) * @param {Object} manualTaskData - Manual task data (optional, for direct task creation without AI)
* @param {boolean} useResearch - Whether to use the research model (passed to unified service) * @param {boolean} useResearch - Whether to use the research model (passed to unified service)
* @param {Object} context - Context object containing session and potentially projectRoot * @returns {number} The new task ID
* @param {string} [context.projectRoot] - Project root path (for MCP/env fallback)
* @param {string} [context.commandName] - The name of the command being executed (for telemetry)
* @param {string} [context.outputType] - The output type ('cli' or 'mcp', for telemetry)
* @returns {Promise<object>} An object containing newTaskId and telemetryData
*/ */
async function addTask( async function addTask(
tasksPath, tasksPath,
prompt, prompt,
dependencies = [], dependencies = [],
priority = null, priority = getDefaultPriority(), // Keep getter for default priority
context = {}, { reportProgress, mcpLog, session } = {},
outputFormat = 'text', // Default to text for CLI outputFormat = 'text',
// customEnv = null, // Removed as AI param overrides are deprecated
manualTaskData = null, manualTaskData = null,
useResearch = false useResearch = false // <-- Add useResearch parameter
) { ) {
const { session, mcpLog, projectRoot, commandName, outputType } = context;
const isMCP = !!mcpLog;
// Create a consistent logFn object regardless of context
const logFn = isMCP
? mcpLog // Use MCP logger if provided
: {
// Create a wrapper around consoleLog for CLI
info: (...args) => consoleLog('info', ...args),
warn: (...args) => consoleLog('warn', ...args),
error: (...args) => consoleLog('error', ...args),
debug: (...args) => consoleLog('debug', ...args),
success: (...args) => consoleLog('success', ...args)
};
const effectivePriority = priority || getDefaultPriority(projectRoot);
logFn.info(
`Adding new task with prompt: "${prompt}", Priority: ${effectivePriority}, Dependencies: ${dependencies.join(', ') || 'None'}, Research: ${useResearch}, ProjectRoot: ${projectRoot}`
);
let loadingIndicator = null; let loadingIndicator = null;
let aiServiceResponse = null; // To store the full response from AI service
// Create custom reporter that checks for MCP log // Create custom reporter that checks for MCP log
const report = (message, level = 'info') => { const report = (message, level = 'info') => {
if (mcpLog) { if (mcpLog) {
mcpLog[level](message); mcpLog[level](message);
} else if (outputFormat === 'text') { } else if (outputFormat === 'text') {
consoleLog(level, message); log(level, message);
} }
}; };
try { try {
// Only display banner and UI elements for text output (CLI)
if (outputFormat === 'text') {
displayBanner();
console.log(
boxen(chalk.white.bold(`Creating New Task`), {
padding: 1,
borderColor: 'blue',
borderStyle: 'round',
margin: { top: 1, bottom: 1 }
})
);
}
// Read the existing tasks // Read the existing tasks
const data = readJSON(tasksPath); const data = readJSON(tasksPath);
if (!data || !data.tasks) { if (!data || !data.tasks) {
@@ -159,7 +147,7 @@ async function addTask(
} else { } else {
report('DEBUG: Taking AI task generation path.', 'debug'); report('DEBUG: Taking AI task generation path.', 'debug');
// --- Refactored AI Interaction --- // --- Refactored AI Interaction ---
report(`Generating task data with AI with prompt:\n${prompt}`, 'info'); report('Generating task data with AI...', 'info');
// Create context string for task creation prompt // Create context string for task creation prompt
let contextTasks = ''; let contextTasks = '';
@@ -219,51 +207,29 @@ async function addTask(
// Start the loading indicator - only for text mode // Start the loading indicator - only for text mode
if (outputFormat === 'text') { if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator( loadingIndicator = startLoadingIndicator(
`Generating new task with ${useResearch ? 'Research' : 'Main'} AI...\n` `Generating new task with ${useResearch ? 'Research' : 'Main'} AI...`
); );
} }
try { try {
// Determine the service role based on the useResearch flag
const serviceRole = useResearch ? 'research' : 'main'; const serviceRole = useResearch ? 'research' : 'main';
report('DEBUG: Calling generateObjectService...', 'debug');
aiServiceResponse = await generateObjectService({ report('DEBUG: Calling generateObjectService...', 'debug');
// Capture the full response // Call the unified AI service
role: serviceRole, const aiGeneratedTaskData = await generateObjectService({
session: session, role: serviceRole, // <-- Use the determined role
projectRoot: projectRoot, session: session, // Pass session for API key resolution
schema: AiTaskDataSchema, schema: AiTaskDataSchema, // Pass the Zod schema
objectName: 'newTaskData', objectName: 'newTaskData', // Name for the object
systemPrompt: systemPrompt, systemPrompt: systemPrompt,
prompt: userPrompt, prompt: userPrompt,
commandName: commandName || 'add-task', // Use passed commandName or default reportProgress // Pass progress reporter if available
outputType: outputType || (isMCP ? 'mcp' : 'cli') // Use passed outputType or derive
}); });
report('DEBUG: generateObjectService returned successfully.', 'debug'); report('DEBUG: generateObjectService returned successfully.', 'debug');
if (!aiServiceResponse || !aiServiceResponse.mainResult) {
throw new Error(
'AI service did not return the expected object structure.'
);
}
// Prefer mainResult if it looks like a valid task object, otherwise try mainResult.object
if (
aiServiceResponse.mainResult.title &&
aiServiceResponse.mainResult.description
) {
taskData = aiServiceResponse.mainResult;
} else if (
aiServiceResponse.mainResult.object &&
aiServiceResponse.mainResult.object.title &&
aiServiceResponse.mainResult.object.description
) {
taskData = aiServiceResponse.mainResult.object;
} else {
throw new Error('AI service did not return a valid task object.');
}
report('Successfully generated task data from AI.', 'success'); report('Successfully generated task data from AI.', 'success');
taskData = aiGeneratedTaskData; // Assign the validated object
} catch (error) { } catch (error) {
report( report(
`DEBUG: generateObjectService caught error: ${error.message}`, `DEBUG: generateObjectService caught error: ${error.message}`,
@@ -288,7 +254,7 @@ async function addTask(
testStrategy: taskData.testStrategy || '', testStrategy: taskData.testStrategy || '',
status: 'pending', status: 'pending',
dependencies: numericDependencies, // Use validated numeric dependencies dependencies: numericDependencies, // Use validated numeric dependencies
priority: effectivePriority, priority: priority,
subtasks: [] // Initialize with empty subtasks array subtasks: [] // Initialize with empty subtasks array
}; };
@@ -374,25 +340,11 @@ async function addTask(
{ padding: 1, borderColor: 'green', borderStyle: 'round' } { padding: 1, borderColor: 'green', borderStyle: 'round' }
) )
); );
// Display AI Usage Summary if telemetryData is available
if (
aiServiceResponse &&
aiServiceResponse.telemetryData &&
(outputType === 'cli' || outputType === 'text')
) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
} }
report( // Return the new task ID
`DEBUG: Returning new task ID: ${newTaskId} and telemetry.`, report(`DEBUG: Returning new task ID: ${newTaskId}`, 'debug');
'debug' return newTaskId;
);
return {
newTaskId: newTaskId,
telemetryData: aiServiceResponse ? aiServiceResponse.telemetryData : null
};
} catch (error) { } catch (error) {
// Stop any loading indicator on error // Stop any loading indicator on error
if (loadingIndicator) { if (loadingIndicator) {

View File

@@ -4,11 +4,7 @@ import readline from 'readline';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js'; import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
import { import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import { generateTextService } from '../ai-services-unified.js'; import { generateTextService } from '../ai-services-unified.js';
@@ -50,7 +46,6 @@ Do not include any explanatory text, markdown formatting, or code block markers
* @param {string} options.output - Path to report output file * @param {string} options.output - Path to report output file
* @param {string|number} [options.threshold] - Complexity threshold * @param {string|number} [options.threshold] - Complexity threshold
* @param {boolean} [options.research] - Use research role * @param {boolean} [options.research] - Use research role
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use) * @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
* @param {number} [options._originalTaskCount] - Original task count (internal use) * @param {number} [options._originalTaskCount] - Original task count (internal use)
* @param {Object} context - Context object, potentially containing session and mcpLog * @param {Object} context - Context object, potentially containing session and mcpLog
@@ -64,7 +59,6 @@ async function analyzeTaskComplexity(options, context = {}) {
const outputPath = options.output || 'scripts/task-complexity-report.json'; const outputPath = options.output || 'scripts/task-complexity-report.json';
const thresholdScore = parseFloat(options.threshold || '5'); const thresholdScore = parseFloat(options.threshold || '5');
const useResearch = options.research || false; const useResearch = options.research || false;
const projectRoot = options.projectRoot;
const outputFormat = mcpLog ? 'json' : 'text'; const outputFormat = mcpLog ? 'json' : 'text';
@@ -200,32 +194,37 @@ async function analyzeTaskComplexity(options, context = {}) {
} }
const prompt = generateInternalComplexityAnalysisPrompt(tasksData); const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
// System prompt remains simple for text generation
const systemPrompt = const systemPrompt =
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.'; 'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
let loadingIndicator = null; let loadingIndicator = null;
if (outputFormat === 'text') { if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator( loadingIndicator = startLoadingIndicator('Calling AI service...');
`${useResearch ? 'Researching' : 'Analyzing'} the complexity of your tasks with AI...\n`
);
} }
let aiServiceResponse = null; let fullResponse = ''; // To store the raw text response
let complexityAnalysis = null;
try { try {
const role = useResearch ? 'research' : 'main'; const role = useResearch ? 'research' : 'main';
reportLog(`Using AI service with role: ${role}`, 'info');
aiServiceResponse = await generateTextService({ // *** CHANGED: Use generateTextService ***
fullResponse = await generateTextService({
prompt, prompt,
systemPrompt, systemPrompt,
role, role,
session, session
projectRoot, // No schema or objectName needed
commandName: 'analyze-complexity',
outputType: mcpLog ? 'mcp' : 'cli'
}); });
// *** End Service Call Change ***
reportLog(
'Successfully received text response via AI service',
'success'
);
// --- Stop Loading Indicator (Unchanged) ---
if (loadingIndicator) { if (loadingIndicator) {
stopLoadingIndicator(loadingIndicator); stopLoadingIndicator(loadingIndicator);
loadingIndicator = null; loadingIndicator = null;
@@ -237,18 +236,26 @@ async function analyzeTaskComplexity(options, context = {}) {
chalk.green('AI service call complete. Parsing response...') chalk.green('AI service call complete. Parsing response...')
); );
} }
// --- End Stop Loading Indicator ---
// --- Re-introduce Manual JSON Parsing & Cleanup ---
reportLog(`Parsing complexity analysis from text response...`, 'info'); reportLog(`Parsing complexity analysis from text response...`, 'info');
let complexityAnalysis;
try { try {
let cleanedResponse = aiServiceResponse.mainResult; let cleanedResponse = fullResponse;
// Basic trim first
cleanedResponse = cleanedResponse.trim(); cleanedResponse = cleanedResponse.trim();
// Remove potential markdown code block fences
const codeBlockMatch = cleanedResponse.match( const codeBlockMatch = cleanedResponse.match(
/```(?:json)?\s*([\s\S]*?)\s*```/ /```(?:json)?\s*([\s\S]*?)\s*```/
); );
if (codeBlockMatch) { if (codeBlockMatch) {
cleanedResponse = codeBlockMatch[1].trim(); cleanedResponse = codeBlockMatch[1].trim(); // Trim content inside block
reportLog('Extracted JSON from code block', 'info');
} else { } else {
// If no code block, ensure it starts with '[' and ends with ']'
// This is less robust but a common fallback
const firstBracket = cleanedResponse.indexOf('['); const firstBracket = cleanedResponse.indexOf('[');
const lastBracket = cleanedResponse.lastIndexOf(']'); const lastBracket = cleanedResponse.lastIndexOf(']');
if (firstBracket !== -1 && lastBracket > firstBracket) { if (firstBracket !== -1 && lastBracket > firstBracket) {
@@ -256,11 +263,13 @@ async function analyzeTaskComplexity(options, context = {}) {
firstBracket, firstBracket,
lastBracket + 1 lastBracket + 1
); );
reportLog('Extracted content between first [ and last ]', 'info');
} else { } else {
reportLog( reportLog(
'Warning: Response does not appear to be a JSON array.', 'Warning: Response does not appear to be a JSON array.',
'warn' 'warn'
); );
// Keep going, maybe JSON.parse can handle it or will fail informatively
} }
} }
@@ -274,23 +283,48 @@ async function analyzeTaskComplexity(options, context = {}) {
); );
} }
complexityAnalysis = JSON.parse(cleanedResponse); try {
} catch (parseError) { complexityAnalysis = JSON.parse(cleanedResponse);
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); } catch (jsonError) {
reportLog(
'Initial JSON parsing failed. Raw response might be malformed.',
'error'
);
reportLog(`Original JSON Error: ${jsonError.message}`, 'error');
if (outputFormat === 'text' && getDebugFlag(session)) {
console.log(chalk.red('--- Start Raw Malformed Response ---'));
console.log(chalk.gray(fullResponse));
console.log(chalk.red('--- End Raw Malformed Response ---'));
}
// Re-throw the specific JSON parsing error
throw new Error(
`Failed to parse JSON response: ${jsonError.message}`
);
}
// Ensure it's an array after parsing
if (!Array.isArray(complexityAnalysis)) {
throw new Error('Parsed response is not a valid JSON array.');
}
} catch (error) {
// Catch errors specifically from the parsing/cleanup block
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); // Ensure indicator stops
reportLog( reportLog(
`Error parsing complexity analysis JSON: ${parseError.message}`, `Error parsing complexity analysis JSON: ${error.message}`,
'error' 'error'
); );
if (outputFormat === 'text') { if (outputFormat === 'text') {
console.error( console.error(
chalk.red( chalk.red(
`Error parsing complexity analysis JSON: ${parseError.message}` `Error parsing complexity analysis JSON: ${error.message}`
) )
); );
} }
throw parseError; throw error; // Re-throw parsing error
} }
// --- End Manual JSON Parsing & Cleanup ---
// --- Post-processing (Missing Task Check) - (Unchanged) ---
const taskIds = tasksData.tasks.map((t) => t.id); const taskIds = tasksData.tasks.map((t) => t.id);
const analysisTaskIds = complexityAnalysis.map((a) => a.taskId); const analysisTaskIds = complexityAnalysis.map((a) => a.taskId);
const missingTaskIds = taskIds.filter( const missingTaskIds = taskIds.filter(
@@ -325,8 +359,10 @@ async function analyzeTaskComplexity(options, context = {}) {
} }
} }
} }
// --- End Post-processing ---
const report = { // --- Report Creation & Writing (Unchanged) ---
const finalReport = {
meta: { meta: {
generatedAt: new Date().toISOString(), generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length, tasksAnalyzed: tasksData.tasks.length,
@@ -337,13 +373,15 @@ async function analyzeTaskComplexity(options, context = {}) {
complexityAnalysis: complexityAnalysis complexityAnalysis: complexityAnalysis
}; };
reportLog(`Writing complexity report to ${outputPath}...`, 'info'); reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, report); writeJSON(outputPath, finalReport);
reportLog( reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`, `Task complexity analysis complete. Report written to ${outputPath}`,
'success' 'success'
); );
// --- End Report Creation & Writing ---
// --- Display CLI Summary (Unchanged) ---
if (outputFormat === 'text') { if (outputFormat === 'text') {
console.log( console.log(
chalk.green( chalk.green(
@@ -397,28 +435,23 @@ async function analyzeTaskComplexity(options, context = {}) {
if (getDebugFlag(session)) { if (getDebugFlag(session)) {
console.debug( console.debug(
chalk.gray( chalk.gray(
`Final analysis object: ${JSON.stringify(report, null, 2)}` `Final analysis object: ${JSON.stringify(finalReport, null, 2)}`
) )
); );
} }
if (aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
} }
// --- End Display CLI Summary ---
return { return finalReport;
report: report, } catch (error) {
telemetryData: aiServiceResponse?.telemetryData // Catches errors from generateTextService call
};
} catch (aiError) {
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
reportLog(`Error during AI service call: ${aiError.message}`, 'error'); reportLog(`Error during AI service call: ${error.message}`, 'error');
if (outputFormat === 'text') { if (outputFormat === 'text') {
console.error( console.error(
chalk.red(`Error during AI service call: ${aiError.message}`) chalk.red(`Error during AI service call: ${error.message}`)
); );
if (aiError.message.includes('API key')) { if (error.message.includes('API key')) {
console.log( console.log(
chalk.yellow( chalk.yellow(
'\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env' '\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env'
@@ -429,9 +462,10 @@ async function analyzeTaskComplexity(options, context = {}) {
); );
} }
} }
throw aiError; throw error; // Re-throw AI service error
} }
} catch (error) { } catch (error) {
// Catches general errors (file read, etc.)
reportLog(`Error analyzing task complexity: ${error.message}`, 'error'); reportLog(`Error analyzing task complexity: ${error.message}`, 'error');
if (outputFormat === 'text') { if (outputFormat === 'text') {
console.error( console.error(

View File

@@ -3,7 +3,7 @@ import chalk from 'chalk';
import boxen from 'boxen'; import boxen from 'boxen';
import Table from 'cli-table3'; import Table from 'cli-table3';
import { log, readJSON, writeJSON, truncate, isSilentMode } from '../utils.js'; import { log, readJSON, writeJSON, truncate } from '../utils.js';
import { displayBanner } from '../ui.js'; import { displayBanner } from '../ui.js';
import generateTaskFiles from './generate-task-files.js'; import generateTaskFiles from './generate-task-files.js';
@@ -22,16 +22,14 @@ function clearSubtasks(tasksPath, taskIds) {
process.exit(1); process.exit(1);
} }
if (!isSilentMode()) { console.log(
console.log( boxen(chalk.white.bold('Clearing Subtasks'), {
boxen(chalk.white.bold('Clearing Subtasks'), { padding: 1,
padding: 1, borderColor: 'blue',
borderColor: 'blue', borderStyle: 'round',
borderStyle: 'round', margin: { top: 1, bottom: 1 }
margin: { top: 1, bottom: 1 } })
}) );
);
}
// Handle multiple task IDs (comma-separated) // Handle multiple task IDs (comma-separated)
const taskIdArray = taskIds.split(',').map((id) => id.trim()); const taskIdArray = taskIds.split(',').map((id) => id.trim());
@@ -87,65 +85,59 @@ function clearSubtasks(tasksPath, taskIds) {
writeJSON(tasksPath, data); writeJSON(tasksPath, data);
// Show summary table // Show summary table
if (!isSilentMode()) { console.log(
console.log( boxen(chalk.white.bold('Subtask Clearing Summary:'), {
boxen(chalk.white.bold('Subtask Clearing Summary:'), { padding: { left: 2, right: 2, top: 0, bottom: 0 },
padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 },
margin: { top: 1, bottom: 0 }, borderColor: 'blue',
borderColor: 'blue', borderStyle: 'round'
borderStyle: 'round' })
}) );
); console.log(summaryTable.toString());
console.log(summaryTable.toString());
}
// Regenerate task files to reflect changes // Regenerate task files to reflect changes
log('info', 'Regenerating task files...'); log('info', 'Regenerating task files...');
generateTaskFiles(tasksPath, path.dirname(tasksPath)); generateTaskFiles(tasksPath, path.dirname(tasksPath));
// Success message // Success message
if (!isSilentMode()) { console.log(
console.log( boxen(
boxen( chalk.green(
chalk.green( `Successfully cleared subtasks from ${chalk.bold(clearedCount)} task(s)`
`Successfully cleared subtasks from ${chalk.bold(clearedCount)} task(s)` ),
), {
{
padding: 1,
borderColor: 'green',
borderStyle: 'round',
margin: { top: 1 }
}
)
);
// Next steps suggestion
console.log(
boxen(
chalk.white.bold('Next Steps:') +
'\n\n' +
`${chalk.cyan('1.')} Run ${chalk.yellow('task-master expand --id=<id>')} to generate new subtasks\n` +
`${chalk.cyan('2.')} Run ${chalk.yellow('task-master list --with-subtasks')} to verify changes`,
{
padding: 1,
borderColor: 'cyan',
borderStyle: 'round',
margin: { top: 1 }
}
)
);
}
} else {
if (!isSilentMode()) {
console.log(
boxen(chalk.yellow('No subtasks were cleared'), {
padding: 1, padding: 1,
borderColor: 'yellow', borderColor: 'green',
borderStyle: 'round', borderStyle: 'round',
margin: { top: 1 } margin: { top: 1 }
}) }
); )
} );
// Next steps suggestion
console.log(
boxen(
chalk.white.bold('Next Steps:') +
'\n\n' +
`${chalk.cyan('1.')} Run ${chalk.yellow('task-master expand --id=<id>')} to generate new subtasks\n` +
`${chalk.cyan('2.')} Run ${chalk.yellow('task-master list --with-subtasks')} to verify changes`,
{
padding: 1,
borderColor: 'cyan',
borderStyle: 'round',
margin: { top: 1 }
}
)
);
} else {
console.log(
boxen(chalk.yellow('No subtasks were cleared'), {
padding: 1,
borderColor: 'yellow',
borderStyle: 'round',
margin: { top: 1 }
})
);
} }
} }

View File

@@ -1,14 +1,7 @@
import { log, readJSON, isSilentMode } from '../utils.js'; import { log, readJSON, isSilentMode } from '../utils.js';
import { import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import expandTask from './expand-task.js'; import expandTask from './expand-task.js';
import { getDebugFlag } from '../config-manager.js'; import { getDebugFlag } from '../config-manager.js';
import { aggregateTelemetry } from '../utils.js';
import chalk from 'chalk';
import boxen from 'boxen';
/** /**
* Expand all eligible pending or in-progress tasks using the expandTask function. * Expand all eligible pending or in-progress tasks using the expandTask function.
@@ -21,7 +14,7 @@ import boxen from 'boxen';
* @param {Object} [context.session] - Session object from MCP. * @param {Object} [context.session] - Session object from MCP.
* @param {Object} [context.mcpLog] - MCP logger object. * @param {Object} [context.mcpLog] - MCP logger object.
* @param {string} [outputFormat='text'] - Output format ('text' or 'json'). MCP calls should use 'json'. * @param {string} [outputFormat='text'] - Output format ('text' or 'json'). MCP calls should use 'json'.
* @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, telemetryData: Array<Object>}>} - Result summary. * @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, message?: string}>} - Result summary.
*/ */
async function expandAllTasks( async function expandAllTasks(
tasksPath, tasksPath,
@@ -58,8 +51,8 @@ async function expandAllTasks(
let loadingIndicator = null; let loadingIndicator = null;
let expandedCount = 0; let expandedCount = 0;
let failedCount = 0; let failedCount = 0;
let tasksToExpandCount = 0; // No skipped count needed now as the filter handles it upfront
const allTelemetryData = []; // Still collect individual data first let tasksToExpandCount = 0; // Renamed for clarity
if (!isMCPCall && outputFormat === 'text') { if (!isMCPCall && outputFormat === 'text') {
loadingIndicator = startLoadingIndicator( loadingIndicator = startLoadingIndicator(
@@ -97,7 +90,6 @@ async function expandAllTasks(
failedCount: 0, failedCount: 0,
skippedCount: 0, skippedCount: 0,
tasksToExpand: 0, tasksToExpand: 0,
telemetryData: allTelemetryData,
message: 'No tasks eligible for expansion.' message: 'No tasks eligible for expansion.'
}; };
// --- End Fix --- // --- End Fix ---
@@ -105,6 +97,19 @@ async function expandAllTasks(
// Iterate over the already filtered tasks // Iterate over the already filtered tasks
for (const task of tasksToExpand) { for (const task of tasksToExpand) {
// --- Remove Redundant Check ---
// The check below is no longer needed as the initial filter handles it
/*
if (task.subtasks && task.subtasks.length > 0 && !force) {
logger.info(
`Skipping task ${task.id}: Already has subtasks. Use --force to overwrite.`
);
skippedCount++;
continue;
}
*/
// --- End Removed Redundant Check ---
// Start indicator for individual task expansion in CLI mode // Start indicator for individual task expansion in CLI mode
let taskIndicator = null; let taskIndicator = null;
if (!isMCPCall && outputFormat === 'text') { if (!isMCPCall && outputFormat === 'text') {
@@ -112,23 +117,17 @@ async function expandAllTasks(
} }
try { try {
// Call the refactored expandTask function AND capture result // Call the refactored expandTask function
const result = await expandTask( await expandTask(
tasksPath, tasksPath,
task.id, task.id,
numSubtasks, numSubtasks, // Pass numSubtasks, expandTask handles defaults/complexity
useResearch, useResearch,
additionalContext, additionalContext,
context, // Pass the whole context object { session, mcpLog } context, // Pass the whole context object { session, mcpLog }
force force // Pass the force flag down
); );
expandedCount++; expandedCount++;
// Collect individual telemetry data
if (result && result.telemetryData) {
allTelemetryData.push(result.telemetryData);
}
if (taskIndicator) { if (taskIndicator) {
stopLoadingIndicator(taskIndicator, `Task ${task.id} expanded.`); stopLoadingIndicator(taskIndicator, `Task ${task.id} expanded.`);
} }
@@ -147,48 +146,18 @@ async function expandAllTasks(
} }
} }
// --- AGGREGATION AND DISPLAY --- // Log final summary (removed skipped count from message)
logger.info( logger.info(
`Expansion complete: ${expandedCount} expanded, ${failedCount} failed.` `Expansion complete: ${expandedCount} expanded, ${failedCount} failed.`
); );
// Aggregate the collected telemetry data // Return summary (skippedCount is now 0) - Add success: true here as well for consistency
const aggregatedTelemetryData = aggregateTelemetry(
allTelemetryData,
'expand-all-tasks'
);
if (outputFormat === 'text') {
const summaryContent =
`${chalk.white.bold('Expansion Summary:')}\n\n` +
`${chalk.cyan('-')} Attempted: ${chalk.bold(tasksToExpandCount)}\n` +
`${chalk.green('-')} Expanded: ${chalk.bold(expandedCount)}\n` +
// Skipped count is always 0 now due to pre-filtering
`${chalk.gray('-')} Skipped: ${chalk.bold(0)}\n` +
`${chalk.red('-')} Failed: ${chalk.bold(failedCount)}`;
console.log(
boxen(summaryContent, {
padding: 1,
margin: { top: 1 },
borderColor: failedCount > 0 ? 'red' : 'green', // Red if failures, green otherwise
borderStyle: 'round'
})
);
}
if (outputFormat === 'text' && aggregatedTelemetryData) {
displayAiUsageSummary(aggregatedTelemetryData, 'cli');
}
// Return summary including the AGGREGATED telemetry data
return { return {
success: true, success: true, // Indicate overall success
expandedCount, expandedCount,
failedCount, failedCount,
skippedCount: 0, skippedCount: 0,
tasksToExpand: tasksToExpandCount, tasksToExpand: tasksToExpandCount
telemetryData: aggregatedTelemetryData
}; };
} catch (error) { } catch (error) {
if (loadingIndicator) if (loadingIndicator)

View File

@@ -4,11 +4,7 @@ import { z } from 'zod';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js'; import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
import { import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import { generateTextService } from '../ai-services-unified.js'; import { generateTextService } from '../ai-services-unified.js';
@@ -146,7 +142,7 @@ function generateResearchUserPrompt(
"id": <number>, // Sequential ID starting from ${nextSubtaskId} "id": <number>, // Sequential ID starting from ${nextSubtaskId}
"title": "<string>", "title": "<string>",
"description": "<string>", "description": "<string>",
"dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]. If no dependencies, use an empty array []. "dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]
"details": "<string>", "details": "<string>",
"testStrategy": "<string>" // Optional "testStrategy": "<string>" // Optional
}, },
@@ -166,8 +162,6 @@ ${contextPrompt}
CRITICAL: Respond ONLY with a valid JSON object containing a single key "subtasks". The value must be an array of the generated subtasks, strictly matching this structure: CRITICAL: Respond ONLY with a valid JSON object containing a single key "subtasks". The value must be an array of the generated subtasks, strictly matching this structure:
${schemaDescription} ${schemaDescription}
Important: For the 'dependencies' field, if a subtask has no dependencies, you MUST use an empty array, for example: "dependencies": []. Do not use null or omit the field.
Do not include ANY explanatory text, markdown, or code block markers. Just the JSON object.`; Do not include ANY explanatory text, markdown, or code block markers. Just the JSON object.`;
} }
@@ -188,153 +182,77 @@ function parseSubtasksFromText(
parentTaskId, parentTaskId,
logger logger
) { ) {
if (typeof text !== 'string') { logger.info('Attempting to parse subtasks object from text response...');
logger.error(
`AI response text is not a string. Received type: ${typeof text}, Value: ${text}`
);
throw new Error('AI response text is not a string.');
}
if (!text || text.trim() === '') { if (!text || text.trim() === '') {
throw new Error('AI response text is empty after trimming.'); throw new Error('AI response text is empty.');
} }
const originalTrimmedResponse = text.trim(); // Store the original trimmed response let cleanedResponse = text.trim();
let jsonToParse = originalTrimmedResponse; // Initialize jsonToParse with it const originalResponseForDebug = cleanedResponse;
logger.debug( // 1. Extract from Markdown code block first
`Original AI Response for parsing (full length: ${jsonToParse.length}): ${jsonToParse.substring(0, 1000)}...` const codeBlockMatch = cleanedResponse.match(
/```(?:json)?\s*([\s\S]*?)\s*```/
); );
if (codeBlockMatch) {
// --- Pre-emptive cleanup for known AI JSON issues --- cleanedResponse = codeBlockMatch[1].trim();
// Fix for "dependencies": , or "dependencies":, logger.info('Extracted JSON content from Markdown code block.');
if (jsonToParse.includes('"dependencies":')) { } else {
const malformedPattern = /"dependencies":\s*,/g; // 2. If no code block, find first '{' and last '}' for the object
if (malformedPattern.test(jsonToParse)) { const firstBrace = cleanedResponse.indexOf('{');
logger.warn('Attempting to fix malformed "dependencies": , issue.'); const lastBrace = cleanedResponse.lastIndexOf('}');
jsonToParse = jsonToParse.replace( if (firstBrace !== -1 && lastBrace > firstBrace) {
malformedPattern, cleanedResponse = cleanedResponse.substring(firstBrace, lastBrace + 1);
'"dependencies": [],' logger.info('Extracted content between first { and last }.');
);
logger.debug(
`JSON after fixing "dependencies": ${jsonToParse.substring(0, 500)}...`
);
}
}
// --- End pre-emptive cleanup ---
let parsedObject;
let primaryParseAttemptFailed = false;
// --- Attempt 1: Simple Parse (with optional Markdown cleanup) ---
logger.debug('Attempting simple parse...');
try {
// Check for markdown code block
const codeBlockMatch = jsonToParse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
let contentToParseDirectly = jsonToParse;
if (codeBlockMatch && codeBlockMatch[1]) {
contentToParseDirectly = codeBlockMatch[1].trim();
logger.debug('Simple parse: Extracted content from markdown code block.');
} else { } else {
logger.debug(
'Simple parse: No markdown code block found, using trimmed original.'
);
}
parsedObject = JSON.parse(contentToParseDirectly);
logger.debug('Simple parse successful!');
// Quick check if it looks like our target object
if (
!parsedObject ||
typeof parsedObject !== 'object' ||
!Array.isArray(parsedObject.subtasks)
) {
logger.warn( logger.warn(
'Simple parse succeeded, but result is not the expected {"subtasks": []} structure. Will proceed to advanced extraction.' 'Response does not appear to contain a JSON object structure. Parsing raw response.'
);
primaryParseAttemptFailed = true;
parsedObject = null; // Reset parsedObject so we enter the advanced logic
}
// If it IS the correct structure, we'll skip advanced extraction.
} catch (e) {
logger.warn(
`Simple parse failed: ${e.message}. Proceeding to advanced extraction logic.`
);
primaryParseAttemptFailed = true;
// jsonToParse is already originalTrimmedResponse if simple parse failed before modifying it for markdown
}
// --- Attempt 2: Advanced Extraction (if simple parse failed or produced wrong structure) ---
if (primaryParseAttemptFailed || !parsedObject) {
// Ensure we try advanced if simple parse gave wrong structure
logger.debug('Attempting advanced extraction logic...');
// Reset jsonToParse to the original full trimmed response for advanced logic
jsonToParse = originalTrimmedResponse;
// (Insert the more complex extraction logic here - the one we worked on with:
// - targetPattern = '{"subtasks":';
// - careful brace counting for that targetPattern
// - fallbacks to last '{' and '}' if targetPattern logic fails)
// This was the logic from my previous message. Let's assume it's here.
// This block should ultimately set `jsonToParse` to the best candidate string.
// Example snippet of that advanced logic's start:
const targetPattern = '{"subtasks":';
const patternStartIndex = jsonToParse.indexOf(targetPattern);
if (patternStartIndex !== -1) {
let openBraces = 0;
let firstBraceFound = false;
let extractedJsonBlock = '';
// ... (loop for brace counting as before) ...
// ... (if successful, jsonToParse = extractedJsonBlock) ...
// ... (if that fails, fallbacks as before) ...
} else {
// ... (fallback to last '{' and '}' if targetPattern not found) ...
}
// End of advanced logic excerpt
logger.debug(
`Advanced extraction: JSON string that will be parsed: ${jsonToParse.substring(0, 500)}...`
);
try {
parsedObject = JSON.parse(jsonToParse);
logger.debug('Advanced extraction parse successful!');
} catch (parseError) {
logger.error(
`Advanced extraction: Failed to parse JSON object: ${parseError.message}`
);
logger.error(
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}`
);
throw new Error( // Re-throw a more specific error if advanced also fails
`Failed to parse JSON response object after both simple and advanced attempts: ${parseError.message}`
); );
} }
} }
// --- Validation (applies to successfully parsedObject from either attempt) --- // 3. Attempt to parse the object
let parsedObject;
try {
parsedObject = JSON.parse(cleanedResponse);
} catch (parseError) {
logger.error(`Failed to parse JSON object: ${parseError.message}`);
logger.error(
`Problematic JSON string (first 500 chars): ${cleanedResponse.substring(0, 500)}`
);
logger.error(
`Original Raw Response (first 500 chars): ${originalResponseForDebug.substring(0, 500)}`
);
throw new Error(
`Failed to parse JSON response object: ${parseError.message}`
);
}
// 4. Validate the object structure and extract the subtasks array
if ( if (
!parsedObject || !parsedObject ||
typeof parsedObject !== 'object' || typeof parsedObject !== 'object' ||
!Array.isArray(parsedObject.subtasks) !Array.isArray(parsedObject.subtasks)
) { ) {
logger.error( logger.error(
`Final parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}` `Parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}`
); );
throw new Error( throw new Error(
'Parsed AI response is not a valid object containing a "subtasks" array after all attempts.' 'Parsed AI response is not a valid object containing a "subtasks" array.'
); );
} }
const parsedSubtasks = parsedObject.subtasks; const parsedSubtasks = parsedObject.subtasks; // Extract the array
logger.info(
`Successfully parsed ${parsedSubtasks.length} potential subtasks from the object.`
);
if (expectedCount && parsedSubtasks.length !== expectedCount) { if (expectedCount && parsedSubtasks.length !== expectedCount) {
logger.warn( logger.warn(
`Expected ${expectedCount} subtasks, but parsed ${parsedSubtasks.length}.` `Expected ${expectedCount} subtasks, but parsed ${parsedSubtasks.length}.`
); );
} }
// 5. Validate and Normalize each subtask using Zod schema
let currentId = startId; let currentId = startId;
const validatedSubtasks = []; const validatedSubtasks = [];
const validationErrors = []; const validationErrors = [];
@@ -342,21 +260,22 @@ function parseSubtasksFromText(
for (const rawSubtask of parsedSubtasks) { for (const rawSubtask of parsedSubtasks) {
const correctedSubtask = { const correctedSubtask = {
...rawSubtask, ...rawSubtask,
id: currentId, id: currentId, // Enforce sequential ID
dependencies: Array.isArray(rawSubtask.dependencies) dependencies: Array.isArray(rawSubtask.dependencies)
? rawSubtask.dependencies ? rawSubtask.dependencies
.map((dep) => (typeof dep === 'string' ? parseInt(dep, 10) : dep)) .map((dep) => (typeof dep === 'string' ? parseInt(dep, 10) : dep))
.filter( .filter(
(depId) => !isNaN(depId) && depId >= startId && depId < currentId (depId) => !isNaN(depId) && depId >= startId && depId < currentId
) ) // Ensure deps are numbers, valid range
: [], : [],
status: 'pending' status: 'pending' // Enforce pending status
// parentTaskId can be added if needed: parentTaskId: parentTaskId
}; };
const result = subtaskSchema.safeParse(correctedSubtask); const result = subtaskSchema.safeParse(correctedSubtask);
if (result.success) { if (result.success) {
validatedSubtasks.push(result.data); validatedSubtasks.push(result.data); // Add the validated data
} else { } else {
logger.warn( logger.warn(
`Subtask validation failed for raw data: ${JSON.stringify(rawSubtask).substring(0, 100)}...` `Subtask validation failed for raw data: ${JSON.stringify(rawSubtask).substring(0, 100)}...`
@@ -366,14 +285,18 @@ function parseSubtasksFromText(
logger.warn(errorMessage); logger.warn(errorMessage);
validationErrors.push(`Subtask ${currentId}: ${errorMessage}`); validationErrors.push(`Subtask ${currentId}: ${errorMessage}`);
}); });
// Optionally, decide whether to include partially valid tasks or skip them
// For now, we'll skip invalid ones
} }
currentId++; currentId++; // Increment ID for the next *potential* subtask
} }
if (validationErrors.length > 0) { if (validationErrors.length > 0) {
logger.error( logger.error(
`Found ${validationErrors.length} validation errors in the generated subtasks.` `Found ${validationErrors.length} validation errors in the generated subtasks.`
); );
// Optionally throw an error here if strict validation is required
// throw new Error(`Subtask validation failed:\n${validationErrors.join('\n')}`);
logger.warn('Proceeding with only the successfully validated subtasks.'); logger.warn('Proceeding with only the successfully validated subtasks.');
} }
@@ -382,6 +305,8 @@ function parseSubtasksFromText(
'AI response contained potential subtasks, but none passed validation.' 'AI response contained potential subtasks, but none passed validation.'
); );
} }
// Ensure we don't return more than expected, preferring validated ones
return validatedSubtasks.slice(0, expectedCount || validatedSubtasks.length); return validatedSubtasks.slice(0, expectedCount || validatedSubtasks.length);
} }
@@ -411,13 +336,9 @@ async function expandTask(
context = {}, context = {},
force = false force = false
) { ) {
const { session, mcpLog, projectRoot: contextProjectRoot } = context; const { session, mcpLog } = context;
const outputFormat = mcpLog ? 'json' : 'text'; const outputFormat = mcpLog ? 'json' : 'text';
// Determine projectRoot: Use from context if available, otherwise derive from tasksPath
const projectRoot =
contextProjectRoot || path.dirname(path.dirname(tasksPath));
// Use mcpLog if available, otherwise use the default console log wrapper // Use mcpLog if available, otherwise use the default console log wrapper
const logger = mcpLog || { const logger = mcpLog || {
info: (msg) => !isSilentMode() && log('info', msg), info: (msg) => !isSilentMode() && log('info', msg),
@@ -442,9 +363,7 @@ async function expandTask(
); );
if (taskIndex === -1) throw new Error(`Task ${taskId} not found`); if (taskIndex === -1) throw new Error(`Task ${taskId} not found`);
const task = data.tasks[taskIndex]; const task = data.tasks[taskIndex];
logger.info( logger.info(`Expanding task ${taskId}: ${task.title}`);
`Expanding task ${taskId}: ${task.title}${useResearch ? ' with research' : ''}`
);
// --- End Task Loading/Filtering --- // --- End Task Loading/Filtering ---
// --- Handle Force Flag: Clear existing subtasks if force=true --- // --- Handle Force Flag: Clear existing subtasks if force=true ---
@@ -462,6 +381,7 @@ async function expandTask(
let complexityReasoningContext = ''; let complexityReasoningContext = '';
let systemPrompt; // Declare systemPrompt here let systemPrompt; // Declare systemPrompt here
const projectRoot = path.dirname(path.dirname(tasksPath));
const complexityReportPath = path.join( const complexityReportPath = path.join(
projectRoot, projectRoot,
'scripts/task-complexity-report.json' 'scripts/task-complexity-report.json'
@@ -568,27 +488,27 @@ async function expandTask(
let loadingIndicator = null; let loadingIndicator = null;
if (outputFormat === 'text') { if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator( loadingIndicator = startLoadingIndicator(
`Generating ${finalSubtaskCount} subtasks...\n` `Generating ${finalSubtaskCount} subtasks...`
); );
} }
let responseText = ''; let responseText = '';
let aiServiceResponse = null;
try { try {
const role = useResearch ? 'research' : 'main'; const role = useResearch ? 'research' : 'main';
logger.info(`Using AI service with role: ${role}`);
// Call generateTextService with the determined prompts and telemetry params // Call generateTextService with the determined prompts
aiServiceResponse = await generateTextService({ responseText = await generateTextService({
prompt: promptContent, prompt: promptContent,
systemPrompt: systemPrompt, systemPrompt: systemPrompt, // Use the determined system prompt
role, role,
session, session
projectRoot,
commandName: 'expand-task',
outputType: outputFormat
}); });
responseText = aiServiceResponse.mainResult; logger.info(
'Successfully received text response from AI service',
'success'
);
// Parse Subtasks // Parse Subtasks
generatedSubtasks = parseSubtasksFromText( generatedSubtasks = parseSubtasksFromText(
@@ -629,23 +549,14 @@ async function expandTask(
// --- End Change: Append instead of replace --- // --- End Change: Append instead of replace ---
data.tasks[taskIndex] = task; // Assign the modified task back data.tasks[taskIndex] = task; // Assign the modified task back
logger.info(`Writing updated tasks to ${tasksPath}`);
writeJSON(tasksPath, data); writeJSON(tasksPath, data);
logger.info(`Generating individual task files...`);
await generateTaskFiles(tasksPath, path.dirname(tasksPath)); await generateTaskFiles(tasksPath, path.dirname(tasksPath));
logger.info(`Task files generated.`);
// --- End Task Update & File Writing ---
// Display AI Usage Summary for CLI return task; // Return the updated task object
if (
outputFormat === 'text' &&
aiServiceResponse &&
aiServiceResponse.telemetryData
) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
// Return the updated task object AND telemetry data
return {
task,
telemetryData: aiServiceResponse?.telemetryData
};
} catch (error) { } catch (error) {
// Catches errors from file reading, parsing, AI call etc. // Catches errors from file reading, parsing, AI call etc.
logger.error(`Error expanding task ${taskId}: ${error.message}`, 'error'); logger.error(`Error expanding task ${taskId}: ${error.message}`, 'error');

View File

@@ -1,6 +1,3 @@
import { log } from '../utils.js';
import { addComplexityToTask } from '../utils.js';
/** /**
* Return the next work item: * Return the next work item:
* • Prefer an eligible SUBTASK that belongs to any parent task * • Prefer an eligible SUBTASK that belongs to any parent task
@@ -18,10 +15,9 @@ import { addComplexityToTask } from '../utils.js';
* ─ parentId → number (present only when it's a subtask) * ─ parentId → number (present only when it's a subtask)
* *
* @param {Object[]} tasks full array of top-level tasks, each may contain .subtasks[] * @param {Object[]} tasks full array of top-level tasks, each may contain .subtasks[]
* @param {Object} [complexityReport=null] - Optional complexity report object
* @returns {Object|null} next work item or null if nothing is eligible * @returns {Object|null} next work item or null if nothing is eligible
*/ */
function findNextTask(tasks, complexityReport = null) { function findNextTask(tasks) {
// ---------- helpers ---------------------------------------------------- // ---------- helpers ----------------------------------------------------
const priorityValues = { high: 3, medium: 2, low: 1 }; const priorityValues = { high: 3, medium: 2, low: 1 };
@@ -95,14 +91,7 @@ function findNextTask(tasks, complexityReport = null) {
if (aPar !== bPar) return aPar - bPar; if (aPar !== bPar) return aPar - bPar;
return aSub - bSub; return aSub - bSub;
}); });
const nextTask = candidateSubtasks[0]; return candidateSubtasks[0];
// Add complexity to the task before returning
if (nextTask && complexityReport) {
addComplexityToTask(nextTask, complexityReport);
}
return nextTask;
} }
// ---------- 2) fall back to top-level tasks (original logic) ------------ // ---------- 2) fall back to top-level tasks (original logic) ------------
@@ -127,11 +116,6 @@ function findNextTask(tasks, complexityReport = null) {
return a.id - b.id; return a.id - b.id;
})[0]; })[0];
// Add complexity to the task before returning
if (nextTask && complexityReport) {
addComplexityToTask(nextTask, complexityReport);
}
return nextTask; return nextTask;
} }

View File

@@ -19,6 +19,8 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
// Determine if we're in MCP mode by checking for mcpLog // Determine if we're in MCP mode by checking for mcpLog
const isMcpMode = !!options?.mcpLog; const isMcpMode = !!options?.mcpLog;
log('info', `Preparing to regenerate task files in ${tasksPath}`);
const data = readJSON(tasksPath); const data = readJSON(tasksPath);
if (!data || !data.tasks) { if (!data || !data.tasks) {
throw new Error(`No valid tasks found in ${tasksPath}`); throw new Error(`No valid tasks found in ${tasksPath}`);
@@ -29,7 +31,7 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
fs.mkdirSync(outputDir, { recursive: true }); fs.mkdirSync(outputDir, { recursive: true });
} }
log('info', `Preparing to regenerate ${data.tasks.length} task files`); log('info', `Found ${data.tasks.length} tasks to regenerate`);
// Validate and fix dependencies before generating files // Validate and fix dependencies before generating files
log('info', `Validating and fixing dependencies`); log('info', `Validating and fixing dependencies`);

View File

@@ -2,20 +2,13 @@ import chalk from 'chalk';
import boxen from 'boxen'; import boxen from 'boxen';
import Table from 'cli-table3'; import Table from 'cli-table3';
import { import { log, readJSON, truncate } from '../utils.js';
log,
readJSON,
truncate,
readComplexityReport,
addComplexityToTask
} from '../utils.js';
import findNextTask from './find-next-task.js'; import findNextTask from './find-next-task.js';
import { import {
displayBanner, displayBanner,
getStatusWithColor, getStatusWithColor,
formatDependenciesWithStatus, formatDependenciesWithStatus,
getComplexityWithColor,
createProgressBar createProgressBar
} from '../ui.js'; } from '../ui.js';
@@ -23,7 +16,6 @@ import {
* List all tasks * List all tasks
* @param {string} tasksPath - Path to the tasks.json file * @param {string} tasksPath - Path to the tasks.json file
* @param {string} statusFilter - Filter by status * @param {string} statusFilter - Filter by status
* @param {string} reportPath - Path to the complexity report
* @param {boolean} withSubtasks - Whether to show subtasks * @param {boolean} withSubtasks - Whether to show subtasks
* @param {string} outputFormat - Output format (text or json) * @param {string} outputFormat - Output format (text or json)
* @returns {Object} - Task list result for json format * @returns {Object} - Task list result for json format
@@ -31,7 +23,6 @@ import {
function listTasks( function listTasks(
tasksPath, tasksPath,
statusFilter, statusFilter,
reportPath = null,
withSubtasks = false, withSubtasks = false,
outputFormat = 'text' outputFormat = 'text'
) { ) {
@@ -46,13 +37,6 @@ function listTasks(
throw new Error(`No valid tasks found in ${tasksPath}`); throw new Error(`No valid tasks found in ${tasksPath}`);
} }
// Add complexity scores to tasks if report exists
const complexityReport = readComplexityReport(reportPath);
// Apply complexity scores to tasks
if (complexityReport && complexityReport.complexityAnalysis) {
data.tasks.forEach((task) => addComplexityToTask(task, complexityReport));
}
// Filter tasks by status if specified // Filter tasks by status if specified
const filteredTasks = const filteredTasks =
statusFilter && statusFilter.toLowerCase() !== 'all' // <-- Added check for 'all' statusFilter && statusFilter.toLowerCase() !== 'all' // <-- Added check for 'all'
@@ -273,8 +257,8 @@ function listTasks(
); );
const avgDependenciesPerTask = totalDependencies / data.tasks.length; const avgDependenciesPerTask = totalDependencies / data.tasks.length;
// Find next task to work on, passing the complexity report // Find next task to work on
const nextItem = findNextTask(data.tasks, complexityReport); const nextItem = findNextTask(data.tasks);
// Get terminal width - more reliable method // Get terminal width - more reliable method
let terminalWidth; let terminalWidth;
@@ -317,11 +301,8 @@ function listTasks(
`${chalk.blue('•')} ${chalk.white('Avg dependencies per task:')} ${avgDependenciesPerTask.toFixed(1)}\n\n` + `${chalk.blue('•')} ${chalk.white('Avg dependencies per task:')} ${avgDependenciesPerTask.toFixed(1)}\n\n` +
chalk.cyan.bold('Next Task to Work On:') + chalk.cyan.bold('Next Task to Work On:') +
'\n' + '\n' +
`ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')} `ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')}\n` +
` + `Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : ''}`;
`Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : ''}
` +
`Complexity: ${nextItem && nextItem.complexityScore ? getComplexityWithColor(nextItem.complexityScore) : chalk.gray('N/A')}`;
// Calculate width for side-by-side display // Calculate width for side-by-side display
// Box borders, padding take approximately 4 chars on each side // Box borders, padding take approximately 4 chars on each side
@@ -431,16 +412,9 @@ function listTasks(
// Make dependencies column smaller as requested (-20%) // Make dependencies column smaller as requested (-20%)
const depsWidthPct = 20; const depsWidthPct = 20;
const complexityWidthPct = 10;
// Calculate title/description width as remaining space (+20% from dependencies reduction) // Calculate title/description width as remaining space (+20% from dependencies reduction)
const titleWidthPct = const titleWidthPct =
100 - 100 - idWidthPct - statusWidthPct - priorityWidthPct - depsWidthPct;
idWidthPct -
statusWidthPct -
priorityWidthPct -
depsWidthPct -
complexityWidthPct;
// Allow 10 characters for borders and padding // Allow 10 characters for borders and padding
const availableWidth = terminalWidth - 10; const availableWidth = terminalWidth - 10;
@@ -450,9 +424,6 @@ function listTasks(
const statusWidth = Math.floor(availableWidth * (statusWidthPct / 100)); const statusWidth = Math.floor(availableWidth * (statusWidthPct / 100));
const priorityWidth = Math.floor(availableWidth * (priorityWidthPct / 100)); const priorityWidth = Math.floor(availableWidth * (priorityWidthPct / 100));
const depsWidth = Math.floor(availableWidth * (depsWidthPct / 100)); const depsWidth = Math.floor(availableWidth * (depsWidthPct / 100));
const complexityWidth = Math.floor(
availableWidth * (complexityWidthPct / 100)
);
const titleWidth = Math.floor(availableWidth * (titleWidthPct / 100)); const titleWidth = Math.floor(availableWidth * (titleWidthPct / 100));
// Create a table with correct borders and spacing // Create a table with correct borders and spacing
@@ -462,17 +433,9 @@ function listTasks(
chalk.cyan.bold('Title'), chalk.cyan.bold('Title'),
chalk.cyan.bold('Status'), chalk.cyan.bold('Status'),
chalk.cyan.bold('Priority'), chalk.cyan.bold('Priority'),
chalk.cyan.bold('Dependencies'), chalk.cyan.bold('Dependencies')
chalk.cyan.bold('Complexity')
],
colWidths: [
idWidth,
titleWidth,
statusWidth,
priorityWidth,
depsWidth,
complexityWidth // Added complexity column width
], ],
colWidths: [idWidth, titleWidth, statusWidth, priorityWidth, depsWidth],
style: { style: {
head: [], // No special styling for header head: [], // No special styling for header
border: [], // No special styling for border border: [], // No special styling for border
@@ -491,8 +454,7 @@ function listTasks(
depText = formatDependenciesWithStatus( depText = formatDependenciesWithStatus(
task.dependencies, task.dependencies,
data.tasks, data.tasks,
true, true
complexityReport
); );
} else { } else {
depText = chalk.gray('None'); depText = chalk.gray('None');
@@ -518,10 +480,7 @@ function listTasks(
truncate(cleanTitle, titleWidth - 3), truncate(cleanTitle, titleWidth - 3),
status, status,
priorityColor(truncate(task.priority || 'medium', priorityWidth - 2)), priorityColor(truncate(task.priority || 'medium', priorityWidth - 2)),
depText, depText // No truncation for dependencies
task.complexityScore
? getComplexityWithColor(task.complexityScore)
: chalk.gray('N/A')
]); ]);
// Add subtasks if requested // Add subtasks if requested
@@ -557,8 +516,6 @@ function listTasks(
// Default to regular task dependency // Default to regular task dependency
const depTask = data.tasks.find((t) => t.id === depId); const depTask = data.tasks.find((t) => t.id === depId);
if (depTask) { if (depTask) {
// Add complexity to depTask before checking status
addComplexityToTask(depTask, complexityReport);
const isDone = const isDone =
depTask.status === 'done' || depTask.status === 'completed'; depTask.status === 'done' || depTask.status === 'completed';
const isInProgress = depTask.status === 'in-progress'; const isInProgress = depTask.status === 'in-progress';
@@ -584,10 +541,7 @@ function listTasks(
chalk.dim(`└─ ${truncate(subtask.title, titleWidth - 5)}`), chalk.dim(`└─ ${truncate(subtask.title, titleWidth - 5)}`),
getStatusWithColor(subtask.status, true), getStatusWithColor(subtask.status, true),
chalk.dim('-'), chalk.dim('-'),
subtaskDepText, subtaskDepText // No truncation for dependencies
subtask.complexityScore
? chalk.gray(`${subtask.complexityScore}`)
: chalk.gray('N/A')
]); ]);
}); });
} }
@@ -643,8 +597,6 @@ function listTasks(
subtasksSection = `\n\n${chalk.white.bold('Subtasks:')}\n`; subtasksSection = `\n\n${chalk.white.bold('Subtasks:')}\n`;
subtasksSection += parentTaskForSubtasks.subtasks subtasksSection += parentTaskForSubtasks.subtasks
.map((subtask) => { .map((subtask) => {
// Add complexity to subtask before display
addComplexityToTask(subtask, complexityReport);
// Using a more simplified format for subtask status display // Using a more simplified format for subtask status display
const status = subtask.status || 'pending'; const status = subtask.status || 'pending';
const statusColors = { const statusColors = {
@@ -673,8 +625,8 @@ function listTasks(
'\n\n' + '\n\n' +
// Use nextItem.priority, nextItem.status, nextItem.dependencies // Use nextItem.priority, nextItem.status, nextItem.dependencies
`${chalk.white('Priority:')} ${priorityColors[nextItem.priority || 'medium'](nextItem.priority || 'medium')} ${chalk.white('Status:')} ${getStatusWithColor(nextItem.status, true)}\n` + `${chalk.white('Priority:')} ${priorityColors[nextItem.priority || 'medium'](nextItem.priority || 'medium')} ${chalk.white('Status:')} ${getStatusWithColor(nextItem.status, true)}\n` +
`${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : chalk.gray('None')}\n\n` + `${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : chalk.gray('None')}\n\n` +
// Use nextTask.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this) // Use nextItem.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this)
// *** Fetching original item for description and details *** // *** Fetching original item for description and details ***
`${chalk.white('Description:')} ${getWorkItemDescription(nextItem, data.tasks)}` + `${chalk.white('Description:')} ${getWorkItemDescription(nextItem, data.tasks)}` +
subtasksSection + // <-- Subtasks are handled above now subtasksSection + // <-- Subtasks are handled above now

View File

@@ -77,7 +77,7 @@ function fetchOpenRouterModels() {
* @returns {Object} RESTful response with current model configuration * @returns {Object} RESTful response with current model configuration
*/ */
async function getModelConfiguration(options = {}) { async function getModelConfiguration(options = {}) {
const { mcpLog, projectRoot, session } = options; const { mcpLog, projectRoot } = options;
const report = (level, ...args) => { const report = (level, ...args) => {
if (mcpLog && typeof mcpLog[level] === 'function') { if (mcpLog && typeof mcpLog[level] === 'function') {
@@ -125,16 +125,12 @@ async function getModelConfiguration(options = {}) {
const fallbackModelId = getFallbackModelId(projectRoot); const fallbackModelId = getFallbackModelId(projectRoot);
// Check API keys // Check API keys
const mainCliKeyOk = isApiKeySet(mainProvider, session, projectRoot); const mainCliKeyOk = isApiKeySet(mainProvider);
const mainMcpKeyOk = getMcpApiKeyStatus(mainProvider, projectRoot); const mainMcpKeyOk = getMcpApiKeyStatus(mainProvider, projectRoot);
const researchCliKeyOk = isApiKeySet( const researchCliKeyOk = isApiKeySet(researchProvider);
researchProvider,
session,
projectRoot
);
const researchMcpKeyOk = getMcpApiKeyStatus(researchProvider, projectRoot); const researchMcpKeyOk = getMcpApiKeyStatus(researchProvider, projectRoot);
const fallbackCliKeyOk = fallbackProvider const fallbackCliKeyOk = fallbackProvider
? isApiKeySet(fallbackProvider, session, projectRoot) ? isApiKeySet(fallbackProvider)
: true; : true;
const fallbackMcpKeyOk = fallbackProvider const fallbackMcpKeyOk = fallbackProvider
? getMcpApiKeyStatus(fallbackProvider, projectRoot) ? getMcpApiKeyStatus(fallbackProvider, projectRoot)
@@ -527,7 +523,7 @@ async function getApiKeyStatusReport(options = {}) {
); // Ollama is not a provider, it's a service, doesn't need an api key usually ); // Ollama is not a provider, it's a service, doesn't need an api key usually
const statusReport = providersToCheck.map((provider) => { const statusReport = providersToCheck.map((provider) => {
// Use provided projectRoot for MCP status check // Use provided projectRoot for MCP status check
const cliOk = isApiKeySet(provider, session, projectRoot); // Pass session and projectRoot for CLI check const cliOk = isApiKeySet(provider, session); // Pass session for CLI check too
const mcpOk = getMcpApiKeyStatus(provider, projectRoot); const mcpOk = getMcpApiKeyStatus(provider, projectRoot);
return { return {
provider, provider,

Some files were not shown because too many files have changed in this diff Show More