Compare commits
57 Commits
parse-prd-
...
gateway
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16e6326010 | ||
|
|
a9c1b6bbcf | ||
|
|
f12fc476d3 | ||
|
|
31178e2f43 | ||
|
|
3fa3be4e1b | ||
|
|
685365270d | ||
|
|
58aa0992f6 | ||
|
|
2819be51d3 | ||
|
|
9b87dd23de | ||
|
|
769275b3bc | ||
|
|
4e9d58a1b0 | ||
|
|
e573db3b3b | ||
|
|
75b7b93fa4 | ||
|
|
6ec3a10083 | ||
|
|
8ad31ac5eb | ||
|
|
2773e347f9 | ||
|
|
bfc39dd377 | ||
|
|
9e6c190af3 | ||
|
|
ab64437ad2 | ||
|
|
cb95a07771 | ||
|
|
c096f3fe9d | ||
|
|
b6a3b8d385 | ||
|
|
78397fe0be | ||
|
|
f9b89dc25c | ||
|
|
ca69e1294f | ||
|
|
ce09d9cdc3 | ||
|
|
669b744ced | ||
|
|
f058543888 | ||
|
|
b5c2cf47b0 | ||
|
|
acd5c1ea3d | ||
|
|
682b54e103 | ||
|
|
6a8a68e1a3 | ||
|
|
80735f9e60 | ||
|
|
ac36e2497e | ||
|
|
1d4b80fe6f | ||
|
|
48732d5423 | ||
|
|
2d520de269 | ||
|
|
023f51c579 | ||
|
|
1e020023ed | ||
|
|
325f5a2aa3 | ||
|
|
de46bfd84b | ||
|
|
cc26c36366 | ||
|
|
15ad34928d | ||
|
|
f74d639110 | ||
|
|
de58e9ede5 | ||
|
|
947541e4ee | ||
|
|
275cd55da7 | ||
|
|
67ac212973 | ||
|
|
235371ff47 | ||
|
|
b60e1cf835 | ||
|
|
d1e45ff50e | ||
|
|
1513858da4 | ||
|
|
59dcf4bd64 | ||
|
|
a09ba021c5 | ||
|
|
e906166141 | ||
|
|
86d8f00af8 | ||
|
|
c882f89a8c |
@@ -1,15 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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
|
||||
44
.changeset/bright-windows-sing.md
Normal file
44
.changeset/bright-windows-sing.md
Normal 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.
|
||||
13
.changeset/cold-pears-poke.md
Normal file
13
.changeset/cold-pears-poke.md
Normal 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.
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
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.
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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.
|
||||
5
.changeset/hungry-geese-work.md
Normal file
5
.changeset/hungry-geese-work.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add AWS bedrock support
|
||||
13
.changeset/itchy-taxes-sip.md
Normal file
13
.changeset/itchy-taxes-sip.md
Normal 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
|
||||
5
.changeset/lemon-apes-sort.md
Normal file
5
.changeset/lemon-apes-sort.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add support for Azure
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
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."
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fixes issue with force/append flag combinations for parse-prd.
|
||||
17
.changeset/moody-results-clean.md
Normal file
17
.changeset/moody-results-clean.md
Normal 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.
|
||||
5
.changeset/new-colts-flow.md
Normal file
5
.changeset/new-colts-flow.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"task-master-ai": minor
|
||||
---
|
||||
|
||||
Increased minimum required node version to > 18 (was > 14)
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
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."
|
||||
5
.changeset/plain-bottles-stand.md
Normal file
5
.changeset/plain-bottles-stand.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Renamed baseUrl to baseURL
|
||||
5
.changeset/shaggy-rice-exist.md
Normal file
5
.changeset/shaggy-rice-exist.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4
|
||||
7
.changeset/sharp-flies-call.md
Normal file
7
.changeset/sharp-flies-call.md
Normal 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.
|
||||
19
.changeset/stale-bats-sin.md
Normal file
19
.changeset/stale-bats-sin.md
Normal 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.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
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.
|
||||
5
.changeset/tidy-seals-rule.md
Normal file
5
.changeset/tidy-seals-rule.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix add-task MCP command causing an error
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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
|
||||
@@ -1,19 +1,44 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"task-master-ai": {
|
||||
"command": "node",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
"mcpServers": {
|
||||
"task-master-ai-tm": {
|
||||
"command": "node",
|
||||
"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": {
|
||||
"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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"env": {
|
||||
"TASKMASTER_TELEMETRY_API_KEY": "339a81c9-5b9c-4d60-92d8-cba2ee2a8cc3",
|
||||
"TASKMASTER_TELEMETRY_USER_EMAIL": "user_1748640077834@taskmaster.dev"
|
||||
}
|
||||
}
|
||||
@@ -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):
|
||||
- **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`.
|
||||
- **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:**
|
||||
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
|
||||
- **`google`**: Requires `GOOGLE_API_KEY`.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
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
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 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**: 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**: 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**: 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.
|
||||
|
||||
@@ -39,12 +39,12 @@ alwaysApply: false
|
||||
- **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)):
|
||||
- Exports `generateTextService`, `generateObjectService`.
|
||||
- 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.
|
||||
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
|
||||
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
|
||||
|
||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
|
||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers): Provider-Specific Implementations**
|
||||
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
|
||||
- **Responsibilities**: Interact directly with Vercel AI SDK adapters.
|
||||
|
||||
@@ -63,7 +63,7 @@ alwaysApply: false
|
||||
- API Key Resolution (`resolveEnvVariable`).
|
||||
- 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.
|
||||
- **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.
|
||||
|
||||
@@ -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
|
||||
|
||||
- **Exception Management**:
|
||||
|
||||
268
.cursor/rules/context_gathering.mdc
Normal file
268
.cursor/rules/context_gathering.mdc
Normal 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.
|
||||
367
.cursor/rules/git_workflow.mdc
Normal file
367
.cursor/rules/git_workflow.mdc
Normal 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)
|
||||
@@ -24,17 +24,22 @@ alwaysApply: false
|
||||
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)).
|
||||
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).
|
||||
- Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`).
|
||||
- Call the service function.
|
||||
- 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.
|
||||
3. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc).
|
||||
4. **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. **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).
|
||||
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.
|
||||
5. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
|
||||
6. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
|
||||
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.
|
||||
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
|
||||
|
||||
|
||||
@@ -112,9 +112,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* **CLI Command:** `task-master show [id] [options]`
|
||||
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.`
|
||||
* **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>`)
|
||||
* **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.
|
||||
|
||||
---
|
||||
|
||||
@@ -366,6 +367,43 @@ 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
|
||||
|
||||
### 24. Generate Task Files (`generate`)
|
||||
|
||||
408
.cursor/rules/tdd_workflow.mdc
Normal file
408
.cursor/rules/tdd_workflow.mdc
Normal 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)
|
||||
@@ -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.
|
||||
@@ -46,7 +46,7 @@ alwaysApply: false
|
||||
- **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).
|
||||
- **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).
|
||||
|
||||
## 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: Respect the configured log level
|
||||
- ❌ 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**:
|
||||
- ✅ 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.
|
||||
@@ -7,3 +7,9 @@ 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
|
||||
|
||||
# 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
40
.github/workflows/update-models-md.yml
vendored
Normal 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
33
.gitignore
vendored
@@ -19,13 +19,26 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
tests/e2e/_runs/
|
||||
tests/e2e/log/
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
coverage/
|
||||
*.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
|
||||
.npm
|
||||
|
||||
@@ -64,3 +77,17 @@ dev-debug.log
|
||||
|
||||
# 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,7 +0,0 @@
|
||||
# Ignore artifacts:
|
||||
build
|
||||
coverage
|
||||
.changeset
|
||||
tasks
|
||||
package-lock.json
|
||||
tests/fixture/*.json
|
||||
11
.prettierrc
11
.prettierrc
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"printWidth": 80,
|
||||
"tabWidth": 2,
|
||||
"useTabs": true,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -1,32 +1,37 @@
|
||||
{
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-sonnet-4-20250514",
|
||||
"maxTokens": 50000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 128000,
|
||||
"temperature": 0.2
|
||||
}
|
||||
},
|
||||
"global": {
|
||||
"logLevel": "info",
|
||||
"debug": false,
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"userId": "1234567890",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
}
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-sonnet-4-20250514",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-5-sonnet-20241022",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2
|
||||
}
|
||||
},
|
||||
"global": {
|
||||
"logLevel": "info",
|
||||
"debug": false,
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseURL": "http://localhost:11434/api",
|
||||
"azureBaseURL": "https://your-endpoint.azure.com/"
|
||||
},
|
||||
"account": {
|
||||
"userId": "1234567890",
|
||||
"email": "",
|
||||
"mode": "byok",
|
||||
"telemetryEnabled": true
|
||||
}
|
||||
}
|
||||
174
CHANGELOG.md
174
CHANGELOG.md
@@ -1,5 +1,179 @@
|
||||
# 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
|
||||
|
||||
### Minor Changes
|
||||
|
||||
335
CONTRIBUTING.md
Normal file
335
CONTRIBUTING.md
Normal 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.
|
||||
96
README.md
96
README.md
@@ -28,13 +28,22 @@ Using the research model is optional but highly recommended. You will need at le
|
||||
|
||||
## 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` |
|
||||
| **VS Code** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` |
|
||||
|
||||
##### Cursor & Windsurf (`mcpServers`)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"mcpServers": {
|
||||
"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:
|
||||
##### VS Code (`servers` + `type`)
|
||||
|
||||
```
|
||||
Can you please initialize taskmaster-ai into my project?
|
||||
```jsonc
|
||||
{
|
||||
"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 editor’s AI chat pane, say:
|
||||
|
||||
```txt
|
||||
Can you parse my PRD at scripts/prd.txt?
|
||||
What's the next task I should work on?
|
||||
Can you help me implement task 3?
|
||||
Can you help me expand task 4?
|
||||
Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively.
|
||||
```
|
||||
|
||||
[Table of available models](docs/models.md)
|
||||
|
||||
#### 4. Initialize Task Master
|
||||
|
||||
In your editor’s 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: `What’s 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
|
||||
|
||||
#### Installation
|
||||
@@ -112,6 +176,12 @@ task-master list
|
||||
# Show the next task to work on
|
||||
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
|
||||
task-master generate
|
||||
```
|
||||
|
||||
@@ -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/"
|
||||
}
|
||||
}
|
||||
47
biome.json
Normal file
47
biome.json
Normal 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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ Welcome to the Task Master documentation. Use the links below to navigate to the
|
||||
|
||||
## 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
|
||||
|
||||
## Examples & Licensing
|
||||
|
||||
@@ -43,10 +43,28 @@ task-master show <id>
|
||||
# or
|
||||
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)
|
||||
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
|
||||
|
||||
```bash
|
||||
@@ -262,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.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -16,14 +16,14 @@ Taskmaster uses two primary methods for configuration:
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2,
|
||||
"baseUrl": "https://api.anthropic.com/v1"
|
||||
"baseURL": "https://api.anthropic.com/v1"
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1,
|
||||
"baseUrl": "https://api.perplexity.ai/v1"
|
||||
"baseURL": "https://api.perplexity.ai/v1"
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
@@ -38,8 +38,10 @@ Taskmaster uses two primary methods for configuration:
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Your Project Name",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
"ollamaBaseURL": "http://localhost:11434/api",
|
||||
"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.
|
||||
- `PERPLEXITY_API_KEY`: Your Perplexity 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.
|
||||
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
|
||||
- `OPENROUTER_API_KEY`: Your OpenRouter API key.
|
||||
- `XAI_API_KEY`: Your X-AI API key.
|
||||
- **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.
|
||||
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseUrl` for the Azure model role).
|
||||
- **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).
|
||||
- `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.
|
||||
|
||||
@@ -78,6 +83,11 @@ PERPLEXITY_API_KEY=pplx-your-key-here
|
||||
# Optional Endpoint Overrides
|
||||
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
|
||||
# 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
|
||||
@@ -102,3 +112,45 @@ git clone https://github.com/eyaltoledano/claude-task-master.git
|
||||
cd claude-task-master
|
||||
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"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -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?
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
```
|
||||
@@ -109,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`)
|
||||
|
||||
## 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
125
docs/models.md
Normal 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 |
|
||||
131
docs/scripts/models-json-to-markdown.js
Normal file
131
docs/scripts/models-json-to-markdown.js
Normal 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();
|
||||
@@ -198,10 +198,15 @@ Ask the agent to list available tasks:
|
||||
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:
|
||||
|
||||
- Run `task-master list` to see all tasks
|
||||
- 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
|
||||
- Prioritize tasks based on priority level and ID order
|
||||
- Suggest the next task(s) to implement
|
||||
@@ -221,6 +226,21 @@ You can ask:
|
||||
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
|
||||
|
||||
Before marking a task as complete, verify it according to:
|
||||
@@ -423,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?
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
export default {
|
||||
// Use Node.js environment for testing
|
||||
testEnvironment: 'node',
|
||||
// Use Node.js environment for testing
|
||||
testEnvironment: "node",
|
||||
|
||||
// Automatically clear mock calls between every test
|
||||
clearMocks: true,
|
||||
// Automatically clear mock calls between every test
|
||||
clearMocks: true,
|
||||
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: false,
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: false,
|
||||
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: 'coverage',
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: "coverage",
|
||||
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
roots: ['<rootDir>/tests'],
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
roots: ["<rootDir>/tests"],
|
||||
|
||||
// The glob patterns Jest uses to detect test files
|
||||
testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
|
||||
// The glob patterns Jest uses to detect test files
|
||||
testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
|
||||
|
||||
// Transform files
|
||||
transform: {},
|
||||
// Transform files
|
||||
transform: {},
|
||||
|
||||
// Disable transformations for node_modules
|
||||
transformIgnorePatterns: ['/node_modules/'],
|
||||
// Disable transformations for node_modules
|
||||
transformIgnorePatterns: ["/node_modules/"],
|
||||
|
||||
// Set moduleNameMapper for absolute paths
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '<rootDir>/$1'
|
||||
},
|
||||
// Set moduleNameMapper for absolute paths
|
||||
moduleNameMapper: {
|
||||
"^@/(.*)$": "<rootDir>/$1",
|
||||
},
|
||||
|
||||
// Setup module aliases
|
||||
moduleDirectories: ['node_modules', '<rootDir>'],
|
||||
// Setup module aliases
|
||||
moduleDirectories: ["node_modules", "<rootDir>"],
|
||||
|
||||
// Configure test coverage thresholds
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
lines: 80,
|
||||
statements: 80
|
||||
}
|
||||
},
|
||||
// Configure test coverage thresholds
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
lines: 80,
|
||||
statements: 80,
|
||||
},
|
||||
},
|
||||
|
||||
// Generate coverage report in these formats
|
||||
coverageReporters: ['text', 'lcov'],
|
||||
// Generate coverage report in these formats
|
||||
coverageReporters: ["text", "lcov"],
|
||||
|
||||
// Verbose output
|
||||
verbose: true,
|
||||
// Verbose output
|
||||
verbose: true,
|
||||
|
||||
// Setup file
|
||||
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
|
||||
// Setup file
|
||||
setupFilesAfterEnv: ["<rootDir>/tests/setup.js"],
|
||||
};
|
||||
|
||||
@@ -13,10 +13,11 @@ import {
|
||||
* 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')
|
||||
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3')
|
||||
* @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}>}
|
||||
*/
|
||||
@@ -64,12 +65,13 @@ export async function moveTaskDirect(args, log, context = {}) {
|
||||
// Enable silent mode to prevent console output during MCP operation
|
||||
enableSilentMode();
|
||||
|
||||
// Call the core moveTask function, always generate files
|
||||
// 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,
|
||||
true
|
||||
generateFiles
|
||||
);
|
||||
|
||||
// Restore console output
|
||||
@@ -78,7 +80,7 @@ export async function moveTaskDirect(args, log, context = {}) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
movedTask: result.movedTask,
|
||||
...result,
|
||||
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
|
||||
}
|
||||
};
|
||||
|
||||
159
mcp-server/src/core/direct-functions/research.js
Normal file
159
mcp-server/src/core/direct-functions/research.js
Normal 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
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
|
||||
import { nextTaskDirect } from './next-task.js';
|
||||
/**
|
||||
* Direct function wrapper for setTaskStatus with error handling.
|
||||
*
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
*/
|
||||
export async function setTaskStatusDirect(args, log) {
|
||||
// Destructure expected args, including the resolved tasksJsonPath
|
||||
const { tasksJsonPath, id, status } = args;
|
||||
const { tasksJsonPath, id, status, complexityReportPath } = args;
|
||||
try {
|
||||
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
|
||||
};
|
||||
|
||||
// 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;
|
||||
} catch (error) {
|
||||
log.error(`Error setting task status: ${error.message}`);
|
||||
|
||||
@@ -66,32 +66,91 @@ export async function showTaskDirect(args, log) {
|
||||
|
||||
const complexityReport = readComplexityReport(reportPath);
|
||||
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
id,
|
||||
complexityReport,
|
||||
status
|
||||
);
|
||||
// Parse comma-separated IDs
|
||||
const taskIds = id
|
||||
.split(',')
|
||||
.map((taskId) => taskId.trim())
|
||||
.filter((taskId) => taskId.length > 0);
|
||||
|
||||
if (!task) {
|
||||
if (taskIds.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_NOT_FOUND',
|
||||
message: `Task or subtask with ID ${id} not found`
|
||||
code: 'INVALID_TASK_ID',
|
||||
message: 'No valid task IDs provided'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(`Successfully retrieved task ${id}.`);
|
||||
// Handle single task ID (existing behavior)
|
||||
if (taskIds.length === 1) {
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
taskIds[0],
|
||||
complexityReport,
|
||||
status
|
||||
);
|
||||
|
||||
const returnData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
returnData._originalSubtaskCount = originalSubtaskCount;
|
||||
returnData._subtaskFilter = status;
|
||||
if (!task) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_NOT_FOUND',
|
||||
message: `Task or subtask with ID ${taskIds[0]} not found`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(`Successfully retrieved task ${taskIds[0]}.`);
|
||||
|
||||
const returnData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
returnData._originalSubtaskCount = originalSubtaskCount;
|
||||
returnData._subtaskFilter = status;
|
||||
}
|
||||
|
||||
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) {
|
||||
log.error(`Error showing task ${id}: ${error.message}`);
|
||||
return {
|
||||
|
||||
@@ -31,6 +31,7 @@ import { removeTaskDirect } from './direct-functions/remove-task.js';
|
||||
import { initializeProjectDirect } from './direct-functions/initialize-project.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
|
||||
export { findTasksJsonPath } from './utils/path-utils.js';
|
||||
@@ -62,7 +63,8 @@ export const directFunctions = new Map([
|
||||
['removeTaskDirect', removeTaskDirect],
|
||||
['initializeProjectDirect', initializeProjectDirect],
|
||||
['modelsDirect', modelsDirect],
|
||||
['moveTaskDirect', moveTaskDirect]
|
||||
['moveTaskDirect', moveTaskDirect],
|
||||
['researchDirect', researchDirect]
|
||||
]);
|
||||
|
||||
// Re-export all direct function implementations
|
||||
@@ -92,5 +94,6 @@ export {
|
||||
removeTaskDirect,
|
||||
initializeProjectDirect,
|
||||
modelsDirect,
|
||||
moveTaskDirect
|
||||
moveTaskDirect,
|
||||
researchDirect
|
||||
};
|
||||
|
||||
@@ -44,7 +44,11 @@ export function registerShowTaskTool(server) {
|
||||
name: 'get_task',
|
||||
description: 'Get detailed information about a specific task',
|
||||
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
|
||||
.string()
|
||||
.optional()
|
||||
@@ -66,7 +70,7 @@ export function registerShowTaskTool(server) {
|
||||
'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;
|
||||
|
||||
try {
|
||||
@@ -110,7 +114,8 @@ export function registerShowTaskTool(server) {
|
||||
status: status,
|
||||
projectRoot: projectRoot
|
||||
},
|
||||
log
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
|
||||
@@ -29,6 +29,7 @@ import { registerRemoveTaskTool } from './remove-task.js';
|
||||
import { registerInitializeProjectTool } from './initialize-project.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
|
||||
@@ -74,6 +75,9 @@ export function registerTaskMasterTools(server) {
|
||||
registerRemoveDependencyTool(server);
|
||||
registerValidateDependenciesTool(server);
|
||||
registerFixDependenciesTool(server);
|
||||
|
||||
// Group 7: AI-Powered Features
|
||||
registerResearchTool(server);
|
||||
} catch (error) {
|
||||
logger.error(`Error registering Task Master tools: ${error.message}`);
|
||||
throw error;
|
||||
|
||||
@@ -41,83 +41,20 @@ export function registerMoveTaskTool(server) {
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
try {
|
||||
// Find tasks.json path if not provided
|
||||
let tasksJsonPath = args.file;
|
||||
// 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 }
|
||||
);
|
||||
|
||||
if (!tasksJsonPath) {
|
||||
tasksJsonPath = findTasksJsonPath(args, log);
|
||||
}
|
||||
|
||||
// Parse comma-separated IDs
|
||||
const fromIds = args.from.split(',').map((id) => id.trim());
|
||||
const toIds = args.to.split(',').map((id) => id.trim());
|
||||
|
||||
// Validate matching IDs count
|
||||
if (fromIds.length !== toIds.length) {
|
||||
return createErrorResponse(
|
||||
'The number of source and destination IDs must match',
|
||||
'MISMATCHED_ID_COUNT'
|
||||
);
|
||||
}
|
||||
|
||||
// If moving multiple tasks
|
||||
if (fromIds.length > 1) {
|
||||
const results = [];
|
||||
// Move tasks one by one, only generate files on the last move
|
||||
for (let i = 0; i < fromIds.length; i++) {
|
||||
const fromId = fromIds[i];
|
||||
const toId = toIds[i];
|
||||
|
||||
// Skip if source and destination are the same
|
||||
if (fromId === toId) {
|
||||
log.info(`Skipping ${fromId} -> ${toId} (same ID)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const shouldGenerateFiles = i === fromIds.length - 1;
|
||||
const result = await moveTaskDirect(
|
||||
{
|
||||
sourceId: fromId,
|
||||
destinationId: toId,
|
||||
tasksJsonPath,
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
log.error(
|
||||
`Failed to move ${fromId} to ${toId}: ${result.error.message}`
|
||||
);
|
||||
} else {
|
||||
results.push(result.data);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
moves: results,
|
||||
message: `Successfully moved ${results.length} tasks`
|
||||
}
|
||||
};
|
||||
} else {
|
||||
// Moving a single task
|
||||
return handleApiResult(
|
||||
await moveTaskDirect(
|
||||
{
|
||||
sourceId: args.from,
|
||||
destinationId: args.to,
|
||||
tasksJsonPath,
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
),
|
||||
log
|
||||
);
|
||||
}
|
||||
return handleApiResult(result, log);
|
||||
} catch (error) {
|
||||
return createErrorResponse(
|
||||
`Failed to move task: ${error.message}`,
|
||||
|
||||
82
mcp-server/src/tools/research.js
Normal file
82
mcp-server/src/tools/research.js
Normal 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);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -9,8 +9,14 @@ import {
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import {
|
||||
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';
|
||||
|
||||
/**
|
||||
@@ -33,6 +39,12 @@ export function registerSetTaskStatusTool(server) {
|
||||
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||
),
|
||||
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
|
||||
.string()
|
||||
.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(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
id: args.id,
|
||||
status: args.status
|
||||
status: args.status,
|
||||
complexityReportPath
|
||||
},
|
||||
log
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
2425
package-lock.json
generated
2425
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"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.",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
@@ -21,8 +21,8 @@
|
||||
"release": "changeset publish",
|
||||
"inspector": "npx @modelcontextprotocol/inspector node mcp-server/server.js",
|
||||
"mcp-server": "node mcp-server/server.js",
|
||||
"format-check": "prettier --check .",
|
||||
"format": "prettier --write ."
|
||||
"format-check": "biome format .",
|
||||
"format": "biome format . --write"
|
||||
},
|
||||
"keywords": [
|
||||
"claude",
|
||||
@@ -39,18 +39,22 @@
|
||||
"author": "Eyal Toledano",
|
||||
"license": "MIT WITH Commons-Clause",
|
||||
"dependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "^2.2.9",
|
||||
"@ai-sdk/anthropic": "^1.2.10",
|
||||
"@ai-sdk/azure": "^1.3.17",
|
||||
"@ai-sdk/google": "^1.2.13",
|
||||
"@ai-sdk/google-vertex": "^2.2.23",
|
||||
"@ai-sdk/mistral": "^1.2.7",
|
||||
"@ai-sdk/openai": "^1.3.20",
|
||||
"@ai-sdk/perplexity": "^1.1.7",
|
||||
"@ai-sdk/xai": "^1.2.15",
|
||||
"@anthropic-ai/sdk": "^0.39.0",
|
||||
"@aws-sdk/credential-providers": "^3.817.0",
|
||||
"@openrouter/ai-sdk-provider": "^0.4.5",
|
||||
"ai": "^4.3.10",
|
||||
"boxen": "^8.0.1",
|
||||
"chalk": "^5.4.1",
|
||||
"cli-highlight": "^2.1.11",
|
||||
"cli-table3": "^0.6.5",
|
||||
"commander": "^11.1.0",
|
||||
"cors": "^2.8.5",
|
||||
@@ -59,19 +63,23 @@
|
||||
"fastmcp": "^1.20.5",
|
||||
"figlet": "^1.8.0",
|
||||
"fuse.js": "^7.1.0",
|
||||
"gpt-tokens": "^1.3.14",
|
||||
"gradient-string": "^3.0.0",
|
||||
"helmet": "^8.1.0",
|
||||
"inquirer": "^12.5.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"lru-cache": "^10.2.0",
|
||||
"ollama-ai-provider": "^1.2.0",
|
||||
"open": "^10.1.2",
|
||||
"openai": "^4.89.0",
|
||||
"ora": "^8.2.0",
|
||||
"task-master-ai": "^0.15.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.23.8"
|
||||
"zod": "^3.23.8",
|
||||
"zod-to-json-schema": "^3.24.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -92,10 +100,11 @@
|
||||
"src/**"
|
||||
],
|
||||
"overrides": {
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-fetch": "^2.6.12",
|
||||
"whatwg-url": "^11.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^1.9.4",
|
||||
"@changesets/changelog-github": "^0.5.1",
|
||||
"@changesets/cli": "^2.28.1",
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -104,7 +113,6 @@
|
||||
"jest": "^29.7.0",
|
||||
"jest-environment-node": "^29.7.0",
|
||||
"mock-fs": "^5.5.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"prettier": "^3.5.3",
|
||||
"react": "^18.3.1",
|
||||
"supertest": "^7.1.0",
|
||||
|
||||
1869
scripts/init.js
1869
scripts/init.js
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
File diff suppressed because it is too large
Load Diff
@@ -5,14 +5,14 @@
|
||||
"swe_score": 0.727,
|
||||
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 120000
|
||||
"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": 120000
|
||||
"max_tokens": 32000
|
||||
},
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
|
||||
@@ -24,6 +24,7 @@ import removeTask from './task-manager/remove-task.js';
|
||||
import taskExists from './task-manager/task-exists.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';
|
||||
// Export task manager functions
|
||||
export {
|
||||
@@ -48,5 +49,6 @@ export {
|
||||
taskExists,
|
||||
isTaskDependentOn,
|
||||
moveTask,
|
||||
performResearch,
|
||||
readComplexityReport
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -308,7 +308,8 @@ function parseSubtasksFromText(
|
||||
logger.error(
|
||||
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}`
|
||||
);
|
||||
throw new Error( // Re-throw a more specific error if advanced also fails
|
||||
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}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -72,14 +72,14 @@ 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")
|
||||
* @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') {
|
||||
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 url = new URL(baseURL);
|
||||
const isHttps = url.protocol === 'https:';
|
||||
const port = url.port || (isHttps ? 443 : 80);
|
||||
const basePath = url.pathname.endsWith('/')
|
||||
@@ -484,13 +484,13 @@ async function setModel(role, modelId, options = {}) {
|
||||
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);
|
||||
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.`
|
||||
`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';
|
||||
@@ -498,7 +498,7 @@ async function setModel(role, modelId, options = {}) {
|
||||
report('warn', warningMessage);
|
||||
} else {
|
||||
// Server is running but model not found
|
||||
const tagsUrl = `${ollamaBaseUrl}/tags`;
|
||||
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}`
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
747
scripts/modules/task-manager/research.js
Normal file
747
scripts/modules/task-manager/research.js
Normal 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 };
|
||||
384
scripts/modules/telemetry-queue.js
Normal file
384
scripts/modules/telemetry-queue.js
Normal 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 };
|
||||
238
scripts/modules/telemetry-submission.js
Normal file
238
scripts/modules/telemetry-submission.js
Normal 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
516
scripts/modules/user-management.js
Normal file
516
scripts/modules/user-management.js
Normal 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,
|
||||
};
|
||||
@@ -60,8 +60,7 @@ function resolveEnvVariable(key, session = null, projectRoot = null) {
|
||||
|
||||
// --- Project Root Finding Utility ---
|
||||
/**
|
||||
* Finds the project root directory by searching upwards from a given starting point
|
||||
* for a marker file or directory (e.g., 'package.json', '.git').
|
||||
* Finds the project root directory by searching for marker files/directories.
|
||||
* @param {string} [startPath=process.cwd()] - The directory to start searching from.
|
||||
* @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.
|
||||
@@ -71,27 +70,35 @@ function findProjectRoot(
|
||||
markers = ['package.json', '.git', '.taskmasterconfig']
|
||||
) {
|
||||
let currentPath = path.resolve(startPath);
|
||||
while (true) {
|
||||
for (const marker of markers) {
|
||||
if (fs.existsSync(path.join(currentPath, marker))) {
|
||||
return currentPath;
|
||||
}
|
||||
const rootPath = path.parse(currentPath).root;
|
||||
|
||||
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;
|
||||
}
|
||||
const parentPath = path.dirname(currentPath);
|
||||
if (parentPath === currentPath) {
|
||||
// Reached the filesystem root
|
||||
return null;
|
||||
}
|
||||
currentPath = parentPath;
|
||||
|
||||
// Move up one directory
|
||||
currentPath = path.dirname(currentPath);
|
||||
}
|
||||
|
||||
// Check the root directory as well
|
||||
const hasMarkerInRoot = markers.some((marker) => {
|
||||
const markerPath = path.join(rootPath, marker);
|
||||
return fs.existsSync(markerPath);
|
||||
});
|
||||
|
||||
return hasMarkerInRoot ? rootPath : null;
|
||||
}
|
||||
|
||||
// --- Dynamic Configuration Function --- (REMOVED)
|
||||
/*
|
||||
function getConfig(session = null) {
|
||||
// ... implementation removed ...
|
||||
}
|
||||
*/
|
||||
|
||||
// --- Logging and Utility Functions ---
|
||||
|
||||
// Set up logging based on log level
|
||||
const LOG_LEVELS = {
|
||||
|
||||
659
scripts/modules/utils/contextGatherer.js
Normal file
659
scripts/modules/utils/contextGatherer.js
Normal 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;
|
||||
376
scripts/modules/utils/fuzzyTaskSearch.js
Normal file
376
scripts/modules/utils/fuzzyTaskSearch.js
Normal 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;
|
||||
186
scripts/modules/utils/gatewayErrorHandler.js
Normal file
186
scripts/modules/utils/gatewayErrorHandler.js
Normal 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 };
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"meta": {
|
||||
"generatedAt": "2025-05-22T05:48:33.026Z",
|
||||
"tasksAnalyzed": 6,
|
||||
"totalTasks": 88,
|
||||
"analysisCount": 43,
|
||||
"generatedAt": "2025-05-27T16:34:53.088Z",
|
||||
"tasksAnalyzed": 1,
|
||||
"totalTasks": 84,
|
||||
"analysisCount": 45,
|
||||
"thresholdScore": 5,
|
||||
"projectName": "Taskmaster",
|
||||
"usedResearch": true
|
||||
@@ -313,14 +313,6 @@
|
||||
"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": 86,
|
||||
"taskTitle": "Update .taskmasterconfig schema and user guide",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Expand this task into subtasks: (1) Draft a migration guide for users, (2) Update user documentation to explain new config fields, (3) Modify schema validation logic in config-manager.js, (4) Test and validate backward compatibility and error messaging.",
|
||||
"reasoning": "The task spans documentation, schema changes, migration guidance, and validation logic. While not algorithmically complex, it requires careful coordination and thorough testing to ensure a smooth user transition and robust validation."
|
||||
},
|
||||
{
|
||||
"taskId": 87,
|
||||
"taskTitle": "Implement validation and error handling",
|
||||
@@ -352,6 +344,30 @@
|
||||
"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."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
* Implementation for interacting with Anthropic models (e.g., Claude)
|
||||
* using the Vercel AI SDK.
|
||||
*/
|
||||
|
||||
import { createAnthropic } from '@ai-sdk/anthropic';
|
||||
import { generateText, streamText, generateObject } from 'ai';
|
||||
import { log } from '../../scripts/modules/utils.js'; // Assuming utils is accessible
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
// TODO: Implement standardized functions for generateText, streamText, generateObject
|
||||
|
||||
@@ -17,207 +17,38 @@ import { log } from '../../scripts/modules/utils.js'; // Assuming utils is acces
|
||||
// Remove the global variable and caching logic
|
||||
// let anthropicClient;
|
||||
|
||||
function getClient(apiKey, baseUrl) {
|
||||
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.');
|
||||
export class AnthropicAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'Anthropic';
|
||||
}
|
||||
// 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({
|
||||
apiKey: apiKey,
|
||||
...(baseUrl && { baseURL: baseUrl }),
|
||||
// Use standard version header instead of beta
|
||||
headers: {
|
||||
'anthropic-beta': 'output-128k-2025-02-19'
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
throw new Error('Anthropic API key is required.');
|
||||
}
|
||||
|
||||
return createAnthropic({
|
||||
apiKey,
|
||||
...(baseURL && { baseURL }),
|
||||
headers: {
|
||||
'anthropic-beta': 'output-128k-2025-02-19'
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// --- 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) {
|
||||
log('error', `Anthropic generateText failed: ${error.message}`);
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
52
src/ai-providers/azure.js
Normal file
52
src/ai-providers/azure.js
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
214
src/ai-providers/base-provider.js
Normal file
214
src/ai-providers/base-provider.js
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/ai-providers/bedrock.js
Normal file
41
src/ai-providers/bedrock.js
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
150
src/ai-providers/google-vertex.js
Normal file
150
src/ai-providers/google-vertex.js
Normal 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}`);
|
||||
}
|
||||
}
|
||||
@@ -1,181 +1,39 @@
|
||||
/**
|
||||
* 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'; // Correct import for customization
|
||||
import { generateText, streamText, generateObject } from 'ai'; // Import from main 'ai' package
|
||||
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
|
||||
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
// Consider making model configurable via config-manager.js later
|
||||
const DEFAULT_MODEL = 'gemini-2.5-pro-exp-03-25'; // Or a suitable default
|
||||
const DEFAULT_TEMPERATURE = 0.2; // Or a suitable default
|
||||
|
||||
function getClient(apiKey, baseUrl) {
|
||||
if (!apiKey) {
|
||||
throw new Error('Google API key is required.');
|
||||
export class GoogleAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'Google';
|
||||
}
|
||||
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,
|
||||
modelId = DEFAULT_MODEL,
|
||||
temperature = DEFAULT_TEMPERATURE,
|
||||
messages,
|
||||
maxTokens,
|
||||
baseUrl
|
||||
}) {
|
||||
if (!apiKey) {
|
||||
throw new Error('Google API key is required.');
|
||||
}
|
||||
log('info', `Generating text with Google model: ${modelId}`);
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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
|
||||
if (!apiKey) {
|
||||
throw new Error('Google API key is required.');
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
log(
|
||||
'error',
|
||||
`Error generating text with Google (${modelId}): ${error.message}`
|
||||
);
|
||||
throw error;
|
||||
|
||||
return createGoogleGenerativeAI({
|
||||
apiKey,
|
||||
...(baseURL && { baseURL })
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', 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
15
src/ai-providers/index.js
Normal 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';
|
||||
@@ -4,160 +4,39 @@
|
||||
*/
|
||||
|
||||
import { createOllama } from 'ollama-ai-provider';
|
||||
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
|
||||
import { generateObject, generateText, streamText } from 'ai';
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
// Consider making model configurable via config-manager.js later
|
||||
const DEFAULT_MODEL = 'llama3'; // Or a suitable default for Ollama
|
||||
const DEFAULT_TEMPERATURE = 0.2;
|
||||
export class OllamaAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'Ollama';
|
||||
}
|
||||
|
||||
function getClient(baseUrl) {
|
||||
// baseUrl is optional, defaults to http://localhost:11434
|
||||
return createOllama({
|
||||
baseUrl: baseUrl || undefined
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}`);
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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) {
|
||||
log(
|
||||
'error',
|
||||
`Error generating text with Ollama (${modelId}): ${error.message}`
|
||||
);
|
||||
throw error;
|
||||
return createOllama({
|
||||
...(baseURL && { baseURL })
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', 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 };
|
||||
|
||||
@@ -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'
|
||||
import { log } from '../../scripts/modules/utils.js';
|
||||
|
||||
function getClient(apiKey, baseUrl) {
|
||||
if (!apiKey) {
|
||||
throw new Error('OpenAI API key is required.');
|
||||
}
|
||||
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.
|
||||
* openai.js
|
||||
* AI provider implementation for OpenAI models using Vercel AI SDK.
|
||||
*/
|
||||
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.');
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
export class OpenAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'OpenAI';
|
||||
}
|
||||
|
||||
const openaiClient = getClient(apiKey, baseUrl);
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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
|
||||
if (!apiKey) {
|
||||
throw new Error('OpenAI API key is required.');
|
||||
}
|
||||
};
|
||||
} 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,
|
||||
modelId,
|
||||
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 createOpenAI({
|
||||
apiKey,
|
||||
...(baseURL && { baseURL })
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', error);
|
||||
}
|
||||
return {
|
||||
object: result.object,
|
||||
usage: {
|
||||
inputTokens: result.usage.promptTokens,
|
||||
outputTokens: result.usage.completionTokens
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
log(
|
||||
'error',
|
||||
`Error in generateOpenAIObject (Model: ${modelId}, Object: ${objectName}): ${error.message}`,
|
||||
{ error }
|
||||
);
|
||||
throw new Error(
|
||||
`OpenAI API error during object generation: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,246 +1,39 @@
|
||||
/**
|
||||
* openrouter.js
|
||||
* AI provider implementation for OpenRouter models using Vercel AI SDK.
|
||||
*/
|
||||
|
||||
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
|
||||
import { generateText, streamText, generateObject } from 'ai';
|
||||
import { log } from '../../scripts/modules/utils.js'; // Assuming utils.js is in scripts/modules
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
function getClient(apiKey, baseUrl) {
|
||||
if (!apiKey) throw new Error('OpenRouter API key is required.');
|
||||
return createOpenRouter({
|
||||
apiKey,
|
||||
...(baseUrl && { baseURL: baseUrl })
|
||||
});
|
||||
}
|
||||
export class OpenRouterAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'OpenRouter';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.');
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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
|
||||
if (!apiKey) {
|
||||
throw new Error('OpenRouter API key is required.');
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
let detailedMessage = `OpenRouter generateText failed for model ${modelId}: ${error.message}`;
|
||||
if (error.cause) {
|
||||
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
|
||||
|
||||
return createOpenRouter({
|
||||
apiKey,
|
||||
...(baseURL && { baseURL })
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', error);
|
||||
}
|
||||
// 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
|
||||
};
|
||||
|
||||
@@ -1,181 +1,39 @@
|
||||
/**
|
||||
* src/ai-providers/perplexity.js
|
||||
*
|
||||
* Implementation for interacting with Perplexity models
|
||||
* using the Vercel AI SDK.
|
||||
* perplexity.js
|
||||
* AI provider implementation for Perplexity models using Vercel AI SDK.
|
||||
*/
|
||||
|
||||
import { createPerplexity } from '@ai-sdk/perplexity';
|
||||
import { generateText, streamText, generateObject, streamObject } from 'ai';
|
||||
import { log } from '../../scripts/modules/utils.js';
|
||||
import { BaseAIProvider } from './base-provider.js';
|
||||
|
||||
// --- Client Instantiation ---
|
||||
// Similar to Anthropic, this expects the resolved API key to be passed in.
|
||||
function getClient(apiKey, baseUrl) {
|
||||
if (!apiKey) {
|
||||
throw new Error('Perplexity API key is required.');
|
||||
export class PerplexityAIProvider extends BaseAIProvider {
|
||||
constructor() {
|
||||
super();
|
||||
this.name = 'Perplexity';
|
||||
}
|
||||
return createPerplexity({
|
||||
apiKey: apiKey,
|
||||
...(baseUrl && { baseURL: baseUrl })
|
||||
});
|
||||
}
|
||||
|
||||
// --- Standardized Service Function Implementations ---
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 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,
|
||||
modelId,
|
||||
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
|
||||
if (!apiKey) {
|
||||
throw new Error('Perplexity API key is required.');
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
log('error', `Perplexity generateText failed: ${error.message}`);
|
||||
throw error;
|
||||
|
||||
return createPerplexity({
|
||||
apiKey,
|
||||
baseURL: baseURL || 'https://api.perplexity.ai'
|
||||
});
|
||||
} catch (error) {
|
||||
this.handleError('client initialization', 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.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user