This commit introduces a standardized pattern for capturing and propagating AI usage telemetry (cost, tokens, model used) across the Task Master stack and applies it to the 'add-task' functionality.
Key changes include:
- **Telemetry Pattern Definition:**
- Added defining the integration pattern for core logic, direct functions, MCP tools, and CLI commands.
- Updated related rules (, ,
Usage: mcp [OPTIONS] COMMAND [ARGS]...
MCP development tools
╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --help Show this message and exit. │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ version Show the MCP version. │
│ dev Run a MCP server with the MCP Inspector. │
│ run Run a MCP server. │
│ install Install a MCP server in the Claude desktop app. │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯, , ) to reference the new telemetry rule.
- **Core Telemetry Implementation ():**
- Refactored the unified AI service to generate and return a object alongside the main AI result.
- Fixed an MCP server startup crash by removing redundant local loading of and instead using the imported from for cost calculations.
- Added to the object.
- ** Integration:**
- Modified (core) to receive from the AI service, return it, and call the new UI display function for CLI output.
- Updated to receive from the core function and include it in the payload of its response.
- Ensured (MCP tool) correctly passes the through via .
- Updated to correctly pass context (, ) to the core function and rely on it for CLI telemetry display.
- **UI Enhancement:**
- Added function to to show telemetry details in the CLI.
- **Project Management:**
- Added subtasks 77.6 through 77.12 to track the rollout of this telemetry pattern to other AI-powered commands (, , , , , , ).
This establishes the foundation for tracking AI usage across the application.
- Enhance error validation in parse-prd.js and update-tasks.js
- Fix bug where mcpLog was incorrectly passed as logWrapper
- Improve error messages and response formatting
- Add --skip-verification flag to E2E tests
- Update MCP server config that ships with init to match new API key structure
- Fix task force/append handling in parse-prd command
- Increase column width in update-tasks display
This commit introduces several improvements and refactorings across MCP tools, core logic, and configuration.
**Major Changes:**
1. **Refactor updateSubtaskById:**
- Switched from generateTextService to generateObjectService for structured AI responses, using a Zod schema (subtaskSchema) for validation.
- Revised prompts to have the AI generate relevant content based on user request and context (parent/sibling tasks), while explicitly preventing AI from handling timestamp/tag formatting.
- Implemented **local timestamp generation (new Date().toISOString()) and formatting** (using <info added on ...> tags) within the function *after* receiving the AI response. This ensures reliable and correctly formatted details are appended.
- Corrected logic to append only the locally formatted, AI-generated content block to the existing subtask.details.
2. **Consolidate MCP Utilities:**
- Moved/consolidated the withNormalizedProjectRoot HOF into mcp-server/src/tools/utils.js.
- Updated MCP tools (like update-subtask.js) to import withNormalizedProjectRoot from the new location.
3. **Refactor Project Initialization:**
- Deleted the redundant mcp-server/src/core/direct-functions/initialize-project-direct.js file.
- Updated mcp-server/src/core/task-master-core.js to import initializeProjectDirect from its correct location (./direct-functions/initialize-project.js).
**Other Changes:**
- Updated .taskmasterconfig fallback model to claude-3-7-sonnet-20250219.
- Clarified model cost representation in the models tool description (taskmaster.mdc and mcp-server/src/tools/models.js).
Refactors the JSON array parsing logic within
in .
The previous logic primarily relied on extracting content from markdown
code blocks (json or javascript), which proved brittle when the AI
response included comments or non-JSON text within the block, leading to
parsing errors for the command.
This change modifies the parsing strategy to first attempt extracting
content directly between the outermost '[' and ']' brackets. This is
more robust as it targets the expected array structure directly. If
bracket extraction fails, it falls back to looking for a strict json
code block, then prefix stripping, before attempting a raw parse.
This approach aligns with the successful parsing strategy used for
single-object responses in and resolves the
parsing errors previously observed with the command.
Problem: expand_task & expand_all MCP tools failed with .env keys due to missing projectRoot propagation for API key resolution. Also fixed a ReferenceError: wasSilent is not defined in expandTaskDirect.
Solution: Modified core logic, direct functions, and MCP tools for expand-task and expand-all to correctly destructure projectRoot from arguments and pass it down through the context object to the AI service call (generateTextService). Fixed wasSilent scope in expandTaskDirect.
Verification: Tested expand_task successfully in MCP using .env keys. Reviewed expand_all flow for correct projectRoot propagation.
Modified update-subtask-by-id core, direct function, and tool to pass projectRoot for .env API key fallback. Removed check preventing appending details to completed subtasks.
Modified update-task-by-id core, direct function, and tool to pass projectRoot. Reverted parsing logic in core function to prioritize `{...}` extraction, resolving parsing errors. Fixed ReferenceError by correctly destructuring projectRoot.
Modified parse-prd core, direct function, and tool to pass projectRoot for .env API key fallback. Corrected Zod schema used in generateObjectService call. Fixed logFn reference error in core parsePRD. Updated unit test mock for utils.js.
Modified add-task core, direct function, and tool to pass projectRoot for .env API key fallback. Fixed logFn reference error and removed deprecated reportProgress call in core addTask function. Verified working.
Modified analyze-task-complexity.js core function, direct function, and analyze.js tool to correctly pass projectRoot. Fixed import error in tools/index.js. Added debug logging to _resolveApiKey in ai-services-unified.js. This enables the .env API key fallback for analyze_project_complexity.
Modified ai-services-unified.js, update.js tool, and update-tasks.js direct function to correctly pass projectRoot. This enables the .env file API key fallback mechanism for the update command when running via MCP, ensuring consistent key resolution with the CLI context.
Problem:
- Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP
- The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly
- This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env
Solution:
- Modified resolveEnvVariable function in utils.js to properly read from .env file at projectRoot
- Updated isApiKeySet to correctly pass projectRoot to resolveEnvVariable
- Enhanced the key detection logic to have consistent behavior between CLI and MCP contexts
- Maintains the correct precedence: session.env → .env file → process.env
Testing:
- Verified working correctly with both MCP and CLI tools
- API keys properly detected in .env file in both contexts
- Deleted .cursor/mcp.json to confirm introspection of .env as fallback works
- Enhance E2E testing and LLM analysis report and:
- Add --analyze-log flag to run_e2e.sh to re-run LLM analysis on existing logs.
- Add test:e2e and analyze-log scripts to package.json for easier execution.
- Correct display errors and dependency validation output:
- Update chalk usage in add-task.js to use bracket notation (chalk[color]) compatible with v5, resolving 'chalk.keyword is not a function' error.
- Modify fix-dependencies command output to show red failure box with issue count instead of green success box when validation fails.
- Refactor interactive model setup:
- Verify inclusion of 'No change' option during interactive model setup flow (task-master models --setup).
- Update model definitions:
- Add max_tokens field for gpt-4o in supported-models.json.
- Remove unused scripts:
- Delete prepare-package.js and rule-transformer.test.js.
Release candidate
- Refactors the core `removeTask` function (`task-manager/remove-task.js`) to accept and iterate over comma-separated task/subtask IDs.
- Updates dependency cleanup and file regeneration logic to run once after processing all specified IDs.
- Adjusts the `remove-task` CLI command (`commands.js`) description and confirmation prompt to handle multiple IDs correctly.
- Fixes a bug in the CLI confirmation prompt where task/subtask titles were not being displayed correctly.
- Updates the `remove_task` MCP tool description to reflect the new multi-ID capability.
This addresses the previously known issue where only the first ID in a comma-separated list was processed.
Closes#140
Adds the ability for users to specify custom model IDs for Ollama and OpenRouter providers, bypassing the internal supported model list.
- Introduces --ollama and --openrouter flags for the 'task-master models --set-<role>' command.
- Updates the interactive 'task-master models --setup' to include options for entering custom Ollama/OpenRouter IDs.
- Implements live validation against the OpenRouter API when a custom OpenRouter ID is provided.
- Refines the model setting logic to prioritize explicit provider flags/choices.
- Adds warnings when custom models are set.
- Updates the changeset file.
- Add OpenAI provider implementation using @ai-sdk/openai.\n- Update `models` command/tool to display API key status for configured providers.\n- Implement model-specific `maxTokens` override logic in `config-manager.js` using `supported-models.json`.\n- Improve AI error message parsing in `ai-services-unified.js` for better clarity.
The add-task command handler in commands.js was incorrectly passing null for the manualTaskData parameter to the core addTask function. This caused the core function to always fall back to the AI generation path, even when only manual flags like --title and --description were provided. This commit updates the call to pass the correctly constructed manualTaskData object, ensuring that manual task creation via the CLI works as intended without unnecessarily calling the AI service.
This commit completes the major refactoring initiative (Task 61) to migrate all AI-interacting task management functions to the unified service layer (`ai-services-unified.js`) and standardized configuration (`config-manager.js`).
Key Changes:
1. **Refactor `update-task-by-id` & `update-subtask-by-id`:**
* Replaced direct AI client logic and config fetching with calls to `generateTextService`.
* Preserved original prompt logic while ensuring JSON output format is requested.
* Implemented robust manual JSON parsing and Zod validation for text-based AI responses.
* Corrected logger implementation (`logFn`/`isMCP`/`report` pattern) for both CLI and MCP contexts.
* Ensured correct passing of `session` context to the unified service.
* Refactored associated direct function wrappers (`updateTaskByIdDirect`, `updateSubtaskByIdDirect`) to remove AI client initialization and call core logic appropriately.
2. **CLI Environment Loading:**
* Added `dotenv.config()` to `scripts/dev.js` to ensure consistent loading of the `.env` file for CLI operations.
3. **Obsolete Code Removal:**
* Deleted unused helper files:
* `scripts/modules/task-manager/get-subtasks-from-ai.js`
* `scripts/modules/task-manager/generate-subtask-prompt.js`
* `scripts/modules/ai-services.js`
* `scripts/modules/ai-client-factory.js`
* `mcp-server/src/core/utils/ai-client-utils.js`
* Removed corresponding imports/exports from `scripts/modules/task-manager.js` and `mcp-server/src/core/task-master-core.js`.
4. **Verification:**
* Successfully tested `update-task` and `update-subtask` via both CLI and MCP after refactoring.
5. **Task Management:**
* Marked subtasks 61.38, 61.39, 61.40, 61.41, and 61.33 as 'done'.
* Includes other task content/status updates as reflected in the diff.
This completes the migration of core AI features to the new architecture, enhancing maintainability and flexibility.
Completes the refactoring of the AI-interacting task management functions by aligning `update-tasks.js` with the unified service architecture and removing now-unused helper files.
Key Changes:
- **`update-tasks.js` Refactoring:**
- Replaced direct AI client calls and AI-specific config fetching with a call to `generateTextService` from `ai-services-unified.js`.
- Preserved the original system and user prompts requesting a JSON array output.
- Implemented manual JSON parsing (`parseUpdatedTasksFromText`) with Zod validation to handle the text response reliably.
- Updated the core function signature to accept the standard `context` object (`{ session, mcpLog }`).
- Corrected logger implementation to handle both MCP (`mcpLog`) and CLI (`consoleLog`) contexts appropriately.
- **Related Component Updates:**
- Refactored `mcp-server/src/core/direct-functions/update-tasks.js` to use the standard direct function pattern (logger wrapper, silent mode, call core function with context).
- Verified `mcp-server/src/tools/update.js` correctly passes arguments and context.
- Verified `scripts/modules/commands.js` (update command) correctly calls the refactored core function.
- **Obsolete File Cleanup:**
- Removed the now-unused `scripts/modules/task-manager/get-subtasks-from-ai.js` file and its export, as its functionality was integrated into `expand-task.js`.
- Removed the now-unused `scripts/modules/task-manager/generate-subtask-prompt.js` file and its export for the same reason.
- **Task Management:**
- Marked subtasks 61.38, 61.39, and 61.41 as complete.
This commit finalizes the alignment of `updateTasks`, `updateTaskById`, `expandTask`, `expandAllTasks`, `analyzeTaskComplexity`, `addTask`, and `parsePRD` with the unified AI service and configuration management patterns.
Refactors the `expandTask` and `expandAllTasks` features to complete subtask 61.38 and enhance functionality based on subtask 61.37's refactor.
Key Changes:
- **Additive Expansion (`expandTask`, `expandAllTasks`):**
- Modified `expandTask` default behavior to append newly generated subtasks to any existing ones.
- Added a `force` flag (passed down from CLI/MCP via `--force` option/parameter) to `expandTask` and `expandAllTasks`. When `force` is true, existing subtasks are cleared before generating new ones.
- Updated relevant CLI command (`expand`), MCP tool (`expand_task`, `expand_all`), and direct function wrappers (`expandTaskDirect`, `expandAllTasksDirect`) to handle and pass the `force` flag.
- **Complexity Report Integration (`expandTask`):**
- `expandTask` now reads `scripts/task-complexity-report.json`.
- If an analysis entry exists for the target task:
- `recommendedSubtasks` is used to determine the number of subtasks to generate (unless `--num` is explicitly provided).
- `expansionPrompt` is used as the primary prompt content for the AI.
- `reasoning` is appended to any additional context provided.
- If no report entry exists or the report is missing, it falls back to default subtask count (from config) and standard prompt generation.
- **`expandAllTasks` Orchestration:**
- Refactored `expandAllTasks` to primarily iterate through eligible tasks (pending/in-progress, considering `force` flag and existing subtasks) and call the updated `expandTask` function for each.
- Removed redundant logic (like complexity reading or explicit subtask clearing) now handled within `expandTask`.
- Ensures correct context (`session`, `mcpLog`) and flags (`useResearch`, `force`) are passed down.
- **Configuration & Cleanup:**
- Updated `.cursor/mcp.json` with new Perplexity/Anthropic API keys (old ones invalidated).
- Completed refactoring of `expandTask` started in 61.37, confirming usage of `generateTextService` and appropriate prompts.
- **Task Management:**
- Marked subtask 61.37 as complete.
- Updated `.changeset/cuddly-zebras-matter.md` to reflect user-facing changes.
These changes finalize the refactoring of the task expansion features, making them more robust, configurable via complexity analysis, and aligned with the unified AI service architecture.
Refactored the `expandTask` feature (`scripts/modules/task-manager/expand-task.js`) and related components (`commands.js`, `mcp-server/src/tools/expand-task.js`, `mcp-server/src/core/direct-functions/expand-task.js`) to integrate with the unified AI service layer (`ai-services-unified.js`) and configuration management (`config-manager.js`).
The refactor involved:
- Removing direct AI client calls and configuration fetching from `expand-task.js`.
- Attempting to use `generateObjectService` for structured subtask generation. This failed due to provider-specific errors (Perplexity internal errors, Anthropic schema translation issues).
- Reverting the core AI interaction to use `generateTextService`, asking the LLM to format its response as JSON containing a "subtasks" array.
- Re-implementing manual JSON parsing and Zod validation (`parseSubtasksFromText`) to handle the text response reliably.
- Updating prompt generation functions (`generateMainSystemPrompt`, `generateMainUserPrompt`, `generateResearchUserPrompt`) to request the correct JSON object structure within the text response.
- Ensuring the `expandTaskDirect` function handles pre-checks (force flag, task status) and correctly passes the `session` context and logger wrapper to the core `expandTask` function.
- Correcting duplicate imports in `commands.js`.
- Validating the refactored feature works correctly via both CLI (`task-master expand --id <id>`) and MCP (`expand_task` tool) for main and research roles.
This aligns the task expansion feature with the new architecture while using the more robust text generation approach due to current limitations with structured output services. Closes subtask 61.37.
Refactored the feature and related components (CLI command, MCP tool, direct function) to integrate with the unified AI service layer ().
Initially, was implemented to leverage structured output generation. However, this approach encountered persistent errors:
- Perplexity provider returned internal server errors.
- Anthropic provider failed with schema type and model errors.
Due to the unreliability of for this specific use case, the core AI interaction within was reverted to use . Basic manual JSON parsing and cleanup logic for the text response were reintroduced.
Key changes include:
- Removed direct AI client initialization (Anthropic, Perplexity).
- Removed direct fetching of AI model configuration parameters.
- Removed manual AI retry/fallback/streaming logic.
- Replaced direct AI calls with a call to .
- Updated wrapper to pass session context correctly.
- Updated MCP tool for correct path resolution and argument passing.
- Updated CLI command for correct path resolution.
- Preserved core functionality: task loading/filtering, report generation, CLI summary display.
Both the CLI command ([INFO] Initialized Perplexity client with OpenAI compatibility layer
[INFO] Initialized Perplexity client with OpenAI compatibility layer
Analyzing task complexity from: tasks/tasks.json
Output report will be saved to: scripts/task-complexity-report.json
Analyzing task complexity and generating expansion recommendations...
[INFO] Reading tasks from tasks/tasks.json...
[INFO] Found 62 total tasks in the task file.
[INFO] Skipping 31 tasks marked as done/cancelled/deferred. Analyzing 31 active tasks.
Skipping 31 tasks marked as done/cancelled/deferred. Analyzing 31 active tasks.
[INFO] Claude API attempt 1/2
[ERROR] Error in Claude API call: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Non-overload Claude API error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
Claude API error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Error during AI analysis: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}
[ERROR] Error analyzing task complexity: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 100000 > 64000, which is the maximum allowed number of output tokens for claude-3-7-sonnet-20250219"}}) and the MCP tool () have been verified to work correctly with this revised approach.
- Fixed MCP server initialization warnings by refactoring config-manager.js to handle missing project roots silently during startup
- Added project root tracking (loadedConfigRoot) to improve config caching and prevent unnecessary reloads
- Modified _loadAndValidateConfig to return defaults without warnings when no explicitRoot provided
- Improved getConfig to only update cache when loading config with a specific project root
- Ensured warning messages still appear when explicitly specified roots have missing/invalid configs
- Prevented console output during MCP startup that was causing JSON parsing errors
- Verified parse_prd and other MCP tools still work correctly with the new config loading approach.
- Replaces test perplexity api key in mcp.json and rolls it. It's invalid now.
Resolves persistent 404 'Not Found' errors when calling Anthropic models via the Vercel AI SDK. The primary issue was likely related to incorrect or missing API headers.
- Refactors Anthropic provider (src/ai-providers/anthropic.js) to use the standard 'anthropic-version' header instead of potentially outdated/incorrect beta headers when creating the client instance.
- Updates the default fallback model ID in .taskmasterconfig to 'claude-3-5-sonnet-20241022'.
- Fixes the interactive model setup (task-master models --setup) in scripts/modules/commands.js to correctly filter and default the main model selection.
- Improves the cost display in the 'task-master models' command output to explicitly show 'Free' for models with zero cost.
- Updates description for the 'id' parameter in the 'set_task_status' MCP tool definition for clarity.
- Updates list of models and costs
This commit implements several related improvements to the models command and configuration system:
- Added MCP support for the models command:
- Created new direct function implementation in models.js
- Registered modelsDirect in task-master-core.js for proper export
- Added models tool registration in tools/index.js
- Ensured project name replacement when copying .taskmasterconfig in init.js
- Improved .taskmasterconfig copying during project initialization:
- Added copyTemplateFile() call in createProjectStructure()
- Ensured project name is properly replaced in the config
- Restructured tool registration in logical workflow groups:
- Organized registration into 6 functional categories
- Improved command ordering to follow typical workflow
- Added clear group comments for maintainability
- Enhanced documentation in cursor rules:
- Updated dev_workflow.mdc with clearer config management instructions
- Added comprehensive models command reference to taskmaster.mdc
- Clarified CLI vs MCP usage patterns and options
- Added warning against manual .taskmasterconfig editing
- Unified Service: Introduced 'scripts/modules/ai-services-unified.js' to centralize AI interactions using provider modules ('src/ai-providers/') and the Vercel AI SDK.
- Provider Modules: Implemented 'anthropic.js' and 'perplexity.js' wrappers for Vercel SDK.
- 'updateSubtaskById' Fix: Refactored the AI call within 'updateSubtaskById' to use 'generateTextService' from the unified layer, resolving runtime errors related to parameter passing and streaming. This serves as the pattern for refactoring other AI calls in 'scripts/modules/task-manager/'.
- Task Status: Marked Subtask 61.19 as 'done'.
- Rules: Added new 'ai-services.mdc' rule.
This centralizes AI logic, replacing previous direct SDK calls and custom implementations. API keys are resolved via 'resolveEnvVariable' within the service layer. The refactoring of 'updateSubtaskById' establishes the standard approach for migrating other AI-dependent functions in the task manager module to use the unified service.
Relates to Task 61.
This commit centralizes configuration and environment variable access across various modules by consistently utilizing getters from scripts/modules/config-manager.js. This replaces direct access to process.env and the global CONFIG object, leading to improved consistency, maintainability, testability, and better handling of session-specific configurations within the MCP context.
Key changes include:
- Centralized Getters: Replaced numerous instances of process.env.* and CONFIG.* with corresponding getter functions (e.g., getLogLevel, getMainModelId, getResearchMaxTokens, getMainTemperature, isApiKeySet, getDebugFlag, getDefaultSubtasks).
- Session Awareness: Ensured that the session object is passed to config getters where necessary, particularly within AI service calls (ai-services.js, add-task.js) and error handling (ai-services.js), allowing for session-specific environment overrides.
- API Key Checks: Standardized API key availability checks using isApiKeySet() instead of directly checking process.env.* (e.g., for Perplexity in commands.js and ai-services.js).
- Client Instantiation Cleanup: Removed now-redundant/obsolete local client instantiation functions (getAnthropicClient, getPerplexityClient) from ai-services.js and the global Anthropic client initialization from dependency-manager.js. Client creation should now rely on the config manager and factory patterns.
- Consistent Debug Flag Usage: Standardized calls to getDebugFlag() in commands.js, removing potentially unnecessary null arguments.
- Accurate Progress Calculation: Updated AI stream progress reporting (ai-services.js, add-task.js) to use getMainMaxTokens(session) for more accurate calculations.
- Minor Cleanup: Removed unused import from scripts/modules/commands.js.
Specific module updates:
- :
- Uses getLogLevel() instead of process.env.LOG_LEVEL.
- :
- Replaced direct env/config access for model IDs, tokens, temperature, API keys, and default subtasks with appropriate getters.
- Passed session to handleClaudeError.
- Removed local getPerplexityClient and getAnthropicClient functions.
- Updated progress calculations to use getMainMaxTokens(session).
- :
- Uses isApiKeySet('perplexity') for API key checks.
- Uses getDebugFlag() consistently for debug checks.
- Removed unused import.
- :
- Removed global Anthropic client initialization.
- :
- Uses config getters (getResearch..., getMain...) for Perplexity and Claude API call parameters, preserving customEnv override logic.
This refactoring also resolves a potential SyntaxError: Identifier 'getPerplexityClient' has already been declared by removing the duplicated/obsolete function definition previously present in ai-services.js.
This commit focuses on standardizing configuration and API key access patterns across key modules as part of subtask 61.34.
Key changes include:
- Refactored `ai-services.js` to remove global AI clients and use `resolveEnvVariable` for API key checks. Client instantiation now relies on `getAnthropicClient`/`getPerplexityClient` accepting a session object.
- Refactored `task-manager.js` (`analyzeTaskComplexity` function) to use the unified `generateTextService` from `ai-services-unified.js`, removing direct AI client calls.
- Replaced direct `process.env` access for model parameters and other configurations (`PERPLEXITY_MODEL`, `CONFIG.*`) in `task-manager.js` with calls to the appropriate getters from `config-manager.js` (e.g., `getResearchModelId(session)`, `getMainMaxTokens(session)`).
- Ensured `utils.js` (`resolveEnvVariable`) correctly handles potentially undefined session objects.
- Updated function signatures where necessary to propagate the `session` object for correct context-aware configuration/key retrieval.
This moves towards the goal of using `ai-client-factory.js` and `ai-services-unified.js` as the standard pattern for AI interactions and centralizing configuration management through `config-manager.js`.