Compare commits

...

76 Commits

Author SHA1 Message Date
Eyal Toledano
16e6326010 fix(config): adds missing import + task management for api key design 2025-06-05 14:20:25 -04:00
Eyal Toledano
a9c1b6bbcf fix(config-manager): Add silent mode check and improve test mocking for ensureConfigFileExists 2025-06-05 13:33:20 -04:00
Eyal Toledano
f12fc476d3 fix(init): Ensure hosted mode option available by creating .taskmasterconfig early
- Added ensureConfigFileExists() to create default config if missing
- Call early in init flows before gateway check - Preserve email from initializeUser()
- Add comprehensive tests
2025-06-05 13:30:14 -04:00
Eyal Toledano
31178e2f43 chore: adjust .taskmasterconfig defaults 2025-06-04 19:04:17 -04:00
Eyal Toledano
3fa3be4e1b chore: fix user email, telemetryEnabled by default 2025-06-04 19:03:47 -04:00
Eyal Toledano
685365270d feat: integrate Supabase authenticated users
- Updated init.js, ai-services-unified.js, user-management.js, telemetry-submission.js, and .taskmasterconfig to support Supabase authentication flow and authenticated gateway calls
2025-06-04 18:53:28 -04:00
Eyal Toledano
58aa0992f6 feat(error-handling): Implement comprehensive gateway error handling with user-friendly messages
- Add comprehensive gateway error handler with friendly user messages
- Handle subscription status errors (inactive BYOK, subscription required)
- Handle authentication errors (invalid API keys, missing tokens)
- Handle rate limiting with retry suggestions
- Handle model availability and validation errors
- Handle network connectivity issues
- Provide actionable solutions for each error type
- Prevent duplicate error messages by returning early after showing friendly error
- Fix telemetry tests to use correct environment variable names (TASKMASTER_API_KEY)
- Fix config manager getUserId function to properly save default userId to file
- All tests now passing (34 test suites, 360 tests)
2025-06-02 12:34:47 -04:00
Eyal Toledano
2819be51d3 feat: Implement TaskMaster AI Gateway integration with enhanced UX
- Fix Zod schema conversion, update headers, add premium telemetry display, improve user auth flow, and standardize email fields

Functionally complete on this end, mostly polish around user experience and need to add in profile, upgrade/downgrade, etc.

But the AI commands are working off the gateway.
2025-06-01 19:37:12 -04:00
Eyal Toledano
9b87dd23de fix(gateway/auth): Implement proper auth/init flow with automatic background userId generation
- Fix getUserId() to use placeholder that triggers auth/init if the auth/init endpoint is down for whatever reason
- Add silent auth/init attempt in AI services
- Improve hosted mode error handling
- Remove fake userId/email generation from init.js
2025-05-31 19:47:18 -04:00
Eyal Toledano
769275b3bc fix(config): Fix config structure and tests after refactoring
- Fixed getUserId() to always return value, never null (sets default '1234567890')
- Updated all test files to match new config.account structure
- Fixed config-manager.test.js default config expectations
- Updated telemetry-submission.test.js and ai-services-unified.test.js mocks
- Added getTelemetryEnabled export to all config-manager mocks
- All 44 tests now passing
2025-05-30 19:40:38 -04:00
Eyal Toledano
4e9d58a1b0 feat(config): Restructure .taskmasterconfig and enhance gateway integration
Config Structure Changes and Gateway Integration

## Configuration Structure Changes
- Restructured .taskmasterconfig to use 'account' section for user settings
- Moved userId, userEmail, mode, telemetryEnabled from global to account section
- API keys remain isolated in .env file (not accessible to AI)
- Enhanced getUserId() to always return value, never null (sets default '1234567890')

## Gateway Integration Enhancements
- Updated registerUserWithGateway() to accept both email and userId parameters
- Enhanced /auth/init endpoint integration for existing user validation
- API key updates automatically written to .env during registration process
- Improved user identification and validation flow

## Code Updates for New Structure
- Fixed config-manager.js getter functions for account section access
- Updated user-management.js to use config.account.userId/mode
- Modified telemetry-submission.js to read from account section
- Added getTelemetryEnabled() function with proper account section access
- Enhanced telemetry configuration reading with new structure

## Comprehensive Test Updates
- Updated integration tests (init-config.test.js) for new config structure
- Fixed unit tests (config-manager.test.js) with updated default config
- Updated telemetry tests (telemetry-submission.test.js) for account structure
- Added missing getTelemetryEnabled mock to ai-services-unified.test.js
- Fixed all test expectations to use config.account.* instead of config.global.*
- Removed references to deprecated config.subscription object

## Configuration Access Consistency
- Standardized configuration access patterns across entire codebase
- Clean separation: user settings in account, API keys in .env, models/global in respective sections
- All tests passing with new configuration structure
- Maintained backward compatibility during transition

Changes support enhanced telemetry system with proper user management and gateway integration while maintaining security through API key isolation.
2025-05-30 18:53:16 -04:00
Eyal Toledano
e573db3b3b feat(task-90): Complete telemetry integration with init flow improvements - Task 90.3: AI Services Integration COMPLETED with automatic submission after AI usage logging and graceful error handling - Init Flow Enhancements: restructured to prioritize gateway selection with beautiful UI for BYOK vs Hosted modes - Telemetry Improvements: modified submission to send FULL data to gateway while maintaining security filtering for users - All 344 tests passing, telemetry integration ready for production 2025-05-30 16:35:40 -04:00
Eyal Toledano
75b7b93fa4 feat(task-90): Complete telemetry integration with /auth/init + fix Roo test brittleness
- Updated telemetry submission to use /auth/init endpoint instead of /api/v1/users
- Hardcoded gateway endpoint to http://localhost:4444/api/v1/telemetry for all users
- Removed unnecessary service API key complexity - simplified authentication
- Enhanced init.js with hosted gateway setup option and user registration
- Added configureTelemetrySettings() to update .taskmasterconfig with credentials
- Fixed brittle Roo integration tests that required exact string matching
- Updated tests to use flexible regex patterns supporting any quote style
- All test suites now green: 332 tests passed, 11 skipped, 0 failed
- All 11 telemetry tests passing with live gateway integration verified
- Ready for ai-services-unified.js integration in subtask 90.3
2025-05-28 22:38:18 -04:00
Eyal Toledano
6ec3a10083 feat(task-90): Complete subtask 90.2 with gateway integration and init.js enhancements
- Hardcoded gateway endpoint to http://localhost:4444/api/v1/telemetry
- Updated credential handling to use config-based approach (not env vars)
- Added registerUserWithGateway() function for user registration/lookup
- Enhanced init.js with hosted gateway setup option and configureTelemetrySettings()
- Updated all 10 tests to reflect new architecture - all passing
- Security features maintained: sensitive data filtering, Bearer token auth
- Ready for ai-services-unified.js integration in subtask 90.3
2025-05-28 21:05:25 -04:00
Eyal Toledano
8ad31ac5eb feat(task-90): Complete subtask 90.2 with secure telemetry submission service - Implemented telemetry submission with Zod validation, retry logic, graceful error handling, and user opt-out support - Used correct Bearer token authentication with X-User-Email header - Successfully tested with live gateway endpoint, all 6 tests passing - Verified security: sensitive data filtered before submission 2025-05-28 15:12:31 -04:00
Eyal Toledano
2773e347f9 feat(task-90): Complete subtask 90.2
- Implement secure telemetry submission service
- Created scripts/modules/telemetry-submission.js with submitTelemetryData function
- Implemented secure filtering: removes commandArgs and fullOutput before remote submission
- Added comprehensive validation using Zod schema for telemetry data integrity
- Implemented exponential backoff retry logic (3 attempts max) with smart retry decisions
- Added graceful error handling that never blocks execution
- Respects user opt-out preferences via config.telemetryEnabled
- Configured for localhost testing endpoint (http://localhost:4444/api/v1/telemetry) for now
- Added comprehensive test coverage with 6/6 passing tests covering all scenarios
- Includes submitTelemetryDataAsync for fire-and-forget submissions
2025-05-28 14:51:42 -04:00
Eyal Toledano
bfc39dd377 feat(task-90): Complete subtask 90.1
- Implement secure telemetry capture with filtering - Enhanced ai-services-unified.js to capture commandArgs and fullOutput in telemetry - Added filterSensitiveTelemetryData() function to prevent sensitive data exposure - Updated processMCPResponseData() to filter telemetry before sending to MCP clients - Verified CLI displayAiUsageSummary() only shows safe fields - Added comprehensive test coverage with 4 passing tests - Resolved critical security issue: API keys and sensitive data now filtered from responses
2025-05-28 14:26:24 -04:00
Eyal Toledano
9e6c190af3 fix(move-task): Fix duplicate task creation when moving subtask to standalone task 2025-05-28 14:05:30 -04:00
Eyal Toledano
ab64437ad2 chore: task management 2025-05-28 11:16:54 -04:00
Eyal Toledano
cb95a07771 chore: task management 2025-05-28 11:16:09 -04:00
Eyal Toledano
c096f3fe9d Merge branch 'v017-adds' into gateway 2025-05-28 11:13:26 -04:00
Eyal Toledano
b6a3b8d385 chore: task management - moves 87,88,89 to 90,91,92 2025-05-28 10:38:33 -04:00
Eyal Toledano
78397fe0be chore: formatting 2025-05-28 10:25:39 -04:00
Eyal Toledano
f9b89dc25c fix(move): Fix move command bug that left duplicate tasks
- Fixed logic in moveTaskToNewId function that was incorrectly treating task-to-task moves as subtask creation instead of task replacement
- Updated moveTaskToNewId to properly handle replacing existing destination tasks instead of just placeholders
- The move command now correctly replaces destination tasks and cleans up properly without leaving duplicates

- Task Management: Moved task 93 (Google Vertex AI Provider) to position 88, Moved task 94 (Azure OpenAI Provider) to position 89, Updated task dependencies and regenerated task files, Cleaned up orphaned task files automatically
- All important validations remain in place: Prevents moving tasks to themselves, Prevents moving parent tasks to their own subtasks, Prevents circular dependencies
- Resolves the issue where moving tasks would leave both source and destination tasks in tasks.json and file system
2025-05-28 10:25:15 -04:00
Eyal Toledano
ca69e1294f Merge branch 'next' of github.com:eyaltoledano/claude-task-master into v017-adds 2025-05-28 10:08:14 -04:00
Eyal Toledano
ce09d9cdc3 chore: task mgmt 2025-05-28 09:56:08 -04:00
Ralph Khreish
669b744ced Feat/add nvmrc (#612)
* feat: Add .nvmrc and align engines to Node 20

* chore: set nvm to 22, engines to 18

* chore: format

* chore: add changeset

---------

Co-authored-by: Amir Golan <amirgolan@Amirs-MacBook-Pro.local>
2025-05-28 15:02:15 +02:00
Nathan Marley
f058543888 Replace prettier with biome (#531) 2025-05-28 14:47:16 +02:00
Eyal Toledano
b5c2cf47b0 chore: task management 2025-05-28 00:29:43 -04:00
Ralph Khreish
acd5c1ea3d chore: add contributing.md (#611) 2025-05-28 00:59:14 +02:00
github-actions[bot]
682b54e103 docs: Auto-update and format models.md 2025-05-27 22:42:42 +00:00
Ralph Khreish
6a8a68e1a3 Feat/add.azure.and.other.providers (#607)
* fix: claude-4 not having the right max_tokens

* feat: add bedrock support

* chore: fix package-lock.json

* fix: rename baseUrl to baseURL

* feat: add azure support

* fix: final touches of azure integration

* feat: add google vertex provider

* chore: fix tests and refactor task-manager.test.js

* chore: move task 92 to 94
2025-05-28 00:42:31 +02:00
Ralph Khreish
80735f9e60 feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution (#604)
* feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution

- Added support for the TASK_MASTER_PROJECT_ROOT environment variable in MCP configuration, establishing a clear precedence order for project root resolution.
- Updated utility functions to prioritize the environment variable, followed by args.projectRoot and session-based resolution.
- Enhanced error handling and logging for project root determination.
- Introduced new tasks for comprehensive testing and documentation updates related to the new configuration options.

* chore: fix CI issues
2025-05-28 00:32:34 +02:00
Eyal Toledano
ac36e2497e chore: task management and removes mistakenly staged changes 2025-05-27 12:43:59 -04:00
Eyal Toledano
1d4b80fe6f chore: task management 2025-05-27 12:41:08 -04:00
github-actions[bot]
48732d5423 docs: Auto-update and format models.md 2025-05-25 22:13:23 -04:00
Eyal Toledano
2d520de269 fix(add-task): removes stdout in add-task which will crash MCP server (#593)
* fix(add-task): fixes an isse in which stdout leaks out of add-task causing the mcp server to crash if used.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-25 22:13:23 -04:00
Eyal Toledano
023f51c579 feat(research): Adds MCP tool for command
- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.
2025-05-25 20:16:48 -04:00
Eyal Toledano
1e020023ed feat(show): add comma-separated ID support for multi-task viewing
- Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations.
- New features include multiple task retrieval, smart display logic, interactive action menu with batch operations, MCP array response for AI agent efficiency, and support for mixed parent tasks and subtasks.
- Implementation includes updated CLI show command, enhanced MCP get_task tool, modified showTaskDirect function, and maintained full backward compatibility.
- Documentation updated across all relevant files.

Benefits include faster context gathering for AI agents, improved workflow with interactive batch operations, better UX with responsive layout, and enhanced API efficiency.
2025-05-25 19:39:23 -04:00
Eyal Toledano
325f5a2aa3 chore: formatting 2025-05-25 18:58:42 -04:00
Eyal Toledano
de46bfd84b chore: removes task004 chat that had like 11k lines lol. 2025-05-25 18:50:59 -04:00
Eyal Toledano
cc26c36366 feat(research): Add subtasks to fuzzy search and follow-up questions
- Enhanced fuzzy search to include subtasks in discovery - Added interactive follow-up question functionality using inquirer
- Improved context discovery by including both tasks and subtasks
- Follow-up option for research with default to 'n' for quick workflow
2025-05-25 18:48:39 -04:00
Eyal Toledano
15ad34928d fix(move-task): Fix critical bugs in task move functionality
- Fixed parent-to-parent task moves where original task would remain as duplicate
- Fixed moving tasks to become subtasks of empty parents (validation errors)
- Fixed moving subtasks between different parent tasks
- Improved comma-separated batch moves with proper error handling
- Updated MCP tool to use core logic instead of custom implementation
- Resolves task duplication issues and enables proper task hierarchy reorganization
2025-05-25 18:03:43 -04:00
Eyal Toledano
f74d639110 fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks. 2025-05-25 17:49:32 -04:00
Eyal Toledano
de58e9ede5 feat(fuzzy): improves fuzzy search to introspect into subtasks as well. might still need improvement. 2025-05-25 17:33:00 -04:00
Eyal Toledano
947541e4ee docs: add context gathering rule and update existing rules
- Create comprehensive context_gathering.mdc rule documenting ContextGatherer utility patterns, FuzzyTaskSearch integration, token breakdown display, code block syntax highlighting, and enhanced result display patterns
- Update new_features.mdc to include context gathering step
- Update commands.mdc with context-aware command pattern
- Update ui.mdc with enhanced display patterns and syntax highlighting
- Update utilities.mdc to document new context gathering utilities
- Update glossary.mdc to include new context_gathering rule
- Establishes standardized patterns for building intelligent, context-aware commands that can leverage project knowledge for better AI assistance
2025-05-25 17:19:28 -04:00
Eyal Toledano
275cd55da7 feat: implement research command with enhanced context gathering - Add comprehensive research command with AI-powered queries - Implement ContextGatherer utility for reusable context extraction - Support multiple context types: tasks, files, custom text, project tree - Add fuzzy search integration for automatic task discovery - Implement detailed token breakdown display with syntax highlighting - Add enhanced UI with boxed output and code block formatting - Support different detail levels (low, medium, high) for responses - Include project-specific context for more relevant AI responses - Add token counting with gpt-tokens library integration - Create reusable patterns for future context-aware commands - Task 94.4 completed 2025-05-25 03:51:51 -04:00
Eyal Toledano
67ac212973 chore: task management 2025-05-25 01:26:14 -04:00
Eyal Toledano
235371ff47 chore: task management and small bug fix. 2025-05-25 01:03:58 -04:00
celgost
b60e1cf835 revamping readme (#522) 2025-05-24 17:21:15 +02:00
Ralph Khreish
d1e45ff50e Merge pull request #589 from eyaltoledano/changeset-release/main
Version Packages
2025-05-24 16:25:26 +02:00
github-actions[bot]
1513858da4 Version Packages 2025-05-24 14:07:53 +00:00
Ralph Khreish
59dcf4bd64 Release 0.15.0
Release 0.15.0
2025-05-24 16:07:24 +02:00
github-actions[bot]
a09ba021c5 chore: rc version bump 2025-05-24 00:44:47 +00:00
Eyal Toledano
e906166141 Merge pull request #567 from eyaltoledano/parse-prd-research
v0.15 improvements & new features
2025-05-23 20:42:41 -04:00
Eyal Toledano
231e569e84 Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7 2025-05-23 20:33:45 -04:00
Eyal Toledano
09add37423 feat(models): Add comprehensive Ollama model validation and interactive setup - Add 'Custom Ollama model' option to interactive setup (--setup) - Implement live validation against local Ollama instance via /api/tags - Support configurable Ollama endpoints from .taskmasterconfig - Add robust error handling for server connectivity and model existence - Enhance user experience with clear validation feedback - Support both MCP server and CLI interfaces 2025-05-23 20:20:39 -04:00
Eyal Toledano
91fc779714 chore: adjusts changesets and an import. 2025-05-23 17:41:25 -04:00
Eyal Toledano
8c69c0aafd Task management, research, improvements for 24, 41 and 51 2025-05-23 17:30:25 -04:00
Eyal Toledano
43ad75c7fa chore: formatting 2025-05-23 14:44:53 -04:00
Eyal Toledano
a59dd037cf chore: changeset for Claude Code rules. depends on us adding it as an init option from the other PR. 2025-05-23 13:23:26 -04:00
Eyal Toledano
3293c7858b feat: adds AGENTS.md to the assets/ folder so we can add it into the project if the user selects Claude Code as the IDE of choice in the init sequence (to be done in another PR) 2025-05-23 13:17:45 -04:00
Eyal Toledano
b371808524 fix(models): Adjusts the Claude 4 models and introduces the llms-install.md file to enable AI agents to install the Taskmaster MCP server programmatically. 2025-05-23 12:59:14 -04:00
Shrey Paharia
86d8f00af8 Add next task to set status for mcp server (#558) 2025-05-22 11:09:36 +02:00
Eyal Toledano
0c55ce0165 chore: linting and prettier 2025-05-22 04:17:06 -04:00
Eyal Toledano
5a91941913 removes changeset for set/mark which i didnt add in the end 2025-05-22 04:15:10 -04:00
Eyal Toledano
04af16de27 feat(move-tasks): Implement move command for tasks and subtasks
Adds a new CLI command and MCP tool to reorganize tasks and subtasks within the hierarchy. Features include:
- Moving tasks between different positions in the task list
- Converting tasks to subtasks and vice versa
- Moving subtasks between parents
- Moving multiple tasks at once with comma-separated IDs
- Creating placeholder tasks when moving to new IDs
- Validation to prevent accidental data loss

This is particularly useful for resolving merge conflicts when multiple team members create tasks on different branches.
2025-05-22 04:14:22 -04:00
Eyal Toledano
edf0f23005 update changesets 2025-05-22 03:03:25 -04:00
Eyal Toledano
e0e1155260 fix(parse-prd): Fix parameter naming inconsistency in CLI parse-prd command 2025-05-22 02:59:32 -04:00
Eyal Toledano
70f4054f26 feat(parse-prd): Add research flag to parse-prd command for enhanced PRD analysis. Significantly improves parse PRD system prompt when used with research. 2025-05-22 02:57:51 -04:00
Eyal Toledano
34c769bcd0 feat(analyze): add task ID filtering to analyze-complexity command
Enhance analyze-complexity to support analyzing specific tasks by ID or range:
- Add --id option for comma-separated task IDs
- Add --from/--to options for analyzing tasks within a range
- Implement intelligent merging with existing reports
- Update CLI, MCP tools, and direct functions for consistent support
- Add changeset documenting the feature
2025-05-22 01:49:41 -04:00
Eyal Toledano
34df2c8bbd feat: automatically create tasks.json when missing (Task #68)
This commit implements automatic tasks.json file creation when it doesn't exist:

- When tasks.json is missing or invalid, create a new one with { tasks: [] }
- Allows adding tasks immediately after initializing a project without parsing a PRD
- Replaces error with informative feedback about file creation
- Enables smoother workflow for new projects or directories

This change improves user experience by removing the requirement to parse a PRD
before adding the first task to a newly initialized project. Closes #494
2025-05-22 01:18:27 -04:00
Eyal Toledano
5e9bc28abe feat(add-task): enhance dependency detection with semantic search
This commit significantly improves the  functionality by implementing
fuzzy semantic search to find contextually relevant dependencies:

- Add Fuse.js for powerful fuzzy search capability with weighted multi-field matching
- Implement score-based relevance ranking with high/medium relevance tiers
- Enhance context generation to include detailed information about similar tasks
- Fix context shadowing issue that prevented detailed task information from
  reaching the AI model
- Add informative CLI output showing semantic search results and dependency patterns
- Improve formatting of dependency information in prompts with task titles

The result is that newly created tasks are automatically placed within the correct
dependency structure without manual intervention, with the AI having much better
context about which tasks are most relevant to the new one being created.

This significantly improves the user experience by reducing the need to manually
update task dependencies after creation, all without increasing token usage or costs.
2025-05-22 01:09:40 -04:00
Eyal Toledano
d2e64318e2 fix(ai-services): add logic for API key checking in fallback sequence 2025-05-21 22:49:25 -04:00
Eyal Toledano
4c835264ac task management 2025-05-21 21:23:39 -04:00
github-actions[bot]
c882f89a8c Version Packages 2025-05-20 18:40:38 +02:00
151 changed files with 42829 additions and 13858 deletions

View File

@@ -0,0 +1,44 @@
---
'task-master-ai': minor
---
Add comprehensive AI-powered research command with intelligent context gathering and interactive follow-ups.
The new `research` command provides AI-powered research capabilities that automatically gather relevant project context to answer your questions. The command intelligently selects context from multiple sources and supports interactive follow-up questions in CLI mode.
**Key Features:**
- **Intelligent Task Discovery**: Automatically finds relevant tasks and subtasks using fuzzy search based on your query keywords, supplementing any explicitly provided task IDs
- **Multi-Source Context**: Gathers context from tasks, files, project structure, and custom text to provide comprehensive answers
- **Interactive Follow-ups**: CLI users can ask follow-up questions that build on the conversation history while allowing fresh context discovery for each question
- **Flexible Detail Levels**: Choose from low (concise), medium (balanced), or high (comprehensive) response detail levels
- **Token Transparency**: Displays detailed token breakdown showing context size, sources, and estimated costs
- **Enhanced Display**: Syntax-highlighted code blocks and structured output with clear visual separation
**Usage Examples:**
```bash
# Basic research with auto-discovered context
task-master research "How should I implement user authentication?"
# Research with specific task context
task-master research "What's the best approach for this?" --id=15,23.2
# Research with file context and project tree
task-master research "How does the current auth system work?" --files=src/auth.js,config/auth.json --tree
# Research with custom context and low detail
task-master research "Quick implementation steps?" --context="Using JWT tokens" --detail=low
```
**Context Sources:**
- **Tasks**: Automatically discovers relevant tasks/subtasks via fuzzy search, plus any explicitly specified via `--id`
- **Files**: Include specific files via `--files` for code-aware responses
- **Project Tree**: Add `--tree` to include project structure overview
- **Custom Context**: Provide additional context via `--context` for domain-specific information
**Interactive Features (CLI only):**
- Follow-up questions that maintain conversation history
- Fresh fuzzy search for each follow-up to discover newly relevant tasks
- Cumulative context building across the conversation
- Clean visual separation between exchanges
The research command integrates with the existing AI service layer and supports all configured AI providers. MCP integration provides the same functionality for programmatic access without interactive features.

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': patch
---
Fix critical bugs in task move functionality:
- **Fixed moving tasks to become subtasks of empty parents**: When moving a task to become a subtask of a parent that had no existing subtasks (e.g., task 89 → task 98.1), the operation would fail with validation errors.
- **Fixed moving subtasks between parents**: Subtasks can now be properly moved between different parent tasks, including to parents that previously had no subtasks.
- **Improved comma-separated batch moves**: Multiple tasks can now be moved simultaneously using comma-separated IDs (e.g., "88,90" → "92,93") with proper error handling and atomic operations.
These fixes enables proper task hierarchy reorganization for corner cases that were previously broken.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add AWS bedrock support

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': minor
---
# Add Google Vertex AI Provider Integration
- Implemented `VertexAIProvider` class extending BaseAIProvider
- Added authentication and configuration handling for Vertex AI
- Updated configuration manager with Vertex-specific getters
- Modified AI services unified system to integrate the provider
- Added documentation for Vertex AI setup and configuration
- Updated environment variable examples for Vertex AI support
- Implemented specialized error handling for Vertex-specific issues

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add support for Azure

View File

@@ -0,0 +1,17 @@
---
'task-master-ai': minor
---
Add comprehensive `research` MCP tool for AI-powered research queries
- **New MCP Tool**: `research` tool enables AI-powered research with project context
- **Context Integration**: Supports task IDs, file paths, custom context, and project tree
- **Fuzzy Task Discovery**: Automatically finds relevant tasks using semantic search
- **Token Management**: Detailed token counting and breakdown by context type
- **Multiple Detail Levels**: Support for low, medium, and high detail research responses
- **Telemetry Integration**: Full cost tracking and usage analytics
- **Direct Function**: `researchDirect` with comprehensive parameter validation
- **Silent Mode**: Prevents console output interference with MCP JSON responses
- **Error Handling**: Robust error handling with proper MCP response formatting
This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

View File

@@ -0,0 +1,5 @@
---
"task-master-ai": minor
---
Increased minimum required node version to > 18 (was > 14)

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Renamed baseUrl to baseURL

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4

View File

@@ -0,0 +1,7 @@
---
'task-master-ai': minor
---
Add TASK_MASTER_PROJECT_ROOT env variable supported in mcp.json and .env for project root resolution
- Some users were having issues where the MCP wasn't able to detect the location of their project root, you can now set the `TASK_MASTER_PROJECT_ROOT` environment variable to the root of your project.

View File

@@ -0,0 +1,19 @@
---
'task-master-ai': minor
---
Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations
**New Features:**
- **Multiple Task Retrieval**: Pass comma-separated IDs to get/show multiple tasks at once (e.g., `task-master show 1,3,5` or MCP `get_task` with `id: "1,3,5"`)
- **Smart Display Logic**: Single ID shows detailed view, multiple IDs show compact summary table with interactive options
- **Batch Action Menu**: Interactive menu for multiple tasks with copy-paste ready commands for common operations (mark as done/in-progress, expand all, view dependencies, etc.)
- **MCP Array Response**: MCP tool returns structured array of task objects for efficient AI agent context gathering
**Benefits:**
- **Faster Context Gathering**: AI agents can collect multiple tasks/subtasks in one call instead of iterating
- **Improved Workflow**: Interactive batch operations reduce repetitive command execution
- **Better UX**: Responsive layout adapts to terminal width, maintains consistency with existing UI patterns
- **API Efficiency**: RESTful array responses in MCP format enable more sophisticated integrations
This enhancement maintains full backward compatibility while significantly improving efficiency for both human users and AI agents working with multiple tasks.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix add-task MCP command causing an error

View File

@@ -1,8 +1,29 @@
{ {
"mcpServers": { "mcpServers": {
"task-master-ai": { "task-master-ai-tm": {
"command": "node", "command": "node",
"args": ["./mcp-server/server.js"], "args": [
"./mcp-server/server.js"
],
"env": {
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
}
},
"task-master-ai": {
"command": "npx",
"args": [
"-y",
"--package=task-master-ai",
"task-master-ai"
],
"env": { "env": {
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE", "ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE", "PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
@@ -15,5 +36,9 @@
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE" "OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
} }
} }
},
"env": {
"TASKMASTER_TELEMETRY_API_KEY": "339a81c9-5b9c-4d60-92d8-cba2ee2a8cc3",
"TASKMASTER_TELEMETRY_USER_EMAIL": "user_1748640077834@taskmaster.dev"
} }
} }

View File

@@ -50,6 +50,7 @@ This rule guides AI assistants on how to view, configure, and interact with the
- **Key Locations** (See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) - Configuration Management): - **Key Locations** (See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) - Configuration Management):
- **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`. - **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`.
- **CLI:** Set keys in a `.env` file in the project root. - **CLI:** Set keys in a `.env` file in the project root.
- As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
- **Provider List & Keys:** - **Provider List & Keys:**
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`. - **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
- **`google`**: Requires `GOOGLE_API_KEY`. - **`google`**: Requires `GOOGLE_API_KEY`.

View File

@@ -1,6 +1,7 @@
--- ---
description: Guidelines for interacting with the unified AI service layer. description: Guidelines for interacting with the unified AI service layer.
globs: scripts/modules/ai-services-unified.js, scripts/modules/task-manager/*.js, scripts/modules/commands.js globs: scripts/modules/ai-services-unified.js, scripts/modules/task-manager/*.js, scripts/modules/commands.js
alwaysApply: false
--- ---
# AI Services Layer Guidelines # AI Services Layer Guidelines
@@ -91,7 +92,7 @@ This document outlines the architecture and usage patterns for interacting with
* ✅ **DO**: Centralize **all** LLM calls through `generateTextService` or `generateObjectService`. * ✅ **DO**: Centralize **all** LLM calls through `generateTextService` or `generateObjectService`.
* ✅ **DO**: Determine the appropriate `role` (`main`, `research`, `fallback`) in your core logic and pass it to the service. * ✅ **DO**: Determine the appropriate `role` (`main`, `research`, `fallback`) in your core logic and pass it to the service.
* ✅ **DO**: Pass the `session` object (received in the `context` parameter, especially from direct function wrappers) to the service call when in MCP context. * ✅ **DO**: Pass the `session` object (received in the `context` parameter, especially from direct function wrappers) to the service call when in MCP context.
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP). * ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP). FYI: As the AI agent, you do not have access to read the .env -- so do not attempt to recreate it!
* ✅ **DO**: Ensure `.taskmasterconfig` exists and has valid provider/model IDs for the roles you intend to use (manage via `task-master models --setup`). * ✅ **DO**: Ensure `.taskmasterconfig` exists and has valid provider/model IDs for the roles you intend to use (manage via `task-master models --setup`).
* ✅ **DO**: Use `generateTextService` and implement robust manual JSON parsing (with Zod validation *after* parsing) when structured output is needed, as `generateObjectService` has shown unreliability with some providers/schemas. * ✅ **DO**: Use `generateTextService` and implement robust manual JSON parsing (with Zod validation *after* parsing) when structured output is needed, as `generateObjectService` has shown unreliability with some providers/schemas.
* ❌ **DON'T**: Import or call anything from the old `ai-services.js`, `ai-client-factory.js`, or `ai-client-utils.js` files. * ❌ **DON'T**: Import or call anything from the old `ai-services.js`, `ai-client-factory.js`, or `ai-client-utils.js` files.

View File

@@ -39,12 +39,12 @@ alwaysApply: false
- **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)): - **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)):
- Exports `generateTextService`, `generateObjectService`. - Exports `generateTextService`, `generateObjectService`.
- Handles provider/model selection based on `role` and `.taskmasterconfig`. - Handles provider/model selection based on `role` and `.taskmasterconfig`.
- Resolves API keys (from `.env` or `session.env`). - Resolves API keys (from `.env` or `session.env`). As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
- 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. - 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.
- **Responsibilities**: Interact directly with Vercel AI SDK adapters. - **Responsibilities**: Interact directly with Vercel AI SDK adapters.
@@ -63,7 +63,7 @@ alwaysApply: false
- API Key Resolution (`resolveEnvVariable`). - API Key Resolution (`resolveEnvVariable`).
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`). - Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
- **[`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`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling.

View File

@@ -329,6 +329,60 @@ When implementing commands that delete or remove data (like `remove-task` or `re
}; };
``` ```
## Context-Aware Command Pattern
For AI-powered commands that benefit from project context, follow the research command pattern:
- **Context Integration**:
- ✅ DO: Use `ContextGatherer` utility for multi-source context extraction
- ✅ DO: Support task IDs, file paths, custom context, and project tree
- ✅ DO: Implement fuzzy search for automatic task discovery
- ✅ DO: Display detailed token breakdown for transparency
```javascript
// ✅ DO: Follow this pattern for context-aware commands
programInstance
.command('research')
.description('Perform AI-powered research queries with project context')
.argument('<prompt>', 'Research prompt to investigate')
.option('-i, --id <ids>', 'Comma-separated task/subtask IDs to include as context')
.option('-f, --files <paths>', 'Comma-separated file paths to include as context')
.option('-c, --context <text>', 'Additional custom context')
.option('--tree', 'Include project file tree structure')
.option('-d, --detail <level>', 'Output detail level: low, medium, high', 'medium')
.action(async (prompt, options) => {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown and execute AI call
// Implementation continues...
});
```
## Error Handling ## Error Handling
- **Exception Management**: - **Exception Management**:

View File

@@ -0,0 +1,268 @@
---
description: Standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
globs:
alwaysApply: false
---
# Context Gathering Patterns and Utilities
This document outlines the standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
## Core Context Gathering Utility
The `ContextGatherer` class (`scripts/modules/utils/contextGatherer.js`) provides a centralized, reusable utility for extracting context from multiple sources:
### **Key Features**
- **Multi-source Context**: Tasks, files, custom text, project file tree
- **Token Counting**: Detailed breakdown using `gpt-tokens` library
- **Format Support**: Different output formats (research, chat, system-prompt)
- **Error Handling**: Graceful handling of missing files, invalid task IDs
- **Performance**: File size limits, depth limits for tree generation
### **Usage Pattern**
```javascript
import { ContextGatherer } from '../utils/contextGatherer.js';
// Initialize with project paths
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// Gather context with detailed token breakdown
const result = await gatherer.gather({
tasks: ['15', '16.2'], // Task and subtask IDs
files: ['src/api.js', 'README.md'], // File paths
customContext: 'Additional context text',
includeProjectTree: true, // Include file tree
format: 'research', // Output format
includeTokenCounts: true // Get detailed token breakdown
});
// Access results
const contextString = result.context;
const tokenBreakdown = result.tokenBreakdown;
```
### **Token Breakdown Structure**
```javascript
{
customContext: { tokens: 150, characters: 800 },
tasks: [
{ id: '15', type: 'task', title: 'Task Title', tokens: 245, characters: 1200 },
{ id: '16.2', type: 'subtask', title: 'Subtask Title', tokens: 180, characters: 900 }
],
files: [
{ path: 'src/api.js', tokens: 890, characters: 4500, size: '4.5 KB' }
],
projectTree: { tokens: 320, characters: 1600 },
total: { tokens: 1785, characters: 8000 }
}
```
## Fuzzy Search Integration
The `FuzzyTaskSearch` class (`scripts/modules/utils/fuzzyTaskSearch.js`) provides intelligent task discovery:
### **Key Features**
- **Semantic Matching**: Uses Fuse.js for similarity scoring
- **Purpose Categories**: Pattern-based task categorization
- **Relevance Scoring**: High/medium/low relevance thresholds
- **Context-Aware**: Different search configurations for different use cases
### **Usage Pattern**
```javascript
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
// Initialize with tasks data and context
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
// Find relevant tasks
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
// Get task IDs for context gathering
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
## Implementation Patterns for Commands
### **1. Context-Aware Command Structure**
```javascript
// In command action handler
async function commandAction(prompt, options) {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown (for CLI)
if (outputFormat === 'text') {
displayDetailedTokenBreakdown(contextResult.tokenBreakdown);
}
// 6. Use context in AI call
const aiResult = await generateTextService(role, session, systemPrompt, userPrompt);
// 7. Display results with enhanced formatting
displayResults(aiResult, contextResult.tokenBreakdown);
}
```
### **2. Token Display Pattern**
```javascript
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
// Build context breakdown
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
if (tokenBreakdown.files?.length > 0) {
const fileDetails = tokenBreakdown.files.map(file =>
` ${file.path}: ${file.tokens.toLocaleString()} (${file.size})`
).join('\n');
sections.push(`Files (${tokenBreakdown.files.reduce((sum, f) => sum + f.tokens, 0).toLocaleString()}):\n${fileDetails}`);
}
// Add prompts breakdown
sections.push(`Prompts: system ${systemTokens.toLocaleString()}, user ${userTokens.toLocaleString()}`);
// Display in clean box
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **3. Enhanced Result Display Pattern**
```javascript
function displayResults(result, query, detailLevel, tokenBreakdown) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and highlight code blocks
const processedResult = processCodeBlocks(result);
// Main content in clean box
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Research complete'));
}
```
## Code Block Enhancement
### **Syntax Highlighting Pattern**
```javascript
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
## Integration Guidelines
### **When to Use Context Gathering**
- ✅ **DO**: Use for AI-powered commands that benefit from project context
- ✅ **DO**: Use when users might want to reference specific tasks or files
- ✅ **DO**: Use for research, analysis, or generation commands
- ❌ **DON'T**: Use for simple CRUD operations that don't need AI context
### **Performance Considerations**
- ✅ **DO**: Set reasonable file size limits (50KB default)
- ✅ **DO**: Limit project tree depth (3-5 levels)
- ✅ **DO**: Provide token counts to help users understand context size
- ✅ **DO**: Allow users to control what context is included
### **Error Handling**
- ✅ **DO**: Gracefully handle missing files with warnings
- ✅ **DO**: Validate task IDs and provide helpful error messages
- ✅ **DO**: Continue processing even if some context sources fail
- ✅ **DO**: Provide fallback behavior when context gathering fails
### **Future Command Integration**
Commands that should consider adopting this pattern:
- `analyze-complexity` - Could benefit from file context
- `expand-task` - Could use related task context
- `update-task` - Could reference similar tasks for consistency
- `add-task` - Could use project context for better task generation
## Export Patterns
### **Context Gatherer Module**
```javascript
export {
ContextGatherer,
createContextGatherer // Factory function
};
```
### **Fuzzy Search Module**
```javascript
export {
FuzzyTaskSearch,
PURPOSE_CATEGORIES,
RELEVANCE_THRESHOLDS
};
```
This context gathering system provides a foundation for building more intelligent, context-aware commands that can leverage project knowledge to provide better AI-powered assistance.

View File

@@ -49,6 +49,7 @@ Task Master offers two primary ways to interact:
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed - Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
- Respect dependency chains and task priorities when selecting work - Respect dependency chains and task priorities when selecting work
- Report progress regularly using `get_tasks` / `task-master list` - Report progress regularly using `get_tasks` / `task-master list`
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
## Task Complexity Analysis ## Task Complexity Analysis
@@ -154,6 +155,25 @@ Taskmaster configuration is managed through two main mechanisms:
- Task files are automatically regenerated after dependency changes - Task files are automatically regenerated after dependency changes
- Dependencies are visualized with status indicators in task listings and files - Dependencies are visualized with status indicators in task listings and files
## Task Reorganization
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
- This command supports several use cases:
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
- The system includes validation to prevent data loss:
- Allows moving to non-existent IDs by creating placeholder tasks
- Prevents moving to existing task IDs that have content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- The system maintains proper parent-child relationships and dependency integrity
- Task files are automatically regenerated after the move operation
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
## Iterative Subtask Implementation ## Iterative Subtask Implementation
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation: Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:

View File

@@ -0,0 +1,367 @@
---
description: Git workflow integrated with Task Master for feature development and collaboration
globs: "**/*"
alwaysApply: true
---
# Git Workflow with Task Master Integration
## **Branch Strategy**
### **Main Branch Protection**
- **main** branch contains production-ready code
- All feature development happens on task-specific branches
- Direct commits to main are prohibited
- All changes merge via Pull Requests
### **Task Branch Naming**
```bash
# ✅ DO: Use consistent task branch naming
task-001 # For Task 1
task-004 # For Task 4
task-015 # For Task 15
# ❌ DON'T: Use inconsistent naming
feature/user-auth
fix-database-issue
random-branch-name
```
## **Workflow Overview**
```mermaid
flowchart TD
A[Start: On main branch] --> B[Pull latest changes]
B --> C[Create task branch<br/>git checkout -b task-XXX]
C --> D[Set task status: in-progress]
D --> E[Get task context & expand if needed]
E --> F[Identify next subtask]
F --> G[Set subtask: in-progress]
G --> H[Research & collect context<br/>update_subtask with findings]
H --> I[Implement subtask]
I --> J[Update subtask with completion]
J --> K[Set subtask: done]
K --> L[Git commit subtask]
L --> M{More subtasks?}
M -->|Yes| F
M -->|No| N[Run final tests]
N --> O[Commit tests if added]
O --> P[Push task branch]
P --> Q[Create Pull Request]
Q --> R[Human review & merge]
R --> S[Switch to main & pull]
S --> T[Delete task branch]
T --> U[Ready for next task]
style A fill:#e1f5fe
style C fill:#f3e5f5
style G fill:#fff3e0
style L fill:#e8f5e8
style Q fill:#fce4ec
style R fill:#f1f8e9
style U fill:#e1f5fe
```
## **Complete Task Development Workflow**
### **Phase 1: Task Preparation**
```bash
# 1. Ensure you're on main branch and pull latest
git checkout main
git pull origin main
# 2. Check current branch status
git branch # Verify you're on main
# 3. Create task-specific branch
git checkout -b task-004 # For Task 4
# 4. Set task status in Task Master
# Use: set_task_status tool or `task-master set-status --id=4 --status=in-progress`
```
### **Phase 2: Task Analysis & Planning**
```bash
# 5. Get task context and expand if needed
# Use: get_task tool or `task-master show 4`
# Use: expand_task tool or `task-master expand --id=4 --research --force` (if complex)
# 6. Identify next subtask to work on
# Use: next_task tool or `task-master next`
```
### **Phase 3: Subtask Implementation Loop**
For each subtask, follow this pattern:
```bash
# 7. Mark subtask as in-progress
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=in-progress`
# 8. Gather context and research (if needed)
# Use: update_subtask tool with research flag or:
# `task-master update-subtask --id=4.1 --prompt="Research findings..." --research`
# 9. Collect code context through AI exploration
# Document findings in subtask using update_subtask
# 10. Implement the subtask
# Write code, tests, documentation
# 11. Update subtask with completion details
# Use: update_subtask tool or:
# `task-master update-subtask --id=4.1 --prompt="Implementation complete..."`
# 12. Mark subtask as done
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=done`
# 13. Commit the subtask implementation
git add .
git commit -m "feat(task-4): Complete subtask 4.1 - [Subtask Title]
- Implementation details
- Key changes made
- Any important notes
Subtask 4.1: [Brief description of what was accomplished]
Relates to Task 4: [Main task title]"
```
### **Phase 4: Task Completion**
```bash
# 14. When all subtasks are complete, run final testing
# Create test file if needed, ensure all tests pass
npm test # or jest, or manual testing
# 15. If tests were added/modified, commit them
git add .
git commit -m "test(task-4): Add comprehensive tests for Task 4
- Unit tests for core functionality
- Integration tests for API endpoints
- All tests passing
Task 4: [Main task title] - Testing complete"
# 16. Push the task branch
git push origin task-004
# 17. Create Pull Request
# Title: "Task 4: [Task Title]"
# Description should include:
# - Task overview
# - Subtasks completed
# - Testing approach
# - Any breaking changes or considerations
```
### **Phase 5: PR Merge & Cleanup**
```bash
# 18. Human reviews and merges PR into main
# 19. Switch back to main and pull merged changes
git checkout main
git pull origin main
# 20. Delete the feature branch (optional cleanup)
git branch -d task-004
git push origin --delete task-004
```
## **Commit Message Standards**
### **Subtask Commits**
```bash
# ✅ DO: Consistent subtask commit format
git commit -m "feat(task-4): Complete subtask 4.1 - Initialize Express server
- Set up Express.js with TypeScript configuration
- Added CORS and body parsing middleware
- Implemented health check endpoints
- Basic error handling middleware
Subtask 4.1: Initialize project with npm and install dependencies
Relates to Task 4: Setup Express.js Server Project"
# ❌ DON'T: Vague or inconsistent commits
git commit -m "fixed stuff"
git commit -m "working on task"
```
### **Test Commits**
```bash
# ✅ DO: Separate test commits when substantial
git commit -m "test(task-4): Add comprehensive tests for Express server setup
- Unit tests for middleware configuration
- Integration tests for health check endpoints
- Mock tests for database connection
- All tests passing with 95% coverage
Task 4: Setup Express.js Server Project - Testing complete"
```
### **Commit Type Prefixes**
- `feat(task-X):` - New feature implementation
- `fix(task-X):` - Bug fixes
- `test(task-X):` - Test additions/modifications
- `docs(task-X):` - Documentation updates
- `refactor(task-X):` - Code refactoring
- `chore(task-X):` - Build/tooling changes
## **Task Master Commands Integration**
### **Essential Commands for Git Workflow**
```bash
# Task management
task-master show <id> # Get task/subtask details
task-master next # Find next task to work on
task-master set-status --id=<id> --status=<status>
task-master update-subtask --id=<id> --prompt="..." --research
# Task expansion (for complex tasks)
task-master expand --id=<id> --research --force
# Progress tracking
task-master list # View all tasks and status
task-master list --status=in-progress # View active tasks
```
### **MCP Tool Equivalents**
When using Cursor or other MCP-integrated tools:
- `get_task` instead of `task-master show`
- `next_task` instead of `task-master next`
- `set_task_status` instead of `task-master set-status`
- `update_subtask` instead of `task-master update-subtask`
## **Branch Management Rules**
### **Branch Protection**
```bash
# ✅ DO: Always work on task branches
git checkout -b task-005
# Make changes
git commit -m "..."
git push origin task-005
# ❌ DON'T: Commit directly to main
git checkout main
git commit -m "..." # NEVER do this
```
### **Keeping Branches Updated**
```bash
# ✅ DO: Regularly sync with main (for long-running tasks)
git checkout task-005
git fetch origin
git rebase origin/main # or merge if preferred
# Resolve any conflicts and continue
```
## **Pull Request Guidelines**
### **PR Title Format**
```
Task <ID>: <Task Title>
Examples:
Task 4: Setup Express.js Server Project
Task 7: Implement User Authentication
Task 12: Add Stripe Payment Integration
```
### **PR Description Template**
```markdown
## Task Overview
Brief description of the main task objective.
## Subtasks Completed
- [x] 4.1: Initialize project with npm and install dependencies
- [x] 4.2: Configure TypeScript, ESLint and Prettier
- [x] 4.3: Create basic Express app with middleware and health check route
## Implementation Details
- Key architectural decisions made
- Important code changes
- Any deviations from original plan
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests passing
- [ ] Manual testing completed
## Breaking Changes
List any breaking changes or migration requirements.
## Related Tasks
Mention any dependent tasks or follow-up work needed.
```
## **Conflict Resolution**
### **Task Conflicts**
```bash
# If multiple people work on overlapping tasks:
# 1. Use Task Master's move functionality to reorganize
task-master move --from=5 --to=25 # Move conflicting task
# 2. Update task dependencies
task-master add-dependency --id=6 --depends-on=5
# 3. Coordinate through PR comments and task updates
```
### **Code Conflicts**
```bash
# Standard Git conflict resolution
git fetch origin
git rebase origin/main
# Resolve conflicts in files
git add .
git rebase --continue
```
## **Emergency Procedures**
### **Hotfixes**
```bash
# For urgent production fixes:
git checkout main
git pull origin main
git checkout -b hotfix-urgent-issue
# Make minimal fix
git commit -m "hotfix: Fix critical production issue
- Specific fix description
- Minimal impact change
- Requires immediate deployment"
git push origin hotfix-urgent-issue
# Create emergency PR for immediate review
```
### **Task Abandonment**
```bash
# If task needs to be abandoned or significantly changed:
# 1. Update task status
task-master set-status --id=<id> --status=cancelled
# 2. Clean up branch
git checkout main
git branch -D task-<id>
git push origin --delete task-<id>
# 3. Document reasoning in task
task-master update-task --id=<id> --prompt="Task cancelled due to..."
```
---
**References:**
- [Task Master Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Architecture Guidelines](mdc:.cursor/rules/architecture.mdc)
- [Task Master Commands](mdc:.cursor/rules/taskmaster.mdc)

View File

@@ -24,17 +24,22 @@ alwaysApply: false
The standard pattern for adding a feature follows this workflow: The standard pattern for adding a feature follows this workflow:
1. **Core Logic**: Implement the business logic in the appropriate module (e.g., [`task-manager.js`](mdc:scripts/modules/task-manager.js)). 1. **Core Logic**: Implement the business logic in the appropriate module (e.g., [`task-manager.js`](mdc:scripts/modules/task-manager.js)).
2. **AI Integration (If Applicable)**: 2. **Context Gathering (If Applicable)**:
- For AI-powered commands that benefit from project context, use the standardized context gathering patterns from [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc).
- Import `ContextGatherer` and `FuzzyTaskSearch` utilities for reusable context extraction.
- Support multiple context types: tasks, files, custom text, project tree.
- Implement detailed token breakdown display for transparency.
3. **AI Integration (If Applicable)**:
- Import necessary service functions (e.g., `generateTextService`, `streamTextService`) from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js). - Import necessary service functions (e.g., `generateTextService`, `streamTextService`) from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`). - Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`).
- Call the service function. - Call the service function.
- Handle the response (direct text or stream object). - Handle the response (direct text or stream object).
- **Important**: Prefer `generateTextService` for calls sending large context (like stringified JSON) where incremental display is not needed. See [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc) for detailed usage patterns and cautions. - **Important**: Prefer `generateTextService` for calls sending large context (like stringified JSON) where incremental display is not needed. See [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc) for detailed usage patterns and cautions.
3. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc). 4. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc). Consider enhanced formatting with syntax highlighting for code blocks.
4. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc). 5. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
5. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc)) 6. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
6. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed. 7. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
7. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). 8. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
## Critical Checklist for New Features ## Critical Checklist for New Features

View File

@@ -112,9 +112,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master show [id] [options]` * **CLI Command:** `task-master show [id] [options]`
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.` * **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.`
* **Key Parameters/Options:** * **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]` positional or `-i, --id <id>`) * `id`: `Required. The ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]. Supports comma-separated list of tasks to get multiple tasks at once.` positional or `-i, --id <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`) * `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Understand the full details, implementation notes, and test strategy for a specific task before starting work. * **Usage:** Understand the full details, implementation notes, and test strategy for a specific task before starting work.
* **CRITICAL INFORMATION** If you need to collect information from multiple tasks, use comma-separated IDs (i.e. 1,2,3) to receive an array of tasks. Do not needlessly get tasks one at a time if you need to get many as that is wasteful.
--- ---
@@ -269,11 +270,36 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`) * `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task. * **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
### 17. Move Task (`move_task`)
* **MCP Tool:** `move_task`
* **CLI Command:** `task-master move [options]`
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
* **Key Parameters/Options:**
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
* Moving a task to become a subtask
* Moving a subtask to become a standalone task
* Moving a subtask to a different parent
* Reordering subtasks within the same parent
* Moving a task to a new, non-existent ID (automatically creates placeholders)
* Moving multiple tasks at once with comma-separated IDs
* **Validation Features:**
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
* Validates that source tasks exist before attempting to move them
* Maintains proper parent-child relationships
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
--- ---
## Dependency Management ## Dependency Management
### 17. Add Dependency (`add_dependency`) ### 18. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency` * **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]` * **CLI Command:** `task-master add-dependency [options]`
@@ -284,7 +310,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`) * `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* **Usage:** Establish the correct order of execution between tasks. * **Usage:** Establish the correct order of execution between tasks.
### 18. Remove Dependency (`remove_dependency`) ### 19. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency` * **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]` * **CLI Command:** `task-master remove-dependency [options]`
@@ -295,7 +321,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`) * `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Update task relationships when the order of execution changes. * **Usage:** Update task relationships when the order of execution changes.
### 19. Validate Dependencies (`validate_dependencies`) ### 20. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies` * **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]` * **CLI Command:** `task-master validate-dependencies [options]`
@@ -304,7 +330,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`) * `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Audit the integrity of your task dependencies. * **Usage:** Audit the integrity of your task dependencies.
### 20. Fix Dependencies (`fix_dependencies`) ### 21. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies` * **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]` * **CLI Command:** `task-master fix-dependencies [options]`
@@ -317,7 +343,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
## Analysis & Reporting ## Analysis & Reporting
### 21. Analyze Project Complexity (`analyze_project_complexity`) ### 22. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity` * **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]` * **CLI Command:** `task-master analyze-complexity [options]`
@@ -330,7 +356,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Usage:** Used before breaking down tasks to identify which ones need the most attention. * **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress. * **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 22. View Complexity Report (`complexity_report`) ### 23. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report` * **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]` * **CLI Command:** `task-master complexity-report [options]`
@@ -341,9 +367,46 @@ This document provides a detailed reference for interacting with Taskmaster, cov
--- ---
## AI-Powered Research
### 25. Research (`research`)
* **MCP Tool:** `research`
* **CLI Command:** `task-master research [options]`
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
* **Key Parameters/Options:**
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
* `taskIds`: `Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
* Get fresh information beyond knowledge cutoff dates
* Research latest best practices, library updates, security patches
* Find implementation examples for specific technologies
* Validate approaches against current industry standards
* Get contextual advice based on project files and tasks
* **When to Consider Using Research:**
* **Before implementing any task** - Research current best practices
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
* **For security-related tasks** - Find latest security recommendations
* **When updating dependencies** - Research breaking changes and migration guides
* **For performance optimization** - Get current performance best practices
* **When debugging complex issues** - Research known solutions and workarounds
* **Research + Action Pattern:**
* Use `research` to gather fresh information
* Use `update_subtask` to commit findings with timestamps
* Use `update_task` to incorporate research into task details
* Use `add_task` with research flag for informed task creation
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
---
## File Management ## File Management
### 23. Generate Task Files (`generate`) ### 24. Generate Task Files (`generate`)
* **MCP Tool:** `generate` * **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]` * **CLI Command:** `task-master generate [options]`

View File

@@ -0,0 +1,408 @@
---
description:
globs:
alwaysApply: true
---
# Test Workflow & Development Process
## **Test-Driven Development (TDD) Integration**
### **Core TDD Cycle with Jest**
```bash
# 1. Start development with watch mode
npm run test:watch
# 2. Write failing test first
# Create test file: src/utils/newFeature.test.ts
# Write test that describes expected behavior
# 3. Implement minimum code to make test pass
# 4. Refactor while keeping tests green
# 5. Add edge cases and error scenarios
```
### **TDD Workflow Per Subtask**
```bash
# When starting a new subtask:
task-master set-status --id=4.1 --status=in-progress
# Begin TDD cycle:
npm run test:watch # Keep running during development
# Document TDD progress in subtask:
task-master update-subtask --id=4.1 --prompt="TDD Progress:
- Written 3 failing tests for core functionality
- Implemented basic feature, tests now passing
- Adding edge case tests for error handling"
# Complete subtask with test summary:
task-master update-subtask --id=4.1 --prompt="Implementation complete:
- Feature implemented with 8 unit tests
- Coverage: 95% statements, 88% branches
- All tests passing, TDD cycle complete"
```
## **Testing Commands & Usage**
### **Development Commands**
```bash
# Primary development command - use during coding
npm run test:watch # Watch mode with Jest
npm run test:watch -- --testNamePattern="auth" # Watch specific tests
# Targeted testing during development
npm run test:unit # Run only unit tests
npm run test:unit -- --coverage # Unit tests with coverage
# Integration testing when APIs are ready
npm run test:integration # Run integration tests
npm run test:integration -- --detectOpenHandles # Debug hanging tests
# End-to-end testing for workflows
npm run test:e2e # Run E2E tests
npm run test:e2e -- --timeout=30000 # Extended timeout for E2E
```
### **Quality Assurance Commands**
```bash
# Full test suite with coverage (before commits)
npm run test:coverage # Complete coverage analysis
# All tests (CI/CD pipeline)
npm test # Run all test projects
# Specific test file execution
npm test -- auth.test.ts # Run specific test file
npm test -- --testNamePattern="should handle errors" # Run specific tests
```
## **Test Implementation Patterns**
### **Unit Test Development**
```typescript
// ✅ DO: Follow established patterns from auth.test.ts
describe('FeatureName', () => {
beforeEach(() => {
jest.clearAllMocks();
// Setup mocks with proper typing
});
describe('functionName', () => {
it('should handle normal case', () => {
// Test implementation with specific assertions
});
it('should throw error for invalid input', async () => {
// Error scenario testing
await expect(functionName(invalidInput))
.rejects.toThrow('Specific error message');
});
});
});
```
### **Integration Test Development**
```typescript
// ✅ DO: Use supertest for API endpoint testing
import request from 'supertest';
import { app } from '../../src/app';
describe('POST /api/auth/register', () => {
beforeEach(async () => {
await integrationTestUtils.cleanupTestData();
});
it('should register user successfully', async () => {
const userData = createTestUser();
const response = await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: userData.email
});
// Verify database state
const user = await prisma.user.findUnique({
where: { email: userData.email }
});
expect(user).toBeTruthy();
});
});
```
### **E2E Test Development**
```typescript
// ✅ DO: Test complete user workflows
describe('User Authentication Flow', () => {
it('should complete registration → login → protected access', async () => {
// Step 1: Register
const userData = createTestUser();
await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
// Step 2: Login
const loginResponse = await request(app)
.post('/api/auth/login')
.send({ email: userData.email, password: userData.password })
.expect(200);
const { token } = loginResponse.body;
// Step 3: Access protected resource
await request(app)
.get('/api/profile')
.set('Authorization', `Bearer ${token}`)
.expect(200);
}, 30000); // Extended timeout for E2E
});
```
## **Mocking & Test Utilities**
### **Established Mocking Patterns**
```typescript
// ✅ DO: Use established bcrypt mocking pattern
jest.mock('bcrypt');
import bcrypt from 'bcrypt';
const mockHash = bcrypt.hash as jest.MockedFunction<typeof bcrypt.hash>;
const mockCompare = bcrypt.compare as jest.MockedFunction<typeof bcrypt.compare>;
// ✅ DO: Use Prisma mocking for unit tests
jest.mock('@prisma/client', () => ({
PrismaClient: jest.fn().mockImplementation(() => ({
user: {
create: jest.fn(),
findUnique: jest.fn(),
},
$connect: jest.fn(),
$disconnect: jest.fn(),
})),
}));
```
### **Test Fixtures Usage**
```typescript
// ✅ DO: Use centralized test fixtures
import { createTestUser, adminUser, invalidUser } from '../fixtures/users';
describe('User Service', () => {
it('should handle admin user creation', async () => {
const userData = createTestUser(adminUser);
// Test implementation
});
it('should reject invalid user data', async () => {
const userData = createTestUser(invalidUser);
// Error testing
});
});
```
## **Coverage Standards & Monitoring**
### **Coverage Thresholds**
- **Global Standards**: 80% lines/functions, 70% branches
- **Critical Code**: 90% utils, 85% middleware
- **New Features**: Must meet or exceed global thresholds
- **Legacy Code**: Gradual improvement with each change
### **Coverage Reporting & Analysis**
```bash
# Generate coverage reports
npm run test:coverage
# View detailed HTML report
open coverage/lcov-report/index.html
# Coverage files generated:
# - coverage/lcov-report/index.html # Detailed HTML report
# - coverage/lcov.info # LCOV format for IDE integration
# - coverage/coverage-final.json # JSON format for tooling
```
### **Coverage Quality Checks**
```typescript
// ✅ DO: Test all code paths
describe('validateInput', () => {
it('should return true for valid input', () => {
expect(validateInput('valid')).toBe(true);
});
it('should return false for various invalid inputs', () => {
expect(validateInput('')).toBe(false); // Empty string
expect(validateInput(null)).toBe(false); // Null value
expect(validateInput(undefined)).toBe(false); // Undefined
});
it('should throw for unexpected input types', () => {
expect(() => validateInput(123)).toThrow('Invalid input type');
});
});
```
## **Testing During Development Phases**
### **Feature Development Phase**
```bash
# 1. Start feature development
task-master set-status --id=X.Y --status=in-progress
# 2. Begin TDD cycle
npm run test:watch
# 3. Document test progress in subtask
task-master update-subtask --id=X.Y --prompt="Test development:
- Created test file with 5 failing tests
- Implemented core functionality
- Tests passing, adding error scenarios"
# 4. Verify coverage before completion
npm run test:coverage
# 5. Update subtask with final test status
task-master update-subtask --id=X.Y --prompt="Testing complete:
- 12 unit tests with full coverage
- All edge cases and error scenarios covered
- Ready for integration testing"
```
### **Integration Testing Phase**
```bash
# After API endpoints are implemented
npm run test:integration
# Update integration test templates
# Replace placeholder tests with real endpoint calls
# Document integration test results
task-master update-subtask --id=X.Y --prompt="Integration tests:
- Updated auth endpoint tests
- Database integration verified
- All HTTP status codes and responses tested"
```
### **Pre-Commit Testing Phase**
```bash
# Before committing code
npm run test:coverage # Verify all tests pass with coverage
npm run test:unit # Quick unit test verification
npm run test:integration # Integration test verification (if applicable)
# Commit pattern for test updates
git add tests/ src/**/*.test.ts
git commit -m "test(task-X): Add comprehensive tests for Feature Y
- Unit tests with 95% coverage (exceeds 90% threshold)
- Integration tests for API endpoints
- Test fixtures for data generation
- Proper mocking patterns established
Task X: Feature Y - Testing complete"
```
## **Error Handling & Debugging**
### **Test Debugging Techniques**
```typescript
// ✅ DO: Use test utilities for debugging
import { testUtils } from '../setup';
it('should debug complex operation', () => {
testUtils.withConsole(() => {
// Console output visible only for this test
console.log('Debug info:', complexData);
service.complexOperation();
});
});
// ✅ DO: Use proper async debugging
it('should handle async operations', async () => {
const promise = service.asyncOperation();
// Test intermediate state
expect(service.isProcessing()).toBe(true);
const result = await promise;
expect(result).toBe('expected');
expect(service.isProcessing()).toBe(false);
});
```
### **Common Test Issues & Solutions**
```bash
# Hanging tests (common with database connections)
npm run test:integration -- --detectOpenHandles
# Memory leaks in tests
npm run test:unit -- --logHeapUsage
# Slow tests identification
npm run test:coverage -- --verbose
# Mock not working properly
# Check: mock is declared before imports
# Check: jest.clearAllMocks() in beforeEach
# Check: TypeScript typing is correct
```
## **Continuous Integration Integration**
### **CI/CD Pipeline Testing**
```yaml
# Example GitHub Actions integration
- name: Run tests
run: |
npm ci
npm run test:coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
file: ./coverage/lcov.info
```
### **Pre-commit Hooks**
```bash
# Setup pre-commit testing (recommended)
# In package.json scripts:
"pre-commit": "npm run test:unit && npm run test:integration"
# Husky integration example:
npx husky add .husky/pre-commit "npm run test:unit"
```
## **Test Maintenance & Evolution**
### **Adding Tests for New Features**
1. **Create test file** alongside source code or in `tests/unit/`
2. **Follow established patterns** from `src/utils/auth.test.ts`
3. **Use existing fixtures** from `tests/fixtures/`
4. **Apply proper mocking** patterns for dependencies
5. **Meet coverage thresholds** for the module
### **Updating Integration/E2E Tests**
1. **Update templates** in `tests/integration/` when APIs change
2. **Modify E2E workflows** in `tests/e2e/` for new user journeys
3. **Update test fixtures** for new data requirements
4. **Maintain database cleanup** utilities
### **Test Performance Optimization**
- **Parallel execution**: Jest runs tests in parallel by default
- **Test isolation**: Use proper setup/teardown for independence
- **Mock optimization**: Mock heavy dependencies appropriately
- **Database efficiency**: Use transaction rollbacks where possible
---
**Key References:**
- [Testing Standards](mdc:.cursor/rules/tests.mdc)
- [Git Workflow](mdc:.cursor/rules/git_workflow.mdc)
- [Development Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Jest Configuration](mdc:jest.config.js)
- [Auth Test Example](mdc:src/utils/auth.test.ts)

View File

@@ -150,4 +150,91 @@ alwaysApply: false
)); ));
``` ```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines. ## Enhanced Display Patterns
### **Token Breakdown Display**
- Use detailed, granular token breakdowns for AI-powered commands
- Display context sources with individual token counts
- Show both token count and character count for transparency
```javascript
// ✅ DO: Display detailed token breakdown
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **Code Block Syntax Highlighting**
- Use `cli-highlight` library for syntax highlighting in terminal output
- Process code blocks in AI responses for better readability
```javascript
// ✅ DO: Enhance code blocks with syntax highlighting
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
### **Multi-Section Result Display**
- Use separate boxes for headers, content, and metadata
- Maintain consistent styling across different result types
```javascript
// ✅ DO: Use structured result display
function displayResults(result, query, detailLevel) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and display main content
const processedResult = processCodeBlocks(result);
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Operation complete'));
}
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples, [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for context display patterns, and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -46,7 +46,7 @@ alwaysApply: false
- **Location**: - **Location**:
- **Core CLI Utilities**: Place utilities used primarily by the core `task-master` CLI logic and command modules (`scripts/modules/*`) into [`scripts/modules/utils.js`](mdc:scripts/modules/utils.js). - **Core CLI Utilities**: Place utilities used primarily by the core `task-master` CLI logic and command modules (`scripts/modules/*`) into [`scripts/modules/utils.js`](mdc:scripts/modules/utils.js).
- **MCP Server Utilities**: Place utilities specifically designed to support the MCP server implementation into the appropriate subdirectories within `mcp-server/src/`. - **MCP Server Utilities**: Place utilities specifically designed to support the MCP server implementation into the appropriate subdirectories within `mcp-server/src/`.
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils/) (e.g., `path-utils.js`). - Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils) (e.g., `path-utils.js`).
- Tool Execution/Response Helpers: [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js). - Tool Execution/Response Helpers: [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
## Documentation Standards ## Documentation Standards
@@ -110,7 +110,7 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
- ✅ DO: Use appropriate icons for different log levels - ✅ DO: Use appropriate icons for different log levels
- ✅ DO: Respect the configured log level - ✅ DO: Respect the configured log level
- ❌ DON'T: Add direct console.log calls outside the logging utility - ❌ DON'T: Add direct console.log calls outside the logging utility
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions. - **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](mdc:...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
- **Logger Wrapper Pattern**: - **Logger Wrapper Pattern**:
- ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors: - ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors:
@@ -548,4 +548,56 @@ export {
}; };
``` ```
Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration. ## Context Gathering Utilities
### **ContextGatherer** (`scripts/modules/utils/contextGatherer.js`)
- **Multi-Source Context Extraction**:
- ✅ DO: Use for AI-powered commands that need project context
- ✅ DO: Support tasks, files, custom text, and project tree context
- ✅ DO: Implement detailed token counting with `gpt-tokens` library
- ✅ DO: Provide multiple output formats (research, chat, system-prompt)
```javascript
// ✅ DO: Use ContextGatherer for consistent context extraction
import { ContextGatherer } from '../utils/contextGatherer.js';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
const result = await gatherer.gather({
tasks: ['15', '16.2'],
files: ['src/api.js'],
customContext: 'Additional context',
includeProjectTree: true,
format: 'research',
includeTokenCounts: true
});
```
### **FuzzyTaskSearch** (`scripts/modules/utils/fuzzyTaskSearch.js`)
- **Intelligent Task Discovery**:
- ✅ DO: Use for automatic task relevance detection
- ✅ DO: Configure search parameters based on use case context
- ✅ DO: Implement purpose-based categorization for better matching
- ✅ DO: Sort results by relevance score and task ID
```javascript
// ✅ DO: Use FuzzyTaskSearch for intelligent task discovery
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
- **Integration Guidelines**:
- ✅ DO: Use fuzzy search to supplement user-provided task IDs
- ✅ DO: Display discovered task IDs to users for transparency
- ✅ DO: Sort discovered task IDs numerically for better readability
- ❌ DON'T: Replace explicit user task selections with fuzzy results
Refer to [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for detailed implementation patterns, [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.

View File

@@ -7,3 +7,9 @@ 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
# Google Vertex AI Configuration
VERTEX_PROJECT_ID=your-gcp-project-id
VERTEX_LOCATION=us-central1
# Optional: Path to service account credentials JSON file (alternative to API key)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json

40
.github/workflows/update-models-md.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Update models.md from supported-models.json
on:
push:
branches:
- main
- next
paths:
- 'scripts/modules/supported-models.json'
- 'docs/scripts/models-json-to-markdown.js'
jobs:
update_markdown:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run transformation script
run: node docs/scripts/models-json-to-markdown.js
- name: Format Markdown with Prettier
run: npx prettier --write docs/models.md
- name: Stage docs/models.md
run: git add docs/models.md
- name: Commit & Push docs/models.md
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref_name }}
message: 'docs: Auto-update and format models.md'
author_name: 'github-actions[bot]'
author_email: 'github-actions[bot]@users.noreply.github.com'

33
.gitignore vendored
View File

@@ -19,13 +19,26 @@ npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
lerna-debug.log* lerna-debug.log*
tests/e2e/_runs/
tests/e2e/log/
# Coverage directory used by tools like istanbul # Coverage directory used by tools like istanbul
coverage coverage/
*.lcov *.lcov
# Jest cache
.jest/
# Test temporary files and directories
tests/temp/
tests/e2e/_runs/
tests/e2e/log/
tests/**/*.log
tests/**/coverage/
# Test database files (if any)
tests/**/*.db
tests/**/*.sqlite
tests/**/*.sqlite3
# Optional npm cache directory # Optional npm cache directory
.npm .npm
@@ -64,3 +77,17 @@ dev-debug.log
# NPMRC # NPMRC
.npmrc .npmrc
# Added by Claude Task Master
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# OS specific
# Task files
tasks.json
tasks/

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
22

View File

@@ -1,7 +0,0 @@
# Ignore artifacts:
build
coverage
.changeset
tasks
package-lock.json
tests/fixture/*.json

View File

@@ -1,11 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": true,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}

View File

@@ -2,8 +2,8 @@
"models": { "models": {
"main": { "main": {
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219", "modelId": "claude-sonnet-4-20250514",
"maxTokens": 100000, "maxTokens": 64000,
"temperature": 0.2 "temperature": 0.2
}, },
"research": { "research": {
@@ -14,8 +14,8 @@
}, },
"fallback": { "fallback": {
"provider": "anthropic", "provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219", "modelId": "claude-3-5-sonnet-20241022",
"maxTokens": 8192, "maxTokens": 64000,
"temperature": 0.2 "temperature": 0.2
} }
}, },
@@ -25,8 +25,13 @@
"defaultSubtasks": 5, "defaultSubtasks": 5,
"defaultPriority": "medium", "defaultPriority": "medium",
"projectName": "Taskmaster", "projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api", "ollamaBaseURL": "http://localhost:11434/api",
"azureBaseURL": "https://your-endpoint.azure.com/"
},
"account": {
"userId": "1234567890", "userId": "1234567890",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/" "email": "",
"mode": "byok",
"telemetryEnabled": true
} }
} }

View File

@@ -1,5 +1,179 @@
# task-master-ai # task-master-ai
## 0.15.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.15.0-rc.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.14.0 ## 0.14.0
### Minor Changes ### Minor Changes

335
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,335 @@
# Contributing to Task Master
Thank you for your interest in contributing to Task Master! We're excited to work with you and appreciate your help in making this project better. 🚀
## 🤝 Our Collaborative Approach
We're a **PR-friendly team** that values collaboration:
-**We review PRs quickly** - Usually within hours, not days
-**We're super reactive** - Expect fast feedback and engagement
-**We sometimes take over PRs** - If your contribution is valuable but needs cleanup, we might jump in to help finish it
-**We're open to all contributions** - From bug fixes to major features
**We don't mind AI-generated code**, but we do expect you to:
-**Review and understand** what the AI generated
-**Test the code thoroughly** before submitting
-**Ensure it's well-written** and follows our patterns
-**Don't submit "AI slop"** - untested, unreviewed AI output
> **Why this matters**: We spend significant time reviewing PRs. Help us help you by submitting quality contributions that save everyone time!
## 🚀 Quick Start for Contributors
### 1. Fork and Clone
```bash
git clone https://github.com/YOUR_USERNAME/claude-task-master.git
cd claude-task-master
npm install
```
### 2. Create a Feature Branch
**Important**: Always target the `next` branch, not `main`:
```bash
git checkout next
git pull origin next
git checkout -b feature/your-feature-name
```
### 3. Make Your Changes
Follow our development guidelines below.
### 4. Test Everything Yourself
**Before submitting your PR**, ensure:
```bash
# Run all tests
npm test
# Check formatting
npm run format-check
# Fix formatting if needed
npm run format
```
### 5. Create a Changeset
**Required for most changes**:
```bash
npm run changeset
```
See the [Changeset Guidelines](#changeset-guidelines) below for details.
### 6. Submit Your PR
- Target the `next` branch
- Write a clear description
- Reference any related issues
## 📋 Development Guidelines
### Branch Strategy
- **`main`**: Production-ready code
- **`next`**: Development branch - **target this for PRs**
- **Feature branches**: `feature/description` or `fix/description`
### Code Quality Standards
1. **Write tests** for new functionality
2. **Follow existing patterns** in the codebase
3. **Add JSDoc comments** for functions
4. **Keep functions focused** and single-purpose
### Testing Requirements
Your PR **must pass all CI checks**:
-**Unit tests**: `npm test`
-**Format check**: `npm run format-check`
**Test your changes locally first** - this saves review time and shows you care about quality.
## 📦 Changeset Guidelines
We use [Changesets](https://github.com/changesets/changesets) to manage versioning and generate changelogs.
### When to Create a Changeset
**Always create a changeset for**:
- ✅ New features
- ✅ Bug fixes
- ✅ Breaking changes
- ✅ Performance improvements
- ✅ User-facing documentation updates
- ✅ Dependency updates that affect functionality
**Skip changesets for**:
- ❌ Internal documentation only
- ❌ Test-only changes
- ❌ Code formatting/linting
- ❌ Development tooling that doesn't affect users
### How to Create a Changeset
1. **After making your changes**:
```bash
npm run changeset
```
2. **Choose the bump type**:
- **Major**: Breaking changes
- **Minor**: New features
- **Patch**: Bug fixes, docs, performance improvements
3. **Write a clear summary**:
```
Add support for custom AI models in MCP configuration
```
4. **Commit the changeset file** with your changes:
```bash
git add .changeset/*.md
git commit -m "feat: add custom AI model support"
```
### Changeset vs Git Commit Messages
- **Changeset summary**: User-facing, goes in CHANGELOG.md
- **Git commit**: Developer-facing, explains the technical change
Example:
```bash
# Changeset summary (user-facing)
"Add support for custom Ollama models"
# Git commit message (developer-facing)
"feat(models): implement custom Ollama model validation
- Add model validation for custom Ollama endpoints
- Update configuration schema to support custom models
- Add tests for new validation logic"
```
## 🔧 Development Setup
### Prerequisites
- Node.js 14+
- npm or yarn
### Environment Setup
1. **Copy environment template**:
```bash
cp .env.example .env
```
2. **Add your API keys** (for testing AI features):
```bash
ANTHROPIC_API_KEY=your_key_here
OPENAI_API_KEY=your_key_here
# Add others as needed
```
### Running Tests
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run with coverage
npm run test:coverage
# Run E2E tests
npm run test:e2e
```
### Code Formatting
We use Prettier for consistent formatting:
```bash
# Check formatting
npm run format-check
# Fix formatting
npm run format
```
## 📝 PR Guidelines
### Before Submitting
- [ ] **Target the `next` branch**
- [ ] **Test everything locally**
- [ ] **Run the full test suite**
- [ ] **Check code formatting**
- [ ] **Create a changeset** (if needed)
- [ ] **Re-read your changes** - ensure they're clean and well-thought-out
### PR Description Template
```markdown
## Description
Brief description of what this PR does.
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] I have tested this locally
- [ ] All existing tests pass
- [ ] I have added tests for new functionality
## Changeset
- [ ] I have created a changeset (or this change doesn't need one)
## Additional Notes
Any additional context or notes for reviewers.
```
### What We Look For
✅ **Good PRs**:
- Clear, focused changes
- Comprehensive testing
- Good commit messages
- Proper changeset (when needed)
- Self-reviewed code
❌ **Avoid**:
- Massive PRs that change everything
- Untested code
- Formatting issues
- Missing changesets for user-facing changes
- AI-generated code that wasn't reviewed
## 🏗️ Project Structure
```
claude-task-master/
├── bin/ # CLI executables
├── mcp-server/ # MCP server implementation
├── scripts/ # Core task management logic
├── src/ # Shared utilities and providers and well refactored code (we are slowly moving everything here)
├── tests/ # Test files
├── docs/ # Documentation
└── .cursor/ # Cursor IDE rules and configuration
└── assets/ # Assets like rules and configuration for all IDEs
```
### Key Areas for Contribution
- **CLI Commands**: `scripts/modules/commands.js`
- **MCP Tools**: `mcp-server/src/tools/`
- **Core Logic**: `scripts/modules/task-manager/`
- **AI Providers**: `src/ai-providers/`
- **Tests**: `tests/`
## 🐛 Reporting Issues
### Bug Reports
Include:
- Task Master version
- Node.js version
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Error messages/logs
### Feature Requests
Include:
- Clear description of the feature
- Use case/motivation
- Proposed implementation (if you have ideas)
- Willingness to contribute
## 💬 Getting Help
- **Discord**: [Join our community](https://discord.gg/taskmasterai)
- **Issues**: [GitHub Issues](https://github.com/eyaltoledano/claude-task-master/issues)
- **Discussions**: [GitHub Discussions](https://github.com/eyaltoledano/claude-task-master/discussions)
## 📄 License
By contributing, you agree that your contributions will be licensed under the same license as the project (MIT with Commons Clause).
---
**Thank you for contributing to Task Master!** 🎉
Your contributions help make AI-driven development more accessible and efficient for everyone.

View File

@@ -28,13 +28,22 @@ Using the research model is optional but highly recommended. You will need at le
## Quick Start ## Quick Start
### Option 1 | MCP (Recommended): ### Option 1: MCP (Recommended)
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor. MCP (Model Control Protocol) lets you run Task Master directly from your editor.
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors): #### 1. Add your MCP config at the following path depending on your editor
```json | Editor | Scope | Linux/macOS Path | Windows Path | Key |
| ------------ | ------- | ------------------------------------- | ------------------------------------------------- | ------------ |
| **Cursor** | Global | `~/.cursor/mcp.json` | `%USERPROFILE%\.cursor\mcp.json` | `mcpServers` |
| | Project | `<project_folder>/.cursor/mcp.json` | `<project_folder>\.cursor\mcp.json` | `mcpServers` |
| **Windsurf** | Global | `~/.codeium/windsurf/mcp_config.json` | `%USERPROFILE%\.codeium\windsurf\mcp_config.json` | `mcpServers` |
| **VSCode** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` |
##### Cursor & Windsurf (`mcpServers`)
```jsonc
{ {
"mcpServers": { "mcpServers": {
"taskmaster-ai": { "taskmaster-ai": {
@@ -56,23 +65,78 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
} }
``` ```
2. **Enable the MCP** in your editor > 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
3. **Prompt the AI** to initialize Task Master: ##### VSCode (`servers` + `type`)
``` ```jsonc
Can you please initialize taskmaster-ai into my project? {
"servers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE",
"GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE",
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
},
"type": "stdio"
}
}
}
``` ```
4. **Use common commands** directly through your AI assistant: > 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
#### 2. (Cursor-only) Enable Taskmaster MCP
Open Cursor Settings (Ctrl+Shift+J) ➡ Click on MCP tab on the left ➡ Enable task-master-ai with the toggle
#### 3. (Optional) Configure the models you want to use
In your editors AI chat pane, say:
```txt ```txt
Can you parse my PRD at scripts/prd.txt? Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively.
What's the next task I should work on?
Can you help me implement task 3?
Can you help me expand task 4?
``` ```
[Table of available models](docs/models.md)
#### 4. Initialize Task Master
In your editors AI chat pane, say:
```txt
Initialize taskmaster-ai in my project
```
#### 5. Make sure you have a PRD in `<project_folder>/scripts/prd.txt`
An example of a PRD is located into `<project_folder>/scripts/example_prd.txt`.
**Always start with a detailed PRD.**
The more detailed your PRD, the better the generated tasks will be.
#### 6. Common Commands
Use your AI assistant to:
- Parse requirements: `Can you parse my PRD at scripts/prd.txt?`
- Plan next step: `Whats the next task I should work on?`
- Implement a task: `Can you help me implement task 3?`
- View multiple tasks: `Can you show me tasks 1, 3, and 5?`
- Expand a task: `Can you help me expand task 4?`
- **Research fresh information**: `Research the latest best practices for implementing JWT authentication with Node.js`
- **Research with context**: `Research React Query v5 migration strategies for our current API implementation in src/api.js`
[More examples on how to use Task Master in chat](docs/examples.md)
### Option 2: Using Command Line ### Option 2: Using Command Line
#### Installation #### Installation
@@ -112,6 +176,12 @@ task-master list
# Show the next task to work on # Show the next task to work on
task-master next task-master next
# Show specific task(s) - supports comma-separated IDs
task-master show 1,3,5
# Research fresh information with project context
task-master research "What are the latest best practices for JWT authentication?"
# Generate task files # Generate task files
task-master generate task-master generate
``` ```

View File

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

413
assets/AGENTS.md Normal file
View File

@@ -0,0 +1,413 @@
# Task Master AI - Claude Code Integration Guide
## Essential Commands
### Core Workflow Commands
```bash
# Project Setup
task-master init # Initialize Task Master in current project
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
task-master models --setup # Configure AI models interactively
# Daily Development Workflow
task-master list # Show all tasks with status
task-master next # Get next available task to work on
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
task-master set-status --id=<id> --status=done # Mark task complete
# Task Management
task-master add-task --prompt="description" --research # Add new task with AI assistance
task-master expand --id=<id> --research --force # Break task into subtasks
task-master update-task --id=<id> --prompt="changes" # Update specific task
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
# Analysis & Planning
task-master analyze-complexity --research # Analyze task complexity
task-master complexity-report # View complexity analysis
task-master expand --all --research # Expand all eligible tasks
# Dependencies & Organization
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
task-master validate-dependencies # Check for dependency issues
task-master generate # Update task markdown files (usually auto-called)
```
## Key Files & Project Structure
### Core Files
- `tasks/tasks.json` - Main task data file (auto-managed)
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
- `scripts/prd.txt` - Product Requirements Document for parsing
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
- `.env` - API keys for CLI usage
### Claude Code Integration Files
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
- `.claude/settings.json` - Claude Code tool allowlist and preferences
- `.claude/commands/` - Custom slash commands for repeated workflows
- `.mcp.json` - MCP server configuration (project-specific)
### Directory Structure
```
project/
├── tasks/
│ ├── tasks.json # Main task database
│ ├── task-1.md # Individual task files
│ └── task-2.md
├── scripts/
│ ├── prd.txt # Product requirements
│ └── task-complexity-report.json
├── .claude/
│ ├── settings.json # Claude Code configuration
│ └── commands/ # Custom slash commands
├── .taskmasterconfig # AI models & settings
├── .env # API keys
├── .mcp.json # MCP configuration
└── CLAUDE.md # This file - auto-loaded by Claude Code
```
## MCP Integration
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
```json
{
"mcpServers": {
"task-master-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "your_key_here",
"PERPLEXITY_API_KEY": "your_key_here",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
}
}
}
}
```
### Essential MCP Tools
```javascript
help; // = shows available taskmaster commands
// Project setup
initialize_project; // = task-master init
parse_prd; // = task-master parse-prd
// Daily workflow
get_tasks; // = task-master list
next_task; // = task-master next
get_task; // = task-master show <id>
set_task_status; // = task-master set-status
// Task management
add_task; // = task-master add-task
expand_task; // = task-master expand
update_task; // = task-master update-task
update_subtask; // = task-master update-subtask
update; // = task-master update
// Analysis
analyze_project_complexity; // = task-master analyze-complexity
complexity_report; // = task-master complexity-report
```
## Claude Code Workflow Integration
### Standard Development Workflow
#### 1. Project Initialization
```bash
# Initialize Task Master
task-master init
# Create or obtain PRD, then parse it
task-master parse-prd scripts/prd.txt
# Analyze complexity and expand tasks
task-master analyze-complexity --research
task-master expand --all --research
```
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
#### 2. Daily Development Loop
```bash
# Start each session
task-master next # Find next available task
task-master show <id> # Review task details
# During implementation, check in code context into the tasks and subtasks
task-master update-subtask --id=<id> --prompt="implementation notes..."
# Complete tasks
task-master set-status --id=<id> --status=done
```
#### 3. Multi-Claude Workflows
For complex projects, use multiple Claude Code sessions:
```bash
# Terminal 1: Main implementation
cd project && claude
# Terminal 2: Testing and validation
cd project-test-worktree && claude
# Terminal 3: Documentation updates
cd project-docs-worktree && claude
```
### Custom Slash Commands
Create `.claude/commands/taskmaster-next.md`:
```markdown
Find the next available Task Master task and show its details.
Steps:
1. Run `task-master next` to get the next task
2. If a task is available, run `task-master show <id>` for full details
3. Provide a summary of what needs to be implemented
4. Suggest the first implementation step
```
Create `.claude/commands/taskmaster-complete.md`:
```markdown
Complete a Task Master task: $ARGUMENTS
Steps:
1. Review the current task with `task-master show $ARGUMENTS`
2. Verify all implementation is complete
3. Run any tests related to this task
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
5. Show the next available task with `task-master next`
```
## Tool Allowlist Recommendations
Add to `.claude/settings.json`:
```json
{
"allowedTools": [
"Edit",
"Bash(task-master *)",
"Bash(git commit:*)",
"Bash(git add:*)",
"Bash(npm run *)",
"mcp__task_master_ai__*"
]
}
```
## Configuration & Setup
### API Keys Required
At least **one** of these API keys must be configured:
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
- `OPENAI_API_KEY` (GPT models)
- `GOOGLE_API_KEY` (Gemini models)
- `MISTRAL_API_KEY` (Mistral models)
- `OPENROUTER_API_KEY` (Multiple models)
- `XAI_API_KEY` (Grok models)
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
### Model Configuration
```bash
# Interactive setup (recommended)
task-master models --setup
# Set specific models
task-master models --set-main claude-3-5-sonnet-20241022
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
task-master models --set-fallback gpt-4o-mini
```
## Task Structure & IDs
### Task ID Format
- Main tasks: `1`, `2`, `3`, etc.
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
### Task Status Values
- `pending` - Ready to work on
- `in-progress` - Currently being worked on
- `done` - Completed and verified
- `deferred` - Postponed
- `cancelled` - No longer needed
- `blocked` - Waiting on external factors
### Task Fields
```json
{
"id": "1.2",
"title": "Implement user authentication",
"description": "Set up JWT-based auth system",
"status": "pending",
"priority": "high",
"dependencies": ["1.1"],
"details": "Use bcrypt for hashing, JWT for tokens...",
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
"subtasks": []
}
```
## Claude Code Best Practices with Task Master
### Context Management
- Use `/clear` between different tasks to maintain focus
- This CLAUDE.md file is automatically loaded for context
- Use `task-master show <id>` to pull specific task context when needed
### Iterative Implementation
1. `task-master show <subtask-id>` - Understand requirements
2. Explore codebase and plan implementation
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
4. `task-master set-status --id=<id> --status=in-progress` - Start work
5. Implement code following logged plan
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
7. `task-master set-status --id=<id> --status=done` - Complete task
### Complex Workflows with Checklists
For large migrations or multi-step processes:
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
4. Work through items systematically, checking them off as completed
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
### Git Integration
Task Master works well with `gh` CLI:
```bash
# Create PR for completed task
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
# Reference task in commits
git commit -m "feat: implement JWT auth (task 1.2)"
```
### Parallel Development with Git Worktrees
```bash
# Create worktrees for parallel task development
git worktree add ../project-auth feature/auth-system
git worktree add ../project-api feature/api-refactor
# Run Claude Code in each worktree
cd ../project-auth && claude # Terminal 1: Auth work
cd ../project-api && claude # Terminal 2: API work
```
## Troubleshooting
### AI Commands Failing
```bash
# Check API keys are configured
cat .env # For CLI usage
# Verify model configuration
task-master models
# Test with different model
task-master models --set-fallback gpt-4o-mini
```
### MCP Connection Issues
- Check `.mcp.json` configuration
- Verify Node.js installation
- Use `--mcp-debug` flag when starting Claude Code
- Use CLI as fallback if MCP unavailable
### Task File Sync Issues
```bash
# Regenerate task files from tasks.json
task-master generate
# Fix dependency issues
task-master fix-dependencies
```
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
## Important Notes
### AI-Powered Operations
These commands make AI calls and may take up to a minute:
- `parse_prd` / `task-master parse-prd`
- `analyze_project_complexity` / `task-master analyze-complexity`
- `expand_task` / `task-master expand`
- `expand_all` / `task-master expand --all`
- `add_task` / `task-master add-task`
- `update` / `task-master update`
- `update_task` / `task-master update-task`
- `update_subtask` / `task-master update-subtask`
### File Management
- Never manually edit `tasks.json` - use commands instead
- Never manually edit `.taskmasterconfig` - use `task-master models`
- Task markdown files in `tasks/` are auto-generated
- Run `task-master generate` after manual changes to tasks.json
### Claude Code Session Management
- Use `/clear` frequently to maintain focused context
- Create custom slash commands for repeated Task Master workflows
- Configure tool allowlist to streamline permissions
- Use headless mode for automation: `claude -p "task-master next"`
### Multi-Task Updates
- Use `update --from=<id>` to update multiple future tasks
- Use `update-task --id=<id>` for single task updates
- Use `update-subtask --id=<id>` for implementation logging
### Research Mode
- Add `--research` flag for research-based AI enhancement
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
- Provides more informed task creation and updates
- Recommended for complex technical tasks
---
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._

47
biome.json Normal file
View File

@@ -0,0 +1,47 @@
{
"files": {
"ignore": [
"build",
"coverage",
".changeset",
"tasks",
"package-lock.json",
"tests/fixture/*.json"
]
},
"formatter": {
"bracketSpacing": true,
"enabled": true,
"indentStyle": "tab",
"lineWidth": 80
},
"javascript": {
"formatter": {
"arrowParentheses": "always",
"quoteStyle": "single",
"trailingCommas": "none"
}
},
"linter": {
"rules": {
"complexity": {
"noForEach": "off",
"useOptionalChain": "off"
},
"correctness": {
"noConstantCondition": "off",
"noUnreachable": "off"
},
"suspicious": {
"noDuplicateTestHooks": "off",
"noPrototypeBuiltins": "off"
},
"style": {
"noUselessElse": "off",
"useNodejsImportProtocol": "off",
"useNumberNamespace": "off",
"noParameterAssign": "off"
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,7 @@ Welcome to the Task Master documentation. Use the links below to navigate to the
## Reference ## Reference
- [Command Reference](command-reference.md) - Complete list of all available commands - [Command Reference](command-reference.md) - Complete list of all available commands (including research and multi-task viewing)
- [Task Structure](task-structure.md) - Understanding the task format and features - [Task Structure](task-structure.md) - Understanding the task format and features
## Examples & Licensing ## Examples & Licensing

View File

@@ -43,10 +43,28 @@ task-master show <id>
# or # or
task-master show --id=<id> task-master show --id=<id>
# View multiple tasks with comma-separated IDs
task-master show 1,3,5
task-master show 44,55
# View a specific subtask (e.g., subtask 2 of task 1) # View a specific subtask (e.g., subtask 2 of task 1)
task-master show 1.2 task-master show 1.2
# Mix parent tasks and subtasks
task-master show 44,44.1,55,55.2
``` ```
**Multiple Task Display:**
- **Single ID**: Shows detailed task view with full implementation details
- **Multiple IDs**: Shows compact summary table with interactive action menu
- **Action Menu**: Provides copy-paste ready commands for batch operations:
- Mark all as in-progress/done
- Show next available task
- Expand all tasks (generate subtasks)
- View dependency relationships
- Generate task files
## Update Tasks ## Update Tasks
```bash ```bash
@@ -187,6 +205,32 @@ task-master validate-dependencies
task-master fix-dependencies task-master fix-dependencies
``` ```
## Move Tasks
```bash
# Move a task or subtask to a new position
task-master move --from=<id> --to=<id>
# Examples:
# Move task to become a subtask
task-master move --from=5 --to=7
# Move subtask to become a standalone task
task-master move --from=5.2 --to=7
# Move subtask to a different parent
task-master move --from=5.2 --to=7.3
# Reorder subtasks within the same parent
task-master move --from=5.2 --to=5.4
# Move a task to a new ID position (creates placeholder if doesn't exist)
task-master move --from=5 --to=25
# Move multiple tasks at once (must have the same number of IDs)
task-master move --from=10,11,12 --to=16,17,18
```
## Add a New Task ## Add a New Task
```bash ```bash
@@ -236,3 +280,42 @@ task-master models --setup
``` ```
Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience. Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience.
## Research Fresh Information
```bash
# Perform AI-powered research with fresh, up-to-date information
task-master research "What are the latest best practices for JWT authentication in Node.js?"
# Research with specific task context
task-master research "How to implement OAuth 2.0?" --id=15,16
# Research with file context for code-aware suggestions
task-master research "How can I optimize this API implementation?" --files=src/api.js,src/auth.js
# Research with custom context and project tree
task-master research "Best practices for error handling" --context="We're using Express.js" --tree
# Research with different detail levels
task-master research "React Query v5 migration guide" --detail=high
# Save research results to a file
task-master research "Database optimization techniques" --save=research/db-optimization.md
```
**The research command is a powerful tool that provides:**
- **Fresh information beyond AI knowledge cutoffs**
- **Project-aware context** from your tasks and files
- **Automatic task discovery** using fuzzy search
- **Multiple detail levels** (low, medium, high)
- **Token counting and cost tracking**
- **Interactive follow-up questions**
**Use research frequently to:**
- Get current best practices before implementing features
- Research new technologies and libraries
- Find solutions to complex problems
- Validate your implementation approaches
- Stay updated with latest security recommendations

View File

@@ -16,14 +16,14 @@ Taskmaster uses two primary methods for configuration:
"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" "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" "baseURL": "https://api.perplexity.ai/v1"
}, },
"fallback": { "fallback": {
"provider": "anthropic", "provider": "anthropic",
@@ -38,8 +38,10 @@ Taskmaster uses two primary methods for configuration:
"defaultSubtasks": 5, "defaultSubtasks": 5,
"defaultPriority": "medium", "defaultPriority": "medium",
"projectName": "Your Project Name", "projectName": "Your Project Name",
"ollamaBaseUrl": "http://localhost:11434/api", "ollamaBaseURL": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/" "azureBaseURL": "https://your-endpoint.azure.com/",
"vertexProjectId": "your-gcp-project-id",
"vertexLocation": "us-central1"
} }
} }
``` ```
@@ -53,15 +55,18 @@ Taskmaster uses two primary methods for configuration:
- `ANTHROPIC_API_KEY`: Your Anthropic API key. - `ANTHROPIC_API_KEY`: Your Anthropic API key.
- `PERPLEXITY_API_KEY`: Your Perplexity API key. - `PERPLEXITY_API_KEY`: Your Perplexity API key.
- `OPENAI_API_KEY`: Your OpenAI API key. - `OPENAI_API_KEY`: Your OpenAI API key.
- `GOOGLE_API_KEY`: Your Google API key. - `GOOGLE_API_KEY`: Your Google API key (also used for Vertex AI provider).
- `MISTRAL_API_KEY`: Your Mistral API key. - `MISTRAL_API_KEY`: Your Mistral API key.
- `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:**
- **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. - **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 (can also be set as `baseUrl` for the Azure model role). - `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`).
- `VERTEX_PROJECT_ID`: Your Google Cloud project ID for Vertex AI. Required when using the 'vertex' provider.
- `VERTEX_LOCATION`: Google Cloud region for Vertex AI (e.g., 'us-central1'). Default is 'us-central1'.
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to service account credentials JSON file for Google Cloud auth (alternative to API key for Vertex AI).
**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.
@@ -78,6 +83,11 @@ PERPLEXITY_API_KEY=pplx-your-key-here
# Optional Endpoint Overrides # Optional Endpoint Overrides
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/ # AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
# OLLAMA_BASE_URL=http://custom-ollama-host:11434/api # OLLAMA_BASE_URL=http://custom-ollama-host:11434/api
# Google Vertex AI Configuration (Required if using 'vertex' provider)
# VERTEX_PROJECT_ID=your-gcp-project-id
# VERTEX_LOCATION=us-central1
# GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json
``` ```
## Troubleshooting ## Troubleshooting
@@ -102,3 +112,45 @@ git clone https://github.com/eyaltoledano/claude-task-master.git
cd claude-task-master cd claude-task-master
node scripts/init.js node scripts/init.js
``` ```
## Provider-Specific Configuration
### Google Vertex AI Configuration
Google Vertex AI is Google Cloud's enterprise AI platform and requires specific configuration:
1. **Prerequisites**:
- A Google Cloud account with Vertex AI API enabled
- Either a Google API key with Vertex AI permissions OR a service account with appropriate roles
- A Google Cloud project ID
2. **Authentication Options**:
- **API Key**: Set the `GOOGLE_API_KEY` environment variable
- **Service Account**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to your service account JSON file
3. **Required Configuration**:
- Set `VERTEX_PROJECT_ID` to your Google Cloud project ID
- Set `VERTEX_LOCATION` to your preferred Google Cloud region (default: us-central1)
4. **Example Setup**:
```bash
# In .env file
GOOGLE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXX
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
Or using service account:
```bash
# In .env file
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
5. **In .taskmasterconfig**:
```json
"global": {
"vertexProjectId": "my-gcp-project-123",
"vertexLocation": "us-central1"
}
```

View File

@@ -21,6 +21,20 @@ What's the next task I should work on? Please consider dependencies and prioriti
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it? I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
``` ```
## Viewing multiple tasks
```
Can you show me tasks 1, 3, and 5 so I can understand their relationship?
```
```
I need to see the status of tasks 44, 55, and their subtasks. Can you show me those?
```
```
Show me tasks 10, 12, and 15 and give me some batch actions I can perform on them.
```
## Managing subtasks ## Managing subtasks
``` ```
@@ -30,7 +44,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
## Handling changes ## Handling changes
``` ```
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change? I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
``` ```
## Completing work ## Completing work
@@ -40,6 +54,34 @@ I've finished implementing the authentication system described in task 2. All te
Please mark it as complete and tell me what I should work on next. Please mark it as complete and tell me what I should work on next.
``` ```
## Reorganizing tasks
```
I think subtask 5.2 would fit better as part of task 7. Can you move it there?
```
(Agent runs: `task-master move --from=5.2 --to=7.3`)
```
Task 8 should actually be a subtask of task 4. Can you reorganize this?
```
(Agent runs: `task-master move --from=8 --to=4.1`)
```
I just merged the main branch and there's a conflict in tasks.json. My teammates created tasks 10-15 on their branch while I created tasks 10-12 on my branch. Can you help me resolve this by moving my tasks?
```
(Agent runs:
```bash
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
)
## Analyzing complexity ## Analyzing complexity
``` ```
@@ -81,3 +123,56 @@ Please add a new task to implement user profile image uploads using Cloudinary,
``` ```
(Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`) (Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`)
## Research-Driven Development
### Getting Fresh Information
```
Research the latest best practices for implementing JWT authentication in Node.js applications.
```
(Agent runs: `task-master research "Latest best practices for JWT authentication in Node.js"`)
### Research with Project Context
```
I'm working on task 15 which involves API optimization. Can you research current best practices for our specific implementation?
```
(Agent runs: `task-master research "API optimization best practices" --id=15 --files=src/api.js`)
### Research Before Implementation
```
Before I implement task 8 (React Query integration), can you research the latest React Query v5 patterns and any breaking changes?
```
(Agent runs: `task-master research "React Query v5 patterns and breaking changes" --id=8`)
### Research and Update Pattern
```
Research the latest security recommendations for Express.js applications and update our authentication task with the findings.
```
(Agent runs:
1. `task-master research "Latest Express.js security recommendations" --id=12`
2. `task-master update-subtask --id=12.3 --prompt="Updated with latest security findings: [research results]"`)
### Research for Debugging
```
I'm having issues with our WebSocket implementation in task 20. Can you research common WebSocket problems and solutions?
```
(Agent runs: `task-master research "Common WebSocket implementation problems and solutions" --id=20 --files=src/websocket.js`)
### Research Technology Comparisons
```
We need to choose between Redis and Memcached for caching. Can you research the current recommendations for our use case?
```
(Agent runs: `task-master research "Redis vs Memcached 2024 comparison for session caching" --tree`)

125
docs/models.md Normal file
View File

@@ -0,0 +1,125 @@
# Available Models as of May 27, 2025
## Main Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o1 | 0.489 | 15 | 60 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o3-mini | 0.493 | 1.1 | 4.4 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| openai | o1-mini | 0.4 | 1.1 | 4.4 |
| openai | o1-pro | — | 150 | 600 |
| openai | gpt-4-5-preview | 0.38 | 75 | 150 |
| openai | gpt-4-1-mini | — | 0.4 | 1.6 |
| openai | gpt-4-1-nano | — | 0.1 | 0.4 |
| openai | gpt-4o-mini | 0.3 | 0.15 | 0.6 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324 | — | 0.27 | 1.1 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/devstral-small | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |
## Research Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | -------------------------- | --------- | ---------- | ----------- |
| openai | gpt-4o-search-preview | 0.33 | 2.5 | 10 |
| openai | gpt-4o-mini-search-preview | 0.3 | 0.15 | 0.6 |
| perplexity | sonar-pro | — | 3 | 15 |
| perplexity | sonar | — | 1 | 1 |
| perplexity | deep-research | 0.211 | 2 | 8 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
## Fallback Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |

View File

@@ -0,0 +1,131 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const supportedModelsPath = path.join(
__dirname,
'..',
'modules',
'supported-models.json'
);
const outputMarkdownPath = path.join(
__dirname,
'..',
'..',
'docs',
'models.md'
);
function formatCost(cost) {
if (cost === null || cost === undefined) {
return '—';
}
return cost;
}
function formatSweScore(score) {
if (score === null || score === undefined || score === 0) {
return '—';
}
return score.toString();
}
function generateMarkdownTable(title, models) {
if (!models || models.length === 0) {
return `## ${title}\n\nNo models in this category.\n\n`;
}
let table = `## ${title}\n\n`;
table += '| Provider | Model Name | SWE Score | Input Cost | Output Cost |\n';
table += '|---|---|---|---|---|\n';
models.forEach((model) => {
table += `| ${model.provider} | ${model.modelName} | ${formatSweScore(model.sweScore)} | ${formatCost(model.inputCost)} | ${formatCost(model.outputCost)} |\n`;
});
table += '\n';
return table;
}
function main() {
try {
const correctSupportedModelsPath = path.join(
__dirname,
'..',
'..',
'scripts',
'modules',
'supported-models.json'
);
const correctOutputMarkdownPath = path.join(__dirname, '..', 'models.md');
const supportedModelsContent = fs.readFileSync(
correctSupportedModelsPath,
'utf8'
);
const supportedModels = JSON.parse(supportedModelsContent);
const mainModels = [];
const researchModels = [];
const fallbackModels = [];
for (const provider in supportedModels) {
if (Object.hasOwnProperty.call(supportedModels, provider)) {
const models = supportedModels[provider];
models.forEach((model) => {
const modelEntry = {
provider: provider,
modelName: model.id,
sweScore: model.swe_score,
inputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.input
: null,
outputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.output
: null
};
if (model.allowed_roles.includes('main')) {
mainModels.push(modelEntry);
}
if (model.allowed_roles.includes('research')) {
researchModels.push(modelEntry);
}
if (model.allowed_roles.includes('fallback')) {
fallbackModels.push(modelEntry);
}
});
}
}
const date = new Date();
const monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const formattedDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
let markdownContent = `# Available Models as of ${formattedDate}\n\n`;
markdownContent += generateMarkdownTable('Main Models', mainModels);
markdownContent += generateMarkdownTable('Research Models', researchModels);
markdownContent += generateMarkdownTable('Fallback Models', fallbackModels);
fs.writeFileSync(correctOutputMarkdownPath, markdownContent, 'utf8');
console.log(`Successfully updated ${correctOutputMarkdownPath}`);
} catch (error) {
console.error('Error transforming models.json to models.md:', error);
process.exit(1);
}
}
main();

View File

@@ -198,10 +198,15 @@ Ask the agent to list available tasks:
What tasks are available to work on next? What tasks are available to work on next?
``` ```
```
Can you show me tasks 1, 3, and 5 to understand their current status?
```
The agent will: The agent will:
- Run `task-master list` to see all tasks - Run `task-master list` to see all tasks
- Run `task-master next` to determine the next task to work on - Run `task-master next` to determine the next task to work on
- Run `task-master show 1,3,5` to display multiple tasks with interactive options
- Analyze dependencies to determine which tasks are ready to be worked on - Analyze dependencies to determine which tasks are ready to be worked on
- Prioritize tasks based on priority level and ID order - Prioritize tasks based on priority level and ID order
- Suggest the next task(s) to implement - Suggest the next task(s) to implement
@@ -221,6 +226,21 @@ You can ask:
Let's implement task 3. What does it involve? Let's implement task 3. What does it involve?
``` ```
### 2.1. Viewing Multiple Tasks
For efficient context gathering and batch operations:
```
Show me tasks 5, 7, and 9 so I can plan my implementation approach.
```
The agent will:
- Run `task-master show 5,7,9` to display a compact summary table
- Show task status, priority, and progress indicators
- Provide an interactive action menu with batch operations
- Allow you to perform group actions like marking multiple tasks as in-progress
### 3. Task Verification ### 3. Task Verification
Before marking a task as complete, verify it according to: Before marking a task as complete, verify it according to:
@@ -268,7 +288,61 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work. This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
### 6. Breaking Down Complex Tasks ### 6. Reorganizing Tasks
If you need to reorganize your task structure:
```
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
```
The agent will execute:
```bash
task-master move --from=5.2 --to=7.3
```
You can reorganize tasks in various ways:
- Moving a standalone task to become a subtask: `--from=5 --to=7`
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
When moving tasks to new IDs:
- The system automatically creates placeholder tasks for non-existent destination IDs
- This prevents accidental data loss during reorganization
- Any tasks that depend on moved tasks will have their dependencies updated
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
This is particularly useful as your project understanding evolves and you need to refine your task structure.
### 7. Resolving Merge Conflicts with Tasks
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
```
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
```
The agent will help you:
1. Keep your teammates' tasks (10-15)
2. Move your tasks to new positions to avoid conflicts:
```bash
# Move your tasks to new positions (e.g., 16-18)
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
### 8. Breaking Down Complex Tasks
For complex tasks that need more granularity: For complex tasks that need more granularity:
@@ -369,3 +443,55 @@ Can you analyze the complexity of our tasks to help me understand which ones nee
``` ```
Can you show me the complexity report in a more readable format? Can you show me the complexity report in a more readable format?
``` ```
### Research-Driven Development
Task Master includes a powerful research tool that provides fresh, up-to-date information beyond the AI's knowledge cutoff. This is particularly valuable for:
#### Getting Current Best Practices
```
Before implementing task 5 (authentication), research the latest JWT security recommendations.
```
The agent will execute:
```bash
task-master research "Latest JWT security recommendations 2024" --id=5
```
#### Research with Project Context
```
Research React Query v5 migration strategies for our current API implementation.
```
The agent will execute:
```bash
task-master research "React Query v5 migration strategies" --files=src/api.js,src/hooks.js
```
#### Research and Update Pattern
A powerful workflow is to research first, then update tasks with findings:
```
Research the latest Node.js performance optimization techniques and update task 12 with the findings.
```
The agent will:
1. Run research: `task-master research "Node.js performance optimization 2024" --id=12`
2. Update the task: `task-master update-subtask --id=12.2 --prompt="Updated with latest performance findings: [research results]"`
#### When to Use Research
- **Before implementing any new technology**
- **When encountering security-related tasks**
- **For performance optimization tasks**
- **When debugging complex issues**
- **Before making architectural decisions**
- **When updating dependencies**
The research tool automatically includes relevant project context and provides fresh information that can significantly improve implementation quality.

View File

@@ -1,6 +1,6 @@
export default { export default {
// Use Node.js environment for testing // Use Node.js environment for testing
testEnvironment: 'node', testEnvironment: "node",
// Automatically clear mock calls between every test // Automatically clear mock calls between every test
clearMocks: true, clearMocks: true,
@@ -9,27 +9,27 @@ export default {
collectCoverage: false, collectCoverage: false,
// The directory where Jest should output its coverage files // The directory where Jest should output its coverage files
coverageDirectory: 'coverage', coverageDirectory: "coverage",
// A list of paths to directories that Jest should use to search for files in // A list of paths to directories that Jest should use to search for files in
roots: ['<rootDir>/tests'], roots: ["<rootDir>/tests"],
// The glob patterns Jest uses to detect test files // The glob patterns Jest uses to detect test files
testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'], testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
// Transform files // Transform files
transform: {}, transform: {},
// Disable transformations for node_modules // Disable transformations for node_modules
transformIgnorePatterns: ['/node_modules/'], transformIgnorePatterns: ["/node_modules/"],
// Set moduleNameMapper for absolute paths // Set moduleNameMapper for absolute paths
moduleNameMapper: { moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1' "^@/(.*)$": "<rootDir>/$1",
}, },
// Setup module aliases // Setup module aliases
moduleDirectories: ['node_modules', '<rootDir>'], moduleDirectories: ["node_modules", "<rootDir>"],
// Configure test coverage thresholds // Configure test coverage thresholds
coverageThreshold: { coverageThreshold: {
@@ -37,16 +37,16 @@ export default {
branches: 80, branches: 80,
functions: 80, functions: 80,
lines: 80, lines: 80,
statements: 80 statements: 80,
} },
}, },
// Generate coverage report in these formats // Generate coverage report in these formats
coverageReporters: ['text', 'lcov'], coverageReporters: ["text", "lcov"],
// Verbose output // Verbose output
verbose: true, verbose: true,
// Setup file // Setup file
setupFilesAfterEnv: ['<rootDir>/tests/setup.js'] setupFilesAfterEnv: ["<rootDir>/tests/setup.js"],
}; };

131
llms-install.md Normal file
View File

@@ -0,0 +1,131 @@
``# Taskmaster AI Installation Guide
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
## What is Taskmaster?
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
## Installation Steps
### Step 1: Add MCP Configuration
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
```json
{
"mcpServers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
"OPENAI_API_KEY": "user_will_add_their_key_here",
"GOOGLE_API_KEY": "user_will_add_their_key_here",
"MISTRAL_API_KEY": "user_will_add_their_key_here",
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
"XAI_API_KEY": "user_will_add_their_key_here"
}
}
}
}
```
### Step 2: API Key Requirements
Inform the user they need **at least one** API key from the following providers:
- **Anthropic** (for Claude models) - Recommended
- **OpenAI** (for GPT models)
- **Google** (for Gemini models)
- **Perplexity** (for research features) - Highly recommended
- **Mistral** (for Mistral models)
- **OpenRouter** (access to multiple models)
- **xAI** (for Grok models)
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
### Step 3: Initialize Project
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
> Can you initialize Task Master in my project?
This will run the `initialize_project` tool to set up the basic file structure.
### Step 4: Create Initial Tasks
Users have two options for creating initial tasks:
**Option A: Parse a PRD (Recommended)**
If they have a Product Requirements Document:
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
**Option B: Start from scratch**
> Can you help me add my first task: [describe the task]
## Common Usage Patterns
### Daily Workflow
> What's the next task I should work on?
> Can you show me the details for task [ID]?
> Can you mark task [ID] as done?
### Task Management
> Can you break down task [ID] into subtasks?
> Can you add a new task: [description]
> Can you analyze the complexity of my tasks?
### Project Organization
> Can you show me all my pending tasks?
> Can you move task [ID] to become a subtask of [parent ID]?
> Can you update task [ID] with this new information: [details]
## Verification Steps
After installation, verify everything is working:
1. **Check MCP Connection**: The AI should be able to access Task Master tools
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
## Troubleshooting
**If MCP server doesn't start:**
- Verify the JSON configuration is valid
- Check that Node.js is installed
- Ensure API keys are properly formatted
**If AI commands fail:**
- Verify at least one API key is configured
- Check API key permissions and quotas
- Try using a different model via the `models` tool
## CLI Fallback
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
## Next Steps
Once installed, users can:
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
- Set up model preferences with `models` tool
- Expand tasks into subtasks with `expand-all` and `expand-task`
- Explore advanced features like research mode and complexity analysis
For detailed documentation, refer to the Task Master docs directory.``

View File

@@ -18,6 +18,9 @@ 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.ids] - Comma-separated list of task IDs to analyze
* @param {number} [args.from] - Starting task ID in a range to analyze
* @param {number} [args.to] - Ending task ID in a range to analyze
* @param {string} [args.projectRoot] - Project root path. * @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
@@ -26,7 +29,16 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
*/ */
export async function analyzeTaskComplexityDirect(args, log, context = {}) { export async function analyzeTaskComplexityDirect(args, log, context = {}) {
const { session } = context; const { session } = context;
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args; const {
tasksJsonPath,
outputPath,
threshold,
research,
projectRoot,
ids,
from,
to
} = args;
const logWrapper = createLogWrapper(log); const logWrapper = createLogWrapper(log);
@@ -58,6 +70,14 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
log.info(`Analyzing task complexity from: ${tasksPath}`); log.info(`Analyzing task complexity from: ${tasksPath}`);
log.info(`Output report will be saved to: ${resolvedOutputPath}`); log.info(`Output report will be saved to: ${resolvedOutputPath}`);
if (ids) {
log.info(`Analyzing specific task IDs: ${ids}`);
} else if (from || to) {
const fromStr = from !== undefined ? from : 'first';
const toStr = to !== undefined ? to : 'last';
log.info(`Analyzing tasks in range: ${fromStr} to ${toStr}`);
}
if (research) { if (research) {
log.info('Using research role for complexity analysis'); log.info('Using research role for complexity analysis');
} }
@@ -68,7 +88,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
output: outputPath, output: outputPath,
threshold: threshold, threshold: threshold,
research: research === true, // Ensure boolean research: research === true, // Ensure boolean
projectRoot: projectRoot // Pass projectRoot here projectRoot: projectRoot, // Pass projectRoot here
id: ids, // Pass the ids parameter to the core function as 'id'
from: from, // Pass from parameter
to: to // Pass to parameter
}; };
// --- End Initial Checks --- // --- End Initial Checks ---

View File

@@ -0,0 +1,101 @@
/**
* Direct function wrapper for moveTask
*/
import { moveTask } from '../../../../scripts/modules/task-manager.js';
import { findTasksJsonPath } from '../utils/path-utils.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
/**
* Move a task or subtask to a new position
* @param {Object} args - Function arguments
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file
* @param {string} args.sourceId - ID of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3' or '7,8,9')
* @param {string} args.file - Alternative path to the tasks.json file
* @param {string} args.projectRoot - Project root directory
* @param {boolean} args.generateFiles - Whether to regenerate task files after moving (default: true)
* @param {Object} log - Logger object
* @returns {Promise<{success: boolean, data?: Object, error?: Object}>}
*/
export async function moveTaskDirect(args, log, context = {}) {
const { session } = context;
// Validate required parameters
if (!args.sourceId) {
return {
success: false,
error: {
message: 'Source ID is required',
code: 'MISSING_SOURCE_ID'
}
};
}
if (!args.destinationId) {
return {
success: false,
error: {
message: 'Destination ID is required',
code: 'MISSING_DESTINATION_ID'
}
};
}
try {
// Find tasks.json path if not provided
let tasksPath = args.tasksJsonPath || args.file;
if (!tasksPath) {
if (!args.projectRoot) {
return {
success: false,
error: {
message:
'Project root is required if tasksJsonPath is not provided',
code: 'MISSING_PROJECT_ROOT'
}
};
}
tasksPath = findTasksJsonPath(args, log);
}
// Enable silent mode to prevent console output during MCP operation
enableSilentMode();
// Call the core moveTask function with file generation control
const generateFiles = args.generateFiles !== false; // Default to true
const result = await moveTask(
tasksPath,
args.sourceId,
args.destinationId,
generateFiles
);
// Restore console output
disableSilentMode();
return {
success: true,
data: {
...result,
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
}
};
} catch (error) {
// Restore console output in case of error
disableSilentMode();
log.error(`Failed to move task: ${error.message}`);
return {
success: false,
error: {
message: error.message,
code: 'MOVE_TASK_ERROR'
}
};
}
}

View File

@@ -31,6 +31,7 @@ export async function parsePRDDirect(args, log, context = {}) {
numTasks: numTasksArg, numTasks: numTasksArg,
force, force,
append, append,
research,
projectRoot projectRoot
} = args; } = args;
@@ -114,8 +115,14 @@ export async function parsePRDDirect(args, log, context = {}) {
} }
} }
if (research) {
logWrapper.info( logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, ProjectRoot: ${projectRoot}` 'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
);
}
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
); );
const wasSilent = isSilentMode(); const wasSilent = isSilentMode();
@@ -135,6 +142,7 @@ export async function parsePRDDirect(args, log, context = {}) {
projectRoot, projectRoot,
force, force,
append, append,
research,
commandName: 'parse-prd', commandName: 'parse-prd',
outputType: 'mcp' outputType: 'mcp'
}, },

View File

@@ -0,0 +1,159 @@
/**
* research.js
* Direct function implementation for AI-powered research queries
*/
import { performResearch } from '../../../../scripts/modules/task-manager.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js';
/**
* Direct function wrapper for performing AI-powered research with project context.
*
* @param {Object} args - Command arguments
* @param {string} args.query - Research query/prompt (required)
* @param {string} [args.taskIds] - Comma-separated list of task/subtask IDs for context
* @param {string} [args.filePaths] - Comma-separated list of file paths for context
* @param {string} [args.customContext] - Additional custom context text
* @param {boolean} [args.includeProjectTree=false] - Include project file tree in context
* @param {string} [args.detailLevel='medium'] - Detail level: 'low', 'medium', 'high'
* @param {string} [args.projectRoot] - Project root path
* @param {Object} log - Logger object
* @param {Object} context - Additional context (session)
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
*/
export async function researchDirect(args, log, context = {}) {
// Destructure expected args
const {
query,
taskIds,
filePaths,
customContext,
includeProjectTree = false,
detailLevel = 'medium',
projectRoot
} = args;
const { session } = context; // Destructure session from context
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
// Create logger wrapper using the utility
const mcpLog = createLogWrapper(log);
try {
// Check required parameters
if (!query || typeof query !== 'string' || query.trim().length === 0) {
log.error('Missing or invalid required parameter: query');
disableSilentMode();
return {
success: false,
error: {
code: 'MISSING_PARAMETER',
message:
'The query parameter is required and must be a non-empty string'
}
};
}
// Parse comma-separated task IDs if provided
const parsedTaskIds = taskIds
? taskIds
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0)
: [];
// Parse comma-separated file paths if provided
const parsedFilePaths = filePaths
? filePaths
.split(',')
.map((path) => path.trim())
.filter((path) => path.length > 0)
: [];
// Validate detail level
const validDetailLevels = ['low', 'medium', 'high'];
if (!validDetailLevels.includes(detailLevel)) {
log.error(`Invalid detail level: ${detailLevel}`);
disableSilentMode();
return {
success: false,
error: {
code: 'INVALID_PARAMETER',
message: `Detail level must be one of: ${validDetailLevels.join(', ')}`
}
};
}
log.info(
`Performing research query: "${query.substring(0, 100)}${query.length > 100 ? '...' : ''}", ` +
`taskIds: [${parsedTaskIds.join(', ')}], ` +
`filePaths: [${parsedFilePaths.join(', ')}], ` +
`detailLevel: ${detailLevel}, ` +
`includeProjectTree: ${includeProjectTree}, ` +
`projectRoot: ${projectRoot}`
);
// Prepare options for the research function
const researchOptions = {
taskIds: parsedTaskIds,
filePaths: parsedFilePaths,
customContext: customContext || '',
includeProjectTree,
detailLevel,
projectRoot
};
// Prepare context for the research function
const researchContext = {
session,
mcpLog,
commandName: 'research',
outputType: 'mcp'
};
// Call the performResearch function
const result = await performResearch(
query.trim(),
researchOptions,
researchContext,
'json', // outputFormat - use 'json' to suppress CLI UI
false // allowFollowUp - disable for MCP calls
);
// Restore normal logging
disableSilentMode();
return {
success: true,
data: {
query: result.query,
result: result.result,
contextSize: result.contextSize,
contextTokens: result.contextTokens,
tokenBreakdown: result.tokenBreakdown,
systemPromptTokens: result.systemPromptTokens,
userPromptTokens: result.userPromptTokens,
totalInputTokens: result.totalInputTokens,
detailLevel: result.detailLevel,
telemetryData: result.telemetryData
}
};
} catch (error) {
// Make sure to restore normal logging even if there's an error
disableSilentMode();
log.error(`Error in researchDirect: ${error.message}`);
return {
success: false,
error: {
code: error.code || 'RESEARCH_ERROR',
message: error.message
}
};
}
}

View File

@@ -9,7 +9,7 @@ import {
disableSilentMode, disableSilentMode,
isSilentMode isSilentMode
} from '../../../../scripts/modules/utils.js'; } from '../../../../scripts/modules/utils.js';
import { nextTaskDirect } from './next-task.js';
/** /**
* Direct function wrapper for setTaskStatus with error handling. * Direct function wrapper for setTaskStatus with error handling.
* *
@@ -19,7 +19,7 @@ import {
*/ */
export async function setTaskStatusDirect(args, log) { export async function setTaskStatusDirect(args, log) {
// Destructure expected args, including the resolved tasksJsonPath // Destructure expected args, including the resolved tasksJsonPath
const { tasksJsonPath, id, status } = args; const { tasksJsonPath, id, status, complexityReportPath } = args;
try { try {
log.info(`Setting task status with args: ${JSON.stringify(args)}`); log.info(`Setting task status with args: ${JSON.stringify(args)}`);
@@ -85,6 +85,39 @@ export async function setTaskStatusDirect(args, log) {
}, },
fromCache: false // This operation always modifies state and should never be cached fromCache: false // This operation always modifies state and should never be cached
}; };
// If the task was completed, attempt to fetch the next task
if (result.data.status === 'done') {
try {
log.info(`Attempting to fetch next task for task ${taskId}`);
const nextResult = await nextTaskDirect(
{
tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath
},
log
);
if (nextResult.success) {
log.info(
`Successfully retrieved next task: ${nextResult.data.nextTask}`
);
result.data = {
...result.data,
nextTask: nextResult.data.nextTask,
isNextSubtask: nextResult.data.isSubtask,
nextSteps: nextResult.data.nextSteps
};
} else {
log.warn(
`Failed to retrieve next task: ${nextResult.error?.message || 'Unknown error'}`
);
}
} catch (nextErr) {
log.error(`Error retrieving next task: ${nextErr.message}`);
}
}
return result; return result;
} catch (error) { } catch (error) {
log.error(`Error setting task status: ${error.message}`); log.error(`Error setting task status: ${error.message}`);

View File

@@ -66,9 +66,27 @@ export async function showTaskDirect(args, log) {
const complexityReport = readComplexityReport(reportPath); const complexityReport = readComplexityReport(reportPath);
// Parse comma-separated IDs
const taskIds = id
.split(',')
.map((taskId) => taskId.trim())
.filter((taskId) => taskId.length > 0);
if (taskIds.length === 0) {
return {
success: false,
error: {
code: 'INVALID_TASK_ID',
message: 'No valid task IDs provided'
}
};
}
// Handle single task ID (existing behavior)
if (taskIds.length === 1) {
const { task, originalSubtaskCount } = findTaskById( const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks, tasksData.tasks,
id, taskIds[0],
complexityReport, complexityReport,
status status
); );
@@ -78,12 +96,12 @@ export async function showTaskDirect(args, log) {
success: false, success: false,
error: { error: {
code: 'TASK_NOT_FOUND', code: 'TASK_NOT_FOUND',
message: `Task or subtask with ID ${id} not found` message: `Task or subtask with ID ${taskIds[0]} not found`
} }
}; };
} }
log.info(`Successfully retrieved task ${id}.`); log.info(`Successfully retrieved task ${taskIds[0]}.`);
const returnData = { ...task }; const returnData = { ...task };
if (originalSubtaskCount !== null) { if (originalSubtaskCount !== null) {
@@ -92,6 +110,47 @@ export async function showTaskDirect(args, log) {
} }
return { success: true, data: returnData }; return { success: true, data: returnData };
}
// Handle multiple task IDs
const foundTasks = [];
const notFoundIds = [];
taskIds.forEach((taskId) => {
const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks,
taskId,
complexityReport,
status
);
if (task) {
const taskData = { ...task };
if (originalSubtaskCount !== null) {
taskData._originalSubtaskCount = originalSubtaskCount;
taskData._subtaskFilter = status;
}
foundTasks.push(taskData);
} else {
notFoundIds.push(taskId);
}
});
log.info(
`Successfully retrieved ${foundTasks.length} of ${taskIds.length} requested tasks.`
);
// Return multiple tasks with metadata
return {
success: true,
data: {
tasks: foundTasks,
requestedIds: taskIds,
foundCount: foundTasks.length,
notFoundIds: notFoundIds,
isMultiple: true
}
};
} catch (error) { } catch (error) {
log.error(`Error showing task ${id}: ${error.message}`); log.error(`Error showing task ${id}: ${error.message}`);
return { return {

View File

@@ -30,6 +30,8 @@ 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.js';
import { modelsDirect } from './direct-functions/models.js'; import { modelsDirect } from './direct-functions/models.js';
import { moveTaskDirect } from './direct-functions/move-task.js';
import { researchDirect } from './direct-functions/research.js';
// Re-export utility functions // Re-export utility functions
export { findTasksJsonPath } from './utils/path-utils.js'; export { findTasksJsonPath } from './utils/path-utils.js';
@@ -60,7 +62,9 @@ export const directFunctions = new Map([
['addDependencyDirect', addDependencyDirect], ['addDependencyDirect', addDependencyDirect],
['removeTaskDirect', removeTaskDirect], ['removeTaskDirect', removeTaskDirect],
['initializeProjectDirect', initializeProjectDirect], ['initializeProjectDirect', initializeProjectDirect],
['modelsDirect', modelsDirect] ['modelsDirect', modelsDirect],
['moveTaskDirect', moveTaskDirect],
['researchDirect', researchDirect]
]); ]);
// Re-export all direct function implementations // Re-export all direct function implementations
@@ -89,5 +93,7 @@ export {
addDependencyDirect, addDependencyDirect,
removeTaskDirect, removeTaskDirect,
initializeProjectDirect, initializeProjectDirect,
modelsDirect modelsDirect,
moveTaskDirect,
researchDirect
}; };

View File

@@ -49,6 +49,24 @@ export function registerAnalyzeProjectComplexityTool(server) {
.describe( .describe(
'Path to the tasks file relative to project root (default: tasks/tasks.json).' 'Path to the tasks file relative to project root (default: tasks/tasks.json).'
), ),
ids: z
.string()
.optional()
.describe(
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
),
from: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Starting task ID in a range to analyze.'),
to: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Ending task ID in a range to analyze.'),
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.')
@@ -107,7 +125,10 @@ export function registerAnalyzeProjectComplexityTool(server) {
outputPath: outputPath, outputPath: outputPath,
threshold: args.threshold, threshold: args.threshold,
research: args.research, research: args.research,
projectRoot: args.projectRoot projectRoot: args.projectRoot,
ids: args.ids,
from: args.from,
to: args.to
}, },
log, log,
{ session } { session }

View File

@@ -44,7 +44,11 @@ export function registerShowTaskTool(server) {
name: 'get_task', name: 'get_task',
description: 'Get detailed information about a specific task', description: 'Get detailed information about a specific task',
parameters: z.object({ parameters: z.object({
id: z.string().describe('Task ID to get'), id: z
.string()
.describe(
'Task ID(s) to get (can be comma-separated for multiple tasks)'
),
status: z status: z
.string() .string()
.optional() .optional()
@@ -66,7 +70,7 @@ export function registerShowTaskTool(server) {
'Absolute path to the project root directory (Optional, usually from session)' 'Absolute path to the project root directory (Optional, usually from session)'
) )
}), }),
execute: withNormalizedProjectRoot(async (args, { log }) => { execute: withNormalizedProjectRoot(async (args, { log, session }) => {
const { id, file, status, projectRoot } = args; const { id, file, status, projectRoot } = args;
try { try {
@@ -110,7 +114,8 @@ export function registerShowTaskTool(server) {
status: status, status: status,
projectRoot: projectRoot projectRoot: projectRoot
}, },
log log,
{ session }
); );
if (result.success) { if (result.success) {

View File

@@ -28,6 +28,8 @@ import { registerAddDependencyTool } from './add-dependency.js';
import { registerRemoveTaskTool } from './remove-task.js'; import { registerRemoveTaskTool } from './remove-task.js';
import { registerInitializeProjectTool } from './initialize-project.js'; import { registerInitializeProjectTool } from './initialize-project.js';
import { registerModelsTool } from './models.js'; import { registerModelsTool } from './models.js';
import { registerMoveTaskTool } from './move-task.js';
import { registerResearchTool } from './research.js';
/** /**
* Register all Task Master tools with the MCP server * Register all Task Master tools with the MCP server
@@ -61,6 +63,7 @@ export function registerTaskMasterTools(server) {
registerRemoveTaskTool(server); registerRemoveTaskTool(server);
registerRemoveSubtaskTool(server); registerRemoveSubtaskTool(server);
registerClearSubtasksTool(server); registerClearSubtasksTool(server);
registerMoveTaskTool(server);
// Group 5: Task Analysis & Expansion // Group 5: Task Analysis & Expansion
registerAnalyzeProjectComplexityTool(server); registerAnalyzeProjectComplexityTool(server);
@@ -72,6 +75,9 @@ export function registerTaskMasterTools(server) {
registerRemoveDependencyTool(server); registerRemoveDependencyTool(server);
registerValidateDependenciesTool(server); registerValidateDependenciesTool(server);
registerFixDependenciesTool(server); registerFixDependenciesTool(server);
// Group 7: AI-Powered Features
registerResearchTool(server);
} catch (error) { } catch (error) {
logger.error(`Error registering Task Master tools: ${error.message}`); logger.error(`Error registering Task Master tools: ${error.message}`);
throw error; throw error;

View File

@@ -0,0 +1,66 @@
/**
* tools/move-task.js
* Tool for moving tasks or subtasks to a new position
*/
import { z } from 'zod';
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { moveTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
/**
* Register the moveTask tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerMoveTaskTool(server) {
server.addTool({
name: 'move_task',
description: 'Move a task or subtask to a new position',
parameters: z.object({
from: z
.string()
.describe(
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
),
to: z
.string()
.describe(
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
),
file: z.string().optional().describe('Custom path to tasks.json file'),
projectRoot: z
.string()
.optional()
.describe(
'Root directory of the project (typically derived from session)'
)
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
// Let the core logic handle comma-separated IDs and validation
const result = await moveTaskDirect(
{
sourceId: args.from,
destinationId: args.to,
file: args.file,
projectRoot: args.projectRoot,
generateFiles: true // Always generate files for MCP operations
},
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
return createErrorResponse(
`Failed to move task: ${error.message}`,
'MOVE_TASK_ERROR'
);
}
})
});
}

View File

@@ -49,6 +49,13 @@ export function registerParsePRDTool(server) {
.optional() .optional()
.default(false) .default(false)
.describe('Append generated tasks to existing file.'), .describe('Append generated tasks to existing file.'),
research: z
.boolean()
.optional()
.default(false)
.describe(
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
),
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.')
@@ -68,6 +75,7 @@ export function registerParsePRDTool(server) {
numTasks: args.numTasks, numTasks: args.numTasks,
force: args.force, force: args.force,
append: args.append, append: args.append,
research: args.research,
projectRoot: args.projectRoot projectRoot: args.projectRoot
}, },
log, log,

View File

@@ -0,0 +1,82 @@
/**
* tools/research.js
* Tool to perform AI-powered research queries with project context
*/
import { z } from 'zod';
import {
createErrorResponse,
handleApiResult,
withNormalizedProjectRoot
} from './utils.js';
import { researchDirect } from '../core/task-master-core.js';
/**
* Register the research tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerResearchTool(server) {
server.addTool({
name: 'research',
description: 'Perform AI-powered research queries with project context',
parameters: z.object({
query: z.string().describe('Research query/prompt (required)'),
taskIds: z
.string()
.optional()
.describe(
'Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")'
),
filePaths: z
.string()
.optional()
.describe(
'Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")'
),
customContext: z
.string()
.optional()
.describe('Additional custom context text to include in the research'),
includeProjectTree: z
.boolean()
.optional()
.describe(
'Include project file tree structure in context (default: false)'
),
detailLevel: z
.enum(['low', 'medium', 'high'])
.optional()
.describe('Detail level for the research response (default: medium)'),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
log.info(
`Starting research with query: "${args.query.substring(0, 100)}${args.query.length > 100 ? '...' : ''}"`
);
// Call the direct function
const result = await researchDirect(
{
query: args.query,
taskIds: args.taskIds,
filePaths: args.filePaths,
customContext: args.customContext,
includeProjectTree: args.includeProjectTree || false,
detailLevel: args.detailLevel || 'medium',
projectRoot: args.projectRoot
},
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
log.error(`Error in research tool: ${error.message}`);
return createErrorResponse(error.message);
}
})
});
}

View File

@@ -9,8 +9,14 @@ import {
createErrorResponse, createErrorResponse,
withNormalizedProjectRoot withNormalizedProjectRoot
} from './utils.js'; } from './utils.js';
import { setTaskStatusDirect } from '../core/task-master-core.js'; import {
import { findTasksJsonPath } from '../core/utils/path-utils.js'; setTaskStatusDirect,
nextTaskDirect
} from '../core/task-master-core.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js'; import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
/** /**
@@ -33,6 +39,12 @@ export function registerSetTaskStatusTool(server) {
"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'."
), ),
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.')
@@ -55,11 +67,23 @@ export function registerSetTaskStatusTool(server) {
); );
} }
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await setTaskStatusDirect( const result = await setTaskStatusDirect(
{ {
tasksJsonPath: tasksJsonPath, tasksJsonPath: tasksJsonPath,
id: args.id, id: args.id,
status: args.status status: args.status,
complexityReportPath
}, },
log log
); );

View File

@@ -3,16 +3,16 @@
* Utility functions for Task Master CLI integration * Utility functions for Task Master CLI integration
*/ */
import { spawnSync } from 'child_process'; 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 path utilities to ensure consistent path resolution // Import path utilities to ensure consistent path resolution
import { import {
lastFoundProjectRoot, lastFoundProjectRoot,
PROJECT_MARKERS PROJECT_MARKERS,
} from '../core/utils/path-utils.js'; } from "../core/utils/path-utils.js";
/** /**
* Get normalized project root path * Get normalized project root path
@@ -22,7 +22,7 @@ import {
*/ */
function getProjectRoot(projectRootRaw, log) { function getProjectRoot(projectRootRaw, log) {
// PRECEDENCE ORDER: // PRECEDENCE ORDER:
// 1. Environment variable override // 1. Environment variable override (TASK_MASTER_PROJECT_ROOT)
// 2. Explicitly provided projectRoot in args // 2. Explicitly provided projectRoot in args
// 3. Previously found/cached project root // 3. Previously found/cached project root
// 4. Current directory if it has project markers // 4. Current directory if it has project markers
@@ -77,7 +77,7 @@ function getProjectRoot(projectRootRaw, log) {
`No task-master project detected in current directory. Using ${currentDir} as project root.` `No task-master project detected in current directory. Using ${currentDir} as project root.`
); );
log.warn( log.warn(
'Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.' "Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable."
); );
return currentDir; return currentDir;
} }
@@ -103,7 +103,7 @@ function getProjectRootFromSession(session, log) {
rootsRootsType: typeof session?.roots?.roots, rootsRootsType: typeof session?.roots?.roots,
isRootsRootsArray: Array.isArray(session?.roots?.roots), isRootsRootsArray: Array.isArray(session?.roots?.roots),
rootsRootsLength: session?.roots?.roots?.length, rootsRootsLength: session?.roots?.roots?.length,
firstRootsRoot: session?.roots?.roots?.[0] firstRootsRoot: session?.roots?.roots?.[0],
})}` })}`
); );
@@ -126,16 +126,16 @@ function getProjectRootFromSession(session, log) {
if (rawRootPath) { if (rawRootPath) {
// Decode URI and strip file:// protocol // Decode URI and strip file:// protocol
decodedPath = rawRootPath.startsWith('file://') decodedPath = rawRootPath.startsWith("file://")
? decodeURIComponent(rawRootPath.slice(7)) ? decodeURIComponent(rawRootPath.slice(7))
: rawRootPath; // Assume non-file URI is already decoded? Or decode anyway? Let's decode. : rawRootPath; // Assume non-file URI is already decoded? Or decode anyway? Let's decode.
if (!rawRootPath.startsWith('file://')) { if (!rawRootPath.startsWith("file://")) {
decodedPath = decodeURIComponent(rawRootPath); // Decode even if no file:// decodedPath = decodeURIComponent(rawRootPath); // Decode even if no file://
} }
// Handle potential Windows drive prefix after stripping protocol (e.g., /C:/...) // Handle potential Windows drive prefix after stripping protocol (e.g., /C:/...)
if ( if (
decodedPath.startsWith('/') && decodedPath.startsWith("/") &&
/[A-Za-z]:/.test(decodedPath.substring(1, 3)) /[A-Za-z]:/.test(decodedPath.substring(1, 3))
) { ) {
decodedPath = decodedPath.substring(1); // Remove leading slash if it's like /C:/... decodedPath = decodedPath.substring(1); // Remove leading slash if it's like /C:/...
@@ -144,7 +144,7 @@ function getProjectRootFromSession(session, log) {
log.info(`Decoded path: ${decodedPath}`); log.info(`Decoded path: ${decodedPath}`);
// Normalize slashes and resolve // Normalize slashes and resolve
const normalizedSlashes = decodedPath.replace(/\\/g, '/'); const normalizedSlashes = decodedPath.replace(/\\/g, "/");
finalPath = path.resolve(normalizedSlashes); // Resolve to absolute path for current OS finalPath = path.resolve(normalizedSlashes); // Resolve to absolute path for current OS
log.info(`Normalized and resolved session path: ${finalPath}`); log.info(`Normalized and resolved session path: ${finalPath}`);
@@ -152,22 +152,22 @@ function getProjectRootFromSession(session, log) {
} }
// Fallback Logic (remains the same) // Fallback Logic (remains the same)
log.warn('No project root URI found in session. Attempting fallbacks...'); 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) // Fallback 1: Use server path deduction (Cursor IDE)
const serverPath = process.argv[1]; const serverPath = process.argv[1];
if (serverPath && serverPath.includes('mcp-server')) { if (serverPath && serverPath.includes("mcp-server")) {
const mcpServerIndex = serverPath.indexOf('mcp-server'); const mcpServerIndex = serverPath.indexOf("mcp-server");
if (mcpServerIndex !== -1) { if (mcpServerIndex !== -1) {
const projectRoot = path.dirname( const projectRoot = path.dirname(
serverPath.substring(0, mcpServerIndex) serverPath.substring(0, mcpServerIndex)
); // Go up one level ); // Go up one level
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(
`Using project root derived from server path: ${projectRoot}` `Using project root derived from server path: ${projectRoot}`
@@ -202,7 +202,7 @@ function getProjectRootFromSession(session, log) {
function handleApiResult( function handleApiResult(
result, result,
log, log,
errorPrefix = 'API error', errorPrefix = "API error",
processFunction = processMCPResponseData processFunction = processMCPResponseData
) { ) {
if (!result.success) { if (!result.success) {
@@ -223,7 +223,7 @@ function handleApiResult(
// Create the response payload including the fromCache flag // Create the response payload including the fromCache flag
const responsePayload = { const responsePayload = {
fromCache: result.fromCache, // Get the flag from the original 'result' fromCache: result.fromCache, // Get the flag from the original 'result'
data: processedData // Nest the processed data under a 'data' key data: processedData, // Nest the processed data under a 'data' key
}; };
// Pass this combined payload to createContentResponse // Pass this combined payload to createContentResponse
@@ -261,10 +261,10 @@ function executeTaskMasterCommand(
// Common options for spawn // Common options for spawn
const spawnOptions = { const spawnOptions = {
encoding: 'utf8', encoding: "utf8",
cwd: cwd, cwd: cwd,
// Merge process.env with customEnv, giving precedence to customEnv // Merge process.env with customEnv, giving precedence to customEnv
env: { ...process.env, ...(customEnv || {}) } env: { ...process.env, ...(customEnv || {}) },
}; };
// Log the environment being passed (optional, for debugging) // Log the environment being passed (optional, for debugging)
@@ -272,13 +272,13 @@ function executeTaskMasterCommand(
// Execute the command using the global task-master CLI or local script // Execute the command using the global task-master CLI or local script
// Try the global CLI first // Try the global CLI first
let result = spawnSync('task-master', fullArgs, spawnOptions); let result = spawnSync("task-master", fullArgs, spawnOptions);
// If global CLI is not available, try fallback to the local script // If global CLI is not available, try fallback to the local script
if (result.error && result.error.code === 'ENOENT') { if (result.error && result.error.code === "ENOENT") {
log.info('Global task-master not found, falling back to local script'); log.info("Global task-master not found, falling back to local script");
// Pass the same spawnOptions (including env) to the fallback // Pass the same spawnOptions (including env) to the fallback
result = spawnSync('node', ['scripts/dev.js', ...fullArgs], spawnOptions); result = spawnSync("node", ["scripts/dev.js", ...fullArgs], spawnOptions);
} }
if (result.error) { if (result.error) {
@@ -291,7 +291,7 @@ function executeTaskMasterCommand(
? result.stderr.trim() ? result.stderr.trim()
: result.stdout : result.stdout
? result.stdout.trim() ? result.stdout.trim()
: 'Unknown error'; : "Unknown error";
throw new Error( throw new Error(
`Command failed with exit code ${result.status}: ${errorOutput}` `Command failed with exit code ${result.status}: ${errorOutput}`
); );
@@ -300,13 +300,13 @@ function executeTaskMasterCommand(
return { return {
success: true, success: true,
stdout: result.stdout, stdout: result.stdout,
stderr: result.stderr stderr: result.stderr,
}; };
} catch (error) { } catch (error) {
log.error(`Error executing task-master command: ${error.message}`); log.error(`Error executing task-master command: ${error.message}`);
return { return {
success: false, success: false,
error: error.message error: error.message,
}; };
} }
} }
@@ -332,7 +332,7 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
// Return the cached data in the same structure as a fresh result // Return the cached data in the same structure as a fresh result
return { return {
...cachedResult, // Spread the cached result to maintain its structure ...cachedResult, // Spread the cached result to maintain its structure
fromCache: true // Just add the fromCache flag fromCache: true, // Just add the fromCache flag
}; };
} }
@@ -360,20 +360,38 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
// Return the fresh result, indicating it wasn't from cache // Return the fresh result, indicating it wasn't from cache
return { return {
...result, ...result,
fromCache: false fromCache: false,
}; };
} }
/**
* Filters sensitive fields from telemetry data before sending to users.
* Removes commandArgs and fullOutput which may contain API keys and sensitive data.
* @param {Object} telemetryData - The telemetry data object to filter.
* @returns {Object} - Filtered telemetry data safe for user exposure.
*/
function filterSensitiveTelemetryData(telemetryData) {
if (!telemetryData || typeof telemetryData !== "object") {
return telemetryData;
}
// Create a copy and remove sensitive fields
const { commandArgs, fullOutput, ...safeTelemetryData } = telemetryData;
return safeTelemetryData;
}
/** /**
* Recursively removes specified fields from task objects, whether single or in an array. * Recursively removes specified fields from task objects, whether single or in an array.
* Handles common data structures returned by task commands. * Handles common data structures returned by task commands.
* Also filters sensitive telemetry data if present.
* @param {Object|Array} taskOrData - A single task object or a data object containing a 'tasks' array. * @param {Object|Array} taskOrData - A single task object or a data object containing a 'tasks' array.
* @param {string[]} fieldsToRemove - An array of field names to remove. * @param {string[]} fieldsToRemove - An array of field names to remove.
* @returns {Object|Array} - The processed data with specified fields removed. * @returns {Object|Array} - The processed data with specified fields removed.
*/ */
function processMCPResponseData( function processMCPResponseData(
taskOrData, taskOrData,
fieldsToRemove = ['details', 'testStrategy'] fieldsToRemove = ["details", "testStrategy"]
) { ) {
if (!taskOrData) { if (!taskOrData) {
return taskOrData; return taskOrData;
@@ -381,7 +399,7 @@ function processMCPResponseData(
// Helper function to process a single task object // Helper function to process a single task object
const processSingleTask = (task) => { const processSingleTask = (task) => {
if (typeof task !== 'object' || task === null) { if (typeof task !== "object" || task === null) {
return task; return task;
} }
@@ -392,6 +410,13 @@ function processMCPResponseData(
delete processedTask[field]; delete processedTask[field];
}); });
// Filter telemetry data if present
if (processedTask.telemetryData) {
processedTask.telemetryData = filterSensitiveTelemetryData(
processedTask.telemetryData
);
}
// Recursively process subtasks if they exist and are an array // Recursively process subtasks if they exist and are an array
if (processedTask.subtasks && Array.isArray(processedTask.subtasks)) { if (processedTask.subtasks && Array.isArray(processedTask.subtasks)) {
// Use processArrayOfTasks to handle the subtasks array // Use processArrayOfTasks to handle the subtasks array
@@ -406,33 +431,41 @@ function processMCPResponseData(
return tasks.map(processSingleTask); return tasks.map(processSingleTask);
}; };
// Handle top-level telemetry data filtering for any response structure
let processedData = { ...taskOrData };
if (processedData.telemetryData) {
processedData.telemetryData = filterSensitiveTelemetryData(
processedData.telemetryData
);
}
// Check if the input is a data structure containing a 'tasks' array (like from listTasks) // Check if the input is a data structure containing a 'tasks' array (like from listTasks)
if ( if (
typeof taskOrData === 'object' && typeof processedData === "object" &&
taskOrData !== null && processedData !== null &&
Array.isArray(taskOrData.tasks) Array.isArray(processedData.tasks)
) { ) {
return { return {
...taskOrData, // Keep other potential fields like 'stats', 'filter' ...processedData, // Keep other potential fields like 'stats', 'filter'
tasks: processArrayOfTasks(taskOrData.tasks) tasks: processArrayOfTasks(processedData.tasks),
}; };
} }
// Check if the input is likely a single task object (add more checks if needed) // Check if the input is likely a single task object (add more checks if needed)
else if ( else if (
typeof taskOrData === 'object' && typeof processedData === "object" &&
taskOrData !== null && processedData !== null &&
'id' in taskOrData && "id" in processedData &&
'title' in taskOrData "title" in processedData
) { ) {
return processSingleTask(taskOrData); return processSingleTask(processedData);
} }
// Check if the input is an array of tasks directly (less common but possible) // Check if the input is an array of tasks directly (less common but possible)
else if (Array.isArray(taskOrData)) { else if (Array.isArray(processedData)) {
return processArrayOfTasks(taskOrData); return processArrayOfTasks(processedData);
} }
// If it doesn't match known task structures, return it as is // If it doesn't match known task structures, return the processed data (with filtered telemetry)
return taskOrData; return processedData;
} }
/** /**
@@ -445,15 +478,15 @@ function createContentResponse(content) {
return { return {
content: [ content: [
{ {
type: 'text', type: "text",
text: text:
typeof content === 'object' typeof content === "object"
? // Format JSON nicely with indentation ? // Format JSON nicely with indentation
JSON.stringify(content, null, 2) JSON.stringify(content, null, 2)
: // Keep other content types as-is : // Keep other content types as-is
String(content) String(content),
} },
] ],
}; };
} }
@@ -466,11 +499,11 @@ function createErrorResponse(errorMessage) {
return { return {
content: [ content: [
{ {
type: 'text', type: "text",
text: `Error: ${errorMessage}` text: `Error: ${errorMessage}`,
} },
], ],
isError: true isError: true,
}; };
} }
@@ -489,7 +522,7 @@ function createLogWrapper(log) {
debug: (message, ...args) => debug: (message, ...args) =>
log.debug ? log.debug(message, ...args) : null, log.debug ? log.debug(message, ...args) : null,
// Map success to info as a common fallback // Map success to info as a common fallback
success: (message, ...args) => log.info(message, ...args) success: (message, ...args) => log.info(message, ...args),
}; };
} }
@@ -520,23 +553,23 @@ function normalizeProjectRoot(rawPath, log) {
} }
// 2. Strip file:// prefix (handle 2 or 3 slashes) // 2. Strip file:// prefix (handle 2 or 3 slashes)
if (pathString.startsWith('file:///')) { if (pathString.startsWith("file:///")) {
pathString = pathString.slice(7); // Slice 7 for file:///, may leave leading / on Windows pathString = pathString.slice(7); // Slice 7 for file:///, may leave leading / on Windows
} else if (pathString.startsWith('file://')) { } else if (pathString.startsWith("file://")) {
pathString = pathString.slice(7); // Slice 7 for file:// pathString = pathString.slice(7); // Slice 7 for file://
} }
// 3. Handle potential Windows leading slash after stripping prefix (e.g., /C:/...) // 3. Handle potential Windows leading slash after stripping prefix (e.g., /C:/...)
// This checks if it starts with / followed by a drive letter C: D: etc. // This checks if it starts with / followed by a drive letter C: D: etc.
if ( if (
pathString.startsWith('/') && pathString.startsWith("/") &&
/[A-Za-z]:/.test(pathString.substring(1, 3)) /[A-Za-z]:/.test(pathString.substring(1, 3))
) { ) {
pathString = pathString.substring(1); // Remove the leading slash pathString = pathString.substring(1); // Remove the leading slash
} }
// 4. Normalize backslashes to forward slashes // 4. Normalize backslashes to forward slashes
pathString = pathString.replace(/\\/g, '/'); pathString = pathString.replace(/\\/g, "/");
// 5. Resolve to absolute path using server's OS convention // 5. Resolve to absolute path using server's OS convention
const resolvedPath = path.resolve(pathString); const resolvedPath = path.resolve(pathString);
@@ -578,6 +611,7 @@ function getRawProjectRootFromSession(session, log) {
/** /**
* Higher-order function to wrap MCP tool execute methods. * Higher-order function to wrap MCP tool execute methods.
* Ensures args.projectRoot is present and normalized before execution. * Ensures args.projectRoot is present and normalized before execution.
* Uses TASK_MASTER_PROJECT_ROOT environment variable with proper precedence.
* @param {Function} executeFn - The original async execute(args, context) function. * @param {Function} executeFn - The original async execute(args, context) function.
* @returns {Function} The wrapped async execute function. * @returns {Function} The wrapped async execute function.
*/ */
@@ -585,34 +619,55 @@ function withNormalizedProjectRoot(executeFn) {
return async (args, context) => { return async (args, context) => {
const { log, session } = context; const { log, session } = context;
let normalizedRoot = null; let normalizedRoot = null;
let rootSource = 'unknown'; let rootSource = "unknown";
try { try {
// Determine raw root: prioritize args, then session // PRECEDENCE ORDER:
let rawRoot = args.projectRoot; // 1. TASK_MASTER_PROJECT_ROOT environment variable (from process.env or session)
if (!rawRoot) { // 2. args.projectRoot (explicitly provided)
rawRoot = getRawProjectRootFromSession(session, log); // 3. Session-based project root resolution
rootSource = 'session'; // 4. Current directory fallback
} else {
rootSource = 'args';
}
if (!rawRoot) { // 1. Check for TASK_MASTER_PROJECT_ROOT environment variable first
log.error('Could not determine project root from args or session.'); if (process.env.TASK_MASTER_PROJECT_ROOT) {
return createErrorResponse( const envRoot = process.env.TASK_MASTER_PROJECT_ROOT;
'Could not determine project root. Please provide projectRoot argument or ensure session contains root info.' normalizedRoot = path.isAbsolute(envRoot)
); ? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = "TASK_MASTER_PROJECT_ROOT environment variable";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// Also check session environment variables for TASK_MASTER_PROJECT_ROOT
else if (session?.env?.TASK_MASTER_PROJECT_ROOT) {
const envRoot = session.env.TASK_MASTER_PROJECT_ROOT;
normalizedRoot = path.isAbsolute(envRoot)
? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = "TASK_MASTER_PROJECT_ROOT session environment variable";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 2. If no environment variable, try args.projectRoot
else if (args.projectRoot) {
normalizedRoot = normalizeProjectRoot(args.projectRoot, log);
rootSource = "args.projectRoot";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 3. If no args.projectRoot, try session-based resolution
else {
const sessionRoot = getProjectRootFromSession(session, log);
if (sessionRoot) {
normalizedRoot = sessionRoot; // getProjectRootFromSession already normalizes
rootSource = "session";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
} }
// Normalize the determined raw root
normalizedRoot = normalizeProjectRoot(rawRoot, log);
if (!normalizedRoot) { if (!normalizedRoot) {
log.error( log.error(
`Failed to normalize project root obtained from ${rootSource}: ${rawRoot}` "Could not determine project root from environment, args, or session."
); );
return createErrorResponse( return createErrorResponse(
`Invalid project root provided or derived from ${rootSource}: ${rawRoot}` "Could not determine project root. Please provide projectRoot argument or ensure TASK_MASTER_PROJECT_ROOT environment variable is set."
); );
} }
@@ -648,5 +703,6 @@ export {
createLogWrapper, createLogWrapper,
normalizeProjectRoot, normalizeProjectRoot,
getRawProjectRootFromSession, getRawProjectRootFromSession,
withNormalizedProjectRoot withNormalizedProjectRoot,
filterSensitiveTelemetryData,
}; };

2427
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "task-master-ai", "name": "task-master-ai",
"version": "0.14.0", "version": "0.15.0",
"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",
@@ -21,8 +21,8 @@
"release": "changeset publish", "release": "changeset publish",
"inspector": "npx @modelcontextprotocol/inspector node mcp-server/server.js", "inspector": "npx @modelcontextprotocol/inspector node mcp-server/server.js",
"mcp-server": "node mcp-server/server.js", "mcp-server": "node mcp-server/server.js",
"format-check": "prettier --check .", "format-check": "biome format .",
"format": "prettier --write ." "format": "biome format . --write"
}, },
"keywords": [ "keywords": [
"claude", "claude",
@@ -39,18 +39,22 @@
"author": "Eyal Toledano", "author": "Eyal Toledano",
"license": "MIT WITH Commons-Clause", "license": "MIT WITH Commons-Clause",
"dependencies": { "dependencies": {
"@ai-sdk/amazon-bedrock": "^2.2.9",
"@ai-sdk/anthropic": "^1.2.10", "@ai-sdk/anthropic": "^1.2.10",
"@ai-sdk/azure": "^1.3.17", "@ai-sdk/azure": "^1.3.17",
"@ai-sdk/google": "^1.2.13", "@ai-sdk/google": "^1.2.13",
"@ai-sdk/google-vertex": "^2.2.23",
"@ai-sdk/mistral": "^1.2.7", "@ai-sdk/mistral": "^1.2.7",
"@ai-sdk/openai": "^1.3.20", "@ai-sdk/openai": "^1.3.20",
"@ai-sdk/perplexity": "^1.1.7", "@ai-sdk/perplexity": "^1.1.7",
"@ai-sdk/xai": "^1.2.15", "@ai-sdk/xai": "^1.2.15",
"@anthropic-ai/sdk": "^0.39.0", "@anthropic-ai/sdk": "^0.39.0",
"@aws-sdk/credential-providers": "^3.817.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", "boxen": "^8.0.1",
"chalk": "^5.4.1", "chalk": "^5.4.1",
"cli-highlight": "^2.1.11",
"cli-table3": "^0.6.5", "cli-table3": "^0.6.5",
"commander": "^11.1.0", "commander": "^11.1.0",
"cors": "^2.8.5", "cors": "^2.8.5",
@@ -58,20 +62,24 @@
"express": "^4.21.2", "express": "^4.21.2",
"fastmcp": "^1.20.5", "fastmcp": "^1.20.5",
"figlet": "^1.8.0", "figlet": "^1.8.0",
"fuse.js": "^7.0.0", "fuse.js": "^7.1.0",
"gpt-tokens": "^1.3.14",
"gradient-string": "^3.0.0", "gradient-string": "^3.0.0",
"helmet": "^8.1.0", "helmet": "^8.1.0",
"inquirer": "^12.5.0", "inquirer": "^12.5.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"lru-cache": "^10.2.0", "lru-cache": "^10.2.0",
"ollama-ai-provider": "^1.2.0", "ollama-ai-provider": "^1.2.0",
"open": "^10.1.2",
"openai": "^4.89.0", "openai": "^4.89.0",
"ora": "^8.2.0", "ora": "^8.2.0",
"task-master-ai": "^0.15.0",
"uuid": "^11.1.0", "uuid": "^11.1.0",
"zod": "^3.23.8" "zod": "^3.23.8",
"zod-to-json-schema": "^3.24.5"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=18.0.0"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -92,10 +100,11 @@
"src/**" "src/**"
], ],
"overrides": { "overrides": {
"node-fetch": "^3.3.2", "node-fetch": "^2.6.12",
"whatwg-url": "^11.0.0" "whatwg-url": "^11.0.0"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^1.9.4",
"@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",
@@ -104,7 +113,6 @@
"jest": "^29.7.0", "jest": "^29.7.0",
"jest-environment-node": "^29.7.0", "jest-environment-node": "^29.7.0",
"mock-fs": "^5.5.0", "mock-fs": "^5.5.0",
"node-fetch": "^3.3.2",
"prettier": "^3.5.3", "prettier": "^3.5.3",
"react": "^18.3.1", "react": "^18.3.1",
"supertest": "^7.1.0", "supertest": "^7.1.0",

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,13 @@
import fs from 'fs'; import fs from "fs";
import path from 'path'; import path from "path";
import chalk from 'chalk'; import chalk from "chalk";
import { fileURLToPath } from 'url'; import { fileURLToPath } from "url";
import { log, resolveEnvVariable, findProjectRoot } from './utils.js'; import {
log,
findProjectRoot,
resolveEnvVariable,
isSilentMode,
} from "./utils.js";
// Calculate __dirname in ESM // Calculate __dirname in ESM
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -12,14 +17,14 @@ const __dirname = path.dirname(__filename);
let MODEL_MAP; let MODEL_MAP;
try { try {
const supportedModelsRaw = fs.readFileSync( const supportedModelsRaw = fs.readFileSync(
path.join(__dirname, 'supported-models.json'), path.join(__dirname, "supported-models.json"),
'utf-8' "utf-8"
); );
MODEL_MAP = JSON.parse(supportedModelsRaw); MODEL_MAP = JSON.parse(supportedModelsRaw);
} catch (error) { } catch (error) {
console.error( console.error(
chalk.red( chalk.red(
'FATAL ERROR: Could not load supported-models.json. Please ensure the file exists and is valid JSON.' "FATAL ERROR: Could not load supported-models.json. Please ensure the file exists and is valid JSON."
), ),
error error
); );
@@ -27,42 +32,49 @@ try {
process.exit(1); // Exit if models can't be loaded process.exit(1); // Exit if models can't be loaded
} }
const CONFIG_FILE_NAME = '.taskmasterconfig'; const CONFIG_FILE_NAME = ".taskmasterconfig";
// Define valid providers dynamically from the loaded MODEL_MAP // Define valid providers dynamically from the loaded MODEL_MAP
const VALID_PROVIDERS = Object.keys(MODEL_MAP || {}); const VALID_PROVIDERS = Object.keys(MODEL_MAP || {});
// Default configuration values (used if .taskmasterconfig is missing or incomplete) // Default configuration structure (updated)
const DEFAULTS = { const defaultConfig = {
global: {
logLevel: "info",
debug: false,
defaultSubtasks: 5,
defaultPriority: "medium",
projectName: "Taskmaster",
ollamaBaseURL: "http://localhost:11434/api",
azureBaseURL: "https://your-endpoint.azure.com/",
},
models: { models: {
main: { main: {
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,
}, },
research: { research: {
provider: 'perplexity', provider: "perplexity",
modelId: 'sonar-pro', modelId: "sonar-pro",
maxTokens: 8700, maxTokens: 8700,
temperature: 0.1 temperature: 0.1,
}, },
fallback: { fallback: {
// No default fallback provider/model initially // No default fallback provider/model initially
provider: 'anthropic', provider: "anthropic",
modelId: 'claude-3-5-sonnet', modelId: "claude-3-5-sonnet",
maxTokens: 64000, // Default parameters if fallback IS configured maxTokens: 64000, // Default parameters if fallback IS configured
temperature: 0.2 temperature: 0.2,
} },
},
account: {
userId: "1234567890", // Placeholder that triggers auth/init
email: "",
mode: "byok",
telemetryEnabled: true,
}, },
global: {
logLevel: 'info',
debug: false,
defaultSubtasks: 5,
defaultPriority: 'medium',
projectName: 'Task Master',
ollamaBaseUrl: 'http://localhost:11434/api'
}
}; };
// --- Internal Config Loading --- // --- Internal Config Loading ---
@@ -73,16 +85,16 @@ let loadedConfigRoot = null; // Track which root loaded the config
class ConfigurationError extends Error { class ConfigurationError extends Error {
constructor(message) { constructor(message) {
super(message); super(message);
this.name = 'ConfigurationError'; this.name = "ConfigurationError";
} }
} }
function _loadAndValidateConfig(explicitRoot = null) { function _loadAndValidateConfig(explicitRoot = null) {
const defaults = DEFAULTS; // Use the defined defaults const defaults = defaultConfig; // Use the defined defaults
let rootToUse = explicitRoot; let rootToUse = explicitRoot;
let configSource = explicitRoot let configSource = explicitRoot
? `explicit root (${explicitRoot})` ? `explicit root (${explicitRoot})`
: 'defaults (no root provided yet)'; : "defaults (no root provided yet)";
// ---> If no explicit root, TRY to find it <--- // ---> If no explicit root, TRY to find it <---
if (!rootToUse) { if (!rootToUse) {
@@ -104,7 +116,7 @@ function _loadAndValidateConfig(explicitRoot = null) {
if (fs.existsSync(configPath)) { if (fs.existsSync(configPath)) {
configExists = true; configExists = true;
try { try {
const rawData = fs.readFileSync(configPath, 'utf-8'); const rawData = fs.readFileSync(configPath, "utf-8");
const parsedConfig = JSON.parse(rawData); const parsedConfig = JSON.parse(rawData);
// Deep merge parsed config onto defaults // Deep merge parsed config onto defaults
@@ -113,15 +125,16 @@ function _loadAndValidateConfig(explicitRoot = null) {
main: { ...defaults.models.main, ...parsedConfig?.models?.main }, main: { ...defaults.models.main, ...parsedConfig?.models?.main },
research: { research: {
...defaults.models.research, ...defaults.models.research,
...parsedConfig?.models?.research ...parsedConfig?.models?.research,
}, },
fallback: fallback:
parsedConfig?.models?.fallback?.provider && parsedConfig?.models?.fallback?.provider &&
parsedConfig?.models?.fallback?.modelId parsedConfig?.models?.fallback?.modelId
? { ...defaults.models.fallback, ...parsedConfig.models.fallback } ? { ...defaults.models.fallback, ...parsedConfig.models.fallback }
: { ...defaults.models.fallback } : { ...defaults.models.fallback },
}, },
global: { ...defaults.global, ...parsedConfig?.global } global: { ...defaults.global, ...parsedConfig?.global },
account: { ...defaults.account, ...parsedConfig?.account },
}; };
configSource = `file (${configPath})`; // Update source info configSource = `file (${configPath})`; // Update source info
@@ -256,68 +269,68 @@ function getModelConfigForRole(role, explicitRoot = null) {
const roleConfig = config?.models?.[role]; const roleConfig = config?.models?.[role];
if (!roleConfig) { if (!roleConfig) {
log( log(
'warn', "warn",
`No model configuration found for role: ${role}. Returning default.` `No model configuration found for role: ${role}. Returning default.`
); );
return DEFAULTS.models[role] || {}; return defaultConfig.models[role] || {};
} }
return roleConfig; return roleConfig;
} }
function getMainProvider(explicitRoot = null) { function getMainProvider(explicitRoot = null) {
return getModelConfigForRole('main', explicitRoot).provider; return getModelConfigForRole("main", explicitRoot).provider;
} }
function getMainModelId(explicitRoot = null) { function getMainModelId(explicitRoot = null) {
return getModelConfigForRole('main', explicitRoot).modelId; return getModelConfigForRole("main", explicitRoot).modelId;
} }
function getMainMaxTokens(explicitRoot = null) { function getMainMaxTokens(explicitRoot = null) {
// Directly return value from config (which includes defaults) // Directly return value from config (which includes defaults)
return getModelConfigForRole('main', explicitRoot).maxTokens; return getModelConfigForRole("main", explicitRoot).maxTokens;
} }
function getMainTemperature(explicitRoot = null) { function getMainTemperature(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('main', explicitRoot).temperature; return getModelConfigForRole("main", explicitRoot).temperature;
} }
function getResearchProvider(explicitRoot = null) { function getResearchProvider(explicitRoot = null) {
return getModelConfigForRole('research', explicitRoot).provider; return getModelConfigForRole("research", explicitRoot).provider;
} }
function getResearchModelId(explicitRoot = null) { function getResearchModelId(explicitRoot = null) {
return getModelConfigForRole('research', explicitRoot).modelId; return getModelConfigForRole("research", explicitRoot).modelId;
} }
function getResearchMaxTokens(explicitRoot = null) { function getResearchMaxTokens(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('research', explicitRoot).maxTokens; return getModelConfigForRole("research", explicitRoot).maxTokens;
} }
function getResearchTemperature(explicitRoot = null) { function getResearchTemperature(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('research', explicitRoot).temperature; return getModelConfigForRole("research", explicitRoot).temperature;
} }
function getFallbackProvider(explicitRoot = null) { function getFallbackProvider(explicitRoot = null) {
// Directly return value from config (will be undefined if not set) // Directly return value from config (will be undefined if not set)
return getModelConfigForRole('fallback', explicitRoot).provider; return getModelConfigForRole("fallback", explicitRoot).provider;
} }
function getFallbackModelId(explicitRoot = null) { function getFallbackModelId(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).modelId; return getModelConfigForRole("fallback", explicitRoot).modelId;
} }
function getFallbackMaxTokens(explicitRoot = null) { function getFallbackMaxTokens(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).maxTokens; return getModelConfigForRole("fallback", explicitRoot).maxTokens;
} }
function getFallbackTemperature(explicitRoot = null) { function getFallbackTemperature(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).temperature; return getModelConfigForRole("fallback", explicitRoot).temperature;
} }
// --- Global Settings Getters --- // --- Global Settings Getters ---
@@ -325,7 +338,7 @@ function getFallbackTemperature(explicitRoot = null) {
function getGlobalConfig(explicitRoot = null) { function getGlobalConfig(explicitRoot = null) {
const config = getConfig(explicitRoot); const config = getConfig(explicitRoot);
// Ensure global defaults are applied if global section is missing // Ensure global defaults are applied if global section is missing
return { ...DEFAULTS.global, ...(config?.global || {}) }; return { ...defaultConfig.global, ...(config?.global || {}) };
} }
function getLogLevel(explicitRoot = null) { function getLogLevel(explicitRoot = null) {
@@ -342,13 +355,13 @@ function getDefaultSubtasks(explicitRoot = null) {
// Directly return value from config, ensure integer // Directly return value from config, ensure integer
const val = getGlobalConfig(explicitRoot).defaultSubtasks; const val = getGlobalConfig(explicitRoot).defaultSubtasks;
const parsedVal = parseInt(val, 10); const parsedVal = parseInt(val, 10);
return isNaN(parsedVal) ? DEFAULTS.global.defaultSubtasks : parsedVal; return isNaN(parsedVal) ? defaultConfig.global.defaultSubtasks : parsedVal;
} }
function getDefaultNumTasks(explicitRoot = null) { function getDefaultNumTasks(explicitRoot = null) {
const val = getGlobalConfig(explicitRoot).defaultNumTasks; const val = getGlobalConfig(explicitRoot).defaultNumTasks;
const parsedVal = parseInt(val, 10); const parsedVal = parseInt(val, 10);
return isNaN(parsedVal) ? DEFAULTS.global.defaultNumTasks : parsedVal; return isNaN(parsedVal) ? defaultConfig.global.defaultNumTasks : parsedVal;
} }
function getDefaultPriority(explicitRoot = null) { function getDefaultPriority(explicitRoot = null) {
@@ -361,9 +374,34 @@ function getProjectName(explicitRoot = null) {
return getGlobalConfig(explicitRoot).projectName; return getGlobalConfig(explicitRoot).projectName;
} }
function getOllamaBaseUrl(explicitRoot = null) { function getOllamaBaseURL(explicitRoot = null) {
// Directly return value from config // Directly return value from config
return getGlobalConfig(explicitRoot).ollamaBaseUrl; return getGlobalConfig(explicitRoot).ollamaBaseURL;
}
function getAzureBaseURL(explicitRoot = null) {
// Directly return value from config
return getGlobalConfig(explicitRoot).azureBaseURL;
}
/**
* Gets the Google Cloud project ID for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The project ID or null if not configured
*/
function getVertexProjectId(explicitRoot = null) {
// Return value from config
return getGlobalConfig(explicitRoot).vertexProjectId;
}
/**
* Gets the Google Cloud location for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string} The location or default value of "us-central1"
*/
function getVertexLocation(explicitRoot = null) {
// Return value from config or default
return getGlobalConfig(explicitRoot).vertexLocation || "us-central1";
} }
/** /**
@@ -391,31 +429,31 @@ function getParametersForRole(role, explicitRoot = null) {
// Check if a model-specific max_tokens is defined and valid // Check if a model-specific max_tokens is defined and valid
if ( if (
modelDefinition && modelDefinition &&
typeof modelDefinition.max_tokens === 'number' && typeof modelDefinition.max_tokens === "number" &&
modelDefinition.max_tokens > 0 modelDefinition.max_tokens > 0
) { ) {
const modelSpecificMaxTokens = modelDefinition.max_tokens; const modelSpecificMaxTokens = modelDefinition.max_tokens;
// Use the minimum of the role default and the model specific limit // Use the minimum of the role default and the model specific limit
effectiveMaxTokens = Math.min(roleMaxTokens, modelSpecificMaxTokens); effectiveMaxTokens = Math.min(roleMaxTokens, modelSpecificMaxTokens);
log( log(
'debug', "debug",
`Applying model-specific max_tokens (${modelSpecificMaxTokens}) for ${modelId}. Effective limit: ${effectiveMaxTokens}` `Applying model-specific max_tokens (${modelSpecificMaxTokens}) for ${modelId}. Effective limit: ${effectiveMaxTokens}`
); );
} else { } else {
log( log(
'debug', "debug",
`No valid model-specific max_tokens override found for ${modelId}. Using role default: ${roleMaxTokens}` `No valid model-specific max_tokens override found for ${modelId}. Using role default: ${roleMaxTokens}`
); );
} }
} else { } else {
log( log(
'debug', "debug",
`No model definitions found for provider ${providerName} in MODEL_MAP. Using role default maxTokens: ${roleMaxTokens}` `No model definitions found for provider ${providerName} in MODEL_MAP. Using role default maxTokens: ${roleMaxTokens}`
); );
} }
} catch (lookupError) { } catch (lookupError) {
log( log(
'warn', "warn",
`Error looking up model-specific max_tokens for ${modelId}: ${lookupError.message}. Using role default: ${roleMaxTokens}` `Error looking up model-specific max_tokens for ${modelId}: ${lookupError.message}. Using role default: ${roleMaxTokens}`
); );
// Fallback to role default on error // Fallback to role default on error
@@ -424,7 +462,7 @@ function getParametersForRole(role, explicitRoot = null) {
return { return {
maxTokens: effectiveMaxTokens, maxTokens: effectiveMaxTokens,
temperature: roleTemperature temperature: roleTemperature,
}; };
} }
@@ -438,25 +476,26 @@ function getParametersForRole(role, explicitRoot = null) {
*/ */
function isApiKeySet(providerName, session = null, projectRoot = null) { function isApiKeySet(providerName, session = null, projectRoot = 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"
} }
const keyMap = { const keyMap = {
openai: 'OPENAI_API_KEY', openai: "OPENAI_API_KEY",
anthropic: 'ANTHROPIC_API_KEY', anthropic: "ANTHROPIC_API_KEY",
google: 'GOOGLE_API_KEY', google: "GOOGLE_API_KEY",
perplexity: 'PERPLEXITY_API_KEY', perplexity: "PERPLEXITY_API_KEY",
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",
vertex: "GOOGLE_API_KEY", // Vertex uses the same key as Google
// Add other providers as needed // Add other providers as needed
}; };
const providerKey = providerName?.toLowerCase(); const providerKey = providerName?.toLowerCase();
if (!providerKey || !keyMap[providerKey]) { if (!providerKey || !keyMap[providerKey]) {
log('warn', `Unknown provider name: ${providerName} in isApiKeySet check.`); log("warn", `Unknown provider name: ${providerName} in isApiKeySet check.`);
return false; return false;
} }
@@ -466,9 +505,9 @@ function isApiKeySet(providerName, session = null, projectRoot = null) {
// 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 (
apiKeyValue && apiKeyValue &&
apiKeyValue.trim() !== '' && apiKeyValue.trim() !== "" &&
!/YOUR_.*_API_KEY_HERE/.test(apiKeyValue) && // General placeholder check !/YOUR_.*_API_KEY_HERE/.test(apiKeyValue) && // General placeholder check
!apiKeyValue.includes('KEY_HERE') !apiKeyValue.includes("KEY_HERE")
); // Another common placeholder pattern ); // Another common placeholder pattern
} }
@@ -483,11 +522,11 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
const rootDir = projectRoot || findProjectRoot(); // Use existing root finding const rootDir = projectRoot || findProjectRoot(); // Use existing root finding
if (!rootDir) { if (!rootDir) {
console.warn( console.warn(
chalk.yellow('Warning: Could not find project root to check mcp.json.') chalk.yellow("Warning: Could not find project root to check mcp.json.")
); );
return false; // Cannot check without root return false; // Cannot check without root
} }
const mcpConfigPath = path.join(rootDir, '.cursor', 'mcp.json'); const mcpConfigPath = path.join(rootDir, ".cursor", "mcp.json");
if (!fs.existsSync(mcpConfigPath)) { if (!fs.existsSync(mcpConfigPath)) {
// console.warn(chalk.yellow('Warning: .cursor/mcp.json not found.')); // console.warn(chalk.yellow('Warning: .cursor/mcp.json not found.'));
@@ -495,10 +534,10 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
} }
try { try {
const mcpConfigRaw = fs.readFileSync(mcpConfigPath, 'utf-8'); const mcpConfigRaw = fs.readFileSync(mcpConfigPath, "utf-8");
const mcpConfig = JSON.parse(mcpConfigRaw); const mcpConfig = JSON.parse(mcpConfigRaw);
const mcpEnv = mcpConfig?.mcpServers?.['taskmaster-ai']?.env; const mcpEnv = mcpConfig?.mcpServers?.["taskmaster-ai"]?.env;
if (!mcpEnv) { if (!mcpEnv) {
// console.warn(chalk.yellow('Warning: Could not find taskmaster-ai env in mcp.json.')); // console.warn(chalk.yellow('Warning: Could not find taskmaster-ai env in mcp.json.'));
return false; // Structure missing return false; // Structure missing
@@ -508,39 +547,43 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
let placeholderValue = null; let placeholderValue = null;
switch (providerName) { switch (providerName) {
case 'anthropic': case "anthropic":
apiKeyToCheck = mcpEnv.ANTHROPIC_API_KEY; apiKeyToCheck = mcpEnv.ANTHROPIC_API_KEY;
placeholderValue = 'YOUR_ANTHROPIC_API_KEY_HERE'; placeholderValue = "YOUR_ANTHROPIC_API_KEY_HERE";
break; break;
case 'openai': case "openai":
apiKeyToCheck = mcpEnv.OPENAI_API_KEY; apiKeyToCheck = mcpEnv.OPENAI_API_KEY;
placeholderValue = 'YOUR_OPENAI_API_KEY_HERE'; // Assuming placeholder matches OPENAI placeholderValue = "YOUR_OPENAI_API_KEY_HERE"; // Assuming placeholder matches OPENAI
break; break;
case 'openrouter': case "openrouter":
apiKeyToCheck = mcpEnv.OPENROUTER_API_KEY; apiKeyToCheck = mcpEnv.OPENROUTER_API_KEY;
placeholderValue = 'YOUR_OPENROUTER_API_KEY_HERE'; placeholderValue = "YOUR_OPENROUTER_API_KEY_HERE";
break; break;
case 'google': case "google":
apiKeyToCheck = mcpEnv.GOOGLE_API_KEY; apiKeyToCheck = mcpEnv.GOOGLE_API_KEY;
placeholderValue = 'YOUR_GOOGLE_API_KEY_HERE'; placeholderValue = "YOUR_GOOGLE_API_KEY_HERE";
break; break;
case 'perplexity': case "perplexity":
apiKeyToCheck = mcpEnv.PERPLEXITY_API_KEY; apiKeyToCheck = mcpEnv.PERPLEXITY_API_KEY;
placeholderValue = 'YOUR_PERPLEXITY_API_KEY_HERE'; placeholderValue = "YOUR_PERPLEXITY_API_KEY_HERE";
break; break;
case 'xai': case "xai":
apiKeyToCheck = mcpEnv.XAI_API_KEY; apiKeyToCheck = mcpEnv.XAI_API_KEY;
placeholderValue = 'YOUR_XAI_API_KEY_HERE'; placeholderValue = "YOUR_XAI_API_KEY_HERE";
break; break;
case 'ollama': case "ollama":
return true; // No key needed return true; // No key needed
case 'mistral': case "mistral":
apiKeyToCheck = mcpEnv.MISTRAL_API_KEY; apiKeyToCheck = mcpEnv.MISTRAL_API_KEY;
placeholderValue = 'YOUR_MISTRAL_API_KEY_HERE'; placeholderValue = "YOUR_MISTRAL_API_KEY_HERE";
break; break;
case 'azure': case "azure":
apiKeyToCheck = mcpEnv.AZURE_OPENAI_API_KEY; apiKeyToCheck = mcpEnv.AZURE_OPENAI_API_KEY;
placeholderValue = 'YOUR_AZURE_OPENAI_API_KEY_HERE'; placeholderValue = "YOUR_AZURE_OPENAI_API_KEY_HERE";
break;
case "vertex":
apiKeyToCheck = mcpEnv.GOOGLE_API_KEY; // Vertex uses Google API key
placeholderValue = "YOUR_GOOGLE_API_KEY_HERE";
break; break;
default: default:
return false; // Unknown provider return false; // Unknown provider
@@ -568,20 +611,20 @@ function getAvailableModels() {
const modelId = modelObj.id; const modelId = modelObj.id;
const sweScore = modelObj.swe_score; const sweScore = modelObj.swe_score;
const cost = modelObj.cost_per_1m_tokens; const cost = modelObj.cost_per_1m_tokens;
const allowedRoles = modelObj.allowed_roles || ['main', 'fallback']; const allowedRoles = modelObj.allowed_roles || ["main", "fallback"];
const nameParts = modelId const nameParts = modelId
.split('-') .split("-")
.map((p) => p.charAt(0).toUpperCase() + p.slice(1)); .map((p) => p.charAt(0).toUpperCase() + p.slice(1));
// Handle specific known names better if needed // Handle specific known names better if needed
let name = nameParts.join(' '); let name = nameParts.join(" ");
if (modelId === 'claude-3.5-sonnet-20240620') if (modelId === "claude-3.5-sonnet-20240620")
name = 'Claude 3.5 Sonnet'; name = "Claude 3.5 Sonnet";
if (modelId === 'claude-3-7-sonnet-20250219') if (modelId === "claude-3-7-sonnet-20250219")
name = 'Claude 3.7 Sonnet'; name = "Claude 3.7 Sonnet";
if (modelId === 'gpt-4o') name = 'GPT-4o'; if (modelId === "gpt-4o") name = "GPT-4o";
if (modelId === 'gpt-4-turbo') name = 'GPT-4 Turbo'; if (modelId === "gpt-4-turbo") name = "GPT-4 Turbo";
if (modelId === 'sonar-pro') name = 'Perplexity Sonar Pro'; if (modelId === "sonar-pro") name = "Perplexity Sonar Pro";
if (modelId === 'sonar-mini') name = 'Perplexity Sonar Mini'; if (modelId === "sonar-mini") name = "Perplexity Sonar Mini";
available.push({ available.push({
id: modelId, id: modelId,
@@ -589,7 +632,7 @@ function getAvailableModels() {
provider: provider, provider: provider,
swe_score: sweScore, swe_score: sweScore,
cost_per_1m_tokens: cost, cost_per_1m_tokens: cost,
allowed_roles: allowedRoles allowed_roles: allowedRoles,
}); });
}); });
} else { } else {
@@ -597,7 +640,7 @@ function getAvailableModels() {
available.push({ available.push({
id: `[${provider}-any]`, id: `[${provider}-any]`,
name: `Any (${provider})`, name: `Any (${provider})`,
provider: provider provider: provider,
}); });
} }
} }
@@ -619,7 +662,7 @@ function writeConfig(config, explicitRoot = null) {
if (!foundRoot) { if (!foundRoot) {
console.error( console.error(
chalk.red( chalk.red(
'Error: Could not determine project root. Configuration not saved.' "Error: Could not determine project root. Configuration not saved."
) )
); );
return false; return false;
@@ -671,30 +714,70 @@ function isConfigFilePresent(explicitRoot = null) {
/** /**
* Gets the user ID from the configuration. * Gets the user ID from the configuration.
* Returns a placeholder that triggers auth/init if no real userId exists.
* @param {string|null} explicitRoot - Optional explicit path to the project root. * @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The user ID or null if not found. * @returns {string|null} The user ID or placeholder, or null if auth unavailable.
*/ */
function getUserId(explicitRoot = null) { function getUserId(explicitRoot = null) {
const config = getConfig(explicitRoot); const config = getConfig(explicitRoot);
if (!config.global) {
config.global = {}; // Ensure global object exists // Ensure account section exists
if (!config.account) {
config.account = { ...defaultConfig.account };
} }
if (!config.global.userId) {
config.global.userId = '1234567890'; // Check if the userId exists in the actual file (not merged config)
// Attempt to write the updated config. let needsToSaveUserId = false;
// It's important that writeConfig correctly resolves the path
// using explicitRoot, similar to how getConfig does. // Load the raw config to check if userId is actually in the file
try {
let rootPath = explicitRoot;
if (explicitRoot === null || explicitRoot === undefined) {
const foundRoot = findProjectRoot();
if (!foundRoot) {
// If no project root, can't check file, assume userId needs to be saved
needsToSaveUserId = true;
} else {
rootPath = foundRoot;
}
}
if (rootPath && !needsToSaveUserId) {
const configPath = path.join(rootPath, CONFIG_FILE_NAME);
if (fs.existsSync(configPath)) {
const rawConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
// Check if userId is missing from the actual file
needsToSaveUserId = !rawConfig.account?.userId;
} else {
// Config file doesn't exist, need to save
needsToSaveUserId = true;
}
}
} catch (error) {
// If there's any error reading the file, assume we need to save
needsToSaveUserId = true;
}
// If userId exists and is not the placeholder, return it
if (config.account.userId && config.account.userId !== "1234567890") {
return config.account.userId;
}
// If userId is missing from the actual file, set the placeholder and save it
if (needsToSaveUserId) {
config.account.userId = "1234567890";
const success = writeConfig(config, explicitRoot); const success = writeConfig(config, explicitRoot);
if (!success) { if (!success) {
// Log an error or handle the failure to write, console.warn("Warning: Failed to save default userId to config file");
// 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.'
);
} }
// Force reload the cached config to reflect the change
loadedConfig = null;
loadedConfigRoot = null;
} }
return config.global.userId;
// Return the placeholder
// This signals to other code that auth/init needs to be attempted
return "1234567890";
} }
/** /**
@@ -707,25 +790,96 @@ function getAllProviders() {
function getBaseUrlForRole(role, explicitRoot = null) { function getBaseUrlForRole(role, explicitRoot = null) {
const roleConfig = getModelConfigForRole(role, explicitRoot); const roleConfig = getModelConfigForRole(role, explicitRoot);
return roleConfig && typeof roleConfig.baseUrl === 'string' return roleConfig && typeof roleConfig.baseURL === "string"
? roleConfig.baseUrl ? roleConfig.baseURL
: undefined; : undefined;
} }
// Get telemetryEnabled from account section
function getTelemetryEnabled(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.telemetryEnabled ?? false;
}
// Update getUserEmail to use account
function getUserEmail(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.email || "";
}
// Update getMode function to use account
function getMode(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.mode || "byok";
}
/**
* Ensures that the .taskmasterconfig file exists, creating it with defaults if it doesn't.
* This is called early in initialization to prevent chicken-and-egg problems.
* @param {string|null} explicitRoot - Optional explicit path to the project root
* @returns {boolean} True if file exists or was created successfully, false otherwise
*/
function ensureConfigFileExists(explicitRoot = null) {
// ---> Determine root path reliably (following existing pattern) <---
let rootPath = explicitRoot;
if (explicitRoot === null || explicitRoot === undefined) {
// Logic matching _loadAndValidateConfig and other functions
const foundRoot = findProjectRoot(); // *** Explicitly call findProjectRoot ***
if (!foundRoot) {
console.warn(
chalk.yellow(
"Warning: Could not determine project root for config file creation."
)
);
return false;
}
rootPath = foundRoot;
}
// ---> End determine root path logic <---
const configPath = path.join(rootPath, CONFIG_FILE_NAME);
// If file already exists, we're good
if (fs.existsSync(configPath)) {
return true;
}
try {
// Create the default config file (following writeConfig pattern)
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
// Only log if not in silent mode
if (!isSilentMode()) {
console.log(chalk.blue(` Created default .taskmasterconfig file`));
}
// Clear any cached config to ensure fresh load
loadedConfig = null;
loadedConfigRoot = null;
return true;
} catch (error) {
console.error(
chalk.red(
`Error creating default .taskmasterconfig file: ${error.message}`
)
);
return false;
}
}
export { export {
// Core config access // Core config access
getConfig, getConfig,
writeConfig, writeConfig,
ConfigurationError, ConfigurationError,
isConfigFilePresent, isConfigFilePresent,
// Validation // Validation
validateProvider, validateProvider,
validateProviderModelCombination, validateProviderModelCombination,
VALID_PROVIDERS, VALID_PROVIDERS,
MODEL_MAP, MODEL_MAP,
getAvailableModels, getAvailableModels,
// Role-specific getters (No env var overrides) // Role-specific getters (No env var overrides)
getMainProvider, getMainProvider,
getMainModelId, getMainModelId,
@@ -740,7 +894,6 @@ export {
getFallbackMaxTokens, getFallbackMaxTokens,
getFallbackTemperature, getFallbackTemperature,
getBaseUrlForRole, getBaseUrlForRole,
// Global setting getters (No env var overrides) // Global setting getters (No env var overrides)
getLogLevel, getLogLevel,
getDebugFlag, getDebugFlag,
@@ -748,13 +901,21 @@ export {
getDefaultSubtasks, getDefaultSubtasks,
getDefaultPriority, getDefaultPriority,
getProjectName, getProjectName,
getOllamaBaseUrl, getOllamaBaseURL,
getAzureBaseURL,
getParametersForRole, getParametersForRole,
getUserId, getUserId,
// API Key Checkers (still relevant) // API Key Checkers (still relevant)
isApiKeySet, isApiKeySet,
getMcpApiKeyStatus, getMcpApiKeyStatus,
// ADD: Function to get all provider names // ADD: Function to get all provider names
getAllProviders getAllProviders,
getVertexProjectId,
getVertexLocation,
// New getters
getTelemetryEnabled,
getUserEmail,
getMode,
// New function
ensureConfigFileExists,
}; };

View File

@@ -1,5 +1,19 @@
{ {
"anthropic": [ "anthropic": [
{
"id": "claude-sonnet-4-20250514",
"swe_score": 0.727,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000
},
{
"id": "claude-opus-4-20250514",
"swe_score": 0.725,
"cost_per_1m_tokens": { "input": 15.0, "output": 75.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 32000
},
{ {
"id": "claude-3-7-sonnet-20250219", "id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623, "swe_score": 0.623,
@@ -191,43 +205,43 @@
], ],
"ollama": [ "ollama": [
{ {
"id": "gemma3:27b", "id": "devstral:latest",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "gemma3:12b", "id": "qwen3:latest",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "qwq", "id": "qwen3:14b",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "deepseek-r1", "id": "qwen3:32b",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "mistral-small3.1", "id": "mistral-small3.1:latest",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "llama3.3", "id": "llama3.3:latest",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
}, },
{ {
"id": "phi4", "id": "phi4:latest",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"] "allowed_roles": ["main", "fallback"]
@@ -235,9 +249,16 @@
], ],
"openrouter": [ "openrouter": [
{ {
"id": "google/gemini-2.0-flash-001", "id": "google/gemini-2.5-flash-preview-05-20",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 }, "cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048576
},
{
"id": "google/gemini-2.5-flash-preview-05-20:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 1048576 "max_tokens": 1048576
}, },
@@ -263,40 +284,25 @@
"max_tokens": 64000 "max_tokens": 64000
}, },
{ {
"id": "deepseek/deepseek-r1:free", "id": "openai/gpt-4.1",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 2, "output": 8 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 163840 "max_tokens": 1000000
}, },
{ {
"id": "microsoft/mai-ds-r1:free", "id": "openai/gpt-4.1-mini",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 163840 "max_tokens": 1000000
}, },
{ {
"id": "google/gemini-2.5-pro-preview-03-25", "id": "openai/gpt-4.1-nano",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 1.25, "output": 10 }, "cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 65535 "max_tokens": 1000000
},
{
"id": "google/gemini-2.5-flash-preview",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main"],
"max_tokens": 65535
},
{
"id": "google/gemini-2.5-flash-preview:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main"],
"max_tokens": 65535
}, },
{ {
"id": "openai/o3", "id": "openai/o3",
@@ -305,6 +311,20 @@
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 200000 "max_tokens": 200000
}, },
{
"id": "openai/codex-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 1.5, "output": 6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "openai/gpt-4o-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{ {
"id": "openai/o4-mini", "id": "openai/o4-mini",
"swe_score": 0.45, "swe_score": 0.45,
@@ -334,46 +354,18 @@
"max_tokens": 1048576 "max_tokens": 1048576
}, },
{ {
"id": "google/gemma-3-12b-it:free", "id": "meta-llama/llama-4-maverick",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 }, "cost_per_1m_tokens": { "input": 0.18, "output": 0.6 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 131072 "max_tokens": 1000000
}, },
{ {
"id": "google/gemma-3-12b-it", "id": "meta-llama/llama-4-scout",
"swe_score": 0, "swe_score": 0,
"cost_per_1m_tokens": { "input": 50, "output": 100 }, "cost_per_1m_tokens": { "input": 0.08, "output": 0.3 },
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 131072 "max_tokens": 1000000
},
{
"id": "google/gemma-3-27b-it:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 96000
},
{
"id": "google/gemma-3-27b-it",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 100, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
},
{
"id": "qwen/qwq-32b:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 40000
},
{
"id": "qwen/qwq-32b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 150, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
}, },
{ {
"id": "qwen/qwen-max", "id": "qwen/qwen-max",
@@ -389,6 +381,13 @@
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 1000000 "max_tokens": 1000000
}, },
{
"id": "qwen/qwen3-235b-a22b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.14, "output": 2 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 24000
},
{ {
"id": "mistralai/mistral-small-3.1-24b-instruct:free", "id": "mistralai/mistral-small-3.1-24b-instruct:free",
"swe_score": 0, "swe_score": 0,
@@ -403,6 +402,20 @@
"allowed_roles": ["main", "fallback"], "allowed_roles": ["main", "fallback"],
"max_tokens": 128000 "max_tokens": 128000
}, },
{
"id": "mistralai/devstral-small",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.3 },
"allowed_roles": ["main"],
"max_tokens": 110000
},
{
"id": "mistralai/mistral-nemo",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.03, "output": 0.07 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{ {
"id": "thudm/glm-4-32b:free", "id": "thudm/glm-4-32b:free",
"swe_score": 0, "swe_score": 0,

View File

@@ -23,6 +23,8 @@ 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 moveTask from './task-manager/move-task.js';
import { performResearch } from './task-manager/research.js';
import { readComplexityReport } from './utils.js'; import { readComplexityReport } from './utils.js';
// Export task manager functions // Export task manager functions
export { export {
@@ -46,5 +48,7 @@ export {
findTaskById, findTaskById,
taskExists, taskExists,
isTaskDependentOn, isTaskDependentOn,
moveTask,
performResearch,
readComplexityReport readComplexityReport
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
import chalk from 'chalk'; import chalk from 'chalk';
import boxen from 'boxen'; import boxen from 'boxen';
import readline from 'readline'; import readline from 'readline';
import fs from 'fs';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js'; import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
@@ -51,6 +52,9 @@ Do not include any explanatory text, markdown formatting, or code block markers
* @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 {string} [options.projectRoot] - Project root path (for MCP/env fallback).
* @param {string} [options.id] - Comma-separated list of task IDs to analyze specifically
* @param {number} [options.from] - Starting task ID in a range to analyze
* @param {number} [options.to] - Ending task ID in a range to analyze
* @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
@@ -65,6 +69,15 @@ async function analyzeTaskComplexity(options, context = {}) {
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 projectRoot = options.projectRoot;
// New parameters for task ID filtering
const specificIds = options.id
? options.id
.split(',')
.map((id) => parseInt(id.trim(), 10))
.filter((id) => !isNaN(id))
: null;
const fromId = options.from !== undefined ? parseInt(options.from, 10) : null;
const toId = options.to !== undefined ? parseInt(options.to, 10) : null;
const outputFormat = mcpLog ? 'json' : 'text'; const outputFormat = mcpLog ? 'json' : 'text';
@@ -88,13 +101,14 @@ async function analyzeTaskComplexity(options, context = {}) {
reportLog(`Reading tasks from ${tasksPath}...`, 'info'); reportLog(`Reading tasks from ${tasksPath}...`, 'info');
let tasksData; let tasksData;
let originalTaskCount = 0; let originalTaskCount = 0;
let originalData = null;
if (options._filteredTasksData) { if (options._filteredTasksData) {
tasksData = options._filteredTasksData; tasksData = options._filteredTasksData;
originalTaskCount = options._originalTaskCount || tasksData.tasks.length; originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
if (!options._originalTaskCount) { if (!options._originalTaskCount) {
try { try {
const originalData = readJSON(tasksPath); originalData = readJSON(tasksPath);
if (originalData && originalData.tasks) { if (originalData && originalData.tasks) {
originalTaskCount = originalData.tasks.length; originalTaskCount = originalData.tasks.length;
} }
@@ -103,22 +117,80 @@ async function analyzeTaskComplexity(options, context = {}) {
} }
} }
} else { } else {
tasksData = readJSON(tasksPath); originalData = readJSON(tasksPath);
if ( if (
!tasksData || !originalData ||
!tasksData.tasks || !originalData.tasks ||
!Array.isArray(tasksData.tasks) || !Array.isArray(originalData.tasks) ||
tasksData.tasks.length === 0 originalData.tasks.length === 0
) { ) {
throw new Error('No tasks found in the tasks file'); throw new Error('No tasks found in the tasks file');
} }
originalTaskCount = tasksData.tasks.length; originalTaskCount = originalData.tasks.length;
// Filter tasks based on active status
const activeStatuses = ['pending', 'blocked', 'in-progress']; const activeStatuses = ['pending', 'blocked', 'in-progress'];
const filteredTasks = tasksData.tasks.filter((task) => let filteredTasks = originalData.tasks.filter((task) =>
activeStatuses.includes(task.status?.toLowerCase() || 'pending') activeStatuses.includes(task.status?.toLowerCase() || 'pending')
); );
// Apply ID filtering if specified
if (specificIds && specificIds.length > 0) {
reportLog(
`Filtering tasks by specific IDs: ${specificIds.join(', ')}`,
'info'
);
filteredTasks = filteredTasks.filter((task) =>
specificIds.includes(task.id)
);
if (outputFormat === 'text') {
if (filteredTasks.length === 0 && specificIds.length > 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found with IDs: ${specificIds.join(', ')}`
)
);
} else if (filteredTasks.length < specificIds.length) {
const foundIds = filteredTasks.map((t) => t.id);
const missingIds = specificIds.filter(
(id) => !foundIds.includes(id)
);
console.log(
chalk.yellow(
`Warning: Some requested task IDs were not found or are not active: ${missingIds.join(', ')}`
)
);
}
}
}
// Apply range filtering if specified
else if (fromId !== null || toId !== null) {
const effectiveFromId = fromId !== null ? fromId : 1;
const effectiveToId =
toId !== null
? toId
: Math.max(...originalData.tasks.map((t) => t.id));
reportLog(
`Filtering tasks by ID range: ${effectiveFromId} to ${effectiveToId}`,
'info'
);
filteredTasks = filteredTasks.filter(
(task) => task.id >= effectiveFromId && task.id <= effectiveToId
);
if (outputFormat === 'text' && filteredTasks.length === 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found in range: ${effectiveFromId}-${effectiveToId}`
)
);
}
}
tasksData = { tasksData = {
...tasksData, ...originalData,
tasks: filteredTasks, tasks: filteredTasks,
_originalTaskCount: originalTaskCount _originalTaskCount: originalTaskCount
}; };
@@ -129,7 +201,18 @@ async function analyzeTaskComplexity(options, context = {}) {
`Found ${originalTaskCount} total tasks in the task file.`, `Found ${originalTaskCount} total tasks in the task file.`,
'info' 'info'
); );
if (skippedCount > 0) {
// Updated messaging to reflect filtering logic
if (specificIds || fromId !== null || toId !== null) {
const filterMsg = specificIds
? `Analyzing ${tasksData.tasks.length} tasks with specific IDs: ${specificIds.join(', ')}`
: `Analyzing ${tasksData.tasks.length} tasks in range: ${fromId || 1} to ${toId || 'end'}`;
reportLog(filterMsg, 'info');
if (outputFormat === 'text') {
console.log(chalk.blue(filterMsg));
}
} else if (skippedCount > 0) {
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`; const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
reportLog(skipMessage, 'info'); reportLog(skipMessage, 'info');
if (outputFormat === 'text') { if (outputFormat === 'text') {
@@ -137,7 +220,59 @@ async function analyzeTaskComplexity(options, context = {}) {
} }
} }
// Check for existing report before doing analysis
let existingReport = null;
let existingAnalysisMap = new Map(); // For quick lookups by task ID
try {
if (fs.existsSync(outputPath)) {
existingReport = readJSON(outputPath);
reportLog(`Found existing complexity report at ${outputPath}`, 'info');
if (
existingReport &&
existingReport.complexityAnalysis &&
Array.isArray(existingReport.complexityAnalysis)
) {
// Create lookup map of existing analysis entries
existingReport.complexityAnalysis.forEach((item) => {
existingAnalysisMap.set(item.taskId, item);
});
reportLog(
`Existing report contains ${existingReport.complexityAnalysis.length} task analyses`,
'info'
);
}
}
} catch (readError) {
reportLog(
`Warning: Could not read existing report: ${readError.message}`,
'warn'
);
existingReport = null;
existingAnalysisMap.clear();
}
if (tasksData.tasks.length === 0) { if (tasksData.tasks.length === 0) {
// If using ID filtering but no matching tasks, return existing report or empty
if (existingReport && (specificIds || fromId !== null || toId !== null)) {
reportLog(
`No matching tasks found for analysis. Keeping existing report.`,
'info'
);
if (outputFormat === 'text') {
console.log(
chalk.yellow(
`No matching tasks found for analysis. Keeping existing report.`
)
);
}
return {
report: existingReport,
telemetryData: null
};
}
// Otherwise create empty report
const emptyReport = { const emptyReport = {
meta: { meta: {
generatedAt: new Date().toISOString(), generatedAt: new Date().toISOString(),
@@ -146,9 +281,9 @@ async function analyzeTaskComplexity(options, context = {}) {
projectName: getProjectName(session), projectName: getProjectName(session),
usedResearch: useResearch usedResearch: useResearch
}, },
complexityAnalysis: [] complexityAnalysis: existingReport?.complexityAnalysis || []
}; };
reportLog(`Writing empty complexity report to ${outputPath}...`, 'info'); reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, emptyReport); writeJSON(outputPath, emptyReport);
reportLog( reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`, `Task complexity analysis complete. Report written to ${outputPath}`,
@@ -196,9 +331,13 @@ async function analyzeTaskComplexity(options, context = {}) {
) )
); );
} }
return emptyReport; return {
report: emptyReport,
telemetryData: null
};
} }
// Continue with regular analysis path
const prompt = generateInternalComplexityAnalysisPrompt(tasksData); const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
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.';
@@ -326,15 +465,47 @@ async function analyzeTaskComplexity(options, context = {}) {
} }
} }
// Merge with existing report
let finalComplexityAnalysis = [];
if (existingReport && Array.isArray(existingReport.complexityAnalysis)) {
// Create a map of task IDs that we just analyzed
const analyzedTaskIds = new Set(
complexityAnalysis.map((item) => item.taskId)
);
// Keep existing entries that weren't in this analysis run
const existingEntriesNotAnalyzed =
existingReport.complexityAnalysis.filter(
(item) => !analyzedTaskIds.has(item.taskId)
);
// Combine with new analysis
finalComplexityAnalysis = [
...existingEntriesNotAnalyzed,
...complexityAnalysis
];
reportLog(
`Merged ${complexityAnalysis.length} new analyses with ${existingEntriesNotAnalyzed.length} existing entries`,
'info'
);
} else {
// No existing report or invalid format, just use the new analysis
finalComplexityAnalysis = complexityAnalysis;
}
const report = { const report = {
meta: { meta: {
generatedAt: new Date().toISOString(), generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length, tasksAnalyzed: tasksData.tasks.length,
totalTasks: originalTaskCount,
analysisCount: finalComplexityAnalysis.length,
thresholdScore: thresholdScore, thresholdScore: thresholdScore,
projectName: getProjectName(session), projectName: getProjectName(session),
usedResearch: useResearch usedResearch: useResearch
}, },
complexityAnalysis: complexityAnalysis complexityAnalysis: finalComplexityAnalysis
}; };
reportLog(`Writing complexity report to ${outputPath}...`, 'info'); reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, report); writeJSON(outputPath, report);
@@ -350,6 +521,7 @@ async function analyzeTaskComplexity(options, context = {}) {
`Task complexity analysis complete. Report written to ${outputPath}` `Task complexity analysis complete. Report written to ${outputPath}`
) )
); );
// Calculate statistics specifically for this analysis run
const highComplexity = complexityAnalysis.filter( const highComplexity = complexityAnalysis.filter(
(t) => t.complexityScore >= 8 (t) => t.complexityScore >= 8
).length; ).length;
@@ -361,18 +533,25 @@ async function analyzeTaskComplexity(options, context = {}) {
).length; ).length;
const totalAnalyzed = complexityAnalysis.length; const totalAnalyzed = complexityAnalysis.length;
console.log('\nComplexity Analysis Summary:'); console.log('\nCurrent Analysis Summary:');
console.log('----------------------------'); console.log('----------------------------');
console.log( console.log(`Tasks analyzed in this run: ${totalAnalyzed}`);
`Active tasks sent for analysis: ${tasksData.tasks.length}`
);
console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
console.log(`High complexity tasks: ${highComplexity}`); console.log(`High complexity tasks: ${highComplexity}`);
console.log(`Medium complexity tasks: ${mediumComplexity}`); console.log(`Medium complexity tasks: ${mediumComplexity}`);
console.log(`Low complexity tasks: ${lowComplexity}`); console.log(`Low complexity tasks: ${lowComplexity}`);
if (existingReport) {
console.log('\nUpdated Report Summary:');
console.log('----------------------------');
console.log( console.log(
`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})` `Total analyses in report: ${finalComplexityAnalysis.length}`
); );
console.log(
`Analyses from previous runs: ${finalComplexityAnalysis.length - totalAnalyzed}`
);
console.log(`New/updated analyses: ${totalAnalyzed}`);
}
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`); console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
console.log( console.log(
`\nSee ${outputPath} for the full report and expansion commands.` `\nSee ${outputPath} for the full report and expansion commands.`

View File

@@ -308,7 +308,8 @@ function parseSubtasksFromText(
logger.error( logger.error(
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}` `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 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}` `Failed to parse JSON response object after both simple and advanced attempts: ${parseError.message}`
); );
} }

View File

@@ -35,6 +35,53 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
log('info', `Validating and fixing dependencies`); log('info', `Validating and fixing dependencies`);
validateAndFixDependencies(data, tasksPath); validateAndFixDependencies(data, tasksPath);
// Get valid task IDs from tasks.json
const validTaskIds = data.tasks.map((task) => task.id);
// Cleanup orphaned task files
log('info', 'Checking for orphaned task files to clean up...');
try {
// Get all task files in the output directory
const files = fs.readdirSync(outputDir);
const taskFilePattern = /^task_(\d+)\.txt$/;
// Filter for task files and check if they match a valid task ID
const orphanedFiles = files.filter((file) => {
const match = file.match(taskFilePattern);
if (match) {
const fileTaskId = parseInt(match[1], 10);
return !validTaskIds.includes(fileTaskId);
}
return false;
});
// Delete orphaned files
if (orphanedFiles.length > 0) {
log(
'info',
`Found ${orphanedFiles.length} orphaned task files to remove`
);
orphanedFiles.forEach((file) => {
const filePath = path.join(outputDir, file);
try {
fs.unlinkSync(filePath);
log('info', `Removed orphaned task file: ${file}`);
} catch (err) {
log(
'warn',
`Failed to remove orphaned task file ${file}: ${err.message}`
);
}
});
} else {
log('info', 'No orphaned task files found');
}
} catch (err) {
log('warn', `Error cleaning up orphaned task files: ${err.message}`);
// Continue with file generation even if cleanup fails
}
// Generate task files // Generate task files
log('info', 'Generating individual task files...'); log('info', 'Generating individual task files...');
data.tasks.forEach((task) => { data.tasks.forEach((task) => {

View File

@@ -6,6 +6,7 @@
import path from 'path'; import path from 'path';
import fs from 'fs'; import fs from 'fs';
import https from 'https'; import https from 'https';
import http from 'http';
import { import {
getMainModelId, getMainModelId,
getResearchModelId, getResearchModelId,
@@ -19,7 +20,8 @@ import {
getConfig, getConfig,
writeConfig, writeConfig,
isConfigFilePresent, isConfigFilePresent,
getAllProviders getAllProviders,
getBaseUrlForRole
} from '../config-manager.js'; } from '../config-manager.js';
/** /**
@@ -68,6 +70,68 @@ function fetchOpenRouterModels() {
}); });
} }
/**
* Fetches the list of models from Ollama instance.
* @param {string} baseURL - The base URL for the Ollama API (e.g., "http://localhost:11434/api")
* @returns {Promise<Array|null>} A promise that resolves with the list of model objects or null if fetch fails.
*/
function fetchOllamaModels(baseURL = 'http://localhost:11434/api') {
return new Promise((resolve) => {
try {
// Parse the base URL to extract hostname, port, and base path
const url = new URL(baseURL);
const isHttps = url.protocol === 'https:';
const port = url.port || (isHttps ? 443 : 80);
const basePath = url.pathname.endsWith('/')
? url.pathname.slice(0, -1)
: url.pathname;
const options = {
hostname: url.hostname,
port: parseInt(port, 10),
path: `${basePath}/tags`,
method: 'GET',
headers: {
Accept: 'application/json'
}
};
const requestLib = isHttps ? https : http;
const req = requestLib.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
try {
const parsedData = JSON.parse(data);
resolve(parsedData.models || []); // Return the array of models
} catch (e) {
console.error('Error parsing Ollama response:', e);
resolve(null); // Indicate failure
}
} else {
console.error(
`Ollama API request failed with status code: ${res.statusCode}`
);
resolve(null); // Indicate failure
}
});
});
req.on('error', (e) => {
console.error('Error fetching Ollama models:', e);
resolve(null); // Indicate failure
});
req.end();
} catch (e) {
console.error('Error parsing Ollama base URL:', e);
resolve(null); // Indicate failure
}
});
}
/** /**
* Get the current model configuration * Get the current model configuration
* @param {Object} [options] - Options for the operation * @param {Object} [options] - Options for the operation
@@ -416,10 +480,29 @@ async function setModel(role, modelId, options = {}) {
); );
} }
} else if (providerHint === 'ollama') { } else if (providerHint === 'ollama') {
// Hinted as Ollama - set provider directly WITHOUT checking OpenRouter // Check Ollama ONLY because hint was ollama
report('info', `Checking Ollama for ${modelId} (as hinted)...`);
// Get the Ollama base URL from config
const ollamaBaseURL = getBaseUrlForRole(role, projectRoot);
const ollamaModels = await fetchOllamaModels(ollamaBaseURL);
if (ollamaModels === null) {
// Connection failed - server probably not running
throw new Error(
`Unable to connect to Ollama server at ${ollamaBaseURL}. Please ensure Ollama is running and try again.`
);
} else if (ollamaModels.some((m) => m.model === modelId)) {
determinedProvider = 'ollama'; determinedProvider = 'ollama';
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`; warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
report('warn', warningMessage); report('warn', warningMessage);
} else {
// Server is running but model not found
const tagsUrl = `${ollamaBaseURL}/tags`;
throw new Error(
`Model ID "${modelId}" not found in the Ollama instance. Please verify the model is pulled and available. You can check available models with: curl ${tagsUrl}`
);
}
} else { } else {
// Invalid provider hint - should not happen // Invalid provider hint - should not happen
throw new Error(`Invalid provider hint received: ${providerHint}`); throw new Error(`Invalid provider hint received: ${providerHint}`);

View File

@@ -0,0 +1,657 @@
import path from "path";
import { log, readJSON, writeJSON } from "../utils.js";
import { isTaskDependentOn } from "../task-manager.js";
import generateTaskFiles from "./generate-task-files.js";
/**
* Move one or more tasks/subtasks to new positions
* @param {string} tasksPath - Path to tasks.json file
* @param {string} sourceId - ID(s) of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
* @param {string} destinationId - ID(s) of the destination (e.g., '7' or '7.3' or '7,8,9')
* @param {boolean} generateFiles - Whether to regenerate task files after moving
* @returns {Object} Result object with moved task details
*/
async function moveTask(
tasksPath,
sourceId,
destinationId,
generateFiles = true
) {
// Check if we have comma-separated IDs (multiple moves)
const sourceIds = sourceId.split(",").map((id) => id.trim());
const destinationIds = destinationId.split(",").map((id) => id.trim());
// If multiple IDs, validate they match in count
if (sourceIds.length > 1 || destinationIds.length > 1) {
if (sourceIds.length !== destinationIds.length) {
throw new Error(
`Number of source IDs (${sourceIds.length}) must match number of destination IDs (${destinationIds.length})`
);
}
// Perform multiple moves
return await moveMultipleTasks(
tasksPath,
sourceIds,
destinationIds,
generateFiles
);
}
// Single move - use existing logic
return await moveSingleTask(
tasksPath,
sourceId,
destinationId,
generateFiles
);
}
/**
* Move multiple tasks/subtasks to new positions
* @param {string} tasksPath - Path to tasks.json file
* @param {string[]} sourceIds - Array of source IDs
* @param {string[]} destinationIds - Array of destination IDs
* @param {boolean} generateFiles - Whether to regenerate task files after moving
* @returns {Object} Result object with moved task details
*/
async function moveMultipleTasks(
tasksPath,
sourceIds,
destinationIds,
generateFiles = true
) {
try {
log(
"info",
`Moving multiple tasks/subtasks: ${sourceIds.join(", ")} to ${destinationIds.join(", ")}...`
);
const results = [];
// Perform moves one by one, but don't regenerate files until the end
for (let i = 0; i < sourceIds.length; i++) {
const result = await moveSingleTask(
tasksPath,
sourceIds[i],
destinationIds[i],
false
);
results.push(result);
}
// Generate task files once at the end if requested
if (generateFiles) {
log("info", "Regenerating task files...");
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
}
return {
message: `Successfully moved ${sourceIds.length} tasks/subtasks`,
moves: results,
};
} catch (error) {
log("error", `Error moving multiple tasks/subtasks: ${error.message}`);
throw error;
}
}
/**
* Move a single task or subtask to a new position
* @param {string} tasksPath - Path to tasks.json file
* @param {string} sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
* @param {string} destinationId - ID of the destination (e.g., '7' or '7.3')
* @param {boolean} generateFiles - Whether to regenerate task files after moving
* @returns {Object} Result object with moved task details
*/
async function moveSingleTask(
tasksPath,
sourceId,
destinationId,
generateFiles = true
) {
try {
log("info", `Moving task/subtask ${sourceId} to ${destinationId}...`);
// Read the existing tasks
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
throw new Error(`Invalid or missing tasks file at ${tasksPath}`);
}
// Parse source ID to determine if it's a task or subtask
const isSourceSubtask = sourceId.includes(".");
let sourceTask,
sourceParentTask,
sourceSubtask,
sourceTaskIndex,
sourceSubtaskIndex;
// Parse destination ID to determine the target
const isDestinationSubtask = destinationId.includes(".");
let destTask, destParentTask, destSubtask, destTaskIndex, destSubtaskIndex;
// Validate source exists
if (isSourceSubtask) {
// Source is a subtask
const [parentIdStr, subtaskIdStr] = sourceId.split(".");
const parentIdNum = parseInt(parentIdStr, 10);
const subtaskIdNum = parseInt(subtaskIdStr, 10);
sourceParentTask = data.tasks.find((t) => t.id === parentIdNum);
if (!sourceParentTask) {
throw new Error(`Source parent task with ID ${parentIdNum} not found`);
}
if (
!sourceParentTask.subtasks ||
sourceParentTask.subtasks.length === 0
) {
throw new Error(`Source parent task ${parentIdNum} has no subtasks`);
}
sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
(st) => st.id === subtaskIdNum
);
if (sourceSubtaskIndex === -1) {
throw new Error(`Source subtask ${sourceId} not found`);
}
sourceSubtask = { ...sourceParentTask.subtasks[sourceSubtaskIndex] };
} else {
// Source is a task
const sourceIdNum = parseInt(sourceId, 10);
sourceTaskIndex = data.tasks.findIndex((t) => t.id === sourceIdNum);
if (sourceTaskIndex === -1) {
throw new Error(`Source task with ID ${sourceIdNum} not found`);
}
sourceTask = { ...data.tasks[sourceTaskIndex] };
}
// Validate destination exists
if (isDestinationSubtask) {
// Destination is a subtask (target will be the parent of this subtask)
const [parentIdStr, subtaskIdStr] = destinationId.split(".");
const parentIdNum = parseInt(parentIdStr, 10);
const subtaskIdNum = parseInt(subtaskIdStr, 10);
destParentTask = data.tasks.find((t) => t.id === parentIdNum);
if (!destParentTask) {
throw new Error(
`Destination parent task with ID ${parentIdNum} not found`
);
}
// Initialize subtasks array if it doesn't exist
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// If there are existing subtasks, try to find the specific destination subtask
if (destParentTask.subtasks.length > 0) {
destSubtaskIndex = destParentTask.subtasks.findIndex(
(st) => st.id === subtaskIdNum
);
if (destSubtaskIndex !== -1) {
destSubtask = destParentTask.subtasks[destSubtaskIndex];
} else {
// Subtask doesn't exist, we'll insert at the end
destSubtaskIndex = destParentTask.subtasks.length - 1;
}
} else {
// No existing subtasks, this will be the first one
destSubtaskIndex = -1; // Will insert at position 0
}
} else {
// Destination is a task
const destIdNum = parseInt(destinationId, 10);
destTaskIndex = data.tasks.findIndex((t) => t.id === destIdNum);
if (destTaskIndex === -1) {
// Create placeholder for destination if it doesn't exist
log("info", `Creating placeholder for destination task ${destIdNum}`);
const newTask = {
id: destIdNum,
title: `Task ${destIdNum}`,
description: "",
status: "pending",
priority: "medium",
details: "",
testStrategy: "",
};
// Find correct position to insert the new task
let insertIndex = 0;
while (
insertIndex < data.tasks.length &&
data.tasks[insertIndex].id < destIdNum
) {
insertIndex++;
}
// Insert the new task at the appropriate position
data.tasks.splice(insertIndex, 0, newTask);
destTaskIndex = insertIndex;
destTask = data.tasks[destTaskIndex];
} else {
destTask = data.tasks[destTaskIndex];
}
}
// Validate that we aren't trying to move a task to itself
if (sourceId === destinationId) {
throw new Error("Cannot move a task/subtask to itself");
}
// Prevent moving a parent to its own subtask
if (!isSourceSubtask && isDestinationSubtask) {
const destParentId = parseInt(destinationId.split(".")[0], 10);
if (parseInt(sourceId, 10) === destParentId) {
throw new Error("Cannot move a parent task to one of its own subtasks");
}
}
// Check for circular dependency when moving tasks
if (!isSourceSubtask && !isDestinationSubtask) {
const sourceIdNum = parseInt(sourceId, 10);
const destIdNum = parseInt(destinationId, 10);
// Check if destination is dependent on source
if (isTaskDependentOn(data.tasks, destTask, sourceIdNum)) {
throw new Error(
`Cannot move task ${sourceId} to task ${destinationId} as it would create a circular dependency`
);
}
}
let movedTask;
// Handle different move scenarios
if (!isSourceSubtask && !isDestinationSubtask) {
// Case: Moving task to task position
// Always treat this as a task replacement/move to new ID
// The destination task will be replaced by the source task
movedTask = moveTaskToNewId(
data,
sourceTask,
sourceTaskIndex,
destTask,
destTaskIndex
);
} else if (!isSourceSubtask && isDestinationSubtask) {
// Case 2: Move standalone task to become a subtask at a specific position
movedTask = moveTaskToSubtaskPosition(
data,
sourceTask,
sourceTaskIndex,
destParentTask,
destSubtaskIndex
);
} else if (isSourceSubtask && !isDestinationSubtask) {
// Case 3: Move subtask to become a standalone task
movedTask = moveSubtaskToTask(
data,
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destTask
);
} else if (isSourceSubtask && isDestinationSubtask) {
// Case 4: Move subtask to another parent or position
// First check if it's the same parent
const sourceParentId = parseInt(sourceId.split(".")[0], 10);
const destParentId = parseInt(destinationId.split(".")[0], 10);
if (sourceParentId === destParentId) {
// Case 4a: Move subtask within the same parent (reordering)
movedTask = reorderSubtask(
sourceParentTask,
sourceSubtaskIndex,
destSubtaskIndex
);
} else {
// Case 4b: Move subtask to a different parent
movedTask = moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskIndex
);
}
}
// Write the updated tasks back to the file
writeJSON(tasksPath, data);
// Generate task files if requested
if (generateFiles) {
log("info", "Regenerating task files...");
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
}
return movedTask;
} catch (error) {
log("error", `Error moving task/subtask: ${error.message}`);
throw error;
}
}
/**
* Move a standalone task to become a subtask of another task
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destTask - Destination task
* @returns {Object} Moved task object
*/
function moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask) {
// Initialize subtasks array if it doesn't exist
if (!destTask.subtasks) {
destTask.subtasks = [];
}
// Find the highest subtask ID to determine the next ID
const highestSubtaskId =
destTask.subtasks.length > 0
? Math.max(...destTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask from the source task
const newSubtask = {
...sourceTask,
id: newSubtaskId,
parentTaskId: destTask.id,
};
// Add to destination's subtasks
destTask.subtasks.push(newSubtask);
// Remove the original task from the tasks array
data.tasks.splice(sourceTaskIndex, 1);
log(
"info",
`Moved task ${sourceTask.id} to become subtask ${destTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a standalone task to become a subtask at a specific position
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destParentTask - Destination parent task
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
* @returns {Object} Moved task object
*/
function moveTaskToSubtaskPosition(
data,
sourceTask,
sourceTaskIndex,
destParentTask,
destSubtaskIndex
) {
// Initialize subtasks array if it doesn't exist
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// Find the highest subtask ID to determine the next ID
const highestSubtaskId =
destParentTask.subtasks.length > 0
? Math.max(...destParentTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask from the source task
const newSubtask = {
...sourceTask,
id: newSubtaskId,
parentTaskId: destParentTask.id,
};
// Insert at specific position
// If destSubtaskIndex is -1, insert at the beginning (position 0)
// Otherwise, insert after the specified subtask
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
// Remove the original task from the tasks array
data.tasks.splice(sourceTaskIndex, 1);
log(
"info",
`Moved task ${sourceTask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a subtask to become a standalone task
* @param {Object} data - Tasks data object
* @param {Object} sourceSubtask - Source subtask to move
* @param {Object} sourceParentTask - Parent task of the source subtask
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
* @param {Object} destTask - Destination task (will be replaced)
* @returns {Object} Moved task object
*/
function moveSubtaskToTask(
data,
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destTask
) {
// Use the destination task's ID instead of generating a new one
const newTaskId = destTask.id;
// Create the new task from the subtask, using the destination task's ID
const newTask = {
...sourceSubtask,
id: newTaskId,
priority: sourceParentTask.priority || "medium", // Inherit priority from parent
};
delete newTask.parentTaskId;
// Add the parent task as a dependency if not already present
if (!newTask.dependencies) {
newTask.dependencies = [];
}
if (!newTask.dependencies.includes(sourceParentTask.id)) {
newTask.dependencies.push(sourceParentTask.id);
}
// Find the destination index to replace the destination task
const destTaskIndex = data.tasks.findIndex((t) => t.id === destTask.id);
// Replace the destination task with the new task
data.tasks[destTaskIndex] = newTask;
// Remove the subtask from the parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// If parent has no more subtasks, remove the subtasks array
if (sourceParentTask.subtasks.length === 0) {
delete sourceParentTask.subtasks;
}
log(
"info",
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become task ${newTaskId}`
);
return newTask;
}
/**
* Reorder a subtask within the same parent
* @param {Object} parentTask - Parent task containing the subtask
* @param {number} sourceIndex - Current index of the subtask
* @param {number} destIndex - Destination index for the subtask
* @returns {Object} Moved subtask object
*/
function reorderSubtask(parentTask, sourceIndex, destIndex) {
// Get the subtask to move
const subtask = parentTask.subtasks[sourceIndex];
// Remove the subtask from its current position
parentTask.subtasks.splice(sourceIndex, 1);
// Insert the subtask at the new position
// If destIndex was after sourceIndex, it's now one less because we removed an item
const adjustedDestIndex = sourceIndex < destIndex ? destIndex - 1 : destIndex;
parentTask.subtasks.splice(adjustedDestIndex, 0, subtask);
log(
"info",
`Reordered subtask ${parentTask.id}.${subtask.id} within parent task ${parentTask.id}`
);
return subtask;
}
/**
* Move a subtask to a different parent
* @param {Object} sourceSubtask - Source subtask to move
* @param {Object} sourceParentTask - Parent task of the source subtask
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
* @param {Object} destParentTask - Destination parent task
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
* @returns {Object} Moved subtask object
*/
function moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskIndex
) {
// Find the highest subtask ID in the destination parent
const highestSubtaskId =
destParentTask.subtasks.length > 0
? Math.max(...destParentTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask with updated parent reference
const newSubtask = {
...sourceSubtask,
id: newSubtaskId,
parentTaskId: destParentTask.id,
};
// If the subtask depends on its original parent, keep that dependency
if (!newSubtask.dependencies) {
newSubtask.dependencies = [];
}
if (!newSubtask.dependencies.includes(sourceParentTask.id)) {
newSubtask.dependencies.push(sourceParentTask.id);
}
// Insert at the destination position
// If destSubtaskIndex is -1, insert at the beginning (position 0)
// Otherwise, insert after the specified subtask
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
// Remove the subtask from the original parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// If original parent has no more subtasks, remove the subtasks array
if (sourceParentTask.subtasks.length === 0) {
delete sourceParentTask.subtasks;
}
log(
"info",
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a standalone task to a new ID position
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destTask - Destination task (will be replaced)
* @param {number} destTaskIndex - Index of destination task in data.tasks
* @returns {Object} Moved task object
*/
function moveTaskToNewId(
data,
sourceTask,
sourceTaskIndex,
destTask,
destTaskIndex
) {
// Create a copy of the source task with the new ID
const movedTask = {
...sourceTask,
id: destTask.id,
};
// Get numeric IDs for comparison
const sourceIdNum = parseInt(sourceTask.id, 10);
const destIdNum = parseInt(destTask.id, 10);
// Handle subtasks if present
if (sourceTask.subtasks && sourceTask.subtasks.length > 0) {
// Update subtasks to reference the new parent ID if needed
movedTask.subtasks = sourceTask.subtasks.map((subtask) => ({
...subtask,
parentTaskId: destIdNum,
}));
}
// Update any dependencies in other tasks that referenced the old source ID
data.tasks.forEach((task) => {
if (task.dependencies && task.dependencies.includes(sourceIdNum)) {
// Replace the old source ID with the new destination ID
const depIndex = task.dependencies.indexOf(sourceIdNum);
task.dependencies[depIndex] = destIdNum;
}
// Also check for subtask dependencies that might reference the source task
if (task.subtasks && task.subtasks.length > 0) {
task.subtasks.forEach((subtask) => {
if (
subtask.dependencies &&
subtask.dependencies.includes(sourceIdNum)
) {
const depIndex = subtask.dependencies.indexOf(sourceIdNum);
subtask.dependencies[depIndex] = destIdNum;
}
});
}
});
// Remove tasks in the correct order to avoid index shifting issues
// Always remove the higher index first to avoid shifting the lower index
if (sourceTaskIndex > destTaskIndex) {
// Remove source first (higher index), then destination
data.tasks.splice(sourceTaskIndex, 1);
data.tasks.splice(destTaskIndex, 1);
// Insert the moved task at the destination position
data.tasks.splice(destTaskIndex, 0, movedTask);
} else {
// Remove destination first (higher index), then source
data.tasks.splice(destTaskIndex, 1);
data.tasks.splice(sourceTaskIndex, 1);
// Insert the moved task at the original destination position (now shifted down by 1)
data.tasks.splice(sourceTaskIndex, 0, movedTask);
}
log("info", `Moved task ${sourceIdNum} to replace task ${destIdNum}`);
return movedTask;
}
export default moveTask;

View File

@@ -50,6 +50,7 @@ const prdResponseSchema = z.object({
* @param {Object} options - Additional options * @param {Object} options - Additional options
* @param {boolean} [options.force=false] - Whether to overwrite existing tasks.json. * @param {boolean} [options.force=false] - Whether to overwrite existing tasks.json.
* @param {boolean} [options.append=false] - Append to existing tasks file. * @param {boolean} [options.append=false] - Append to existing tasks file.
* @param {boolean} [options.research=false] - Use research model for enhanced PRD analysis.
* @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused). * @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused).
* @param {Object} [options.mcpLog] - MCP logger object (optional). * @param {Object} [options.mcpLog] - MCP logger object (optional).
* @param {Object} [options.session] - Session object from MCP server (optional). * @param {Object} [options.session] - Session object from MCP server (optional).
@@ -63,7 +64,8 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
session, session,
projectRoot, projectRoot,
force = false, force = false,
append = false append = false,
research = false
} = options; } = options;
const isMCP = !!mcpLog; const isMCP = !!mcpLog;
const outputFormat = isMCP ? 'json' : 'text'; const outputFormat = isMCP ? 'json' : 'text';
@@ -90,7 +92,9 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
} }
}; };
report(`Parsing PRD file: ${prdPath}, Force: ${force}, Append: ${append}`); report(
`Parsing PRD file: ${prdPath}, Force: ${force}, Append: ${append}, Research: ${research}`
);
let existingTasks = []; let existingTasks = [];
let nextId = 1; let nextId = 1;
@@ -148,8 +152,22 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
throw new Error(`Input file ${prdPath} is empty or could not be read.`); throw new Error(`Input file ${prdPath} is empty or could not be read.`);
} }
// Build system prompt for PRD parsing // Research-specific enhancements to the system prompt
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format. const researchPromptAddition = research
? `\nBefore breaking down the PRD into tasks, you will:
1. Research and analyze the latest technologies, libraries, frameworks, and best practices that would be appropriate for this project
2. Identify any potential technical challenges, security concerns, or scalability issues not explicitly mentioned in the PRD without discarding any explicit requirements or going overboard with complexity -- always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
3. Consider current industry standards and evolving trends relevant to this project (this step aims to solve LLM hallucinations and out of date information due to training data cutoff dates)
4. Evaluate alternative implementation approaches and recommend the most efficient path
5. Include specific library versions, helpful APIs, and concrete implementation guidance based on your research
6. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
Your task breakdown should incorporate this research, resulting in more detailed implementation guidance, more accurate dependency mapping, and more precise technology recommendations than would be possible from the PRD text alone, while maintaining all explicit requirements and best practices and all details and nuances of the PRD.`
: '';
// Base system prompt for PRD parsing
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.${researchPromptAddition}
Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task. Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content. Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
@@ -176,13 +194,13 @@ Guidelines:
5. Include clear validation/testing approach for each task 5. Include clear validation/testing approach for each task
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable) 6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable)
7. Assign priority (high/medium/low) based on criticality and dependency order 7. Assign priority (high/medium/low) based on criticality and dependency order
8. Include detailed implementation guidance in the "details" field 8. Include detailed implementation guidance in the "details" field${research ? ', with specific libraries and version recommendations based on your research' : ''}
9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance 9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements 10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches`; 11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches${research ? '\n12. For each task, include specific, actionable guidance based on current industry standards and best practices discovered through research' : ''}`;
// Build user prompt with PRD content // Build user prompt with PRD content
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:\n\n${prdContent}\n\n const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:${research ? '\n\nRemember to thoroughly research current best practices and technologies before task breakdown to provide specific, actionable implementation details.' : ''}\n\n${prdContent}\n\n
Return your response in this format: Return your response in this format:
{ {
@@ -204,11 +222,14 @@ Guidelines:
}`; }`;
// Call the unified AI service // Call the unified AI service
report('Calling AI service to generate tasks from PRD...', 'info'); report(
`Calling AI service to generate tasks from PRD${research ? ' with research-backed analysis' : ''}...`,
'info'
);
// Call generateObjectService with the CORRECT schema and additional telemetry params // Call generateObjectService with the CORRECT schema and additional telemetry params
aiServiceResponse = await generateObjectService({ aiServiceResponse = await generateObjectService({
role: 'main', role: research ? 'research' : 'main', // Use research role if flag is set
session: session, session: session,
projectRoot: projectRoot, projectRoot: projectRoot,
schema: prdResponseSchema, schema: prdResponseSchema,
@@ -224,7 +245,9 @@ Guidelines:
if (!fs.existsSync(tasksDir)) { if (!fs.existsSync(tasksDir)) {
fs.mkdirSync(tasksDir, { recursive: true }); fs.mkdirSync(tasksDir, { recursive: true });
} }
logFn.success('Successfully parsed PRD via AI service.\n'); logFn.success(
`Successfully parsed PRD via AI service${research ? ' with research-backed analysis' : ''}.`
);
// Validate and Process Tasks // Validate and Process Tasks
// const generatedData = aiServiceResponse?.mainResult?.object; // const generatedData = aiServiceResponse?.mainResult?.object;
@@ -294,7 +317,7 @@ Guidelines:
// Write the final tasks to the file // Write the final tasks to the file
writeJSON(tasksPath, outputData); writeJSON(tasksPath, outputData);
report( report(
`Successfully ${append ? 'appended' : 'generated'} ${processedNewTasks.length} tasks in ${tasksPath}`, `Successfully ${append ? 'appended' : 'generated'} ${processedNewTasks.length} tasks in ${tasksPath}${research ? ' with research-backed analysis' : ''}`,
'success' 'success'
); );
@@ -306,7 +329,7 @@ Guidelines:
console.log( console.log(
boxen( boxen(
chalk.green( chalk.green(
`Successfully generated ${processedNewTasks.length} new tasks. Total tasks in ${tasksPath}: ${finalTasks.length}` `Successfully generated ${processedNewTasks.length} new tasks${research ? ' with research-backed analysis' : ''}. Total tasks in ${tasksPath}: ${finalTasks.length}`
), ),
{ padding: 1, borderColor: 'green', borderStyle: 'round' } { padding: 1, borderColor: 'green', borderStyle: 'round' }
) )

View File

@@ -0,0 +1,747 @@
/**
* research.js
* Core research functionality for AI-powered queries with project context
*/
import path from 'path';
import chalk from 'chalk';
import boxen from 'boxen';
import inquirer from 'inquirer';
import { highlight } from 'cli-highlight';
import { ContextGatherer } from '../utils/contextGatherer.js';
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
import { generateTextService } from '../ai-services-unified.js';
import { log as consoleLog, findProjectRoot, readJSON } from '../utils.js';
import {
displayAiUsageSummary,
startLoadingIndicator,
stopLoadingIndicator
} from '../ui.js';
/**
* Perform AI-powered research with project context
* @param {string} query - Research query/prompt
* @param {Object} options - Research options
* @param {Array<string>} [options.taskIds] - Task/subtask IDs for context
* @param {Array<string>} [options.filePaths] - File paths for context
* @param {string} [options.customContext] - Additional custom context
* @param {boolean} [options.includeProjectTree] - Include project file tree
* @param {string} [options.detailLevel] - Detail level: 'low', 'medium', 'high'
* @param {string} [options.projectRoot] - Project root directory
* @param {Object} [context] - Execution context
* @param {Object} [context.session] - MCP session object
* @param {Object} [context.mcpLog] - MCP logger object
* @param {string} [context.commandName] - Command name for telemetry
* @param {string} [context.outputType] - Output type ('cli' or 'mcp')
* @param {string} [outputFormat] - Output format ('text' or 'json')
* @param {boolean} [allowFollowUp] - Whether to allow follow-up questions (default: true)
* @returns {Promise<Object>} Research results with telemetry data
*/
async function performResearch(
query,
options = {},
context = {},
outputFormat = 'text',
allowFollowUp = true
) {
const {
taskIds = [],
filePaths = [],
customContext = '',
includeProjectTree = false,
detailLevel = 'medium',
projectRoot: providedProjectRoot
} = options;
const {
session,
mcpLog,
commandName = 'research',
outputType = 'cli'
} = context;
const isMCP = !!mcpLog;
// Determine project root
const projectRoot = providedProjectRoot || findProjectRoot();
if (!projectRoot) {
throw new Error('Could not determine project root directory');
}
// Create consistent logger
const logFn = isMCP
? mcpLog
: {
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)
};
// Show UI banner for CLI mode
if (outputFormat === 'text') {
console.log(
boxen(chalk.cyan.bold(`🔍 AI Research Query`), {
padding: 1,
borderColor: 'cyan',
borderStyle: 'round',
margin: { top: 1, bottom: 1 }
})
);
}
try {
// Initialize context gatherer
const contextGatherer = new ContextGatherer(projectRoot);
// Auto-discover relevant tasks using fuzzy search to supplement provided tasks
let finalTaskIds = [...taskIds]; // Start with explicitly provided tasks
let autoDiscoveredIds = [];
try {
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
const tasksData = await readJSON(tasksPath);
if (tasksData && tasksData.tasks && tasksData.tasks.length > 0) {
// Flatten tasks to include subtasks for fuzzy search
const flattenedTasks = flattenTasksWithSubtasks(tasksData.tasks);
const fuzzySearch = new FuzzyTaskSearch(flattenedTasks, 'research');
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
autoDiscoveredIds = fuzzySearch.getTaskIds(searchResults);
// Remove any auto-discovered tasks that were already explicitly provided
const uniqueAutoDiscovered = autoDiscoveredIds.filter(
(id) => !finalTaskIds.includes(id)
);
// Add unique auto-discovered tasks to the final list
finalTaskIds = [...finalTaskIds, ...uniqueAutoDiscovered];
if (outputFormat === 'text' && finalTaskIds.length > 0) {
// Sort task IDs numerically for better display
const sortedTaskIds = finalTaskIds
.map((id) => parseInt(id))
.sort((a, b) => a - b)
.map((id) => id.toString());
// Show different messages based on whether tasks were explicitly provided
if (taskIds.length > 0) {
const sortedProvidedIds = taskIds
.map((id) => parseInt(id))
.sort((a, b) => a - b)
.map((id) => id.toString());
console.log(
chalk.gray('Provided tasks: ') +
chalk.cyan(sortedProvidedIds.join(', '))
);
if (uniqueAutoDiscovered.length > 0) {
const sortedAutoIds = uniqueAutoDiscovered
.map((id) => parseInt(id))
.sort((a, b) => a - b)
.map((id) => id.toString());
console.log(
chalk.gray('+ Auto-discovered related tasks: ') +
chalk.cyan(sortedAutoIds.join(', '))
);
}
} else {
console.log(
chalk.gray('Auto-discovered relevant tasks: ') +
chalk.cyan(sortedTaskIds.join(', '))
);
}
}
}
} catch (error) {
// Silently continue without auto-discovered tasks if there's an error
logFn.debug(`Could not auto-discover tasks: ${error.message}`);
}
const contextResult = await contextGatherer.gather({
tasks: finalTaskIds,
files: filePaths,
customContext,
includeProjectTree,
format: 'research', // Use research format for AI consumption
includeTokenCounts: true
});
const gatheredContext = contextResult.context;
const tokenBreakdown = contextResult.tokenBreakdown;
// Build system prompt based on detail level
const systemPrompt = buildResearchSystemPrompt(detailLevel, projectRoot);
// Build user prompt with context
const userPrompt = buildResearchUserPrompt(
query,
gatheredContext,
detailLevel
);
// Count tokens for system and user prompts
const systemPromptTokens = contextGatherer.countTokens(systemPrompt);
const userPromptTokens = contextGatherer.countTokens(userPrompt);
const totalInputTokens = systemPromptTokens + userPromptTokens;
if (outputFormat === 'text') {
// Display detailed token breakdown in a clean box
displayDetailedTokenBreakdown(
tokenBreakdown,
systemPromptTokens,
userPromptTokens
);
}
// Only log detailed info in debug mode or MCP
if (outputFormat !== 'text') {
logFn.info(
`Calling AI service with research role, context size: ${tokenBreakdown.total} tokens (${gatheredContext.length} characters)`
);
}
// Start loading indicator for CLI mode
let loadingIndicator = null;
if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator('Researching with AI...\n');
}
let aiResult;
try {
// Call AI service with research role
aiResult = await generateTextService({
role: 'research', // Always use research role for research command
session,
projectRoot,
systemPrompt,
prompt: userPrompt,
commandName,
outputType
});
} catch (error) {
if (loadingIndicator) {
stopLoadingIndicator(loadingIndicator);
}
throw error;
} finally {
if (loadingIndicator) {
stopLoadingIndicator(loadingIndicator);
}
}
const researchResult = aiResult.mainResult;
const telemetryData = aiResult.telemetryData;
// Format and display results
if (outputFormat === 'text') {
displayResearchResults(
researchResult,
query,
detailLevel,
tokenBreakdown
);
// Display AI usage telemetry for CLI users
if (telemetryData) {
displayAiUsageSummary(telemetryData, 'cli');
}
// Offer follow-up question option (only for initial CLI queries, not MCP)
if (allowFollowUp && !isMCP) {
await handleFollowUpQuestions(
options,
context,
outputFormat,
projectRoot,
logFn,
query,
researchResult
);
}
}
logFn.success('Research query completed successfully');
return {
query,
result: researchResult,
contextSize: gatheredContext.length,
contextTokens: tokenBreakdown.total,
tokenBreakdown,
systemPromptTokens,
userPromptTokens,
totalInputTokens,
detailLevel,
telemetryData
};
} catch (error) {
logFn.error(`Research query failed: ${error.message}`);
if (outputFormat === 'text') {
console.error(chalk.red(`\n❌ Research failed: ${error.message}`));
}
throw error;
}
}
/**
* Build system prompt for research based on detail level
* @param {string} detailLevel - Detail level: 'low', 'medium', 'high'
* @param {string} projectRoot - Project root for context
* @returns {string} System prompt
*/
function buildResearchSystemPrompt(detailLevel, projectRoot) {
const basePrompt = `You are an expert AI research assistant helping with a software development project. You have access to project context including tasks, files, and project structure.
Your role is to provide comprehensive, accurate, and actionable research responses based on the user's query and the provided project context.`;
const detailInstructions = {
low: `
**Response Style: Concise & Direct**
- Provide brief, focused answers (2-4 paragraphs maximum)
- Focus on the most essential information
- Use bullet points for key takeaways
- Avoid lengthy explanations unless critical
- Skip pleasantries, introductions, and conclusions
- No phrases like "Based on your project context" or "I'll provide guidance"
- No summary outros or alignment statements
- Get straight to the actionable information
- Use simple, direct language - users want info, not explanation`,
medium: `
**Response Style: Balanced & Comprehensive**
- Provide thorough but well-structured responses (4-8 paragraphs)
- Include relevant examples and explanations
- Balance depth with readability
- Use headings and bullet points for organization`,
high: `
**Response Style: Detailed & Exhaustive**
- Provide comprehensive, in-depth analysis (8+ paragraphs)
- Include multiple perspectives and approaches
- Provide detailed examples, code snippets, and step-by-step guidance
- Cover edge cases and potential pitfalls
- Use clear structure with headings, subheadings, and lists`
};
return `${basePrompt}
${detailInstructions[detailLevel]}
**Guidelines:**
- Always consider the project context when formulating responses
- Reference specific tasks, files, or project elements when relevant
- Provide actionable insights that can be applied to the project
- If the query relates to existing project tasks, suggest how the research applies to those tasks
- Use markdown formatting for better readability
- Be precise and avoid speculation unless clearly marked as such
**For LOW detail level specifically:**
- Start immediately with the core information
- No introductory phrases or context acknowledgments
- No concluding summaries or project alignment statements
- Focus purely on facts, steps, and actionable items`;
}
/**
* Build user prompt with query and context
* @param {string} query - User's research query
* @param {string} gatheredContext - Gathered project context
* @param {string} detailLevel - Detail level for response guidance
* @returns {string} Complete user prompt
*/
function buildResearchUserPrompt(query, gatheredContext, detailLevel) {
let prompt = `# Research Query
${query}`;
if (gatheredContext && gatheredContext.trim()) {
prompt += `
# Project Context
${gatheredContext}`;
}
prompt += `
# Instructions
Please research and provide a ${detailLevel}-detail response to the query above. Consider the project context provided and make your response as relevant and actionable as possible for this specific project.`;
return prompt;
}
/**
* Display detailed token breakdown for context and prompts
* @param {Object} tokenBreakdown - Token breakdown from context gatherer
* @param {number} systemPromptTokens - System prompt token count
* @param {number} userPromptTokens - User prompt token count
*/
function displayDetailedTokenBreakdown(
tokenBreakdown,
systemPromptTokens,
userPromptTokens
) {
const parts = [];
// Custom context
if (tokenBreakdown.customContext) {
parts.push(
chalk.cyan('Custom: ') +
chalk.yellow(tokenBreakdown.customContext.tokens.toLocaleString())
);
}
// Tasks breakdown
if (tokenBreakdown.tasks && tokenBreakdown.tasks.length > 0) {
const totalTaskTokens = tokenBreakdown.tasks.reduce(
(sum, task) => sum + task.tokens,
0
);
const taskDetails = tokenBreakdown.tasks
.map((task) => {
const titleDisplay =
task.title.length > 30
? task.title.substring(0, 30) + '...'
: task.title;
return ` ${chalk.gray(task.id)} ${chalk.white(titleDisplay)} ${chalk.yellow(task.tokens.toLocaleString())} tokens`;
})
.join('\n');
parts.push(
chalk.cyan('Tasks: ') +
chalk.yellow(totalTaskTokens.toLocaleString()) +
chalk.gray(` (${tokenBreakdown.tasks.length} items)`) +
'\n' +
taskDetails
);
}
// Files breakdown
if (tokenBreakdown.files && tokenBreakdown.files.length > 0) {
const totalFileTokens = tokenBreakdown.files.reduce(
(sum, file) => sum + file.tokens,
0
);
const fileDetails = tokenBreakdown.files
.map((file) => {
const pathDisplay =
file.path.length > 40
? '...' + file.path.substring(file.path.length - 37)
: file.path;
return ` ${chalk.gray(pathDisplay)} ${chalk.yellow(file.tokens.toLocaleString())} tokens ${chalk.gray(`(${file.sizeKB}KB)`)}`;
})
.join('\n');
parts.push(
chalk.cyan('Files: ') +
chalk.yellow(totalFileTokens.toLocaleString()) +
chalk.gray(` (${tokenBreakdown.files.length} files)`) +
'\n' +
fileDetails
);
}
// Project tree
if (tokenBreakdown.projectTree) {
parts.push(
chalk.cyan('Project Tree: ') +
chalk.yellow(tokenBreakdown.projectTree.tokens.toLocaleString()) +
chalk.gray(
` (${tokenBreakdown.projectTree.fileCount} files, ${tokenBreakdown.projectTree.dirCount} dirs)`
)
);
}
// Prompts breakdown
const totalPromptTokens = systemPromptTokens + userPromptTokens;
const promptDetails = [
` ${chalk.gray('System:')} ${chalk.yellow(systemPromptTokens.toLocaleString())} tokens`,
` ${chalk.gray('User:')} ${chalk.yellow(userPromptTokens.toLocaleString())} tokens`
].join('\n');
parts.push(
chalk.cyan('Prompts: ') +
chalk.yellow(totalPromptTokens.toLocaleString()) +
chalk.gray(' (generated)') +
'\n' +
promptDetails
);
// Display the breakdown in a clean box
if (parts.length > 0) {
const content = parts.join('\n\n');
const tokenBox = boxen(content, {
title: chalk.blue.bold('Context Analysis'),
titleAlignment: 'left',
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'blue'
});
console.log(tokenBox);
}
}
/**
* Process research result text to highlight code blocks
* @param {string} text - Raw research result text
* @returns {string} Processed text with highlighted code blocks
*/
function processCodeBlocks(text) {
// Regex to match code blocks with optional language specification
const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
return text.replace(codeBlockRegex, (match, language, code) => {
try {
// Default to javascript if no language specified
const lang = language || 'javascript';
// Highlight the code using cli-highlight
const highlightedCode = highlight(code.trim(), {
language: lang,
ignoreIllegals: true // Don't fail on unrecognized syntax
});
// Add a subtle border around code blocks
const codeBox = boxen(highlightedCode, {
padding: { top: 0, bottom: 0, left: 1, right: 1 },
margin: { top: 0, bottom: 0 },
borderStyle: 'single',
borderColor: 'dim'
});
return '\n' + codeBox + '\n';
} catch (error) {
// If highlighting fails, return the original code block with basic formatting
return (
'\n' +
chalk.gray('```' + (language || '')) +
'\n' +
chalk.white(code.trim()) +
'\n' +
chalk.gray('```') +
'\n'
);
}
});
}
/**
* Display research results in formatted output
* @param {string} result - AI research result
* @param {string} query - Original query
* @param {string} detailLevel - Detail level used
* @param {Object} tokenBreakdown - Detailed token usage
*/
function displayResearchResults(result, query, detailLevel, tokenBreakdown) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') +
'\n\n' +
chalk.gray('Query: ') +
chalk.white(query) +
'\n' +
chalk.gray('Detail Level: ') +
chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process the result to highlight code blocks
const processedResult = processCodeBlocks(result);
// Main research content in a clean box
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
// Success footer
console.log(chalk.green('✅ Research completed'));
}
/**
* Flatten tasks array to include subtasks as individual searchable items
* @param {Array} tasks - Array of task objects
* @returns {Array} Flattened array including both tasks and subtasks
*/
function flattenTasksWithSubtasks(tasks) {
const flattened = [];
for (const task of tasks) {
// Add the main task
flattened.push({
...task,
searchableId: task.id.toString(), // For consistent ID handling
isSubtask: false
});
// Add subtasks if they exist
if (task.subtasks && task.subtasks.length > 0) {
for (const subtask of task.subtasks) {
flattened.push({
...subtask,
searchableId: `${task.id}.${subtask.id}`, // Format: "15.2"
isSubtask: true,
parentId: task.id,
parentTitle: task.title,
// Enhance subtask context with parent information
title: `${subtask.title} (subtask of: ${task.title})`,
description: `${subtask.description} [Parent: ${task.description}]`
});
}
}
}
return flattened;
}
/**
* Handle follow-up questions in interactive mode
* @param {Object} originalOptions - Original research options
* @param {Object} context - Execution context
* @param {string} outputFormat - Output format
* @param {string} projectRoot - Project root directory
* @param {Object} logFn - Logger function
* @param {string} initialQuery - Initial query for context
* @param {string} initialResult - Initial AI result for context
*/
async function handleFollowUpQuestions(
originalOptions,
context,
outputFormat,
projectRoot,
logFn,
initialQuery,
initialResult
) {
try {
// Initialize conversation history with the initial Q&A
const conversationHistory = [
{
question: initialQuery,
answer: initialResult,
type: 'initial'
}
];
while (true) {
// Ask if user wants to ask a follow-up question
const { wantFollowUp } = await inquirer.prompt([
{
type: 'confirm',
name: 'wantFollowUp',
message: 'Would you like to ask a follow-up question?',
default: false // Default to 'n' as requested
}
]);
if (!wantFollowUp) {
break;
}
// Get the follow-up question
const { followUpQuery } = await inquirer.prompt([
{
type: 'input',
name: 'followUpQuery',
message: 'Enter your follow-up question:',
validate: (input) => {
if (!input || input.trim().length === 0) {
return 'Please enter a valid question.';
}
return true;
}
}
]);
if (!followUpQuery || followUpQuery.trim().length === 0) {
continue;
}
console.log('\n' + chalk.gray('─'.repeat(60)) + '\n');
// Build cumulative conversation context from all previous exchanges
const conversationContext = buildConversationContext(conversationHistory);
// Create enhanced options for follow-up with full conversation context
// Remove explicit task IDs to allow fresh fuzzy search based on new question
const followUpOptions = {
...originalOptions,
taskIds: [], // Clear task IDs to allow fresh fuzzy search
customContext:
conversationContext +
(originalOptions.customContext
? `\n\n--- Original Context ---\n${originalOptions.customContext}`
: '')
};
// Perform follow-up research with fresh fuzzy search and conversation context
// Disable follow-up prompts for nested calls to prevent infinite recursion
const followUpResult = await performResearch(
followUpQuery.trim(),
followUpOptions,
context,
outputFormat,
false // allowFollowUp = false for nested calls
);
// Add this exchange to the conversation history
conversationHistory.push({
question: followUpQuery.trim(),
answer: followUpResult.result,
type: 'followup'
});
}
} catch (error) {
// If there's an error with inquirer (e.g., non-interactive terminal),
// silently continue without follow-up functionality
logFn.debug(`Follow-up questions not available: ${error.message}`);
}
}
/**
* Build conversation context string from conversation history
* @param {Array} conversationHistory - Array of conversation exchanges
* @returns {string} Formatted conversation context
*/
function buildConversationContext(conversationHistory) {
if (conversationHistory.length === 0) {
return '';
}
const contextParts = ['--- Conversation History ---'];
conversationHistory.forEach((exchange, index) => {
const questionLabel =
exchange.type === 'initial' ? 'Initial Question' : `Follow-up ${index}`;
const answerLabel =
exchange.type === 'initial' ? 'Initial Answer' : `Answer ${index}`;
contextParts.push(`\n${questionLabel}: ${exchange.question}`);
contextParts.push(`${answerLabel}: ${exchange.answer}`);
});
return contextParts.join('\n');
}
export { performResearch };

View File

@@ -0,0 +1,384 @@
import fs from "fs";
import path from "path";
import { submitTelemetryData } from "./telemetry-submission.js";
import { getDebugFlag } from "./config-manager.js";
import { log } from "./utils.js";
class TelemetryQueue {
constructor() {
this.queue = [];
this.processing = false;
this.backgroundInterval = null;
this.stats = {
pending: 0,
processed: 0,
failed: 0,
lastProcessedAt: null,
};
this.logFile = null;
}
/**
* Initialize the queue with comprehensive logging file path
* @param {string} projectRoot - Project root directory for log file
*/
initialize(projectRoot) {
if (projectRoot) {
this.logFile = path.join(projectRoot, ".taskmaster-activity.log");
this.loadPersistedQueue();
}
}
/**
* Add telemetry data to queue without blocking
* @param {Object} telemetryData - Command telemetry data
*/
addToQueue(telemetryData) {
const queueItem = {
...telemetryData,
queuedAt: new Date().toISOString(),
attempts: 0,
};
this.queue.push(queueItem);
this.stats.pending = this.queue.length;
// Log the activity immediately to .log file
this.logActivity("QUEUED", {
commandName: telemetryData.commandName,
queuedAt: queueItem.queuedAt,
userId: telemetryData.userId,
success: telemetryData.success,
executionTimeMs: telemetryData.executionTimeMs,
});
if (getDebugFlag()) {
log("debug", `Added ${telemetryData.commandName} to telemetry queue`);
}
// Persist queue state if file is configured
this.persistQueue();
}
/**
* Log activity to comprehensive .log file
* @param {string} action - The action being logged (QUEUED, SUBMITTED, FAILED, etc.)
* @param {Object} data - The data to log
*/
logActivity(action, data) {
if (!this.logFile) return;
try {
const timestamp = new Date().toISOString();
const logEntry = `${timestamp} [${action}] ${JSON.stringify(data)}\n`;
fs.appendFileSync(this.logFile, logEntry);
} catch (error) {
if (getDebugFlag()) {
log("error", `Failed to write to activity log: ${error.message}`);
}
}
}
/**
* Process all queued telemetry items
* @returns {Object} Processing result with stats
*/
async processQueue() {
if (this.processing || this.queue.length === 0) {
return { processed: 0, failed: 0, errors: [] };
}
this.processing = true;
const errors = [];
let processed = 0;
let failed = 0;
this.logActivity("PROCESSING_START", { queueSize: this.queue.length });
// Process items in batches to avoid overwhelming the gateway
const batchSize = 5;
const itemsToProcess = [...this.queue];
for (let i = 0; i < itemsToProcess.length; i += batchSize) {
const batch = itemsToProcess.slice(i, i + batchSize);
for (const item of batch) {
try {
item.attempts++;
const result = await submitTelemetryData(item);
if (result.success) {
// Remove from queue on success
const index = this.queue.findIndex(
(q) => q.queuedAt === item.queuedAt
);
if (index > -1) {
this.queue.splice(index, 1);
}
processed++;
// Log successful submission
this.logActivity("SUBMITTED", {
commandName: item.commandName,
queuedAt: item.queuedAt,
attempts: item.attempts,
});
} else {
// Retry failed items up to 3 times
if (item.attempts >= 3) {
const index = this.queue.findIndex(
(q) => q.queuedAt === item.queuedAt
);
if (index > -1) {
this.queue.splice(index, 1);
}
failed++;
const errorMsg = `Failed to submit ${item.commandName} after 3 attempts: ${result.error}`;
errors.push(errorMsg);
// Log final failure
this.logActivity("FAILED", {
commandName: item.commandName,
queuedAt: item.queuedAt,
attempts: item.attempts,
error: result.error,
});
} else {
// Log retry attempt
this.logActivity("RETRY", {
commandName: item.commandName,
queuedAt: item.queuedAt,
attempts: item.attempts,
error: result.error,
});
}
}
} catch (error) {
// Network or unexpected errors
if (item.attempts >= 3) {
const index = this.queue.findIndex(
(q) => q.queuedAt === item.queuedAt
);
if (index > -1) {
this.queue.splice(index, 1);
}
failed++;
const errorMsg = `Exception submitting ${item.commandName}: ${error.message}`;
errors.push(errorMsg);
// Log exception failure
this.logActivity("EXCEPTION", {
commandName: item.commandName,
queuedAt: item.queuedAt,
attempts: item.attempts,
error: error.message,
});
} else {
// Log retry for exception
this.logActivity("RETRY_EXCEPTION", {
commandName: item.commandName,
queuedAt: item.queuedAt,
attempts: item.attempts,
error: error.message,
});
}
}
}
// Small delay between batches
if (i + batchSize < itemsToProcess.length) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
this.stats.pending = this.queue.length;
this.stats.processed += processed;
this.stats.failed += failed;
this.stats.lastProcessedAt = new Date().toISOString();
this.processing = false;
this.persistQueue();
// Log processing completion
this.logActivity("PROCESSING_COMPLETE", {
processed,
failed,
remainingInQueue: this.queue.length,
});
if (getDebugFlag() && (processed > 0 || failed > 0)) {
log(
"debug",
`Telemetry queue processed: ${processed} success, ${failed} failed`
);
}
return { processed, failed, errors };
}
/**
* Start background processing at specified interval
* @param {number} intervalMs - Processing interval in milliseconds (default: 30000)
*/
startBackgroundProcessor(intervalMs = 30000) {
if (this.backgroundInterval) {
clearInterval(this.backgroundInterval);
}
this.backgroundInterval = setInterval(async () => {
try {
await this.processQueue();
} catch (error) {
if (getDebugFlag()) {
log(
"error",
`Background telemetry processing error: ${error.message}`
);
}
}
}, intervalMs);
if (getDebugFlag()) {
log(
"debug",
`Started telemetry background processor (${intervalMs}ms interval)`
);
}
}
/**
* Stop background processing
*/
stopBackgroundProcessor() {
if (this.backgroundInterval) {
clearInterval(this.backgroundInterval);
this.backgroundInterval = null;
if (getDebugFlag()) {
log("debug", "Stopped telemetry background processor");
}
}
}
/**
* Get queue statistics
* @returns {Object} Queue stats
*/
getQueueStats() {
return {
...this.stats,
pending: this.queue.length,
};
}
/**
* Load persisted queue from file (now reads from .log file)
*/
loadPersistedQueue() {
// For the .log file, we'll look for a companion .json file for queue state
if (!this.logFile) return;
const stateFile = this.logFile.replace(".log", "-queue-state.json");
if (!fs.existsSync(stateFile)) {
return;
}
try {
const data = fs.readFileSync(stateFile, "utf8");
const persistedData = JSON.parse(data);
this.queue = persistedData.queue || [];
this.stats = { ...this.stats, ...persistedData.stats };
if (getDebugFlag()) {
log(
"debug",
`Loaded ${this.queue.length} items from telemetry queue state`
);
}
} catch (error) {
if (getDebugFlag()) {
log(
"error",
`Failed to load persisted telemetry queue: ${error.message}`
);
}
}
}
/**
* Persist queue state to companion file
*/
persistQueue() {
if (!this.logFile) return;
const stateFile = this.logFile.replace(".log", "-queue-state.json");
try {
const data = {
queue: this.queue,
stats: this.stats,
lastUpdated: new Date().toISOString(),
};
fs.writeFileSync(stateFile, JSON.stringify(data, null, 2));
} catch (error) {
if (getDebugFlag()) {
log("error", `Failed to persist telemetry queue: ${error.message}`);
}
}
}
}
// Global instance
const telemetryQueue = new TelemetryQueue();
/**
* Add command telemetry to queue (non-blocking)
* @param {Object} commandData - Command execution data
*/
export function queueCommandTelemetry(commandData) {
telemetryQueue.addToQueue(commandData);
}
/**
* Initialize telemetry queue with project root
* @param {string} projectRoot - Project root directory
*/
export function initializeTelemetryQueue(projectRoot) {
telemetryQueue.initialize(projectRoot);
}
/**
* Start background telemetry processing
* @param {number} intervalMs - Processing interval in milliseconds
*/
export function startTelemetryBackgroundProcessor(intervalMs = 30000) {
telemetryQueue.startBackgroundProcessor(intervalMs);
}
/**
* Stop background telemetry processing
*/
export function stopTelemetryBackgroundProcessor() {
telemetryQueue.stopBackgroundProcessor();
}
/**
* Get telemetry queue statistics
* @returns {Object} Queue statistics
*/
export function getTelemetryQueueStats() {
return telemetryQueue.getQueueStats();
}
/**
* Manually process telemetry queue
* @returns {Object} Processing result
*/
export function processTelemetryQueue() {
return telemetryQueue.processQueue();
}
export { telemetryQueue };

View File

@@ -0,0 +1,238 @@
/**
* Telemetry Submission Service
* Handles sending telemetry data to remote gateway endpoint
*/
import { z } from "zod";
import { getConfig } from "./config-manager.js";
import { getTelemetryEnabled } from "./config-manager.js";
import { resolveEnvVariable } from "./utils.js";
// Telemetry data validation schema
const TelemetryDataSchema = z.object({
timestamp: z.string().datetime(),
userId: z.string().min(1),
commandName: z.string().min(1),
modelUsed: z.string().optional(),
providerName: z.string().optional(),
inputTokens: z.number().optional(),
outputTokens: z.number().optional(),
totalTokens: z.number().optional(),
totalCost: z.number().optional(),
currency: z.string().optional(),
commandArgs: z.any().optional(),
fullOutput: z.any().optional(),
});
// Hardcoded configuration for TaskMaster telemetry gateway
const TASKMASTER_BASE_URL = "http://localhost:4444";
const TASKMASTER_TELEMETRY_ENDPOINT = `${TASKMASTER_BASE_URL}/api/v1/telemetry`;
const TASKMASTER_USER_REGISTRATION_ENDPOINT = `${TASKMASTER_BASE_URL}/auth/init`;
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1 second
/**
* Get telemetry configuration from hardcoded service ID, user token, and config
* @returns {Object} Configuration object with serviceId, apiKey, userId, and email
*/
function getTelemetryConfig() {
// Get the config which contains userId and email
const config = getConfig();
// Hardcoded service ID for TaskMaster telemetry service
const hardcodedServiceId = "98fb3198-2dfc-42d1-af53-07b99e4f3bde";
// Get user's API token from .env (managed by user-management.js)
const userApiKey = resolveEnvVariable("TASKMASTER_API_KEY");
return {
serviceId: hardcodedServiceId, // Hardcoded service identifier
apiKey: userApiKey || null, // User's Bearer token from .env
userId: config?.account?.userId || null, // From config
email: config?.account?.email || null, // From config
};
}
/**
* Register or lookup user with the TaskMaster telemetry gateway using /auth/init
* @param {string} email - User's email address
* @param {string} userId - User's ID
* @returns {Promise<{success: boolean, apiKey?: string, userId?: string, email?: string, isNewUser?: boolean, error?: string}>}
*/
export async function registerUserWithGateway(email = null, userId = null) {
try {
const requestBody = {};
if (email) requestBody.email = email;
if (userId) requestBody.userId = userId;
const response = await fetch(TASKMASTER_USER_REGISTRATION_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
return {
success: false,
error: `Gateway registration failed: ${response.status} ${response.statusText}`,
};
}
const result = await response.json();
// Handle the /auth/init response format
if (result.success && result.data) {
return {
success: true,
apiKey: result.data.token,
userId: result.data.userId,
email: email,
isNewUser: result.data.isNewUser,
};
} else {
return {
success: false,
error: result.error || result.message || "Unknown registration error",
};
}
} catch (error) {
return {
success: false,
error: `Gateway registration error: ${error.message}`,
};
}
}
/**
* Submits telemetry data to the remote gateway endpoint
* @param {Object} telemetryData - The telemetry data to submit
* @returns {Promise<Object>} - Result object with success status and details
*/
export async function submitTelemetryData(telemetryData) {
try {
// Check user opt-out preferences first, but hosted mode always sends telemetry
const config = getConfig();
const isHostedMode = config?.account?.mode === "hosted";
if (!isHostedMode && !getTelemetryEnabled()) {
return {
success: true,
skipped: true,
reason: "Telemetry disabled by user preference",
};
}
// Get telemetry configuration
const telemetryConfig = getTelemetryConfig();
if (
!telemetryConfig.apiKey ||
!telemetryConfig.userId ||
!telemetryConfig.email
) {
return {
success: false,
error:
"Telemetry configuration incomplete. Please ensure you have completed 'task-master init' to set up your user account.",
};
}
// Validate telemetry data
try {
TelemetryDataSchema.parse(telemetryData);
} catch (validationError) {
return {
success: false,
error: `Telemetry data validation failed: ${validationError.message}`,
};
}
// Send FULL telemetry data to gateway (including commandArgs and fullOutput)
// Note: Sensitive data filtering is handled separately for user-facing responses
const completeTelemetryData = {
...telemetryData,
userId: telemetryConfig.userId, // Ensure correct userId
};
// Attempt submission with retry logic
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
const response = await fetch(TASKMASTER_TELEMETRY_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-taskmaster-service-id": telemetryConfig.serviceId, // Hardcoded service ID
Authorization: `Bearer ${telemetryConfig.apiKey}`, // User's Bearer token
"X-User-Email": telemetryConfig.email, // User's email from config
},
body: JSON.stringify(completeTelemetryData),
});
if (response.ok) {
const result = await response.json();
return {
success: true,
id: result.id,
attempt,
};
} else {
// Handle HTTP error responses
const errorData = await response.json().catch(() => ({}));
const errorMessage = `HTTP ${response.status} ${response.statusText}`;
// Don't retry on certain status codes (rate limiting, auth errors, etc.)
if (
response.status === 429 ||
response.status === 401 ||
response.status === 403
) {
return {
success: false,
error: errorMessage,
statusCode: response.status,
};
}
// For other HTTP errors, continue retrying
lastError = new Error(errorMessage);
}
} catch (networkError) {
lastError = networkError;
}
// Wait before retry (exponential backoff)
if (attempt < MAX_RETRIES) {
await new Promise((resolve) =>
setTimeout(resolve, RETRY_DELAY * Math.pow(2, attempt - 1))
);
}
}
// All retries failed
return {
success: false,
error: lastError.message,
attempts: MAX_RETRIES,
};
} catch (error) {
// Graceful error handling - never throw
return {
success: false,
error: `Telemetry submission failed: ${error.message}`,
};
}
}
/**
* Submits telemetry data asynchronously without blocking execution
* @param {Object} telemetryData - The telemetry data to submit
*/
export function submitTelemetryDataAsync(telemetryData) {
// Fire and forget - don't block execution
submitTelemetryData(telemetryData).catch((error) => {
// Silently log errors without blocking
console.debug("Telemetry submission failed:", error);
});
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,516 @@
import fs from "fs";
import path from "path";
import { log, findProjectRoot } from "./utils.js";
import { getConfig, writeConfig, getUserId } from "./config-manager.js";
/**
* Registers or finds a user via the gateway's /auth/init endpoint
* @param {string|null} email - Optional user's email address (only needed for billing)
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {Promise<{success: boolean, userId: string, token: string, isNewUser: boolean, error?: string}>}
*/
async function registerUserWithGateway(email = null, explicitRoot = null) {
try {
const gatewayUrl =
process.env.TASKMASTER_GATEWAY_URL || "http://localhost:4444";
// Check for existing userId and email to pass to gateway
const existingUserId = getUserId(explicitRoot);
const existingEmail = email || getUserEmail(explicitRoot);
// Build request body with existing values (gateway can handle userId for existing users)
const requestBody = {};
if (existingUserId && existingUserId !== "1234567890") {
requestBody.userId = existingUserId;
}
if (existingEmail) {
requestBody.email = existingEmail;
}
const response = await fetch(`${gatewayUrl}/auth/init`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
return {
success: false,
userId: "",
token: "",
isNewUser: false,
error: `Gateway registration failed: ${response.status} ${errorText}`,
};
}
const result = await response.json();
if (result.success && result.data) {
return {
success: true,
userId: result.data.userId,
token: result.data.token,
isNewUser: result.data.isNewUser,
};
} else {
return {
success: false,
userId: "",
token: "",
isNewUser: false,
error: "Invalid response format from gateway",
};
}
} catch (error) {
return {
success: false,
userId: "",
token: "",
isNewUser: false,
error: `Network error: ${error.message}`,
};
}
}
/**
* Updates the user configuration with gateway registration results
* @param {string} userId - User ID from gateway
* @param {string} token - User authentication token from gateway (stored in .env)
* @param {string} mode - User mode ('byok' or 'hosted')
* @param {string|null} email - Optional user email to save
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {boolean} Success status
*/
function updateUserConfig(
userId,
token,
mode,
email = null,
explicitRoot = null
) {
try {
const config = getConfig(explicitRoot);
// Ensure account section exists
if (!config.account) {
config.account = {};
}
// Ensure global section exists for email
if (!config.global) {
config.global = {};
}
// Update user configuration in account section
config.account.userId = userId;
config.account.mode = mode; // 'byok' or 'hosted'
// Save email if provided
if (email) {
config.account.email = email;
}
// Write user authentication token to .env file (not config)
if (token) {
writeApiKeyToEnv(token, explicitRoot);
}
// Save updated config
const success = writeConfig(config, explicitRoot);
if (success) {
const emailInfo = email ? `, email=${email}` : "";
log(
"info",
`User configuration updated: userId=${userId}, mode=${mode}${emailInfo}`
);
} else {
log("error", "Failed to write updated user configuration");
}
return success;
} catch (error) {
log("error", `Error updating user config: ${error.message}`);
return false;
}
}
/**
* Writes the user authentication token to the .env file
* This token is used as Bearer auth for gateway API calls
* @param {string} token - Authentication token to write
* @param {string|null} explicitRoot - Optional explicit project root path
*/
function writeApiKeyToEnv(token, explicitRoot = null) {
try {
// Determine project root
let rootPath = explicitRoot;
if (!rootPath) {
rootPath = findProjectRoot();
if (!rootPath) {
log("warn", "Could not determine project root for .env file");
return;
}
}
const envPath = path.join(rootPath, ".env");
let envContent = "";
// Read existing .env content if file exists
if (fs.existsSync(envPath)) {
envContent = fs.readFileSync(envPath, "utf8");
}
// Check if TASKMASTER_API_KEY already exists
const lines = envContent.split("\n");
let keyExists = false;
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("TASKMASTER_API_KEY=")) {
lines[i] = `TASKMASTER_API_KEY=${token}`;
keyExists = true;
break;
}
}
// Add key if it doesn't exist
if (!keyExists) {
if (envContent && !envContent.endsWith("\n")) {
envContent += "\n";
}
envContent += `TASKMASTER_API_KEY=${token}\n`;
} else {
envContent = lines.join("\n");
}
// Write updated content
fs.writeFileSync(envPath, envContent);
} catch (error) {
log("error", `Failed to write user token to .env: ${error.message}`);
}
}
/**
* Gets the current user mode from configuration
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {string} User mode ('byok', 'hosted', or 'unknown')
*/
function getUserMode(explicitRoot = null) {
try {
const config = getConfig(explicitRoot);
return config?.account?.mode || "unknown";
} catch (error) {
log("error", `Error getting user mode: ${error.message}`);
return "unknown";
}
}
/**
* Checks if user is in hosted mode
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {boolean} True if user is in hosted mode
*/
function isHostedMode(explicitRoot = null) {
return getUserMode(explicitRoot) === "hosted";
}
/**
* Checks if user is in BYOK mode
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {boolean} True if user is in BYOK mode
*/
function isByokMode(explicitRoot = null) {
return getUserMode(explicitRoot) === "byok";
}
/**
* Complete user setup: register with gateway and configure TaskMaster
* @param {string|null} email - Optional user's email (only needed for billing)
* @param {string} mode - User's mode: 'byok' or 'hosted'
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {Promise<{success: boolean, userId: string, mode: string, error?: string}>}
*/
async function setupUser(email = null, mode = "hosted", explicitRoot = null) {
try {
// Step 1: Register with gateway (email optional)
const registrationResult = await registerUserWithGateway(
email,
explicitRoot
);
if (!registrationResult.success) {
return {
success: false,
userId: "",
mode: "",
error: registrationResult.error,
};
}
// Step 2: Update config with userId, mode, and email
const configResult = updateUserConfig(
registrationResult.userId,
registrationResult.token,
mode,
email,
explicitRoot
);
if (!configResult) {
return {
success: false,
userId: registrationResult.userId,
mode: "",
error: "Failed to update user configuration",
};
}
return {
success: true,
userId: registrationResult.userId,
mode: mode,
message: email
? `User setup complete with email ${email}`
: "User setup complete (email will be collected during billing setup)",
};
} catch (error) {
return {
success: false,
userId: "",
mode: "",
error: `Setup failed: ${error.message}`,
};
}
}
/**
* Initialize TaskMaster user (typically called during init)
* Gets userId from gateway without requiring email upfront
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {Promise<{success: boolean, userId: string, error?: string}>}
*/
async function initializeUser(explicitRoot = null) {
const config = getConfig(explicitRoot);
const mode = config.account?.mode || "byok";
if (mode === "byok") {
return await initializeBYOKUser(explicitRoot);
} else {
return await initializeHostedUser(explicitRoot);
}
}
async function initializeBYOKUser(projectRoot) {
try {
const gatewayUrl =
process.env.TASKMASTER_GATEWAY_URL || "http://localhost:4444";
// Check if we already have an anonymous user ID stored
let config = getConfig(projectRoot);
const existingAnonymousUserId = config?.account?.userId;
// Prepare headers for the request
const headers = {
"Content-Type": "application/json",
"X-TaskMaster-Service-ID": "98fb3198-2dfc-42d1-af53-07b99e4f3bde",
};
// If we have an existing anonymous user ID, try to reuse it
if (existingAnonymousUserId && existingAnonymousUserId !== "1234567890") {
headers["X-Anonymous-User-ID"] = existingAnonymousUserId;
}
// Call gateway /auth/anonymous to create or reuse a user account
// BYOK users still get an account for potential future hosted mode switch
const response = await fetch(`${gatewayUrl}/auth/anonymous`, {
method: "POST",
headers,
body: JSON.stringify({}),
});
if (response.ok) {
const result = await response.json();
// Store the user token (same as hosted users)
// BYOK users won't use this for AI calls, but will have it for potential mode switch
if (result.session && result.session.access_token) {
writeApiKeyToEnv(result.session.access_token, projectRoot);
}
// Update config with BYOK user info, ensuring we store the anonymous user ID
if (!config.account) {
config.account = {};
}
config.account.userId = result.anonymousUserId || result.user.id;
config.account.mode = "byok";
config.account.email =
result.user.email ||
`anon-${result.anonymousUserId || result.user.id}@taskmaster.temp`;
config.account.telemetryEnabled = true;
writeConfig(config, projectRoot);
return {
success: true,
userId: result.anonymousUserId || result.user.id,
token: result.session?.access_token || null,
mode: "byok",
isAnonymous: true,
isReused: result.isReused || false,
};
} else {
const errorText = await response.text();
return {
success: false,
error: `Gateway not available: ${response.status} ${errorText}`,
};
}
} catch (error) {
return {
success: false,
error: `Network error: ${error.message}`,
};
}
}
async function initializeHostedUser(projectRoot) {
try {
// For hosted users, we need proper authentication
// This would typically involve OAuth flow or registration
const gatewayUrl =
process.env.TASKMASTER_GATEWAY_URL || "http://localhost:4444";
// Check if we already have stored credentials
const existingToken = getUserToken(projectRoot);
const existingUserId = getUserId(projectRoot);
if (existingToken && existingUserId && existingUserId !== "1234567890") {
// Try to validate existing credentials
try {
const response = await fetch(`${gatewayUrl}/auth/validate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${existingToken}`,
"X-TaskMaster-Service-ID": "98fb3198-2dfc-42d1-af53-07b99e4f3bde",
},
});
if (response.ok) {
return {
success: true,
userId: existingUserId,
token: existingToken,
mode: "hosted",
isExisting: true,
};
}
} catch (error) {
// Fall through to re-authentication
}
}
// If no valid credentials, use the existing registration flow
const registrationResult = await registerUserWithGateway(null, projectRoot);
if (registrationResult.success) {
// Update config for hosted mode
updateUserConfig(
registrationResult.userId,
registrationResult.token,
"hosted",
null,
projectRoot
);
return {
success: true,
userId: registrationResult.userId,
token: registrationResult.token,
mode: "hosted",
isNewUser: registrationResult.isNewUser,
};
} else {
return {
success: false,
error: `Hosted mode setup failed: ${registrationResult.error}`,
};
}
} catch (error) {
return {
success: false,
error: `Hosted user initialization failed: ${error.message}`,
};
}
}
/**
* Gets the current user authentication token from .env file
* This is the Bearer token used for gateway API calls
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {string|null} User authentication token or null if not found
*/
function getUserToken(explicitRoot = null) {
try {
// Determine project root
let rootPath = explicitRoot;
if (!rootPath) {
rootPath = findProjectRoot();
if (!rootPath) {
log("error", "Could not determine project root for .env file");
return null;
}
}
const envPath = path.join(rootPath, ".env");
if (!fs.existsSync(envPath)) {
return null;
}
const envContent = fs.readFileSync(envPath, "utf8");
const lines = envContent.split("\n");
for (const line of lines) {
if (line.startsWith("TASKMASTER_API_KEY=")) {
return line.substring("TASKMASTER_API_KEY=".length).trim();
}
}
return null;
} catch (error) {
log("error", `Error getting user token from .env: ${error.message}`);
return null;
}
}
/**
* Gets the current user email from configuration
* @param {string|null} explicitRoot - Optional explicit project root path
* @returns {string|null} User email or null if not found
*/
function getUserEmail(explicitRoot = null) {
try {
const config = getConfig(explicitRoot);
return config?.account?.email || null;
} catch (error) {
log("error", `Error getting user email: ${error.message}`);
return null;
}
}
export {
registerUserWithGateway,
updateUserConfig,
writeApiKeyToEnv,
getUserMode,
isHostedMode,
isByokMode,
setupUser,
initializeUser,
initializeBYOKUser,
initializeHostedUser,
getUserToken,
getUserEmail,
};

View File

@@ -60,8 +60,7 @@ function resolveEnvVariable(key, session = null, projectRoot = null) {
// --- Project Root Finding Utility --- // --- Project Root Finding Utility ---
/** /**
* Finds the project root directory by searching upwards from a given starting point * Finds the project root directory by searching for marker files/directories.
* for a marker file or directory (e.g., 'package.json', '.git').
* @param {string} [startPath=process.cwd()] - The directory to start searching from. * @param {string} [startPath=process.cwd()] - The directory to start searching from.
* @param {string[]} [markers=['package.json', '.git', '.taskmasterconfig']] - Marker files/dirs to look for. * @param {string[]} [markers=['package.json', '.git', '.taskmasterconfig']] - Marker files/dirs to look for.
* @returns {string|null} The path to the project root directory, or null if not found. * @returns {string|null} The path to the project root directory, or null if not found.
@@ -71,27 +70,35 @@ function findProjectRoot(
markers = ['package.json', '.git', '.taskmasterconfig'] markers = ['package.json', '.git', '.taskmasterconfig']
) { ) {
let currentPath = path.resolve(startPath); let currentPath = path.resolve(startPath);
while (true) { const rootPath = path.parse(currentPath).root;
for (const marker of markers) {
if (fs.existsSync(path.join(currentPath, marker))) { while (currentPath !== rootPath) {
// Check if any marker exists in the current directory
const hasMarker = markers.some((marker) => {
const markerPath = path.join(currentPath, marker);
return fs.existsSync(markerPath);
});
if (hasMarker) {
return currentPath; return currentPath;
} }
// Move up one directory
currentPath = path.dirname(currentPath);
} }
const parentPath = path.dirname(currentPath);
if (parentPath === currentPath) { // Check the root directory as well
// Reached the filesystem root const hasMarkerInRoot = markers.some((marker) => {
return null; const markerPath = path.join(rootPath, marker);
} return fs.existsSync(markerPath);
currentPath = parentPath; });
}
return hasMarkerInRoot ? rootPath : null;
} }
// --- Dynamic Configuration Function --- (REMOVED) // --- Dynamic Configuration Function --- (REMOVED)
/*
function getConfig(session = null) { // --- Logging and Utility Functions ---
// ... implementation removed ...
}
*/
// Set up logging based on log level // Set up logging based on log level
const LOG_LEVELS = { const LOG_LEVELS = {

View File

@@ -0,0 +1,659 @@
/**
* contextGatherer.js
* Comprehensive context gathering utility for Task Master AI operations
* Supports task context, file context, project tree, and custom context
*/
import fs from 'fs';
import path from 'path';
import pkg from 'gpt-tokens';
import { readJSON, findTaskById, truncate } from '../utils.js';
const { encode } = pkg;
/**
* Context Gatherer class for collecting and formatting context from various sources
*/
export class ContextGatherer {
constructor(projectRoot) {
this.projectRoot = projectRoot;
this.tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
}
/**
* Count tokens in a text string using gpt-tokens
* @param {string} text - Text to count tokens for
* @returns {number} Token count
*/
countTokens(text) {
if (!text || typeof text !== 'string') {
return 0;
}
try {
return encode(text).length;
} catch (error) {
// Fallback to rough character-based estimation if tokenizer fails
// Rough estimate: ~4 characters per token for English text
return Math.ceil(text.length / 4);
}
}
/**
* Main method to gather context from multiple sources
* @param {Object} options - Context gathering options
* @param {Array<string>} [options.tasks] - Task/subtask IDs to include
* @param {Array<string>} [options.files] - File paths to include
* @param {string} [options.customContext] - Additional custom context
* @param {boolean} [options.includeProjectTree] - Include project file tree
* @param {string} [options.format] - Output format: 'research', 'chat', 'system-prompt'
* @returns {Promise<string>} Formatted context string
*/
async gather(options = {}) {
const {
tasks = [],
files = [],
customContext = '',
includeProjectTree = false,
format = 'research',
includeTokenCounts = false
} = options;
const contextSections = [];
const tokenBreakdown = {
customContext: null,
tasks: [],
files: [],
projectTree: null,
total: 0
};
// Add custom context first if provided
if (customContext && customContext.trim()) {
const formattedCustom = this._formatCustomContext(customContext, format);
contextSections.push(formattedCustom);
if (includeTokenCounts) {
tokenBreakdown.customContext = {
tokens: this.countTokens(formattedCustom),
characters: formattedCustom.length
};
}
}
// Add task context
if (tasks.length > 0) {
const taskContextResult = await this._gatherTaskContext(
tasks,
format,
includeTokenCounts
);
if (taskContextResult.context) {
contextSections.push(taskContextResult.context);
if (includeTokenCounts) {
tokenBreakdown.tasks = taskContextResult.breakdown;
}
}
}
// Add file context
if (files.length > 0) {
const fileContextResult = await this._gatherFileContext(
files,
format,
includeTokenCounts
);
if (fileContextResult.context) {
contextSections.push(fileContextResult.context);
if (includeTokenCounts) {
tokenBreakdown.files = fileContextResult.breakdown;
}
}
}
// Add project tree context
if (includeProjectTree) {
const treeContextResult = await this._gatherProjectTreeContext(
format,
includeTokenCounts
);
if (treeContextResult.context) {
contextSections.push(treeContextResult.context);
if (includeTokenCounts) {
tokenBreakdown.projectTree = treeContextResult.breakdown;
}
}
}
// Join all sections based on format
const finalContext = this._joinContextSections(contextSections, format);
if (includeTokenCounts) {
tokenBreakdown.total = this.countTokens(finalContext);
return {
context: finalContext,
tokenBreakdown: tokenBreakdown
};
}
return finalContext;
}
/**
* Parse task ID strings into structured format
* Supports formats: "15", "15.2", "16,17.1"
* @param {Array<string>} taskIds - Array of task ID strings
* @returns {Array<Object>} Parsed task identifiers
*/
_parseTaskIds(taskIds) {
const parsed = [];
for (const idStr of taskIds) {
if (idStr.includes('.')) {
// Subtask format: "15.2"
const [parentId, subtaskId] = idStr.split('.');
parsed.push({
type: 'subtask',
parentId: parseInt(parentId, 10),
subtaskId: parseInt(subtaskId, 10),
fullId: idStr
});
} else {
// Task format: "15"
parsed.push({
type: 'task',
taskId: parseInt(idStr, 10),
fullId: idStr
});
}
}
return parsed;
}
/**
* Gather context from tasks and subtasks
* @param {Array<string>} taskIds - Task/subtask IDs
* @param {string} format - Output format
* @param {boolean} includeTokenCounts - Whether to include token breakdown
* @returns {Promise<Object>} Task context result with breakdown
*/
async _gatherTaskContext(taskIds, format, includeTokenCounts = false) {
try {
const tasksData = readJSON(this.tasksPath);
if (!tasksData || !tasksData.tasks) {
return { context: null, breakdown: [] };
}
const parsedIds = this._parseTaskIds(taskIds);
const contextItems = [];
const breakdown = [];
for (const parsed of parsedIds) {
let formattedItem = null;
let itemInfo = null;
if (parsed.type === 'task') {
const result = findTaskById(tasksData.tasks, parsed.taskId);
if (result.task) {
formattedItem = this._formatTaskForContext(result.task, format);
itemInfo = {
id: parsed.fullId,
type: 'task',
title: result.task.title,
tokens: includeTokenCounts ? this.countTokens(formattedItem) : 0,
characters: formattedItem.length
};
}
} else if (parsed.type === 'subtask') {
const parentResult = findTaskById(tasksData.tasks, parsed.parentId);
if (parentResult.task && parentResult.task.subtasks) {
const subtask = parentResult.task.subtasks.find(
(st) => st.id === parsed.subtaskId
);
if (subtask) {
formattedItem = this._formatSubtaskForContext(
subtask,
parentResult.task,
format
);
itemInfo = {
id: parsed.fullId,
type: 'subtask',
title: subtask.title,
parentTitle: parentResult.task.title,
tokens: includeTokenCounts
? this.countTokens(formattedItem)
: 0,
characters: formattedItem.length
};
}
}
}
if (formattedItem && itemInfo) {
contextItems.push(formattedItem);
if (includeTokenCounts) {
breakdown.push(itemInfo);
}
}
}
if (contextItems.length === 0) {
return { context: null, breakdown: [] };
}
const finalContext = this._formatTaskContextSection(contextItems, format);
return {
context: finalContext,
breakdown: includeTokenCounts ? breakdown : []
};
} catch (error) {
console.warn(`Warning: Could not gather task context: ${error.message}`);
return { context: null, breakdown: [] };
}
}
/**
* Format a task for context inclusion
* @param {Object} task - Task object
* @param {string} format - Output format
* @returns {string} Formatted task context
*/
_formatTaskForContext(task, format) {
const sections = [];
sections.push(`**Task ${task.id}: ${task.title}**`);
sections.push(`Description: ${task.description}`);
sections.push(`Status: ${task.status || 'pending'}`);
sections.push(`Priority: ${task.priority || 'medium'}`);
if (task.dependencies && task.dependencies.length > 0) {
sections.push(`Dependencies: ${task.dependencies.join(', ')}`);
}
if (task.details) {
const details = truncate(task.details, 500);
sections.push(`Implementation Details: ${details}`);
}
if (task.testStrategy) {
const testStrategy = truncate(task.testStrategy, 300);
sections.push(`Test Strategy: ${testStrategy}`);
}
if (task.subtasks && task.subtasks.length > 0) {
sections.push(`Subtasks: ${task.subtasks.length} subtasks defined`);
}
return sections.join('\n');
}
/**
* Format a subtask for context inclusion
* @param {Object} subtask - Subtask object
* @param {Object} parentTask - Parent task object
* @param {string} format - Output format
* @returns {string} Formatted subtask context
*/
_formatSubtaskForContext(subtask, parentTask, format) {
const sections = [];
sections.push(
`**Subtask ${parentTask.id}.${subtask.id}: ${subtask.title}**`
);
sections.push(`Parent Task: ${parentTask.title}`);
sections.push(`Description: ${subtask.description}`);
sections.push(`Status: ${subtask.status || 'pending'}`);
if (subtask.dependencies && subtask.dependencies.length > 0) {
sections.push(`Dependencies: ${subtask.dependencies.join(', ')}`);
}
if (subtask.details) {
const details = truncate(subtask.details, 500);
sections.push(`Implementation Details: ${details}`);
}
return sections.join('\n');
}
/**
* Gather context from files
* @param {Array<string>} filePaths - File paths to read
* @param {string} format - Output format
* @param {boolean} includeTokenCounts - Whether to include token breakdown
* @returns {Promise<Object>} File context result with breakdown
*/
async _gatherFileContext(filePaths, format, includeTokenCounts = false) {
const fileContents = [];
const breakdown = [];
for (const filePath of filePaths) {
try {
const fullPath = path.isAbsolute(filePath)
? filePath
: path.join(this.projectRoot, filePath);
if (!fs.existsSync(fullPath)) {
console.warn(`Warning: File not found: ${filePath}`);
continue;
}
const stats = fs.statSync(fullPath);
if (!stats.isFile()) {
console.warn(`Warning: Path is not a file: ${filePath}`);
continue;
}
// Check file size (limit to 50KB for context)
if (stats.size > 50 * 1024) {
console.warn(
`Warning: File too large, skipping: ${filePath} (${Math.round(stats.size / 1024)}KB)`
);
continue;
}
const content = fs.readFileSync(fullPath, 'utf-8');
const relativePath = path.relative(this.projectRoot, fullPath);
const fileData = {
path: relativePath,
size: stats.size,
content: content,
lastModified: stats.mtime
};
fileContents.push(fileData);
// Calculate tokens for this individual file if requested
if (includeTokenCounts) {
const formattedFile = this._formatSingleFileForContext(
fileData,
format
);
breakdown.push({
path: relativePath,
sizeKB: Math.round(stats.size / 1024),
tokens: this.countTokens(formattedFile),
characters: formattedFile.length
});
}
} catch (error) {
console.warn(
`Warning: Could not read file ${filePath}: ${error.message}`
);
}
}
if (fileContents.length === 0) {
return { context: null, breakdown: [] };
}
const finalContext = this._formatFileContextSection(fileContents, format);
return {
context: finalContext,
breakdown: includeTokenCounts ? breakdown : []
};
}
/**
* Generate project file tree context
* @param {string} format - Output format
* @param {boolean} includeTokenCounts - Whether to include token breakdown
* @returns {Promise<Object>} Project tree context result with breakdown
*/
async _gatherProjectTreeContext(format, includeTokenCounts = false) {
try {
const tree = this._generateFileTree(this.projectRoot, 5); // Max depth 5
const finalContext = this._formatProjectTreeSection(tree, format);
const breakdown = includeTokenCounts
? {
tokens: this.countTokens(finalContext),
characters: finalContext.length,
fileCount: tree.fileCount || 0,
dirCount: tree.dirCount || 0
}
: null;
return {
context: finalContext,
breakdown: breakdown
};
} catch (error) {
console.warn(
`Warning: Could not generate project tree: ${error.message}`
);
return { context: null, breakdown: null };
}
}
/**
* Format a single file for context (used for token counting)
* @param {Object} fileData - File data object
* @param {string} format - Output format
* @returns {string} Formatted file context
*/
_formatSingleFileForContext(fileData, format) {
const header = `**File: ${fileData.path}** (${Math.round(fileData.size / 1024)}KB)`;
const content = `\`\`\`\n${fileData.content}\n\`\`\``;
return `${header}\n\n${content}`;
}
/**
* Generate file tree structure
* @param {string} dirPath - Directory path
* @param {number} maxDepth - Maximum depth to traverse
* @param {number} currentDepth - Current depth
* @returns {Object} File tree structure
*/
_generateFileTree(dirPath, maxDepth, currentDepth = 0) {
const ignoreDirs = [
'.git',
'node_modules',
'.env',
'coverage',
'dist',
'build'
];
const ignoreFiles = ['.DS_Store', '.env', '.env.local', '.env.production'];
if (currentDepth >= maxDepth) {
return null;
}
try {
const items = fs.readdirSync(dirPath);
const tree = {
name: path.basename(dirPath),
type: 'directory',
children: [],
fileCount: 0,
dirCount: 0
};
for (const item of items) {
if (ignoreDirs.includes(item) || ignoreFiles.includes(item)) {
continue;
}
const itemPath = path.join(dirPath, item);
const stats = fs.statSync(itemPath);
if (stats.isDirectory()) {
tree.dirCount++;
if (currentDepth < maxDepth - 1) {
const subtree = this._generateFileTree(
itemPath,
maxDepth,
currentDepth + 1
);
if (subtree) {
tree.children.push(subtree);
}
}
} else {
tree.fileCount++;
tree.children.push({
name: item,
type: 'file',
size: stats.size
});
}
}
return tree;
} catch (error) {
return null;
}
}
/**
* Format custom context section
* @param {string} customContext - Custom context string
* @param {string} format - Output format
* @returns {string} Formatted custom context
*/
_formatCustomContext(customContext, format) {
switch (format) {
case 'research':
return `## Additional Context\n\n${customContext}`;
case 'chat':
return `**Additional Context:**\n${customContext}`;
case 'system-prompt':
return `Additional context: ${customContext}`;
default:
return customContext;
}
}
/**
* Format task context section
* @param {Array<string>} taskItems - Formatted task items
* @param {string} format - Output format
* @returns {string} Formatted task context section
*/
_formatTaskContextSection(taskItems, format) {
switch (format) {
case 'research':
return `## Task Context\n\n${taskItems.join('\n\n---\n\n')}`;
case 'chat':
return `**Task Context:**\n\n${taskItems.join('\n\n')}`;
case 'system-prompt':
return `Task context: ${taskItems.join(' | ')}`;
default:
return taskItems.join('\n\n');
}
}
/**
* Format file context section
* @param {Array<Object>} fileContents - File content objects
* @param {string} format - Output format
* @returns {string} Formatted file context section
*/
_formatFileContextSection(fileContents, format) {
const fileItems = fileContents.map((file) => {
const header = `**File: ${file.path}** (${Math.round(file.size / 1024)}KB)`;
const content = `\`\`\`\n${file.content}\n\`\`\``;
return `${header}\n\n${content}`;
});
switch (format) {
case 'research':
return `## File Context\n\n${fileItems.join('\n\n---\n\n')}`;
case 'chat':
return `**File Context:**\n\n${fileItems.join('\n\n')}`;
case 'system-prompt':
return `File context: ${fileContents.map((f) => `${f.path} (${f.content.substring(0, 200)}...)`).join(' | ')}`;
default:
return fileItems.join('\n\n');
}
}
/**
* Format project tree section
* @param {Object} tree - File tree structure
* @param {string} format - Output format
* @returns {string} Formatted project tree section
*/
_formatProjectTreeSection(tree, format) {
const treeString = this._renderFileTree(tree);
switch (format) {
case 'research':
return `## Project Structure\n\n\`\`\`\n${treeString}\n\`\`\``;
case 'chat':
return `**Project Structure:**\n\`\`\`\n${treeString}\n\`\`\``;
case 'system-prompt':
return `Project structure: ${treeString.replace(/\n/g, ' | ')}`;
default:
return treeString;
}
}
/**
* Render file tree as string
* @param {Object} tree - File tree structure
* @param {string} prefix - Current prefix for indentation
* @returns {string} Rendered tree string
*/
_renderFileTree(tree, prefix = '') {
let result = `${prefix}${tree.name}/`;
if (tree.fileCount > 0 || tree.dirCount > 0) {
result += ` (${tree.fileCount} files, ${tree.dirCount} dirs)`;
}
result += '\n';
if (tree.children) {
tree.children.forEach((child, index) => {
const isLast = index === tree.children.length - 1;
const childPrefix = prefix + (isLast ? '└── ' : '├── ');
const nextPrefix = prefix + (isLast ? ' ' : '│ ');
if (child.type === 'directory') {
result += this._renderFileTree(child, childPrefix);
} else {
result += `${childPrefix}${child.name}\n`;
}
});
}
return result;
}
/**
* Join context sections based on format
* @param {Array<string>} sections - Context sections
* @param {string} format - Output format
* @returns {string} Joined context string
*/
_joinContextSections(sections, format) {
if (sections.length === 0) {
return '';
}
switch (format) {
case 'research':
return sections.join('\n\n---\n\n');
case 'chat':
return sections.join('\n\n');
case 'system-prompt':
return sections.join(' ');
default:
return sections.join('\n\n');
}
}
}
/**
* Factory function to create a context gatherer instance
* @param {string} projectRoot - Project root directory
* @returns {ContextGatherer} Context gatherer instance
*/
export function createContextGatherer(projectRoot) {
return new ContextGatherer(projectRoot);
}
export default ContextGatherer;

View File

@@ -0,0 +1,376 @@
/**
* fuzzyTaskSearch.js
* Reusable fuzzy search utility for finding relevant tasks based on semantic similarity
*/
import Fuse from 'fuse.js';
/**
* Configuration for different search contexts
*/
const SEARCH_CONFIGS = {
research: {
threshold: 0.5, // More lenient for research (broader context)
limit: 20,
keys: [
{ name: 'title', weight: 2.0 },
{ name: 'description', weight: 1.0 },
{ name: 'details', weight: 0.5 },
{ name: 'dependencyTitles', weight: 0.5 }
]
},
addTask: {
threshold: 0.4, // Stricter for add-task (more precise context)
limit: 15,
keys: [
{ name: 'title', weight: 2.0 },
{ name: 'description', weight: 1.5 },
{ name: 'details', weight: 0.8 },
{ name: 'dependencyTitles', weight: 0.5 }
]
},
default: {
threshold: 0.4,
limit: 15,
keys: [
{ name: 'title', weight: 2.0 },
{ name: 'description', weight: 1.5 },
{ name: 'details', weight: 1.0 },
{ name: 'dependencyTitles', weight: 0.5 }
]
}
};
/**
* Purpose categories for pattern-based task matching
*/
const PURPOSE_CATEGORIES = [
{ pattern: /(command|cli|flag)/i, label: 'CLI commands' },
{ pattern: /(task|subtask|add)/i, label: 'Task management' },
{ pattern: /(dependency|depend)/i, label: 'Dependency handling' },
{ pattern: /(AI|model|prompt|research)/i, label: 'AI integration' },
{ pattern: /(UI|display|show|interface)/i, label: 'User interface' },
{ pattern: /(schedule|time|cron)/i, label: 'Scheduling' },
{ pattern: /(config|setting|option)/i, label: 'Configuration' },
{ pattern: /(test|testing|spec)/i, label: 'Testing' },
{ pattern: /(auth|login|user)/i, label: 'Authentication' },
{ pattern: /(database|db|data)/i, label: 'Data management' },
{ pattern: /(api|endpoint|route)/i, label: 'API development' },
{ pattern: /(deploy|build|release)/i, label: 'Deployment' },
{ pattern: /(security|auth|login|user)/i, label: 'Security' },
{ pattern: /.*/, label: 'Other' }
];
/**
* Relevance score thresholds
*/
const RELEVANCE_THRESHOLDS = {
high: 0.25,
medium: 0.4,
low: 0.6
};
/**
* Fuzzy search utility class for finding relevant tasks
*/
export class FuzzyTaskSearch {
constructor(tasks, searchType = 'default') {
this.tasks = tasks;
this.config = SEARCH_CONFIGS[searchType] || SEARCH_CONFIGS.default;
this.searchableTasks = this._prepareSearchableTasks(tasks);
this.fuse = new Fuse(this.searchableTasks, {
includeScore: true,
threshold: this.config.threshold,
keys: this.config.keys,
shouldSort: true,
useExtendedSearch: true,
limit: this.config.limit
});
}
/**
* Prepare tasks for searching by expanding dependency titles
* @param {Array} tasks - Array of task objects
* @returns {Array} Tasks with expanded dependency information
*/
_prepareSearchableTasks(tasks) {
return tasks.map((task) => {
// Get titles of this task's dependencies if they exist
const dependencyTitles =
task.dependencies?.length > 0
? task.dependencies
.map((depId) => {
const depTask = tasks.find((t) => t.id === depId);
return depTask ? depTask.title : '';
})
.filter((title) => title)
.join(' ')
: '';
return {
...task,
dependencyTitles
};
});
}
/**
* Extract significant words from a prompt
* @param {string} prompt - The search prompt
* @returns {Array<string>} Array of significant words
*/
_extractPromptWords(prompt) {
return prompt
.toLowerCase()
.replace(/[^\w\s-]/g, ' ') // Replace non-alphanumeric chars with spaces
.split(/\s+/)
.filter((word) => word.length > 3); // Words at least 4 chars
}
/**
* Find tasks related to a prompt using fuzzy search
* @param {string} prompt - The search prompt
* @param {Object} options - Search options
* @param {number} [options.maxResults=8] - Maximum number of results to return
* @param {boolean} [options.includeRecent=true] - Include recent tasks in results
* @param {boolean} [options.includeCategoryMatches=true] - Include category-based matches
* @returns {Object} Search results with relevance breakdown
*/
findRelevantTasks(prompt, options = {}) {
const {
maxResults = 8,
includeRecent = true,
includeCategoryMatches = true
} = options;
// Extract significant words from prompt
const promptWords = this._extractPromptWords(prompt);
// Perform fuzzy search with full prompt
const fuzzyResults = this.fuse.search(prompt);
// Also search for each significant word to catch different aspects
let wordResults = [];
for (const word of promptWords) {
if (word.length > 5) {
// Only use significant words
const results = this.fuse.search(word);
if (results.length > 0) {
wordResults.push(...results);
}
}
}
// Merge and deduplicate results
const mergedResults = [...fuzzyResults];
// Add word results that aren't already in fuzzyResults
for (const wordResult of wordResults) {
if (!mergedResults.some((r) => r.item.id === wordResult.item.id)) {
mergedResults.push(wordResult);
}
}
// Group search results by relevance
const highRelevance = mergedResults
.filter((result) => result.score < RELEVANCE_THRESHOLDS.high)
.map((result) => ({ ...result.item, score: result.score }));
const mediumRelevance = mergedResults
.filter(
(result) =>
result.score >= RELEVANCE_THRESHOLDS.high &&
result.score < RELEVANCE_THRESHOLDS.medium
)
.map((result) => ({ ...result.item, score: result.score }));
const lowRelevance = mergedResults
.filter(
(result) =>
result.score >= RELEVANCE_THRESHOLDS.medium &&
result.score < RELEVANCE_THRESHOLDS.low
)
.map((result) => ({ ...result.item, score: result.score }));
// Get recent tasks (newest first) if requested
const recentTasks = includeRecent
? [...this.tasks].sort((a, b) => b.id - a.id).slice(0, 5)
: [];
// Find category-based matches if requested
let categoryTasks = [];
let promptCategory = null;
if (includeCategoryMatches) {
promptCategory = PURPOSE_CATEGORIES.find((cat) =>
cat.pattern.test(prompt)
);
categoryTasks = promptCategory
? this.tasks
.filter(
(t) =>
promptCategory.pattern.test(t.title) ||
promptCategory.pattern.test(t.description) ||
(t.details && promptCategory.pattern.test(t.details))
)
.slice(0, 3)
: [];
}
// Combine all relevant tasks, prioritizing by relevance
const allRelevantTasks = [...highRelevance];
// Add medium relevance if not already included
for (const task of mediumRelevance) {
if (!allRelevantTasks.some((t) => t.id === task.id)) {
allRelevantTasks.push(task);
}
}
// Add low relevance if not already included
for (const task of lowRelevance) {
if (!allRelevantTasks.some((t) => t.id === task.id)) {
allRelevantTasks.push(task);
}
}
// Add category tasks if not already included
for (const task of categoryTasks) {
if (!allRelevantTasks.some((t) => t.id === task.id)) {
allRelevantTasks.push(task);
}
}
// Add recent tasks if not already included
for (const task of recentTasks) {
if (!allRelevantTasks.some((t) => t.id === task.id)) {
allRelevantTasks.push(task);
}
}
// Get top N results for final output
const finalResults = allRelevantTasks.slice(0, maxResults);
return {
results: finalResults,
breakdown: {
highRelevance,
mediumRelevance,
lowRelevance,
categoryTasks,
recentTasks,
promptCategory,
promptWords
},
metadata: {
totalSearched: this.tasks.length,
fuzzyMatches: fuzzyResults.length,
wordMatches: wordResults.length,
finalCount: finalResults.length
}
};
}
/**
* Get task IDs from search results
* @param {Object} searchResults - Results from findRelevantTasks
* @returns {Array<string>} Array of task ID strings
*/
getTaskIds(searchResults) {
return searchResults.results.map((task) => {
// Use searchableId if available (for flattened tasks with subtasks)
// Otherwise fall back to regular id
return task.searchableId || task.id.toString();
});
}
/**
* Get task IDs including subtasks from search results
* @param {Object} searchResults - Results from findRelevantTasks
* @param {boolean} [includeSubtasks=false] - Whether to include subtask IDs
* @returns {Array<string>} Array of task and subtask ID strings
*/
getTaskIdsWithSubtasks(searchResults, includeSubtasks = false) {
const taskIds = [];
for (const task of searchResults.results) {
taskIds.push(task.id.toString());
if (includeSubtasks && task.subtasks && task.subtasks.length > 0) {
for (const subtask of task.subtasks) {
taskIds.push(`${task.id}.${subtask.id}`);
}
}
}
return taskIds;
}
/**
* Format search results for display
* @param {Object} searchResults - Results from findRelevantTasks
* @param {Object} options - Formatting options
* @returns {string} Formatted search results summary
*/
formatSearchSummary(searchResults, options = {}) {
const { includeScores = false, includeBreakdown = false } = options;
const { results, breakdown, metadata } = searchResults;
let summary = `Found ${results.length} relevant tasks from ${metadata.totalSearched} total tasks`;
if (includeBreakdown && breakdown) {
const parts = [];
if (breakdown.highRelevance.length > 0)
parts.push(`${breakdown.highRelevance.length} high relevance`);
if (breakdown.mediumRelevance.length > 0)
parts.push(`${breakdown.mediumRelevance.length} medium relevance`);
if (breakdown.lowRelevance.length > 0)
parts.push(`${breakdown.lowRelevance.length} low relevance`);
if (breakdown.categoryTasks.length > 0)
parts.push(`${breakdown.categoryTasks.length} category matches`);
if (parts.length > 0) {
summary += ` (${parts.join(', ')})`;
}
if (breakdown.promptCategory) {
summary += `\nCategory detected: ${breakdown.promptCategory.label}`;
}
}
return summary;
}
}
/**
* Factory function to create a fuzzy search instance
* @param {Array} tasks - Array of task objects
* @param {string} [searchType='default'] - Type of search configuration to use
* @returns {FuzzyTaskSearch} Fuzzy search instance
*/
export function createFuzzyTaskSearch(tasks, searchType = 'default') {
return new FuzzyTaskSearch(tasks, searchType);
}
/**
* Quick utility function to find relevant task IDs for a prompt
* @param {Array} tasks - Array of task objects
* @param {string} prompt - Search prompt
* @param {Object} options - Search options
* @returns {Array<string>} Array of relevant task ID strings
*/
export function findRelevantTaskIds(tasks, prompt, options = {}) {
const {
searchType = 'default',
maxResults = 8,
includeSubtasks = false
} = options;
const fuzzySearch = new FuzzyTaskSearch(tasks, searchType);
const results = fuzzySearch.findRelevantTasks(prompt, { maxResults });
return includeSubtasks
? fuzzySearch.getTaskIdsWithSubtasks(results, true)
: fuzzySearch.getTaskIds(results);
}
export default FuzzyTaskSearch;

View File

@@ -0,0 +1,186 @@
/**
* Enhanced error handler for gateway responses
* @param {Error} error - The error from the gateway call
* @param {string} commandName - The command being executed
*/
function handleGatewayError(error, commandName) {
try {
// Extract status code and response from error message
const match = error.message.match(/Gateway AI call failed: (\d+) (.+)/);
if (!match) {
throw new Error(`Unexpected error format: ${error.message}`);
}
const [, statusCode, responseText] = match;
const status = parseInt(statusCode);
let response;
try {
response = JSON.parse(responseText);
} catch {
// Handle non-JSON error responses
console.error(`[ERROR] Gateway error (${status}): ${responseText}`);
return;
}
switch (status) {
case 400:
handleValidationError(response, commandName);
break;
case 401:
handleAuthError(response, commandName);
break;
case 402:
handleCreditError(response, commandName);
break;
case 403:
handleAccessDeniedError(response, commandName);
break;
case 429:
handleRateLimitError(response, commandName);
break;
case 500:
handleServerError(response, commandName);
break;
default:
console.error(
`[ERROR] Unexpected gateway error (${status}):`,
response
);
}
} catch (parseError) {
console.error(`[ERROR] Failed to parse gateway error: ${error.message}`);
}
}
function handleValidationError(response, commandName) {
if (response.error?.includes("Unsupported model")) {
console.error("🚫 The selected AI model is not supported by the gateway.");
console.error(
"💡 Try running `task-master models` to see available models."
);
return;
}
if (response.error?.includes("schema is required")) {
console.error("🚫 This command requires a schema for structured output.");
console.error("💡 This is likely a bug - please report it.");
return;
}
console.error(`🚫 Invalid request: ${response.error}`);
if (response.details?.length > 0) {
response.details.forEach((detail) => {
console.error(`${detail.message || detail}`);
});
}
}
function handleAuthError(response, commandName) {
console.error("🔐 Authentication failed with TaskMaster gateway.");
if (response.message?.includes("Invalid token")) {
console.error("💡 Your auth token may have expired. Try running:");
console.error(" task-master init");
} else if (response.message?.includes("Missing X-TaskMaster-Service-ID")) {
console.error(
"💡 Service authentication issue. This is likely a bug - please report it."
);
} else {
console.error("💡 Please check your authentication settings.");
}
}
function handleCreditError(response, commandName) {
console.error("💳 Insufficient credits for this operation.");
console.error(`💡 ${response.message || "Your account needs more credits."}`);
console.error(" • Visit your dashboard to add credits");
console.error(" • Or upgrade to a plan with more credits");
console.error(
" • You can also switch to BYOK mode to use your own API keys"
);
}
function handleAccessDeniedError(response, commandName) {
const { details, hint } = response;
if (
details?.planType === "byok" &&
details?.subscriptionStatus === "inactive"
) {
console.error(
"🔒 BYOK users need active subscriptions for hosted AI services."
);
console.error("💡 You have two options:");
console.error(" 1. Upgrade to a paid plan for hosted AI services");
console.error(" 2. Switch to BYOK mode and use your own API keys");
console.error("");
console.error(" To use your own API keys:");
console.error(
" • Set your API keys in .env file (e.g., ANTHROPIC_API_KEY=...)"
);
console.error(" • The system will automatically use direct API calls");
return;
}
if (details?.subscriptionStatus === "past_due") {
console.error("💳 Your subscription payment is overdue.");
console.error(
"💡 Please update your payment method to continue using AI services."
);
console.error(
" Visit your account dashboard to update billing information."
);
return;
}
if (details?.planType === "free" && commandName === "research") {
console.error("🔬 Research features require a paid subscription.");
console.error("💡 Upgrade your plan to access research-powered commands.");
return;
}
console.error(`🔒 Access denied: ${response.message}`);
if (hint) {
console.error(`💡 ${hint}`);
}
}
function handleRateLimitError(response, commandName) {
const retryAfter = response.retryAfter || 60;
console.error("⏱️ Rate limit exceeded - too many requests.");
console.error(`💡 Please wait ${retryAfter} seconds before trying again.`);
console.error(" Consider upgrading your plan for higher rate limits.");
}
function handleServerError(response, commandName) {
const retryAfter = response.retryAfter || 10;
if (response.error?.includes("Service temporarily unavailable")) {
console.error("🚧 TaskMaster gateway is temporarily unavailable.");
console.error(
`💡 The service should recover automatically. Try again in ${retryAfter} seconds.`
);
console.error(
" You can also switch to BYOK mode to use direct API calls."
);
return;
}
if (response.message?.includes("No user message found")) {
console.error("🚫 Invalid request format - missing user message.");
console.error("💡 This is likely a bug - please report it.");
return;
}
console.error("⚠️ Gateway server error occurred.");
console.error(
`💡 Try again in ${retryAfter} seconds. If the problem persists:`
);
console.error(" • Check TaskMaster status page");
console.error(" • Switch to BYOK mode as a workaround");
console.error(" • Contact support if the issue continues");
}
// Export the main handler function
export { handleGatewayError };

View File

@@ -1,10 +1,12 @@
{ {
"meta": { "meta": {
"generatedAt": "2025-05-17T22:29:22.179Z", "generatedAt": "2025-05-27T16:34:53.088Z",
"tasksAnalyzed": 40, "tasksAnalyzed": 1,
"totalTasks": 84,
"analysisCount": 45,
"thresholdScore": 5, "thresholdScore": 5,
"projectName": "Taskmaster", "projectName": "Taskmaster",
"usedResearch": false "usedResearch": true
}, },
"complexityAnalysis": [ "complexityAnalysis": [
{ {
@@ -215,22 +217,6 @@
"expansionPrompt": "The current 2 subtasks for implementing task creation without PRD appear appropriate. Consider if any additional subtasks are needed for validation, error handling, or integration with existing task management workflows.", "expansionPrompt": "The current 2 subtasks for implementing task creation without PRD appear appropriate. Consider if any additional subtasks are needed for validation, error handling, or integration with existing task management workflows.",
"reasoning": "This task involves a relatively simple modification to allow task creation without requiring a PRD document. The complexity is low as it primarily involves creating a form interface and saving functionality. The 2 existing subtasks cover the main implementation areas of UI design and data saving." "reasoning": "This task involves a relatively simple modification to allow task creation without requiring a PRD document. The complexity is low as it primarily involves creating a form interface and saving functionality. The 2 existing subtasks cover the main implementation areas of UI design and data saving."
}, },
{
"taskId": 69,
"taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
"complexityScore": 5,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for enhancing the analyze-complexity feature appear well-structured. Consider if any additional subtasks are needed for performance optimization with large task sets or visualization improvements.",
"reasoning": "This task involves modifying the existing analyze-complexity feature to support analyzing specific task IDs and updating reports. The complexity is moderate as it requires careful handling of report merging and filtering logic. The 4 existing subtasks cover the main implementation areas from core logic to testing."
},
{
"taskId": 70,
"taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for implementing the 'diagram' command appear well-structured. Consider if any additional subtasks are needed for handling large dependency graphs, additional output formats, or integration with existing visualization tools.",
"reasoning": "This task involves creating a new command that generates Mermaid diagrams to visualize task dependencies. The complexity is moderate as it requires parsing task relationships, generating proper Mermaid syntax, and handling various output options. The 4 existing subtasks cover the main implementation areas from interface design to documentation."
},
{ {
"taskId": 72, "taskId": 72,
"taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview", "taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview",
@@ -304,28 +290,84 @@
"reasoning": "This task involves creating a utility function to count tokens for different AI models. The complexity is moderate as it requires integration with the tiktoken library and handling different tokenization schemes. No subtasks are necessary as the task is well-defined and focused." "reasoning": "This task involves creating a utility function to count tokens for different AI models. The complexity is moderate as it requires integration with the tiktoken library and handling different tokenization schemes. No subtasks are necessary as the task is well-defined and focused."
}, },
{ {
"taskId": 85, "taskId": 69,
"taskTitle": "Update ai-services-unified.js for dynamic token limits", "taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
"complexityScore": 6, "complexityScore": 7,
"recommendedSubtasks": 1, "recommendedSubtasks": 6,
"expansionPrompt": "This task appears well-defined enough to be implemented without further subtasks. Focus on implementing dynamic token limit adjustment based on input length and model capabilities.", "expansionPrompt": "Break down the task 'Enhance Analyze Complexity for Specific Task IDs' into 6 subtasks focusing on: 1) Core logic modification to accept ID parameters, 2) Report merging functionality, 3) CLI interface updates, 4) MCP tool integration, 5) Documentation updates, and 6) Comprehensive testing across all components.",
"reasoning": "This task involves modifying the AI service runner to use the new token counting utility and dynamically adjust output token limits. The complexity is moderate to high as it requires careful integration with existing code and handling various edge cases. No subtasks are necessary as the task is well-defined and focused." "reasoning": "This task involves modifying existing functionality across multiple components (core logic, CLI, MCP) with complex logic for filtering tasks and merging reports. The implementation requires careful handling of different parameter combinations and edge cases. The task has interdependent components that need to work together seamlessly, and the report merging functionality adds significant complexity."
}, },
{ {
"taskId": 86, "taskId": 70,
"taskTitle": "Update .taskmasterconfig schema and user guide", "taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
"complexityScore": 4, "complexityScore": 6,
"recommendedSubtasks": 1, "recommendedSubtasks": 5,
"expansionPrompt": "This task appears straightforward enough to be implemented without further subtasks. Focus on creating clear migration guidance and updating documentation.", "expansionPrompt": "Break down the 'diagram' command implementation into 5 subtasks: 1) Command interface and parameter handling, 2) Task data extraction and transformation to Mermaid syntax, 3) Diagram rendering with status color coding, 4) Output formatting and file export functionality, and 5) Error handling and edge case management.",
"reasoning": "This task involves creating a migration guide for users to update their configuration files and documenting the new token limit options. The complexity is relatively low as it primarily involves documentation and schema validation. No subtasks are necessary as the task is well-defined and focused." "reasoning": "This task requires implementing a new feature rather than modifying existing code, which reduces complexity from integration challenges. However, it involves working with visualization logic, dependency mapping, and multiple output formats. The color coding based on status and handling of dependency relationships adds moderate complexity. The task is well-defined but requires careful attention to diagram formatting and error handling."
},
{
"taskId": 85,
"taskTitle": "Update ai-services-unified.js for dynamic token limits",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the update of ai-services-unified.js for dynamic token limits into subtasks such as: (1) Import and integrate the token counting utility, (2) Refactor _unifiedServiceRunner to calculate and enforce dynamic token limits, (3) Update error handling for token limit violations, (4) Add and verify logging for token usage, (5) Write and execute tests for various prompt and model scenarios.",
"reasoning": "This task involves significant code changes to a core function, integration of a new utility, dynamic logic for multiple models, and robust error handling. It also requires comprehensive testing for edge cases and integration, making it moderately complex and best managed by splitting into focused subtasks."
}, },
{ {
"taskId": 87, "taskId": 87,
"taskTitle": "Implement validation and error handling", "taskTitle": "Implement validation and error handling",
"complexityScore": 5, "complexityScore": 5,
"recommendedSubtasks": 1, "recommendedSubtasks": 4,
"expansionPrompt": "This task appears well-defined enough to be implemented without further subtasks. Focus on comprehensive validation and helpful error messages throughout the system.", "expansionPrompt": "Decompose this task into: (1) Add validation logic for model and config loading, (2) Implement error handling and fallback mechanisms, (3) Enhance logging and reporting for token usage, (4) Develop helper functions for configuration suggestions and improvements.",
"reasoning": "This task involves adding validation and error handling for token limits throughout the system. The complexity is moderate as it requires careful integration with multiple components and creating helpful error messages. No subtasks are necessary as the task is well-defined and focused." "reasoning": "This task is primarily about adding validation, error handling, and logging. While important for robustness, the logic is straightforward and can be modularized into a few clear subtasks."
},
{
"taskId": 89,
"taskTitle": "Introduce Prioritize Command with Enhanced Priority Levels",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Expand this task into: (1) Implement the prioritize command with all required flags and shorthands, (2) Update CLI output and help documentation for new priority levels, (3) Ensure backward compatibility with existing commands, (4) Add error handling for invalid inputs, (5) Write and run tests for all command scenarios.",
"reasoning": "This CLI feature requires command parsing, updating internal logic for new priority levels, documentation, and robust error handling. The complexity is moderate due to the need for backward compatibility and comprehensive testing."
},
{
"taskId": 90,
"taskTitle": "Implement Subtask Progress Analyzer and Reporting System",
"complexityScore": 8,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the analyzer implementation into: (1) Design and implement progress tracking logic, (2) Develop status validation and issue detection, (3) Build the reporting system with multiple output formats, (4) Integrate analyzer with the existing task management system, (5) Optimize for performance and scalability, (6) Write unit, integration, and performance tests.",
"reasoning": "This is a complex, multi-faceted feature involving data analysis, reporting, integration, and performance optimization. It touches many parts of the system and requires careful design, making it one of the most complex tasks in the list."
},
{
"taskId": 91,
"taskTitle": "Implement Move Command for Tasks and Subtasks",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Expand this task into: (1) Implement move logic for tasks and subtasks, (2) Handle edge cases (invalid ids, non-existent parents, circular dependencies), (3) Update CLI to support move command with flags, (4) Ensure data integrity and update relationships, (5) Write and execute tests for various move scenarios.",
"reasoning": "Moving tasks and subtasks requires careful handling of hierarchical data, edge cases, and data integrity. The command must be robust and user-friendly, necessitating multiple focused subtasks for safe implementation."
},
{
"taskId": 92,
"taskTitle": "Add Global Joke Flag to All CLI Commands",
"complexityScore": 8,
"recommendedSubtasks": 7,
"expansionPrompt": "Break down the implementation of the global --joke flag into the following subtasks: (1) Update CLI foundation to support global flags, (2) Develop the joke-service module with joke management and category support, (3) Integrate joke output into existing output utilities, (4) Update all CLI commands for joke flag compatibility, (5) Add configuration options for joke categories and custom jokes, (6) Implement comprehensive testing (flag recognition, output, content, integration, performance, regression), (7) Update documentation and usage examples.",
"reasoning": "This task requires changes across the CLI foundation, output utilities, all command modules, and configuration management. It introduces a new service module, global flag handling, and output logic that must not interfere with existing features (including JSON output). The need for robust testing and backward compatibility further increases complexity. The scope spans multiple code areas and requires careful integration, justifying a high complexity score and a detailed subtask breakdown to manage risk and ensure maintainability.[2][3][5]"
},
{
"taskId": 94,
"taskTitle": "Implement Standalone 'research' CLI Command for AI-Powered Queries",
"complexityScore": 7,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the implementation of the 'research' CLI command into logical subtasks covering command registration, parameter handling, context gathering, AI service integration, output formatting, and documentation.",
"reasoning": "This task has moderate to high complexity (7/10) due to multiple interconnected components: CLI argument parsing, integration with AI services, context gathering from various sources, and output formatting with different modes. The cyclomatic complexity would be significant with multiple decision paths for handling different flags and options. The task requires understanding existing patterns and extending the codebase in a consistent manner, suggesting the need for careful decomposition into manageable subtasks."
},
{
"taskId": 86,
"taskTitle": "Implement GitHub Issue Export Feature",
"complexityScore": 9,
"recommendedSubtasks": 10,
"expansionPrompt": "Break down the implementation of the GitHub Issue Export Feature into detailed subtasks covering: command structure and CLI integration, GitHub API client development, authentication and error handling, task-to-issue mapping logic, content formatting and markdown conversion, bidirectional linking and metadata management, extensible architecture and adapter interfaces, configuration and settings management, documentation, and comprehensive testing (unit, integration, edge cases, performance).",
"reasoning": "This task involves designing and implementing a robust, extensible export system with deep integration into GitHub, including bidirectional workflows, complex data mapping, error handling, and support for future platforms. The requirements span CLI design, API integration, content transformation, metadata management, extensibility, configuration, and extensive testing. The breadth and depth of these requirements, along with the need for maintainability and future extensibility, place this task at a high complexity level. Breaking it into at least 10 subtasks will ensure each major component and concern is addressed systematically, reducing risk and improving quality."
} }
] ]
} }

View File

@@ -4,9 +4,9 @@
* Implementation for interacting with Anthropic models (e.g., Claude) * Implementation for interacting with Anthropic models (e.g., Claude)
* using the Vercel AI SDK. * using the Vercel AI SDK.
*/ */
import { createAnthropic } from '@ai-sdk/anthropic'; import { createAnthropic } from '@ai-sdk/anthropic';
import { generateText, streamText, generateObject } from 'ai'; import { BaseAIProvider } from './base-provider.js';
import { log } from '../../scripts/modules/utils.js'; // Assuming utils is accessible
// TODO: Implement standardized functions for generateText, streamText, generateObject // TODO: Implement standardized functions for generateText, streamText, generateObject
@@ -17,208 +17,39 @@ import { log } from '../../scripts/modules/utils.js'; // Assuming utils is acces
// Remove the global variable and caching logic // Remove the global variable and caching logic
// let anthropicClient; // let anthropicClient;
function getClient(apiKey, baseUrl) { export class AnthropicAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Anthropic';
}
/**
* Creates and returns an Anthropic client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - Anthropic API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} Anthropic client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
if (!apiKey) { if (!apiKey) {
// In a real scenario, this would use the config resolver.
// Throwing error here if key isn't passed for simplicity.
// Keep the error check for the passed key
throw new Error('Anthropic API key is required.'); throw new Error('Anthropic API key is required.');
} }
// Remove the check for anthropicClient
// if (!anthropicClient) {
// TODO: Explore passing options like default headers if needed
// Create and return a new instance directly with standard version header
return createAnthropic({ return createAnthropic({
apiKey: apiKey, apiKey,
...(baseUrl && { baseURL: baseUrl }), ...(baseURL && { baseURL }),
// Use standard version header instead of beta
headers: { headers: {
'anthropic-beta': 'output-128k-2025-02-19' 'anthropic-beta': 'output-128k-2025-02-19'
} }
}); });
}
// --- Standardized Service Function Implementations ---
/**
* Generates text using an Anthropic model.
*
* @param {object} params - Parameters for the text generation.
* @param {string} params.apiKey - The Anthropic API key.
* @param {string} params.modelId - The specific Anthropic model ID.
* @param {Array<object>} params.messages - The messages array (e.g., [{ role: 'user', content: '...' }]).
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
* @returns {Promise<object>} The generated text content and usage.
* @throws {Error} If the API call fails.
*/
export async function generateAnthropicText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Generating Anthropic text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
const result = await generateText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
// Beta header moved to client initialization
// TODO: Add other relevant parameters like topP, topK if needed
});
log(
'debug',
`Anthropic generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
// Return both text and usage
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log('error', `Anthropic generateText failed: ${error.message}`); this.handleError('client initialization', error);
// Consider more specific error handling or re-throwing a standardized error
throw error;
} }
} }
/**
* Streams text using an Anthropic model.
*
* @param {object} params - Parameters for the text streaming.
* @param {string} params.apiKey - The Anthropic API key.
* @param {string} params.modelId - The specific Anthropic model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
* @returns {Promise<object>} The full stream result object from the Vercel AI SDK.
* @throws {Error} If the API call fails to initiate the stream.
*/
export async function streamAnthropicText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Streaming Anthropic text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
log(
'debug',
'[streamAnthropicText] Parameters received by streamText:',
JSON.stringify(
{
modelId: modelId,
messages: messages,
maxTokens: maxTokens,
temperature: temperature
},
null,
2
)
);
const stream = await streamText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
// TODO: Add other relevant parameters
});
// *** RETURN THE FULL STREAM OBJECT, NOT JUST stream.textStream ***
return stream;
} catch (error) {
log('error', `Anthropic streamText failed: ${error.message}`, error.stack);
throw error;
}
}
/**
* Generates a structured object using an Anthropic model.
* NOTE: Anthropic's tool/function calling support might have limitations
* compared to OpenAI, especially regarding complex schemas or enforcement.
* The Vercel AI SDK attempts to abstract this.
*
* @param {object} params - Parameters for object generation.
* @param {string} params.apiKey - The Anthropic API key.
* @param {string} params.modelId - The specific Anthropic model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the object.
* @param {string} params.objectName - A name for the object/tool.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {number} [params.maxRetries] - Max retries for validation/generation.
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
* @returns {Promise<object>} The generated object matching the schema and usage.
* @throws {Error} If generation or validation fails.
*/
export async function generateAnthropicObject({
apiKey,
modelId,
messages,
schema,
objectName = 'generated_object',
maxTokens,
temperature,
maxRetries = 3,
baseUrl
}) {
log(
'debug',
`Generating Anthropic object ('${objectName}') with model: ${modelId}`
);
try {
const client = getClient(apiKey, baseUrl);
log(
'debug',
`Using maxTokens: ${maxTokens}, temperature: ${temperature}, model: ${modelId}`
);
const result = await generateObject({
model: client(modelId),
mode: 'tool',
schema: schema,
messages: messages,
tool: {
name: objectName,
description: `Generate a ${objectName} based on the prompt.`
},
maxTokens: maxTokens,
temperature: temperature,
maxRetries: maxRetries
});
log(
'debug',
`Anthropic generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
// Return both object and usage
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`Anthropic generateObject ('${objectName}') failed: ${error.message}`
);
throw error;
}
} }
// TODO: Implement streamAnthropicObject if needed and supported well by the SDK for Anthropic. // TODO: Implement streamAnthropicObject if needed and supported well by the SDK for Anthropic.

52
src/ai-providers/azure.js Normal file
View File

@@ -0,0 +1,52 @@
/**
* azure.js
* AI provider implementation for Azure OpenAI models using Vercel AI SDK.
*/
import { createAzure } from '@ai-sdk/azure';
import { BaseAIProvider } from './base-provider.js';
export class AzureProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Azure OpenAI';
}
/**
* Validates Azure-specific authentication parameters
* @param {object} params - Parameters to validate
* @throws {Error} If required parameters are missing
*/
validateAuth(params) {
if (!params.apiKey) {
throw new Error('Azure API key is required');
}
if (!params.baseURL) {
throw new Error(
'Azure endpoint URL is required. Set it in .taskmasterconfig global.azureBaseURL or models.[role].baseURL'
);
}
}
/**
* Creates and returns an Azure OpenAI client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - Azure OpenAI API key
* @param {string} params.baseURL - Azure OpenAI endpoint URL (from .taskmasterconfig global.azureBaseURL or models.[role].baseURL)
* @returns {Function} Azure OpenAI client function
* @throws {Error} If required parameters are missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
return createAzure({
apiKey,
baseURL
});
} catch (error) {
this.handleError('client initialization', error);
}
}
}

View File

@@ -0,0 +1,214 @@
import { generateText, streamText, generateObject } from 'ai';
import { log } from '../../scripts/modules/index.js';
/**
* Base class for all AI providers
*/
export class BaseAIProvider {
constructor() {
if (this.constructor === BaseAIProvider) {
throw new Error('BaseAIProvider cannot be instantiated directly');
}
// Each provider must set their name
this.name = this.constructor.name;
}
/**
* Validates authentication parameters - can be overridden by providers
* @param {object} params - Parameters to validate
*/
validateAuth(params) {
// Default: require API key (most providers need this)
if (!params.apiKey) {
throw new Error(`${this.name} API key is required`);
}
}
/**
* Validates common parameters across all methods
* @param {object} params - Parameters to validate
*/
validateParams(params) {
// Validate authentication (can be overridden by providers)
this.validateAuth(params);
// Validate required model ID
if (!params.modelId) {
throw new Error(`${this.name} Model ID is required`);
}
// Validate optional parameters
this.validateOptionalParams(params);
}
/**
* Validates optional parameters like temperature and maxTokens
* @param {object} params - Parameters to validate
*/
validateOptionalParams(params) {
if (
params.temperature !== undefined &&
(params.temperature < 0 || params.temperature > 1)
) {
throw new Error('Temperature must be between 0 and 1');
}
if (params.maxTokens !== undefined && params.maxTokens <= 0) {
throw new Error('maxTokens must be greater than 0');
}
}
/**
* Validates message array structure
*/
validateMessages(messages) {
if (!messages || !Array.isArray(messages) || messages.length === 0) {
throw new Error('Invalid or empty messages array provided');
}
for (const msg of messages) {
if (!msg.role || !msg.content) {
throw new Error(
'Invalid message format. Each message must have role and content'
);
}
}
}
/**
* Common error handler
*/
handleError(operation, error) {
const errorMessage = error.message || 'Unknown error occurred';
log('error', `${this.name} ${operation} failed: ${errorMessage}`, {
error
});
throw new Error(
`${this.name} API error during ${operation}: ${errorMessage}`
);
}
/**
* Creates and returns a client instance for the provider
* @abstract
*/
getClient(params) {
throw new Error('getClient must be implemented by provider');
}
/**
* Generates text using the provider's model
*/
async generateText(params) {
try {
this.validateParams(params);
this.validateMessages(params.messages);
log(
'debug',
`Generating ${this.name} text with model: ${params.modelId}`
);
const client = this.getClient(params);
const result = await generateText({
model: client(params.modelId),
messages: params.messages,
maxTokens: params.maxTokens,
temperature: params.temperature
});
log(
'debug',
`${this.name} generateText completed successfully for model: ${params.modelId}`
);
return {
text: result.text,
usage: {
inputTokens: result.usage?.promptTokens,
outputTokens: result.usage?.completionTokens,
totalTokens: result.usage?.totalTokens
}
};
} catch (error) {
this.handleError('text generation', error);
}
}
/**
* Streams text using the provider's model
*/
async streamText(params) {
try {
this.validateParams(params);
this.validateMessages(params.messages);
log('debug', `Streaming ${this.name} text with model: ${params.modelId}`);
const client = this.getClient(params);
const stream = await streamText({
model: client(params.modelId),
messages: params.messages,
maxTokens: params.maxTokens,
temperature: params.temperature
});
log(
'debug',
`${this.name} streamText initiated successfully for model: ${params.modelId}`
);
return stream;
} catch (error) {
this.handleError('text streaming', error);
}
}
/**
* Generates a structured object using the provider's model
*/
async generateObject(params) {
try {
this.validateParams(params);
this.validateMessages(params.messages);
if (!params.schema) {
throw new Error('Schema is required for object generation');
}
if (!params.objectName) {
throw new Error('Object name is required for object generation');
}
log(
'debug',
`Generating ${this.name} object ('${params.objectName}') with model: ${params.modelId}`
);
const client = this.getClient(params);
const result = await generateObject({
model: client(params.modelId),
messages: params.messages,
schema: params.schema,
mode: 'tool',
maxTokens: params.maxTokens,
temperature: params.temperature
});
log(
'debug',
`${this.name} generateObject completed successfully for model: ${params.modelId}`
);
return {
object: result.object,
usage: {
inputTokens: result.usage?.promptTokens,
outputTokens: result.usage?.completionTokens,
totalTokens: result.usage?.totalTokens
}
};
} catch (error) {
this.handleError('object generation', error);
}
}
}

View File

@@ -0,0 +1,41 @@
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
import { BaseAIProvider } from './base-provider.js';
export class BedrockAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Bedrock';
}
/**
* Override auth validation - Bedrock uses AWS credentials instead of API keys
* @param {object} params - Parameters to validate
*/
validateAuth(params) {}
/**
* Creates and returns a Bedrock client instance.
* See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
* for AWS SDK environment variables and configuration options.
*/
getClient(params) {
try {
const {
profile = process.env.AWS_PROFILE || 'default',
region = process.env.AWS_DEFAULT_REGION || 'us-east-1',
baseURL
} = params;
const credentialProvider = fromNodeProviderChain({ profile });
return createAmazonBedrock({
region,
credentialProvider,
...(baseURL && { baseURL })
});
} catch (error) {
this.handleError('client initialization', error);
}
}
}

View File

@@ -0,0 +1,150 @@
/**
* google-vertex.js
* AI provider implementation for Google Vertex AI models using Vercel AI SDK.
*/
import { createVertex } from '@ai-sdk/google-vertex';
import { BaseAIProvider } from './base-provider.js';
import { resolveEnvVariable } from '../../scripts/modules/utils.js';
import { log } from '../../scripts/modules/utils.js';
// Vertex-specific error classes
class VertexAuthError extends Error {
constructor(message) {
super(message);
this.name = 'VertexAuthError';
this.code = 'vertex_auth_error';
}
}
class VertexConfigError extends Error {
constructor(message) {
super(message);
this.name = 'VertexConfigError';
this.code = 'vertex_config_error';
}
}
class VertexApiError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'VertexApiError';
this.code = 'vertex_api_error';
this.statusCode = statusCode;
}
}
export class VertexAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Google Vertex AI';
}
/**
* Validates Vertex AI-specific authentication parameters
* @param {object} params - Parameters to validate
* @throws {Error} If required parameters are missing
*/
validateAuth(params) {
const { apiKey, projectId, location, credentials } = params;
// Check for API key OR service account credentials
if (!apiKey && !credentials) {
throw new VertexAuthError(
'Either Google API key (GOOGLE_API_KEY) or service account credentials (GOOGLE_APPLICATION_CREDENTIALS) is required for Vertex AI'
);
}
// Project ID is required for Vertex AI
if (!projectId) {
throw new VertexConfigError(
'Google Cloud project ID is required for Vertex AI. Set VERTEX_PROJECT_ID environment variable.'
);
}
// Location is required for Vertex AI
if (!location) {
throw new VertexConfigError(
'Google Cloud location is required for Vertex AI. Set VERTEX_LOCATION environment variable (e.g., "us-central1").'
);
}
}
/**
* Creates and returns a Google Vertex AI client instance.
* @param {object} params - Parameters for client initialization
* @param {string} [params.apiKey] - Google API key
* @param {string} params.projectId - Google Cloud project ID
* @param {string} params.location - Google Cloud location (e.g., "us-central1")
* @param {object} [params.credentials] - Service account credentials object
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} Google Vertex AI client function
* @throws {Error} If required parameters are missing or initialization fails
*/
getClient(params) {
try {
// Validate required parameters
this.validateAuth(params);
const { apiKey, projectId, location, credentials, baseURL } = params;
// Configure auth options - either API key or service account
const authOptions = {};
if (apiKey) {
authOptions.apiKey = apiKey;
} else if (credentials) {
authOptions.googleAuthOptions = credentials;
}
// Return Vertex AI client
return createVertex({
...authOptions,
projectId,
location,
...(baseURL && { baseURL })
});
} catch (error) {
this.handleError('client initialization', error);
}
}
/**
* Handle errors from Vertex AI
* @param {string} operation - Description of the operation that failed
* @param {Error} error - The error object
* @throws {Error} Rethrows the error with additional context
*/
handleError(operation, error) {
log('error', `Vertex AI ${operation} error:`, error);
// Handle known error types
if (
error.name === 'VertexAuthError' ||
error.name === 'VertexConfigError' ||
error.name === 'VertexApiError'
) {
throw error;
}
// Handle network/API errors
if (error.response) {
const statusCode = error.response.status;
const errorMessage = error.response.data?.error?.message || error.message;
// Categorize by status code
if (statusCode === 401 || statusCode === 403) {
throw new VertexAuthError(`Authentication failed: ${errorMessage}`);
} else if (statusCode === 400) {
throw new VertexConfigError(`Invalid request: ${errorMessage}`);
} else {
throw new VertexApiError(
`API error (${statusCode}): ${errorMessage}`,
statusCode
);
}
}
// Generic error handling
throw new Error(`Vertex AI ${operation} failed: ${error.message}`);
}
}

View File

@@ -1,181 +1,39 @@
/** /**
* google.js * google.js
* AI provider implementation for Google AI models (e.g., Gemini) using Vercel AI SDK. * AI provider implementation for Google AI models using Vercel AI SDK.
*/ */
// import { GoogleGenerativeAI } from '@ai-sdk/google'; // Incorrect import import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { createGoogleGenerativeAI } from '@ai-sdk/google'; // Correct import for customization import { BaseAIProvider } from './base-provider.js';
import { generateText, streamText, generateObject } from 'ai'; // Import from main 'ai' package
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
// Consider making model configurable via config-manager.js later export class GoogleAIProvider extends BaseAIProvider {
const DEFAULT_MODEL = 'gemini-2.5-pro-exp-03-25'; // Or a suitable default constructor() {
const DEFAULT_TEMPERATURE = 0.2; // Or a suitable default super();
this.name = 'Google';
}
/**
* Creates and returns a Google AI client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - Google API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} Google AI client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
function getClient(apiKey, baseUrl) {
if (!apiKey) { if (!apiKey) {
throw new Error('Google API key is required.'); throw new Error('Google API key is required.');
} }
return createGoogleGenerativeAI({ return createGoogleGenerativeAI({
apiKey: apiKey,
...(baseUrl && { baseURL: baseUrl })
});
}
/**
* Generates text using a Google AI model.
*
* @param {object} params - Parameters for the generation.
* @param {string} params.apiKey - Google API Key.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history (system/user prompts).
* @param {number} [params.maxTokens] - Optional max tokens.
* @returns {Promise<string>} The generated text content.
* @throws {Error} If API key is missing or API call fails.
*/
async function generateGoogleText({
apiKey, apiKey,
modelId = DEFAULT_MODEL, ...(baseURL && { baseURL })
temperature = DEFAULT_TEMPERATURE,
messages,
maxTokens,
baseUrl
}) {
if (!apiKey) {
throw new Error('Google API key is required.');
}
log('info', `Generating text with Google model: ${modelId}`);
try {
const googleProvider = getClient(apiKey, baseUrl);
const model = googleProvider(modelId);
const result = await generateText({
model,
messages,
temperature,
maxOutputTokens: maxTokens
}); });
// Assuming result structure provides text directly or within a property
// return result.text; // Adjust based on actual SDK response
// Return both text and usage
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log( this.handleError('client initialization', error);
'error',
`Error generating text with Google (${modelId}): ${error.message}`
);
throw error;
} }
} }
/**
* Streams text using a Google AI model.
*
* @param {object} params - Parameters for the streaming.
* @param {string} params.apiKey - Google API Key.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history.
* @param {number} [params.maxTokens] - Optional max tokens.
* @returns {Promise<ReadableStream>} A readable stream of text deltas.
* @throws {Error} If API key is missing or API call fails.
*/
async function streamGoogleText({
apiKey,
modelId = DEFAULT_MODEL,
temperature = DEFAULT_TEMPERATURE,
messages,
maxTokens,
baseUrl
}) {
if (!apiKey) {
throw new Error('Google API key is required.');
} }
log('info', `Streaming text with Google model: ${modelId}`);
try {
const googleProvider = getClient(apiKey, baseUrl);
const model = googleProvider(modelId);
const stream = await streamText({
model,
messages,
temperature,
maxOutputTokens: maxTokens
});
return stream;
} catch (error) {
log(
'error',
`Error streaming text with Google (${modelId}): ${error.message}`
);
throw error;
}
}
/**
* Generates a structured object using a Google AI model.
*
* @param {object} params - Parameters for the object generation.
* @param {string} params.apiKey - Google API Key.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history.
* @param {import('zod').ZodSchema} params.schema - Zod schema for the expected object.
* @param {string} params.objectName - Name for the object generation context.
* @param {number} [params.maxTokens] - Optional max tokens.
* @returns {Promise<object>} The generated object matching the schema.
* @throws {Error} If API key is missing or API call fails.
*/
async function generateGoogleObject({
apiKey,
modelId = DEFAULT_MODEL,
temperature = DEFAULT_TEMPERATURE,
messages,
schema,
objectName, // Note: Vercel SDK might use this differently or not at all
maxTokens,
baseUrl
}) {
if (!apiKey) {
throw new Error('Google API key is required.');
}
log('info', `Generating object with Google model: ${modelId}`);
try {
const googleProvider = getClient(apiKey, baseUrl);
const model = googleProvider(modelId);
const result = await generateObject({
model,
schema,
messages,
temperature,
maxOutputTokens: maxTokens
});
// return object; // Return the parsed object
// Return both object and usage
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`Error generating object with Google (${modelId}): ${error.message}`
);
throw error;
}
}
export { generateGoogleText, streamGoogleText, generateGoogleObject };

15
src/ai-providers/index.js Normal file
View File

@@ -0,0 +1,15 @@
/**
* src/ai-providers/index.js
* Central export point for all AI provider classes
*/
export { AnthropicAIProvider } from './anthropic.js';
export { PerplexityAIProvider } from './perplexity.js';
export { GoogleAIProvider } from './google.js';
export { OpenAIProvider } from './openai.js';
export { XAIProvider } from './xai.js';
export { OpenRouterAIProvider } from './openrouter.js';
export { OllamaAIProvider } from './ollama.js';
export { BedrockAIProvider } from './bedrock.js';
export { AzureProvider } from './azure.js';
export { VertexAIProvider } from './google-vertex.js';

View File

@@ -4,160 +4,39 @@
*/ */
import { createOllama } from 'ollama-ai-provider'; import { createOllama } from 'ollama-ai-provider';
import { log } from '../../scripts/modules/utils.js'; // Import logging utility import { BaseAIProvider } from './base-provider.js';
import { generateObject, generateText, streamText } from 'ai';
// Consider making model configurable via config-manager.js later export class OllamaAIProvider extends BaseAIProvider {
const DEFAULT_MODEL = 'llama3'; // Or a suitable default for Ollama constructor() {
const DEFAULT_TEMPERATURE = 0.2; super();
this.name = 'Ollama';
}
/**
* Override auth validation - Ollama doesn't require API keys
* @param {object} params - Parameters to validate
*/
validateAuth(_params) {
// Ollama runs locally and doesn't require API keys
// No authentication validation needed
}
/**
* Creates and returns an Ollama client instance.
* @param {object} params - Parameters for client initialization
* @param {string} [params.baseURL] - Optional Ollama base URL (defaults to http://localhost:11434)
* @returns {Function} Ollama client function
* @throws {Error} If initialization fails
*/
getClient(params) {
try {
const { baseURL } = params;
function getClient(baseUrl) {
// baseUrl is optional, defaults to http://localhost:11434
return createOllama({ return createOllama({
baseUrl: baseUrl || undefined ...(baseURL && { baseURL })
}); });
}
/**
* Generates text using an Ollama model.
*
* @param {object} params - Parameters for the generation.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history (system/user prompts).
* @param {number} [params.maxTokens] - Optional max tokens.
* @param {string} [params.baseUrl] - Optional Ollama base URL.
* @returns {Promise<string>} The generated text content.
* @throws {Error} If API call fails.
*/
async function generateOllamaText({
modelId = DEFAULT_MODEL,
messages,
maxTokens,
temperature = DEFAULT_TEMPERATURE,
baseUrl
}) {
log('info', `Generating text with Ollama model: ${modelId}`);
try {
const client = getClient(baseUrl);
const result = await generateText({
model: client(modelId),
messages,
maxTokens,
temperature
});
log('debug', `Ollama generated text: ${result.text}`);
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log( this.handleError('client initialization', error);
'error',
`Error generating text with Ollama (${modelId}): ${error.message}`
);
throw error;
} }
} }
/**
* Streams text using an Ollama model.
*
* @param {object} params - Parameters for the streaming.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history.
* @param {number} [params.maxTokens] - Optional max tokens.
* @param {string} [params.baseUrl] - Optional Ollama base URL.
* @returns {Promise<ReadableStream>} A readable stream of text deltas.
* @throws {Error} If API call fails.
*/
async function streamOllamaText({
modelId = DEFAULT_MODEL,
temperature = DEFAULT_TEMPERATURE,
messages,
maxTokens,
baseUrl
}) {
log('info', `Streaming text with Ollama model: ${modelId}`);
try {
const ollama = getClient(baseUrl);
const stream = await streamText({
model: modelId,
messages,
temperature,
maxTokens
});
return stream;
} catch (error) {
log(
'error',
`Error streaming text with Ollama (${modelId}): ${error.message}`
);
throw error;
} }
}
/**
* Generates a structured object using an Ollama model using the Vercel AI SDK's generateObject.
*
* @param {object} params - Parameters for the object generation.
* @param {string} params.modelId - Specific model ID to use (overrides default).
* @param {number} params.temperature - Generation temperature.
* @param {Array<object>} params.messages - The conversation history.
* @param {import('zod').ZodSchema} params.schema - Zod schema for the expected object.
* @param {string} params.objectName - Name for the object generation context.
* @param {number} [params.maxTokens] - Optional max tokens.
* @param {number} [params.maxRetries] - Max retries for validation/generation.
* @param {string} [params.baseUrl] - Optional Ollama base URL.
* @returns {Promise<object>} The generated object matching the schema.
* @throws {Error} If generation or validation fails.
*/
async function generateOllamaObject({
modelId = DEFAULT_MODEL,
temperature = DEFAULT_TEMPERATURE,
messages,
schema,
objectName = 'generated_object',
maxTokens,
maxRetries = 3,
baseUrl
}) {
log('info', `Generating object with Ollama model: ${modelId}`);
try {
const ollama = getClient(baseUrl);
const result = await generateObject({
model: ollama(modelId),
mode: 'tool',
schema: schema,
messages: messages,
tool: {
name: objectName,
description: `Generate a ${objectName} based on the prompt.`
},
maxOutputTokens: maxTokens,
temperature: temperature,
maxRetries: maxRetries
});
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`Ollama generateObject ('${objectName}') failed: ${error.message}`
);
throw error;
}
}
export { generateOllamaText, streamOllamaText, generateOllamaObject };

View File

@@ -1,199 +1,39 @@
import { createOpenAI } from '@ai-sdk/openai'; // Using openai provider from Vercel AI SDK /**
import { generateObject, generateText } from 'ai'; // Import necessary functions from 'ai' * openai.js
import { log } from '../../scripts/modules/utils.js'; * AI provider implementation for OpenAI models using Vercel AI SDK.
*/
import { createOpenAI } from '@ai-sdk/openai';
import { BaseAIProvider } from './base-provider.js';
export class OpenAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'OpenAI';
}
/**
* Creates and returns an OpenAI client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - OpenAI API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} OpenAI client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
function getClient(apiKey, baseUrl) {
if (!apiKey) { if (!apiKey) {
throw new Error('OpenAI API key is required.'); throw new Error('OpenAI API key is required.');
} }
return createOpenAI({ return createOpenAI({
apiKey: apiKey,
...(baseUrl && { baseURL: baseUrl })
});
}
/**
* Generates text using OpenAI models via Vercel AI SDK.
*
* @param {object} params - Parameters including apiKey, modelId, messages, maxTokens, temperature, baseUrl.
* @returns {Promise<object>} The generated text content and usage.
* @throws {Error} If API call fails.
*/
export async function generateOpenAIText(params) {
const { apiKey, modelId, messages, maxTokens, temperature, baseUrl } = params;
log('debug', `generateOpenAIText called with model: ${modelId}`);
if (!apiKey) {
throw new Error('OpenAI API key is required.');
}
if (!modelId) {
throw new Error('OpenAI Model ID is required.');
}
if (!messages || !Array.isArray(messages) || messages.length === 0) {
throw new Error('Invalid or empty messages array provided for OpenAI.');
}
const openaiClient = getClient(apiKey, baseUrl);
try {
const result = await generateText({
model: openaiClient(modelId),
messages,
maxTokens,
temperature
});
if (!result || !result.text) {
log(
'warn',
'OpenAI generateText response did not contain expected content.',
{ result }
);
throw new Error('Failed to extract content from OpenAI response.');
}
log(
'debug',
`OpenAI generateText completed successfully for model: ${modelId}`
);
return {
text: result.text.trim(),
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`Error in generateOpenAIText (Model: ${modelId}): ${error.message}`,
{ error }
);
throw new Error(
`OpenAI API error during text generation: ${error.message}`
);
}
}
/**
* Streams text using OpenAI models via Vercel AI SDK.
*
* @param {object} params - Parameters including apiKey, modelId, messages, maxTokens, temperature, baseUrl.
* @returns {Promise<ReadableStream>} A readable stream of text deltas.
* @throws {Error} If API call fails.
*/
export async function streamOpenAIText(params) {
const { apiKey, modelId, messages, maxTokens, temperature, baseUrl } = params;
log('debug', `streamOpenAIText called with model: ${modelId}`);
if (!apiKey) {
throw new Error('OpenAI API key is required.');
}
if (!modelId) {
throw new Error('OpenAI Model ID is required.');
}
if (!messages || !Array.isArray(messages) || messages.length === 0) {
throw new Error(
'Invalid or empty messages array provided for OpenAI streaming.'
);
}
const openaiClient = getClient(apiKey, baseUrl);
try {
const stream = await openaiClient.chat.stream(messages, {
model: modelId,
max_tokens: maxTokens,
temperature
});
log(
'debug',
`OpenAI streamText initiated successfully for model: ${modelId}`
);
return stream;
} catch (error) {
log(
'error',
`Error initiating OpenAI stream (Model: ${modelId}): ${error.message}`,
{ error }
);
throw new Error(
`OpenAI API error during streaming initiation: ${error.message}`
);
}
}
/**
* Generates structured objects using OpenAI models via Vercel AI SDK.
*
* @param {object} params - Parameters including apiKey, modelId, messages, schema, objectName, maxTokens, temperature, baseUrl.
* @returns {Promise<object>} The generated object matching the schema and usage.
* @throws {Error} If API call fails or object generation fails.
*/
export async function generateOpenAIObject(params) {
const {
apiKey, apiKey,
modelId, ...(baseURL && { baseURL })
messages,
schema,
objectName,
maxTokens,
temperature,
baseUrl
} = params;
log(
'debug',
`generateOpenAIObject called with model: ${modelId}, object: ${objectName}`
);
if (!apiKey) throw new Error('OpenAI API key is required.');
if (!modelId) throw new Error('OpenAI Model ID is required.');
if (!messages || !Array.isArray(messages) || messages.length === 0)
throw new Error('Invalid messages array for OpenAI object generation.');
if (!schema)
throw new Error('Schema is required for OpenAI object generation.');
if (!objectName)
throw new Error('Object name is required for OpenAI object generation.');
const openaiClient = getClient(apiKey, baseUrl);
try {
const result = await generateObject({
model: openaiClient(modelId),
schema: schema,
messages: messages,
mode: 'tool',
maxTokens: maxTokens,
temperature: temperature
}); });
log(
'debug',
`OpenAI generateObject completed successfully for model: ${modelId}`
);
if (!result || typeof result.object === 'undefined') {
log(
'warn',
'OpenAI generateObject response did not contain expected object.',
{ result }
);
throw new Error('Failed to extract object from OpenAI response.');
}
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log( this.handleError('client initialization', error);
'error', }
`Error in generateOpenAIObject (Model: ${modelId}, Object: ${objectName}): ${error.message}`,
{ error }
);
throw new Error(
`OpenAI API error during object generation: ${error.message}`
);
} }
} }

View File

@@ -1,246 +1,39 @@
import { createOpenRouter } from '@openrouter/ai-sdk-provider'; /**
import { generateText, streamText, generateObject } from 'ai'; * openrouter.js
import { log } from '../../scripts/modules/utils.js'; // Assuming utils.js is in scripts/modules * AI provider implementation for OpenRouter models using Vercel AI SDK.
*/
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { BaseAIProvider } from './base-provider.js';
export class OpenRouterAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'OpenRouter';
}
/**
* Creates and returns an OpenRouter client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - OpenRouter API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} OpenRouter client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
if (!apiKey) {
throw new Error('OpenRouter API key is required.');
}
function getClient(apiKey, baseUrl) {
if (!apiKey) throw new Error('OpenRouter API key is required.');
return createOpenRouter({ return createOpenRouter({
apiKey, apiKey,
...(baseUrl && { baseURL: baseUrl }) ...(baseURL && { baseURL })
}); });
}
/**
* Generates text using an OpenRouter chat model.
*
* @param {object} params - Parameters for the text generation.
* @param {string} params.apiKey - OpenRouter API key.
* @param {string} params.modelId - The OpenRouter model ID (e.g., 'anthropic/claude-3.5-sonnet').
* @param {Array<object>} params.messages - Array of message objects (system, user, assistant).
* @param {number} [params.maxTokens] - Maximum tokens to generate.
* @param {number} [params.temperature] - Sampling temperature.
* @param {string} [params.baseUrl] - Base URL for the OpenRouter API.
* @returns {Promise<string>} The generated text content.
* @throws {Error} If the API call fails.
*/
async function generateOpenRouterText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl,
...rest // Capture any other Vercel AI SDK compatible parameters
}) {
if (!apiKey) throw new Error('OpenRouter API key is required.');
if (!modelId) throw new Error('OpenRouter model ID is required.');
if (!messages || messages.length === 0)
throw new Error('Messages array cannot be empty.');
try {
const openrouter = getClient(apiKey, baseUrl);
const model = openrouter.chat(modelId); // Assuming chat model
// Capture the full result from generateText
const result = await generateText({
model,
messages,
maxTokens,
temperature,
...rest // Pass any additional parameters
});
// Check if text and usage are present
if (!result || typeof result.text !== 'string') {
log(
'warn',
`OpenRouter generateText for model ${modelId} did not return expected text.`,
{ result }
);
throw new Error('Failed to extract text from OpenRouter response.');
}
if (!result.usage) {
log(
'warn',
`OpenRouter generateText for model ${modelId} did not return usage data.`,
{ result }
);
// Decide if this is critical. For now, let it pass but telemetry will be incomplete.
}
log('debug', `OpenRouter generateText completed for model ${modelId}`);
// Return text and usage
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
let detailedMessage = `OpenRouter generateText failed for model ${modelId}: ${error.message}`; this.handleError('client initialization', error);
if (error.cause) {
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
}
// Vercel AI SDK sometimes wraps the actual API error response in error.data
if (error.data) {
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
}
// Log the original error object for full context if needed for deeper debugging
log('error', detailedMessage, { originalErrorObject: error });
throw error;
} }
} }
/**
* Streams text using an OpenRouter chat model.
*
* @param {object} params - Parameters for the text streaming.
* @param {string} params.apiKey - OpenRouter API key.
* @param {string} params.modelId - The OpenRouter model ID (e.g., 'anthropic/claude-3.5-sonnet').
* @param {Array<object>} params.messages - Array of message objects (system, user, assistant).
* @param {number} [params.maxTokens] - Maximum tokens to generate.
* @param {number} [params.temperature] - Sampling temperature.
* @param {string} [params.baseUrl] - Base URL for the OpenRouter API.
* @returns {Promise<ReadableStream<string>>} A readable stream of text deltas.
* @throws {Error} If the API call fails.
*/
async function streamOpenRouterText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl,
...rest
}) {
if (!apiKey) throw new Error('OpenRouter API key is required.');
if (!modelId) throw new Error('OpenRouter model ID is required.');
if (!messages || messages.length === 0)
throw new Error('Messages array cannot be empty.');
try {
const openrouter = getClient(apiKey, baseUrl);
const model = openrouter.chat(modelId);
// Directly return the stream from the Vercel AI SDK function
const stream = await streamText({
model,
messages,
maxTokens,
temperature,
...rest
});
return stream;
} catch (error) {
let detailedMessage = `OpenRouter streamText failed for model ${modelId}: ${error.message}`;
if (error.cause) {
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
} }
if (error.data) {
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
}
log('error', detailedMessage, { originalErrorObject: error });
throw error;
}
}
/**
* Generates a structured object using an OpenRouter chat model.
*
* @param {object} params - Parameters for object generation.
* @param {string} params.apiKey - OpenRouter API key.
* @param {string} params.modelId - The OpenRouter model ID.
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the expected object.
* @param {Array<object>} params.messages - Array of message objects.
* @param {string} [params.objectName='generated_object'] - Name for object/tool.
* @param {number} [params.maxRetries=3] - Max retries for object generation.
* @param {number} [params.maxTokens] - Maximum tokens.
* @param {number} [params.temperature] - Temperature.
* @param {string} [params.baseUrl] - Base URL for the OpenRouter API.
* @returns {Promise<object>} The generated object matching the schema.
* @throws {Error} If the API call fails or validation fails.
*/
async function generateOpenRouterObject({
apiKey,
modelId,
schema,
messages,
objectName = 'generated_object',
maxRetries = 3,
maxTokens,
temperature,
baseUrl,
...rest
}) {
if (!apiKey) throw new Error('OpenRouter API key is required.');
if (!modelId) throw new Error('OpenRouter model ID is required.');
if (!schema) throw new Error('Zod schema is required for object generation.');
if (!messages || messages.length === 0)
throw new Error('Messages array cannot be empty.');
try {
const openrouter = getClient(apiKey, baseUrl);
const model = openrouter.chat(modelId);
// Capture the full result from generateObject
const result = await generateObject({
model,
schema,
mode: 'tool',
tool: {
name: objectName,
description: `Generate an object conforming to the ${objectName} schema.`,
parameters: schema
},
messages,
maxTokens,
temperature,
maxRetries,
...rest
});
// Check if object and usage are present
if (!result || typeof result.object === 'undefined') {
log(
'warn',
`OpenRouter generateObject for model ${modelId} did not return expected object.`,
{ result }
);
throw new Error('Failed to extract object from OpenRouter response.');
}
if (!result.usage) {
log(
'warn',
`OpenRouter generateObject for model ${modelId} did not return usage data.`,
{ result }
);
}
log('debug', `OpenRouter generateObject completed for model ${modelId}`);
// Return object and usage
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
let detailedMessage = `OpenRouter generateObject failed for model ${modelId}: ${error.message}`;
if (error.cause) {
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
}
if (error.data) {
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
}
log('error', detailedMessage, { originalErrorObject: error });
throw error;
}
}
export {
generateOpenRouterText,
streamOpenRouterText,
generateOpenRouterObject
};

View File

@@ -1,181 +1,39 @@
/** /**
* src/ai-providers/perplexity.js * perplexity.js
* * AI provider implementation for Perplexity models using Vercel AI SDK.
* Implementation for interacting with Perplexity models
* using the Vercel AI SDK.
*/ */
import { createPerplexity } from '@ai-sdk/perplexity';
import { generateText, streamText, generateObject, streamObject } from 'ai';
import { log } from '../../scripts/modules/utils.js';
// --- Client Instantiation --- import { createPerplexity } from '@ai-sdk/perplexity';
// Similar to Anthropic, this expects the resolved API key to be passed in. import { BaseAIProvider } from './base-provider.js';
function getClient(apiKey, baseUrl) {
export class PerplexityAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Perplexity';
}
/**
* Creates and returns a Perplexity client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - Perplexity API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} Perplexity client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
if (!apiKey) { if (!apiKey) {
throw new Error('Perplexity API key is required.'); throw new Error('Perplexity API key is required.');
} }
return createPerplexity({ return createPerplexity({
apiKey: apiKey,
...(baseUrl && { baseURL: baseUrl })
});
}
// --- Standardized Service Function Implementations ---
/**
* Generates text using a Perplexity model.
*
* @param {object} params - Parameters for the text generation.
* @param {string} params.apiKey - The Perplexity API key.
* @param {string} params.modelId - The specific Perplexity model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - Base URL for the Perplexity API.
* @returns {Promise<string>} The generated text content.
* @throws {Error} If the API call fails.
*/
export async function generatePerplexityText({
apiKey, apiKey,
modelId, baseURL: baseURL || 'https://api.perplexity.ai'
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Generating Perplexity text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
const result = await generateText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
}); });
log(
'debug',
`Perplexity generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log('error', `Perplexity generateText failed: ${error.message}`); this.handleError('client initialization', error);
throw error;
} }
} }
/**
* Streams text using a Perplexity model.
*
* @param {object} params - Parameters for the text streaming.
* @param {string} params.apiKey - The Perplexity API key.
* @param {string} params.modelId - The specific Perplexity model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - Base URL for the Perplexity API.
* @returns {Promise<object>} The full stream result object from the Vercel AI SDK.
* @throws {Error} If the API call fails to initiate the stream.
*/
export async function streamPerplexityText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Streaming Perplexity text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
const stream = await streamText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
});
return stream;
} catch (error) {
log('error', `Perplexity streamText failed: ${error.message}`);
throw error;
} }
}
/**
* Generates a structured object using a Perplexity model.
* Note: Perplexity API might not directly support structured object generation
* in the same way as OpenAI or Anthropic. This function might need
* adjustments or might not be feasible depending on the model's capabilities
* and the Vercel AI SDK's support for Perplexity in this context.
*
* @param {object} params - Parameters for object generation.
* @param {string} params.apiKey - The Perplexity API key.
* @param {string} params.modelId - The specific Perplexity model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the object.
* @param {string} params.objectName - A name for the object/tool.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {number} [params.maxRetries] - Max retries for validation/generation.
* @param {string} [params.baseUrl] - Base URL for the Perplexity API.
* @returns {Promise<object>} The generated object matching the schema.
* @throws {Error} If generation or validation fails or is unsupported.
*/
export async function generatePerplexityObject({
apiKey,
modelId,
messages,
schema,
objectName = 'generated_object',
maxTokens,
temperature,
maxRetries = 1,
baseUrl
}) {
log(
'debug',
`Attempting to generate Perplexity object ('${objectName}') with model: ${modelId}`
);
log(
'warn',
'generateObject support for Perplexity might be limited or experimental.'
);
try {
const client = getClient(apiKey, baseUrl);
const result = await generateObject({
model: client(modelId),
schema: schema,
messages: messages,
maxTokens: maxTokens,
temperature: temperature,
maxRetries: maxRetries
});
log(
'debug',
`Perplexity generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`Perplexity generateObject ('${objectName}') failed: ${error.message}`
);
throw new Error(
`Failed to generate object with Perplexity: ${error.message}. Structured output might not be fully supported.`
);
}
}
// TODO: Implement streamPerplexityObject if needed and feasible.

View File

@@ -1,178 +1,39 @@
/** /**
* src/ai-providers/xai.js * xai.js
* * AI provider implementation for xAI models using Vercel AI SDK.
* Implementation for interacting with xAI models (e.g., Grok)
* using the Vercel AI SDK.
*/ */
import { createXai } from '@ai-sdk/xai';
import { generateText, streamText, generateObject } from 'ai'; // Only import what's used
import { log } from '../../scripts/modules/utils.js'; // Assuming utils is accessible
// --- Client Instantiation --- import { createXai } from '@ai-sdk/xai';
function getClient(apiKey, baseUrl) { import { BaseAIProvider } from './base-provider.js';
export class XAIProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'xAI';
}
/**
* Creates and returns an xAI client instance.
* @param {object} params - Parameters for client initialization
* @param {string} params.apiKey - xAI API key
* @param {string} [params.baseURL] - Optional custom API endpoint
* @returns {Function} xAI client function
* @throws {Error} If API key is missing or initialization fails
*/
getClient(params) {
try {
const { apiKey, baseURL } = params;
if (!apiKey) { if (!apiKey) {
throw new Error('xAI API key is required.'); throw new Error('xAI API key is required.');
} }
return createXai({ return createXai({
apiKey: apiKey,
...(baseUrl && { baseURL: baseUrl })
});
}
// --- Standardized Service Function Implementations ---
/**
* Generates text using an xAI model.
*
* @param {object} params - Parameters for the text generation.
* @param {string} params.apiKey - The xAI API key.
* @param {string} params.modelId - The specific xAI model ID (e.g., 'grok-3').
* @param {Array<object>} params.messages - The messages array (e.g., [{ role: 'user', content: '...' }]).
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - The base URL for the xAI API.
* @returns {Promise<object>} The generated text content and usage.
* @throws {Error} If the API call fails.
*/
export async function generateXaiText({
apiKey, apiKey,
modelId, baseURL: baseURL || 'https://api.x.ai/v1'
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Generating xAI text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
const result = await generateText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
}); });
log(
'debug',
`xAI generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
// Return text and usage
return {
text: result.text,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) { } catch (error) {
log('error', `xAI generateText failed: ${error.message}`); this.handleError('client initialization', error);
throw error;
} }
} }
/**
* Streams text using an xAI model.
*
* @param {object} params - Parameters for the text streaming.
* @param {string} params.apiKey - The xAI API key.
* @param {string} params.modelId - The specific xAI model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {string} [params.baseUrl] - The base URL for the xAI API.
* @returns {Promise<object>} The full stream result object from the Vercel AI SDK.
* @throws {Error} If the API call fails to initiate the stream.
*/
export async function streamXaiText({
apiKey,
modelId,
messages,
maxTokens,
temperature,
baseUrl
}) {
log('debug', `Streaming xAI text with model: ${modelId}`);
try {
const client = getClient(apiKey, baseUrl);
const stream = await streamText({
model: client(modelId),
messages: messages,
maxTokens: maxTokens,
temperature: temperature
});
return stream;
} catch (error) {
log('error', `xAI streamText failed: ${error.message}`, error.stack);
throw error;
}
}
/**
* Generates a structured object using an xAI model.
* Note: Based on search results, xAI models do not currently support Object Generation.
* This function is included for structural consistency but will likely fail if called.
*
* @param {object} params - Parameters for object generation.
* @param {string} params.apiKey - The xAI API key.
* @param {string} params.modelId - The specific xAI model ID.
* @param {Array<object>} params.messages - The messages array.
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the object.
* @param {string} params.objectName - A name for the object/tool.
* @param {number} [params.maxTokens] - Maximum tokens for the response.
* @param {number} [params.temperature] - Temperature for generation.
* @param {number} [params.maxRetries] - Max retries for validation/generation.
* @param {string} [params.baseUrl] - The base URL for the xAI API.
* @returns {Promise<object>} The generated object matching the schema and its usage.
* @throws {Error} If generation or validation fails.
*/
export async function generateXaiObject({
apiKey,
modelId,
messages,
schema,
objectName = 'generated_xai_object',
maxTokens,
temperature,
maxRetries = 3,
baseUrl
}) {
log(
'warn',
`Attempting to generate xAI object ('${objectName}') with model: ${modelId}. This may not be supported by the provider.`
);
try {
const client = getClient(apiKey, baseUrl);
const result = await generateObject({
model: client(modelId),
// Note: mode might need adjustment if xAI ever supports object generation differently
mode: 'tool',
schema: schema,
messages: messages,
tool: {
name: objectName,
description: `Generate a ${objectName} based on the prompt.`,
parameters: schema
},
maxTokens: maxTokens,
temperature: temperature,
maxRetries: maxRetries
});
log(
'debug',
`xAI generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
);
// Return object and usage
return {
object: result.object,
usage: {
inputTokens: result.usage.promptTokens,
outputTokens: result.usage.completionTokens
}
};
} catch (error) {
log(
'error',
`xAI generateObject ('${objectName}') failed: ${error.message}. (Likely unsupported by provider)`
);
throw error;
}
} }

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