Skip to content

feat: update package dependencies and configurations#143

Merged
ssdeanx merged 1 commit intomainfrom
develop
Apr 18, 2026
Merged

feat: update package dependencies and configurations#143
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Copy Markdown
Owner

@ssdeanx ssdeanx commented Apr 18, 2026

  • Updated several package versions in package.json for improved stability and features, including:
    • Upgraded @dotenvx/dotenvx to version 1.61.1
    • Upgraded @mastra/client-js to version 1.13.5-alpha.5
    • Upgraded @mastra/cloudflare to version 1.3.2-alpha.0
    • Upgraded @mastra/cloudflare-d1 to version 1.0.5-alpha.0
    • Upgraded @mastra/convex to version 1.0.8-alpha.0
    • Upgraded @mastra/core to version 1.26.0-alpha.5
    • Upgraded eslint to version 10.2.1
    • Upgraded marked to version 18.0.1
    • Upgraded convert-csv-to-json to version 4.36.0
    • Upgraded crawlee to version 4.0.0-beta.47
  • Removed unnecessary lines in package.json for better readability.

fix: modify researchAgent configurations

  • Changed defaultOptions in researchAgent.ts to enable includeRawChunks and disable autoResumeSuspendedTools for better tool management.

style: update logger level

  • Changed logger level from 'info' to 'debug' in logger.ts for more verbose logging during development.

refactor: clean up index.ts imports and configurations

  • Removed unused imports and commented-out code in index.ts for clarity.
  • Adjusted CORS headers in the mastra configuration for better API security.

refactor: enhance document chunking tool

  • Updated embedding model references in document-chunking.tool.ts to use fastembed directly.
  • Changed span types from TOOL_CALL to MODEL_CHUNK for better observability.
  • Added experimental telemetry options for embedding functions to track inputs and outputs.

feat: implement Composio agent

  • Created a new Composio agent in compsio.ts that integrates with Composio's API for enhanced task automation.

feat: add process manager for sandbox

  • Introduced a new process manager in process-manager.ts to handle sandbox processes more effectively.

docs: add Weaving API documentation

  • Created weavingapi.md to document the Weaving API, detailing its functionality and usage for spell casting in gaming contexts.

feat: implement Composio MCP client

  • Added composio-mcp.ts to manage interactions with Composio's MCP, including OAuth handling and prompt management.

Summary by Sourcery

Update agent tooling, sandbox configuration, embeddings, and documentation while integrating Composio and refreshing dependencies.

New Features:

  • Add a Composio-powered agent wired into the main workspace and browser to execute Composio tools for user tasks.
  • Introduce a Composio MCP client to interact with Composio MCP servers using OAuth-based authentication.
  • Add a custom sandbox process manager scaffold for managing local sandbox processes.
  • Document a Vanilla/TBC-only shaman weaving API with precise timing, latency-aware prediction, and swing-state integration.

Enhancements:

  • Relax and enrich the main sandbox configuration with explicit isolation settings, network and filesystem permissions, API_URL env wiring, and direct LocalSandbox usage in the main workspace.
  • Switch workspace and document-chunking tooling to use the fastembed model directly with telemetry-enabled embedding calls and improved span typing for observability.
  • Align vector operations in the document chunking tools with the LibSQL vector store and refine tracing names for chunking and reranking tools.
  • Adjust research agent defaults to stream function-call arguments, include raw chunks, and enable flexible service tiering for better tool-call behavior.
  • Increase logger verbosity to debug for more detailed runtime diagnostics and clean up unused imports and commented code in the Mastra entrypoint.
  • Tighten CORS configuration to explicitly allow key headers required by frontend and research tooling.

Build:

  • Refresh package dependencies, including Mastra, ESLint, Crawlee, marked, CSV utilities, Rive, TanStack, dotenvx, and others, and add Composio-related packages to support the new agent integrations.

Documentation:

  • Add detailed Weaving API documentation describing spell-rank handling, latency-aware timing, and integration with the swing timer.
  • Update memory-bank progress and active-context logs to capture the latest weaving and swing-timer behavior changes.

- Updated several package versions in package.json for improved stability and features, including:
  - Upgraded @dotenvx/dotenvx to version 1.61.1
  - Upgraded @mastra/client-js to version 1.13.5-alpha.5
  - Upgraded @mastra/cloudflare to version 1.3.2-alpha.0
  - Upgraded @mastra/cloudflare-d1 to version 1.0.5-alpha.0
  - Upgraded @mastra/convex to version 1.0.8-alpha.0
  - Upgraded @mastra/core to version 1.26.0-alpha.5
  - Upgraded eslint to version 10.2.1
  - Upgraded marked to version 18.0.1
  - Upgraded convert-csv-to-json to version 4.36.0
  - Upgraded crawlee to version 4.0.0-beta.47
- Removed unnecessary lines in package.json for better readability.

fix: modify researchAgent configurations
- Changed defaultOptions in researchAgent.ts to enable includeRawChunks and disable autoResumeSuspendedTools for better tool management.

style: update logger level
- Changed logger level from 'info' to 'debug' in logger.ts for more verbose logging during development.

refactor: clean up index.ts imports and configurations
- Removed unused imports and commented-out code in index.ts for clarity.
- Adjusted CORS headers in the mastra configuration for better API security.

refactor: enhance document chunking tool
- Updated embedding model references in document-chunking.tool.ts to use fastembed directly.
- Changed span types from TOOL_CALL to MODEL_CHUNK for better observability.
- Added experimental telemetry options for embedding functions to track inputs and outputs.

feat: implement Composio agent
- Created a new Composio agent in compsio.ts that integrates with Composio's API for enhanced task automation.

feat: add process manager for sandbox
- Introduced a new process manager in process-manager.ts to handle sandbox processes more effectively.

docs: add Weaving API documentation
- Created weavingapi.md to document the Weaving API, detailing its functionality and usage for spell casting in gaming contexts.

feat: implement Composio MCP client
- Added composio-mcp.ts to manage interactions with Composio's MCP, including OAuth handling and prompt management.
Copilot AI review requested due to automatic review settings April 18, 2026 12:08
@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 18, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agent-stack Error Error Apr 18, 2026 0:08am

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 18, 2026

Reviewer's Guide

This PR upgrades multiple dependencies, tightens Mastra workspace and sandbox configuration (including telemetry-enabled embeddings and native sandbox options), introduces Composio integration (agent + MCP client), adds a basic process manager, and documents a new Vanilla/TBC-focused Weaving API and related progress context while cleaning up logging, agent defaults, and imports.

Sequence diagram for composioAgent handling a tool-enabled user request

sequenceDiagram
    actor User
    participant Mastra as MastraCore
    participant Agent as composioAgent
    participant ComposioCore as Composio
    participant Tool as ExternalToolAPI

    User->>Mastra: Send request (task requiring external action)
    Mastra->>Agent: generate(messages)

    activate Agent
    Agent->>ComposioCore: session.tools() (pre-fetched tools)
    ComposioCore-->>Agent: comptools

    Agent->>Agent: Plan requires tool invocation
    Agent->>ComposioCore: Invoke selected tool with arguments
    ComposioCore->>Tool: HTTP / API call
    Tool-->>ComposioCore: Tool result
    ComposioCore-->>Agent: Structured tool output

    Agent->>Agent: Integrate tool result into reasoning
    Agent-->>Mastra: Final response text
    deactivate Agent

    Mastra-->>User: Surface response via UI / API
Loading

Class diagram for Composio integration and sandbox process manager

classDiagram
    class Agent {
      +string id
      +string name
      +string instructions
      +string model
      +any memory
      +any[] tools
      +any browser
      +any workspace
      +number maxRetries
    }

    class Composio {
      +MastraProvider provider
      +string apiKey
      +create(userId string, options any) Promise<ComposioSession>
    }

    class MastraProvider {
    }

    class ComposioSession {
      +tools() Promise<any[]>
    }

    class composioAgent {
      +id "composio-agent"
      +name "Composio Agent"
      +instructions
      +model "opencode/minimax-m2.5-free"
      +memory LibsqlMemory
      +tools comptools
      +browser agentBrowser
      +workspace mainWorkspace
      +maxRetries 5
    }

    class LibsqlMemory {
    }

    class agentBrowser {
    }

    class mainWorkspace {
    }

    class InternalSpans {
      <<enumeration>>
      AGENT
    }

    class composio {
      +ComposioSession create(userId string, options any)
    }

    class MyProcessManager {
      +spawn(command string, options SpawnProcessOptions) Promise<ProcessHandle>
      +list() Promise<ProcessInfo[]>
      -Map<number, ProcessHandle> _tracked
    }

    class SandboxProcessManager {
      <<abstract>>
      +spawn(command string, options SpawnProcessOptions) Promise<ProcessHandle>
      +list() Promise<ProcessInfo[]>
      -Map<number, ProcessHandle> _tracked
    }

    class MySandbox {
      +string id
      +string name "MySandbox"
      +string provider "local"
      +ProviderStatus status
      +setStatus(status ProviderStatus) void
      +markRunning() void
      +markStopped() void
    }

    class MastraSandbox {
      <<abstract>>
      +string id
      +string name
      +string provider
      +ProviderStatus status
    }

    class MCPClient {
      +prompts MCPPromptApi
    }

    class MCPOAuthClientProvider {
      +onRedirectToAuthorization(url string) void
    }

    class MCPPromptApi {
      +list() Promise<any>
      +get(serverName string, name string, args any) Promise<any>
    }

    class composioMcp {
      +MCPClient client
    }

    class ProcessHandle {
      +number pid
      +number exitCode
      +ReadableStream reader
      +WritableStream writer
    }

    class ProcessInfo {
      +number pid
      +boolean running
      +number exitCode
    }

    class SpawnProcessOptions {
    }

    class ProviderStatus {
      <<enumeration>>
      running
      stopped
    }

    composioAgent --|> Agent
    composioAgent --> LibsqlMemory
    composioAgent --> agentBrowser
    composioAgent --> mainWorkspace
    composioAgent ..> InternalSpans

    composio --> MastraProvider
    composio --o ComposioSession
    ComposioSession --> composioAgent : provides tools

    MyProcessManager --|> SandboxProcessManager
    MySandbox --|> MastraSandbox
    MySandbox --> MyProcessManager

    composioMcp --> MCPClient
    MCPClient --> MCPPromptApi
    MCPOAuthClientProvider --> MCPClient
Loading

State diagram for WeavingAPI casting and swing prediction lifecycle

stateDiagram-v2
    [*] --> Idle

    Idle: No tracked spell being cast
    CastingTrackedSpell: Player casting a tracked weaving spell
    CastingUntrackedSpell: Player casting but spell not in spellIds

    Idle --> CastingTrackedSpell: UNIT_SPELLCAST_START
      note right of CastingTrackedSpell
        spellIds[spellId] == true and
        trackedSpellLookup[spellId] exists
      end note

    Idle --> CastingUntrackedSpell: UNIT_SPELLCAST_START
      note right of CastingUntrackedSpell
        spellIds[spellId] == false
        or no cached spell info
      end note

    CastingTrackedSpell --> CastingTrackedSpell: UNIT_SPELLCAST_DELAYED

    CastingTrackedSpell --> Idle: UNIT_SPELLCAST_STOP
    CastingTrackedSpell --> Idle: UNIT_SPELLCAST_INTERRUPTED
    CastingTrackedSpell --> Idle: UNIT_SPELLCAST_FAILED
    CastingTrackedSpell --> Idle: UNIT_SPELLCAST_SUCCEEDED

    CastingUntrackedSpell --> CastingUntrackedSpell: UNIT_SPELLCAST_DELAYED
    CastingUntrackedSpell --> Idle: UNIT_SPELLCAST_STOP
    CastingUntrackedSpell --> Idle: UNIT_SPELLCAST_INTERRUPTED
    CastingUntrackedSpell --> Idle: UNIT_SPELLCAST_FAILED
    CastingUntrackedSpell --> Idle: UNIT_SPELLCAST_SUCCEEDED

    Idle --> Idle: PLAYER_ENTERING_WORLD /
      refreshSwingState()
      rebuildSpellCatalog()

    CastingTrackedSpell --> CastingTrackedSpell: UNIT_AURA, UNIT_ATTACK_SPEED,
      PLAYER_EQUIPMENT_CHANGED, COMBAT_RATING_UPDATE /
        refreshSwingState()
        mainEventsHandler()

    CastingTrackedSpell --> CastingTrackedSpell: SPELLS_CHANGED /
        spellCatalogDirty = true
        mainEventsHandler()

    state CastingTrackedSpell {
      [*] --> Predicting
      Predicting --> Predicting: mainEventsHandler()
        / updateStatus()
        / swingWillBeClipped()
        / emit WEAVING_UPDATE_STATUS
        / emit SWING_TIMER_WILL_CLIPPED
    }
Loading

File-Level Changes

Change Details Files
Update Mastra workspaces to use native sandbox options and telemetry-enabled fastembed-based vector embeddings.
  • Make S3 filesystem instance local instead of exported to avoid accidental external use.
  • Extend main sandbox options with isolation, instructions, nativeSandbox permissions, and API_URL env wiring.
  • Instantiate a new LocalSandbox inline for the main workspace instead of reusing an imported sandbox.
  • Switch workspace embedder functions from fastembed.base to fastembed with retry, abort signal, and experimental telemetry options for observability.
  • Comment out the TypeScript language server spawn and LSP connection code to prevent automatic background processes.
src/mastra/workspaces.ts
Enhance the document chunking and reranking tools to use fastembed directly, libsqlvector for storage, and richer telemetry and tracing.
  • Default embedding model parameters from fastembed.base to fastembed in both document and libsql chunkers and reranker.
  • Change span types from TOOL_CALL to MODEL_CHUNK for chunking and reranking spans to better represent model activity.
  • Add experimental_telemetry blocks to embed/embedMany calls for chunkers and reranker to record inputs/outputs with function identifiers.
  • Replace pgVector createIndex/query/upsert calls with libsqlvector equivalents and fix related comments and log labels.
  • Remove verbose onOutput logging hook from the document reranker and rely on span-based tracing and step logging instead.
src/mastra/tools/document-chunking.tool.ts
Refresh research agent defaults, logger configuration, and Mastra root setup for better debugging and CORS behavior.
  • Change researchAgent defaultOptions to enable includeRawChunks and disable autoResumeSuspendedTools, and turn on streamed function-call arguments and flex serviceTier for the Google model.
  • Increase logger verbosity by setting the global Pino logger level from info to debug.
  • Clean up Mastra index imports by removing unused workspaces and voice/auth imports and leaving Composio agent wiring commented for future enablement.
  • Tighten CORS configuration by explicitly allowing a list of headers instead of leaving allowHeaders commented out.
src/mastra/agents/researchAgent.ts
src/mastra/config/logger.ts
src/mastra/index.ts
Introduce a simple process manager and sandbox implementation for managing local sandbox processes.
  • Create MyProcessManager extending SandboxProcessManager that can list tracked processes and stub spawn for future implementation.
  • Define MySandbox extending MastraSandbox with local provider, status tracking helpers, and unique IDs per instance.
  • Wire the custom process manager into the sandbox via the MastraSandbox constructor configuration.
src/mastra/process-manager.ts
Add Composio integration via a dedicated agent and MCP client tooling.
  • Create a Composio MCP OAuth client provider and MCPClient setup that targets Composio MCP servers and logs auth URLs for manual completion.
  • Instantiate a Composio client/session with MastraProvider using COMPOSIO_API_KEY/COMPOSIO_USER_ID and expose a composioAgent configured with tools, browser, Libsql memory, and mainWorkspace.
  • Configure composioAgent with tracing via InternalSpans.AGENT and a non-default model and retry policy for tool-heavy tasks.
  • Keep example usage of composioAgent and MCP prompts commented out to serve as documentation without running at startup.
src/mastra/tools/composio-mcp.ts
src/mastra/agents/compsio.ts
Upgrade package dependencies and tidy package.json scripts and dev tooling.
  • Add @composio/core and @composio/mastra dependencies for the new Composio agent integration.
  • Bump multiple @mastra packages, mastra CLI, and related libraries (libsql, editor, mcp, memory, mongodb, observability) to newer alpha versions.
  • Update various third-party libraries (dotenvx, rive, tanstack/react-virtual, convert-csv-to-json, crawlee, marked, eslint and eslint-plugin-react-hooks) to newer patch/beta versions for stability and features.
  • Remove an extraneous blank line from the scripts section and duplicate eslint entries while adding a devDependency entry for @mastra/core to match runtime usage.
package.json
package-lock.json
Document and track progress for the new Weaving API and swingtimer behavior in the memory bank.
  • Add weavingapi.md describing a Vanilla/TBC-focused shaman weaving API with precise timing, latency handling, spell-rank caching, and swing clipping detection that integrates with SwingTimer via WEAVING_UPDATE_STATUS and SWING_TIMER_WILL_CLIPPED.
  • Update memory-bank progress and activeContext docs to record the weaving API refactor, TBC-only rank usage, latency/haste-aware timing, and swingtimer precise-clock/aura-refresh improvements while preserving existing event contracts.
src/mastra/public/workspace/weavingapi.md
memory-bank/progress.md
memory-bank/activeContext.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions
Copy link
Copy Markdown

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 18, 2026

Summary by CodeRabbit

  • New Features

    • Composio agent integration for extended automation capabilities.
    • Swing-clipping prediction for WoW weaving optimization.
    • MCP OAuth client provider for third-party connectivity.
  • Improvements

    • Updated embedding models across document processing tools.
    • Enhanced agent configuration and observability tracing.
    • Expanded sandbox and workspace configuration options.
  • Dependencies

    • Multiple framework and library updates, including Composio integration packages.

Walkthrough

This PR integrates Composio API connector with the Mastra framework, updates dependencies across multiple packages, introduces new workspace configurations with sandbox settings, adds a Weaving API module for WoW swing-clipping prediction, and restructures workspace/agent initialization while enabling debug-level logging.

Changes

Cohort / File(s) Summary
Dependency Management
package.json
Added @composio/core and @composio/mastra (^0.6.10), bumped @dotenvx/dotenvx and multiple @mastra/* packages to alpha versions, updated @rive-app/react-webgl2, @tanstack/react-virtual, convert-csv-to-json, crawlee, marked, and eslint dependencies with version increments.
Composio Agent Integration
src/mastra/agents/compsio.ts
New module creating a Composio-backed agent with MastraProvider initialization, session setup with tool fetching, and configured with Composio API key, Libsql memory, browser/workspace integrations, and tracing policy.
Agent Configuration Updates
src/mastra/agents/researchAgent.ts, src/mastra/config/logger.ts
Enabled raw chunk inclusion in research agent, added Google provider streaming/tier settings, and changed logger level from 'info' to 'debug'.
Workspace and Sandbox Infrastructure
src/mastra/workspaces.ts, src/mastra/index.ts, src/mastra/process-manager.ts
Restructured mainWorkspace to use inline LocalSandbox with isolation/instruction/native-sandbox settings, removed s3filesystem export, added process manager class for sandbox lifecycle, and updated embedder models to fastembed with retry/telemetry configuration.
Tool/MCP Infrastructure
src/mastra/tools/composio-mcp.ts, src/mastra/tools/document-chunking.tool.ts
New Composio MCP client with OAuth configuration and server endpoint, updated document chunking to use libsqlvector backend instead of pgVector, changed embedding model references, added telemetry/retry logic, and switched tracing span types to MODEL_CHUNK.
Workspace API and Documentation
src/mastra/public/workspace/weavingapi.md, memory-bank/activeContext.md, memory-bank/progress.md
New Weaving API module implementing swing-clipping prediction for TBC-era shaman spells with cached spell-rank resolution, latency-aware cast prediction, and event-driven state tracking; updated memory-bank with context and progress notes documenting swing-timing and weaving behavior changes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • AgentStack#105: Modified workspace initialization and mainWorkspace wiring in src/mastra/index.ts, directly related to this PR's workspace restructuring changes.
  • AgentStack#138: Updates multiple @mastra/* dependency versions in package.json, overlapping with this PR's extensive dependency bumps.
  • AgentStack#33: Modifies package.json dependency versions for @mastra/* and related packages, related through shared package manifest updates.

Suggested reviewers

  • sourcery-ai

Poem

🐰 A rabbit hops through Composio's door,
Weaving spells and swing-timers galore,
Dependencies dance in alpha grace,
Workspace rebuilds at a friskier pace!
With debug logs bright and latency right,
Our framework blooms—what a glorious sight!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is partially related but overly broad—it mentions only dependency and configuration updates, yet the changeset includes major new features (Composio agent, process manager, Weaving API docs) and substantial refactoring. Consider a more specific title that reflects the primary changes, such as 'feat: integrate Composio agent, process manager, and Weaving API docs with dependency updates' to better capture the scope.
✅ Passed checks (2 passed)
Check name Status Explanation
Description check ✅ Passed The description is comprehensive and well-organized, covering package updates, agent configuration changes, logging adjustments, refactoring, new features, and documentation additions that align with the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch develop

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

@kilo-code-bot
Copy link
Copy Markdown
Contributor

kilo-code-bot Bot commented Apr 18, 2026

Code Review Summary

Status: 3 Issues Found | Recommendation: Address warnings before merge

Overview

Severity Count
CRITICAL 0
WARNING 2
SUGGESTION 1
Issue Details (click to expand)

WARNING

File Line Issue
src/mastra/workspaces.ts 4718 Sandbox configuration allows system binary access and network access with isolation disabled
src/mastra/process-manager.ts 3882 spawn method throws 'not implemented' error

SUGGESTION

File Line Issue
src/mastra/tools/document-chunking.tool.ts 4591 Changed from pgVector to libsqlvector
Files Reviewed (9 files)
  • src/mastra/agents/compsio.ts - New Composio agent implementation
  • src/mastra/agents/researchAgent.ts - Configuration changes for tool handling
  • src/mastra/config/logger.ts - Log level changed to debug
  • src/mastra/index.ts - Import and CORS configuration changes
  • src/mastra/process-manager.ts - New process manager with unimplemented spawn method
  • src/mastra/public/workspace/weavingapi.md - Updated WoW addon weaving API
  • src/mastra/tools/composio-mcp.ts - New MCP client for Composio
  • src/mastra/tools/document-chunking.tool.ts - Vector store migration and telemetry additions
  • src/mastra/workspaces.ts - Sandbox configuration and embedder updates

Reviewed by grok-code-fast-1:optimized:free · 901,074 tokens

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues, and left some high level feedback:

  • The new MyProcessManager/MySandbox in process-manager.ts currently has an unimplemented spawn and no exports/usages, so either wire this into the sandbox configuration or remove/guard it to avoid dead code and runtime errors if it is accidentally instantiated.
  • In composio-mcp.ts you construct oauthProvider and composioMcp but don't export or consume them; consider either exporting these clients or inlining this logic where it's needed to avoid accumulating unused integration code.
  • The mainSandboxOptions now use isolation: 'none' with nativeSandbox.allowNetwork: true; if this is intended only for local/dev, it may be worth making these flags environment-driven so you don't accidentally run with a very permissive sandbox in production.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `MyProcessManager`/`MySandbox` in `process-manager.ts` currently has an unimplemented `spawn` and no exports/usages, so either wire this into the sandbox configuration or remove/guard it to avoid dead code and runtime errors if it is accidentally instantiated.
- In `composio-mcp.ts` you construct `oauthProvider` and `composioMcp` but don't export or consume them; consider either exporting these clients or inlining this logic where it's needed to avoid accumulating unused integration code.
- The `mainSandboxOptions` now use `isolation: 'none'` with `nativeSandbox.allowNetwork: true`; if this is intended only for local/dev, it may be worth making these flags environment-driven so you don't accidentally run with a very permissive sandbox in production.

## Individual Comments

### Comment 1
<location path="src/mastra/workspaces.ts" line_range="208" />
<code_context>
     workingDirectory: localWorkspacePath,
+    isolation: 'none',
+    instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
+    nativeSandbox: {
+        allowNetwork: true, // Block network access (default)
+        readWritePaths: ['*'], // Additional writable paths
+        readOnlyPaths: [], // Additional read-only paths
</code_context>
<issue_to_address>
**suggestion (bug_risk):** The `allowNetwork` setting contradicts the inline comment and could be confusing.

`allowNetwork: true` enables network access, but the inline comment says network is blocked by default. Please either change the value to `false` if you want to block network access, or update the comment to describe the actual behavior.

```suggestion
        allowNetwork: true, // Enable network access for this sandbox (default is blocked)
```
</issue_to_address>

### Comment 2
<location path="src/mastra/config/logger.ts" line_range="23-27" />
<code_context>
 // Logger intentionally contains no tracing logic. Observability exporters/bridges handle traces separately.
 export const log = new PinoLogger({
     name: 'MastraLogger',
-    level: 'info',
+    level: 'debug',
     prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
     transports: {
</code_context>
<issue_to_address>
**suggestion (performance):** Using `debug` as the global log level may create excessive logs and impact performance in production.

`debug` is useful locally, but in long‑running or production environments it can flood logs, add I/O overhead, and obscure important events. Please make the level configurable (e.g., via `process.env.LOG_LEVEL`) and default to `info`/`warn` outside of local debugging.

```suggestion
export const log = new PinoLogger({
    name: 'MastraLogger',
    // Log level is configurable via environment; default to 'info' to avoid excessive logging in production
    level: process.env.LOG_LEVEL ?? 'info',
    prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
    transports: {
```
</issue_to_address>

### Comment 3
<location path="src/mastra/process-manager.ts" line_range="11-13" />
<code_context>
+
+let sandboxInstanceCounter = 0
+
+class MyProcessManager extends SandboxProcessManager<MySandbox> {
+    async spawn(_command: string, _options: SpawnProcessOptions = {}): Promise<ProcessHandle> {
+        throw new Error('spawn method not implemented')
+    }
+
</code_context>
<issue_to_address>
**issue (bug_risk):** Leaving `spawn` unimplemented will cause runtime failures for any process operations using this manager.

Since `MyProcessManager.spawn` always throws, any use of `MySandbox.processes` will fail at runtime. If this is only a stub, consider either not wiring this manager into any sandbox (or marking it abstract), or providing a minimal `spawn` implementation that safely reflects current capabilities (e.g., no-op with a logged warning).
</issue_to_address>

### Comment 4
<location path="src/mastra/tools/composio-mcp.ts" line_range="17-22" />
<code_context>
+    log.info(`Please visit: ${url}`)
+  },
+})
+const composioKey = process.env.COMPOSIO_API_KEY
+
+const composioMcp = new MCPClient({
+  servers: {
+    composio: {
+      url: new URL(`https://connect.composio.dev/mcp?apiKey=${composioKey}`),
+    },
+    //googleSheets: {
</code_context>
<issue_to_address>
**issue (bug_risk):** Using `COMPOSIO_API_KEY` directly in the URL without validation may result in `apiKey=undefined` and confusing failures.

If `COMPOSIO_API_KEY` is missing, the MCP URL becomes `...mcp?apiKey=undefined`, leading to hard-to-diagnose remote errors. It would be better to validate `composioKey` during initialization and either fail fast with a clear configuration error or skip registering the `composio` server when the key is absent.
</issue_to_address>

### Comment 5
<location path="src/mastra/agents/compsio.ts" line_range="9-18" />
<code_context>
+import { agentBrowser } from "../browsers";
+import { mainWorkspace } from "../workspaces";
+
+const composio = new Composio({
+  provider: new MastraProvider(),
+  apiKey: process.env.COMPOSIO_API_KEY,
+});
+// Create a session for your user
+const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';
+
+const session = await composio.create(userId, {
+  manageConnections: true,
+});
+
+const comptools = await session.tools();
+
+export const composioAgent = new Agent({
+  id: "composio-agent",
+  name: "Composio Agent",
</code_context>
<issue_to_address>
**issue (bug_risk):** Top-level `await` and network-dependent initialization on module load can hurt startup and fail when env vars are missing.

Because `composio.create(...)` and `session.tools()` run at module import time, any missing/invalid `COMPOSIO_API_KEY` or `COMPOSIO_USER_ID` will cause import-time failures and added network latency on startup. Consider wrapping this in a lazy async initializer (e.g., a factory that initializes on first use) and validating the required env vars with clear error messages before making network calls.
</issue_to_address>

### Comment 6
<location path="memory-bank/activeContext.md" line_range="947" />
<code_context>

+## Active Context Update (2026-04-17 - weavingapi nil-safety and haste-aware prediction)
+- Reworked `src/mastra/public/workspace/weavingapi.md` so it now resolves the highest valid rank per spell family, avoiding nil `castTime` crashes when a WotLK-only rank is missing on a TBC/Classic client.
+- Added live cast prediction based on `GetSpellHaste()` / `UnitSpellHaste()` with `GetHaste()` fallback, plus latency-aware timing, while keeping `swingtimer.md` untouched.
+- Kept the WeakAuras event contract intact (`WEAVING_UPDATE_STATUS` / `SWING_TIMER_WILL_CLIPPED`) and added safe guards around `GetSpellInfo`, `UnitAttackSpeed`, and swing-state updates.
+
</code_context>
<issue_to_address>
**issue:** Mention of `GetSpellHaste()` / `GetHaste()` fallback doesn’t match the current weaving API implementation.

The bullet implies live cast prediction uses `GetSpellHaste()` / `UnitSpellHaste()` with a `GetHaste()` fallback, but the `weavingapi.md` Lua example only calls `UnitSpellHaste("player")` via `getSpellHastePercent()` and doesn’t reference `GetSpellHaste` or `GetHaste`. Please either update the example to include these fallbacks or adjust the wording here so it matches the actual implementation.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/mastra/workspaces.ts
isolation: 'none',
instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
nativeSandbox: {
allowNetwork: true, // Block network access (default)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): The allowNetwork setting contradicts the inline comment and could be confusing.

allowNetwork: true enables network access, but the inline comment says network is blocked by default. Please either change the value to false if you want to block network access, or update the comment to describe the actual behavior.

Suggested change
allowNetwork: true, // Block network access (default)
allowNetwork: true, // Enable network access for this sandbox (default is blocked)

Comment on lines 23 to 27
export const log = new PinoLogger({
name: 'MastraLogger',
level: 'info',
level: 'debug',
prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
transports: {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Using debug as the global log level may create excessive logs and impact performance in production.

debug is useful locally, but in long‑running or production environments it can flood logs, add I/O overhead, and obscure important events. Please make the level configurable (e.g., via process.env.LOG_LEVEL) and default to info/warn outside of local debugging.

Suggested change
export const log = new PinoLogger({
name: 'MastraLogger',
level: 'info',
level: 'debug',
prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
transports: {
export const log = new PinoLogger({
name: 'MastraLogger',
// Log level is configurable via environment; default to 'info' to avoid excessive logging in production
level: process.env.LOG_LEVEL ?? 'info',
prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
transports: {

Comment on lines +11 to +13
class MyProcessManager extends SandboxProcessManager<MySandbox> {
async spawn(_command: string, _options: SpawnProcessOptions = {}): Promise<ProcessHandle> {
throw new Error('spawn method not implemented')
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Leaving spawn unimplemented will cause runtime failures for any process operations using this manager.

Since MyProcessManager.spawn always throws, any use of MySandbox.processes will fail at runtime. If this is only a stub, consider either not wiring this manager into any sandbox (or marking it abstract), or providing a minimal spawn implementation that safely reflects current capabilities (e.g., no-op with a logged warning).

Comment on lines +17 to +22
const composioKey = process.env.COMPOSIO_API_KEY

const composioMcp = new MCPClient({
servers: {
composio: {
url: new URL(`https://connect.composio.dev/mcp?apiKey=${composioKey}`),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Using COMPOSIO_API_KEY directly in the URL without validation may result in apiKey=undefined and confusing failures.

If COMPOSIO_API_KEY is missing, the MCP URL becomes ...mcp?apiKey=undefined, leading to hard-to-diagnose remote errors. It would be better to validate composioKey during initialization and either fail fast with a clear configuration error or skip registering the composio server when the key is absent.

Comment on lines +9 to +18
const composio = new Composio({
provider: new MastraProvider(),
apiKey: process.env.COMPOSIO_API_KEY,
});
// Create a session for your user
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';

const session = await composio.create(userId, {
manageConnections: true,
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Top-level await and network-dependent initialization on module load can hurt startup and fail when env vars are missing.

Because composio.create(...) and session.tools() run at module import time, any missing/invalid COMPOSIO_API_KEY or COMPOSIO_USER_ID will cause import-time failures and added network latency on startup. Consider wrapping this in a lazy async initializer (e.g., a factory that initializes on first use) and validating the required env vars with clear error messages before making network calls.


## Active Context Update (2026-04-17 - weavingapi nil-safety and haste-aware prediction)
- Reworked `src/mastra/public/workspace/weavingapi.md` so it now resolves the highest valid rank per spell family, avoiding nil `castTime` crashes when a WotLK-only rank is missing on a TBC/Classic client.
- Added live cast prediction based on `GetSpellHaste()` / `UnitSpellHaste()` with `GetHaste()` fallback, plus latency-aware timing, while keeping `swingtimer.md` untouched.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Mention of GetSpellHaste() / GetHaste() fallback doesn’t match the current weaving API implementation.

The bullet implies live cast prediction uses GetSpellHaste() / UnitSpellHaste() with a GetHaste() fallback, but the weavingapi.md Lua example only calls UnitSpellHaste("player") via getSpellHastePercent() and doesn’t reference GetSpellHaste or GetHaste. Please either update the example to include these fallbacks or adjust the wording here so it matches the actual implementation.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a Composio agent and MCP client, a new process manager, and updates the shaman weaving API for TBC Classic. It transitions vector storage to LibSQL, adds experimental telemetry to embedding tools, and refines sandbox isolation settings. Feedback focuses on implementing the spawn method in the process manager and addressing architectural concerns regarding top-level await for service initialization. Additionally, the reviewer recommends restoring removed observability hooks and cleaning up dead code, logs, and unused variables across the new modules.

I am having trouble creating individual review comments. Click here to see my feedback.

src/mastra/process-manager.ts (12-14)

high

The spawn method is a core functionality of a process manager but is currently unimplemented and throws an error. If this class is intended for production use, a valid implementation must be provided. If it is a placeholder or base class, consider marking it as abstract.

src/mastra/agents/compsio.ts (16-20)

medium

Performing asynchronous initialization like creating a session and fetching tools at the module level (top-level await) can cause several issues: it makes the module difficult to test, can significantly slow down application startup, and will cause the entire application to crash if the external service is unavailable or if environment variables are missing. Consider moving this logic into a factory function or handling it lazily when the agent is first used.

src/mastra/agents/compsio.ts (39-43)

medium

Commented-out code and console logs should be removed to maintain a clean and professional codebase. If this code is intended as an example, it would be better placed in a documentation file or a dedicated test suite.

src/mastra/tools/composio-mcp.ts (4-16)

medium

The oauthProvider constant is defined but never used in the MCPClient configuration or elsewhere in the file. To avoid confusion and keep the code clean, it should be removed if it is not required for the current implementation.

src/mastra/tools/composio-mcp.ts (34-44)

medium

Remove commented-out code to improve the maintainability and readability of the tool definition.

src/mastra/tools/document-chunking.tool.ts (1467-1476)

medium

The onOutput hook was removed from the documentRerankerTool. This hook provided essential logging for observability, such as the number of reranked documents and processing time. Unless there is a specific reason for its removal, it should be restored to maintain visibility into the tool's performance.

src/mastra/index.ts (192-194)

medium

Avoid committing commented-out imports and code in the main entry point. If these features are not yet ready for production, they should be managed in a separate feature branch or removed until they are fully implemented.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates core dependencies and refactors parts of the Mastra workspace/tooling setup, adding initial Composio integration and expanding sandbox/vector/embedding configurations.

Changes:

  • Upgraded multiple dependencies (Mastra packages, eslint, marked, crawlee, etc.) and updated the lockfile.
  • Refactored workspace + document chunking embedding configuration (fastembed usage, libsql vector ops, telemetry/span types).
  • Added new Composio MCP/client and sandbox process-manager scaffolding, plus new workspace documentation content.

Reviewed changes

Copilot reviewed 12 out of 13 changed files in this pull request and generated 14 comments.

Show a summary per file
File Description
src/mastra/workspaces.ts Updates sandbox options and workspace embedder configuration/telemetry.
src/mastra/tools/document-chunking.tool.ts Switches embedding model defaulting, span types, telemetry, and vector store calls.
src/mastra/tools/composio-mcp.ts Adds an MCP client config for Composio.
src/mastra/process-manager.ts Adds a sandbox process manager/sandbox skeleton.
src/mastra/index.ts Adjusts server CORS header configuration.
src/mastra/config/logger.ts Sets logger verbosity to debug.
src/mastra/agents/researchAgent.ts Adjusts default agent options for chunk/tool handling.
src/mastra/agents/compsio.ts Adds a Composio-backed agent (currently initialized at module load).
src/mastra/public/workspace/weavingapi.md Adds Weaving API documentation.
package.json Dependency upgrades + new Composio deps.
package-lock.json Lockfile updates reflecting dependency upgrades.
memory-bank/progress.md Updates project progress notes.
memory-bank/activeContext.md Updates project active context notes.
Comments suppressed due to low confidence (1)

src/mastra/workspaces.ts:97

  • The S3 filesystem config includes hardcoded access credentials (accessKeyId/secretAccessKey). Even for local MinIO defaults, committing credentials is a security risk and makes rotating keys difficult. Load these from environment variables (or a secret manager) and avoid checking secrets into source control.
const s3filesystem = new S3Filesystem({
  bucket: 'my-bucket',
  region: 'us-east-1',
  endpoint: 'http://localhost:9000',
  accessKeyId: 'minioadmin',

Comment thread src/mastra/workspaces.ts
name: 'MainWorkspace',
filesystem: mainFilesystem,
sandbox: mainSandbox,
sandbox:new LocalSandbox(mainSandboxOptions),
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mainWorkspace is being constructed with a new LocalSandbox(mainSandboxOptions) instead of reusing the exported mainSandbox. This creates two separate sandbox instances (and separate process tracking), while helper functions in this module default to mainSandbox, which can lead to inconsistent behavior when spawning/killing processes. Reuse mainSandbox here (or update helpers to use the same instance).

Suggested change
sandbox:new LocalSandbox(mainSandboxOptions),
sandbox: mainSandbox,

Copilot uses AI. Check for mistakes.
const indexName = inputData.indexName ?? 'memory_messages_768'
const embeddingModel =
inputData.embeddingModel ?? fastembed.base
inputData.embeddingModel ?? fastembed
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

embeddingModel is validated as a string (defaulting to fastembed.base), but the fallback here assigns the fastembed object (inputData.embeddingModel ?? fastembed). That breaks the type contract and is later passed into ModelRouterEmbeddingModel, which likely expects a string model id. Keep embeddingModel consistently a string (e.g., fastembed.base) or change the schema/types and downstream usage to accept the model object.

Suggested change
inputData.embeddingModel ?? fastembed
inputData.embeddingModel ?? fastembed.base

Copilot uses AI. Check for mistakes.
Comment thread src/mastra/workspaces.ts
Comment on lines 202 to +212
export const mainSandboxOptions: LocalSandboxOptions = {
id: 'sandbox',
workingDirectory: localWorkspacePath,
isolation: 'none',
instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
nativeSandbox: {
allowNetwork: true, // Block network access (default)
readWritePaths: ['*'], // Additional writable paths
readOnlyPaths: [], // Additional read-only paths
allowSystemBinaries: true, // Allow access to system binaries (default: false)
},
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mainSandboxOptions disables most isolation (isolation: 'none') while also enabling network access and allowing readWritePaths: ['*']. This effectively removes sandbox protections and can allow arbitrary filesystem/network access from tool calls. Consider using a safer default (restricted paths, network off, system binaries off) and only relaxing these behind an explicit dev-only flag/env var.

Suggested change
export const mainSandboxOptions: LocalSandboxOptions = {
id: 'sandbox',
workingDirectory: localWorkspacePath,
isolation: 'none',
instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
nativeSandbox: {
allowNetwork: true, // Block network access (default)
readWritePaths: ['*'], // Additional writable paths
readOnlyPaths: [], // Additional read-only paths
allowSystemBinaries: true, // Allow access to system binaries (default: false)
},
const isUnsafeSandboxEnabled =
process.env.MASTRA_ENABLE_UNSAFE_SANDBOX === 'true'
const mainSandboxIsolation: LocalSandboxOptions['isolation'] =
isUnsafeSandboxEnabled ? 'none' : 'process'
const mainSandboxNativeOptions: NonNullable<LocalSandboxOptions['nativeSandbox']> =
isUnsafeSandboxEnabled
? {
allowNetwork: true,
readWritePaths: ['*'],
readOnlyPaths: [],
allowSystemBinaries: true,
}
: {
allowNetwork: false,
readWritePaths: [localWorkspacePath],
readOnlyPaths: [],
allowSystemBinaries: false,
}
export const mainSandboxOptions: LocalSandboxOptions = {
id: 'sandbox',
workingDirectory: localWorkspacePath,
isolation: mainSandboxIsolation,
instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
nativeSandbox: mainSandboxNativeOptions,

Copilot uses AI. Check for mistakes.
Comment thread src/mastra/workspaces.ts
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'mainWorkspace-embedder',
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

experimental_telemetry.functionId is set to 'mainWorkspace-embedder' inside agentFsWorkspace as well, which makes telemetry ambiguous across workspaces. Use a distinct functionId for the AgentFS workspace embedder so traces/metrics can be attributed correctly.

Suggested change
functionId: 'mainWorkspace-embedder',
functionId: 'agentFsWorkspace-embedder',

Copilot uses AI. Check for mistakes.
Comment on lines +17 to +22
const composioKey = process.env.COMPOSIO_API_KEY

const composioMcp = new MCPClient({
servers: {
composio: {
url: new URL(`https://connect.composio.dev/mcp?apiKey=${composioKey}`),
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The API key is interpolated into the MCP server URL query string. This can leak secrets via logs, proxies, and error reporting, and it will also produce apiKey=undefined if the env var is missing. Validate COMPOSIO_API_KEY at startup and, if supported by the MCP server/SDK, prefer sending credentials via headers instead of URL query params.

Suggested change
const composioKey = process.env.COMPOSIO_API_KEY
const composioMcp = new MCPClient({
servers: {
composio: {
url: new URL(`https://connect.composio.dev/mcp?apiKey=${composioKey}`),
const composioKey = process.env.COMPOSIO_API_KEY?.trim()
if (!composioKey) {
throw new Error('COMPOSIO_API_KEY environment variable is required')
}
const composioMcp = new MCPClient({
servers: {
composio: {
url: new URL('https://connect.composio.dev/mcp'),
headers: {
Authorization: `Bearer ${composioKey}`,
},

Copilot uses AI. Check for mistakes.
Comment on lines +9 to +39
const composio = new Composio({
provider: new MastraProvider(),
apiKey: process.env.COMPOSIO_API_KEY,
});
// Create a session for your user
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';

const session = await composio.create(userId, {
manageConnections: true,
});

const comptools = await session.tools();

export const composioAgent = new Agent({
id: "composio-agent",
name: "Composio Agent",
instructions: "You are a helpful assistant that can use tools to perform tasks for the user. Use the tools provided to you to complete the user's requests. Always use the tools when appropriate. If you don't know how to do something, use the tools to find out. Be concise and efficient in your responses.",
model: 'opencode/minimax-m2.5-free',
memory: LibsqlMemory,
tools: comptools,
browser: agentBrowser,
workspace: mainWorkspace,
maxRetries: 5,
options: {
tracingPolicy: {
internal: InternalSpans.AGENT,
},
},
});

//const { text } = await composioAgent.generate([
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This module performs networked Composio session setup (composio.create(...), session.tools()) at import time via top-level await. That can slow startup and will crash module loading when env vars are missing or the API is unavailable. Move this initialization behind an explicit async factory/init function, validate required env vars up front, and consider lazy-loading tools so the agent can still boot in degraded mode.

Suggested change
const composio = new Composio({
provider: new MastraProvider(),
apiKey: process.env.COMPOSIO_API_KEY,
});
// Create a session for your user
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';
const session = await composio.create(userId, {
manageConnections: true,
});
const comptools = await session.tools();
export const composioAgent = new Agent({
id: "composio-agent",
name: "Composio Agent",
instructions: "You are a helpful assistant that can use tools to perform tasks for the user. Use the tools provided to you to complete the user's requests. Always use the tools when appropriate. If you don't know how to do something, use the tools to find out. Be concise and efficient in your responses.",
model: 'opencode/minimax-m2.5-free',
memory: LibsqlMemory,
tools: comptools,
browser: agentBrowser,
workspace: mainWorkspace,
maxRetries: 5,
options: {
tracingPolicy: {
internal: InternalSpans.AGENT,
},
},
});
//const { text } = await composioAgent.generate([
const DEFAULT_COMPOSIO_USER_ID = "agenstack-admin";
const COMPOSIO_AGENT_ID = "composio-agent";
const COMPOSIO_AGENT_NAME = "Composio Agent";
const COMPOSIO_AGENT_INSTRUCTIONS =
"You are a helpful assistant that can use tools to perform tasks for the user. Use the tools provided to you to complete the user's requests. Always use the tools when appropriate. If you don't know how to do something, use the tools to find out. Be concise and efficient in your responses.";
const COMPOSIO_AGENT_MODEL = "opencode/minimax-m2.5-free";
let composioAgentPromise: Promise<Agent> | null = null;
/**
* Read a required environment variable and fail fast with a clear error.
*
* @param name - Environment variable name to resolve.
* @returns The non-empty environment variable value.
* @throws {Error} When the environment variable is missing or blank.
*/
function getRequiredEnv(name: string): string {
const value = process.env[name]?.trim();
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
/**
* Resolve the Composio user id, using the configured value when available.
*
* @returns The Composio user id to use for the session.
*/
function getComposioUserId(): string {
return process.env.COMPOSIO_USER_ID?.trim() || DEFAULT_COMPOSIO_USER_ID;
}
/**
* Load Composio tools for the configured user session.
*
* Returns an empty tool set if the remote API is unavailable so the agent
* can still be created in degraded mode.
*
* @returns The loaded tool collection, or an empty object on tool-load failure.
*/
async function getComposioTools() {
const composio = new Composio({
provider: new MastraProvider(),
apiKey: getRequiredEnv("COMPOSIO_API_KEY"),
});
const session = await composio.create(getComposioUserId(), {
manageConnections: true,
});
try {
return await session.tools();
} catch (error) {
console.warn("Failed to load Composio tools; continuing in degraded mode.", error);
return {};
}
}
/**
* Create the Composio-backed agent on demand and cache the result.
*
* This avoids networked initialization during module import and lets callers
* decide when to pay the startup cost.
*
* @returns A cached Composio agent instance.
*/
export async function createComposioAgent(): Promise<Agent> {
if (!composioAgentPromise) {
composioAgentPromise = (async () => {
const composioTools = await getComposioTools();
return new Agent({
id: COMPOSIO_AGENT_ID,
name: COMPOSIO_AGENT_NAME,
instructions: COMPOSIO_AGENT_INSTRUCTIONS,
model: COMPOSIO_AGENT_MODEL,
memory: LibsqlMemory,
tools: composioTools,
browser: agentBrowser,
workspace: mainWorkspace,
maxRetries: 5,
options: {
tracingPolicy: {
internal: InternalSpans.AGENT,
},
},
});
})().catch((error) => {
composioAgentPromise = null;
throw error;
});
}
return composioAgentPromise;
}
//const agent = await createComposioAgent();
//const { text } = await agent.generate([

Copilot uses AI. Check for mistakes.
Comment thread src/mastra/workspaces.ts
embedder: async (text: string) => {
const { embedding } = await embed({
model: fastembed.base,
model: fastembed,
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The embedder uses model: fastembed, but other parts of the codebase treat the embedding model as fastembed.base (e.g., src/mastra/config/libsql.ts:12) and document-chunking.tool.ts validates embeddingModel as a string. If fastembed is not a valid ai.embed model instance, this will fail at runtime. Align on a single model value (likely fastembed.base) or update types/validators accordingly.

Suggested change
model: fastembed,
model: fastembed.base,

Copilot uses AI. Check for mistakes.
Comment on lines +1 to +16
import { MCPClient, MCPOAuthClientProvider } from '@mastra/mcp'
import { log } from '../config/logger'

const oauthProvider = new MCPOAuthClientProvider({
redirectUrl: 'http://localhost:3000/oauth/callback',
clientMetadata: {
redirect_uris: ['http://localhost:3000/oauth/callback'],
client_name: 'My MCP Client',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
},
onRedirectToAuthorization: url => {
// Handle authorization redirect (open browser, redirect response, etc.)
log.info(`Please visit: ${url}`)
},
})
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oauthProvider is created but never used, and this file doesn’t export anything. If OAuth is required for the MCP client, wire the provider into MCPClient (or whatever integration point the SDK expects); otherwise remove the unused provider to avoid dead code and confusion.

Suggested change
import { MCPClient, MCPOAuthClientProvider } from '@mastra/mcp'
import { log } from '../config/logger'
const oauthProvider = new MCPOAuthClientProvider({
redirectUrl: 'http://localhost:3000/oauth/callback',
clientMetadata: {
redirect_uris: ['http://localhost:3000/oauth/callback'],
client_name: 'My MCP Client',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
},
onRedirectToAuthorization: url => {
// Handle authorization redirect (open browser, redirect response, etc.)
log.info(`Please visit: ${url}`)
},
})
import { MCPClient } from '@mastra/mcp'

Copilot uses AI. Check for mistakes.
Comment thread src/mastra/index.ts
credentials: true,
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
// allowHeaders: ['*', 'Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
allowHeaders: ['*', 'Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allowHeaders includes '*' alongside an explicit list. For CORS, wildcard allow-headers support is inconsistent across clients and middleware, and may cause preflight failures. Prefer an explicit allow-list (or have the server echo Access-Control-Request-Headers if that’s what this framework supports) rather than mixing '*' with specific headers.

Suggested change
allowHeaders: ['*', 'Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
allowHeaders: ['Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],

Copilot uses AI. Check for mistakes.
Comment thread package.json
Comment on lines +346 to +347
"@typescript-eslint/eslint-plugin": "^8.58.2",
"@mastra/core": "^1.26.0-alpha.5"
Copy link

Copilot AI Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

package.json lists @mastra/core in both dependencies and devDependencies. Duplicating the same package across sections can lead to confusing installs/resolution issues and makes upgrades error-prone. Keep it in a single section (typically dependencies for runtime usage) and remove the duplicate entry.

Suggested change
"@typescript-eslint/eslint-plugin": "^8.58.2",
"@mastra/core": "^1.26.0-alpha.5"
"@typescript-eslint/eslint-plugin": "^8.58.2"

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 16

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
src/mastra/index.ts (1)

444-450: ⚠️ Potential issue | 🟡 Minor

CORS: allowHeaders: ['*', …] with credentials: true is a footgun and likely not what you want.

With credentials: true, browsers treat Access-Control-Allow-Headers: * literally (not as a wildcard). The '*' entry therefore adds no permissions — the explicit header names after it are doing all the work, and the '*' either is silently ignored or (depending on the underlying framework's serialization) is emitted as a literal header name that never matches a real request header. This is confusing and masks the security posture you actually want.

Please remove the '*' and keep only the explicit list. Also note that exposeHeaders is commented out; if the browser client needs to read any of these (e.g., x-user-id), uncomment that line.

🛠 Proposed fix
-            allowHeaders: ['*', 'Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
-           // exposeHeaders: ['Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
+            allowHeaders: ['Authorization', 'Content-Type', 'x-user-id', 'x-role', 'accept-language', 'x-research-phase', 'api-key'],
+            exposeHeaders: ['x-user-id', 'x-role', 'x-research-phase'],

As per coding guidelines: "Always validate user input on the server-side for security" and "Implement secure authentication and authorization mechanisms".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/index.ts` around lines 444 - 450, In the CORS config in
src/mastra/index.ts (the cors object), remove the literal '*' from allowHeaders
so only explicit header names remain (update the array used by allowHeaders in
the cors config) and, if browser clients need to read headers like x-user-id or
Authorization, uncomment and populate the exposeHeaders line to include those
header names; ensure you edit the cors block where allowHeaders and the
commented exposeHeaders are defined to make these changes.
src/mastra/tools/document-chunking.tool.ts (3)

21-22: 🛠️ Refactor suggestion | 🟠 Major

Remove the unused libsqlvector as pgVector alias import.

After the migration from pgVector to libsqlvector, the aliased import is no longer referenced (all call sites now use libsqlvector). Keeping the alias is misleading to future readers grepping for pgVector.

♻️ Proposed cleanup
-import { libsqlvector as pgVector } from '../config/libsql'
 import { libsqlvector } from '../config/libsql'

Also update the stale comment on line 1579 ("PGVector query accepts Mongo/Sift-style filter") and the documentRerankerTool description at lines 1405/1419–1427 which still reference "PgVector" instead of LibSQL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/tools/document-chunking.tool.ts` around lines 21 - 22, Remove the
unused aliased import "libsqlvector as pgVector" from the imports and keep only
"libsqlvector" to avoid confusing references to pgVector; update any stale
references/comments that mention "PgVector" to "LibSQL" — specifically search
for and edit the comment that currently reads "PGVector query accepts
Mongo/Sift-style filter" and the description text for documentRerankerTool (the
block around documentRerankerTool) to replace "PgVector"/"PGVector" with
"LibSQL" so all call sites and docs consistently reference libsqlvector and
documentRerankerTool.

256-274: ⚠️ Potential issue | 🟡 Minor

Standardize span types across all document-chunking tools to use SpanType.TOOL_CALL.

All four tools—mastraChunker (L257), mdocumentChunker (L567), libsqlChunker (L1037), and documentRerankerTool (L1507)—are created with createTool() and should use consistent span types. Per the coding guidelines: "Create a TOOL_CALL child span using tracingContext?.currentSpan?.createChildSpan() with the tracingContext pattern using SpanType.TOOL_CALL."

Currently, only mastraChunker uses SpanType.TOOL_CALL; the other three use SpanType.MODEL_CHUNK, which is reserved for LLM streaming chunks, not tool invocations. Update lines 567, 1037, and 1507 to use SpanType.TOOL_CALL for consistency with the guideline and with mastraChunker.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/tools/document-chunking.tool.ts` around lines 256 - 274, The span
types for the document-chunking tools must be standardized: update the
child-span creation in the tool factories (mastraChunker, mdocumentChunker,
libsqlChunker, and documentRerankerTool) to use SpanType.TOOL_CALL and the
tracing pattern tracingContext?.currentSpan?.createChildSpan(...) instead of
SpanType.MODEL_CHUNK; locate the span creation calls inside each createTool()
implementation and replace the span type argument with SpanType.TOOL_CALL while
preserving the existing requestContext, input metadata and tracingContext usage.

93-98: ⚠️ Potential issue | 🔴 Critical

Schema default(fastembed.base) violates Zod type contract—must be a string.

embeddingModel is declared as z.string().default(fastembed.base), but fastembed.base is an embedding-model object, not a string. Zod 4.3.6 (used in package.json) requires "Default values must match the output type of the schema." This will either fail validation or silently coerce to "[object Object]", which then breaks ModelRouterEmbeddingModel(embeddingModel) at line 758—it expects a valid model routing key string (e.g. 'google/gemini-embedding-2-preview'), not an object.

The fallback at lines 545–546 and 1015–1016 has the same issue: inputData.embeddingModel ?? fastembed also passes an object instead of a string.

🛠 Fix
-    // Embedding model name for ModelRouterEmbeddingModel (e.g. 'google/gemini-embedding-2-preview')
-    embeddingModel: z.string().default(fastembed.base),
+    // Embedding model routing key for ModelRouterEmbeddingModel
+    // (e.g. 'google/gemini-embedding-2-preview' or 'fastembed/base')
+    embeddingModel: z.string().default('fastembed/base'),

Then at lines 545–546 and 1015–1016, use a string literal fallback instead of the fastembed module object.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/tools/document-chunking.tool.ts` around lines 93 - 98, The schema
default is using an object (fastembed.base) where a string is required: change
the embeddingModel z.string().default(...) to provide a valid model-routing key
string (e.g. 'google/gemini-embedding-2-preview') instead of fastembed.base, and
update the two fallback sites that use inputData.embeddingModel ?? fastembed to
use the same string literal fallback (or a named string constant) so
ModelRouterEmbeddingModel receives a proper string rather than the fastembed
object; target the symbols embeddingModel, fastembed.base,
ModelRouterEmbeddingModel and the two occurrences of inputData.embeddingModel ??
fastembed when making this change.
src/mastra/agents/researchAgent.ts (1)

393-419: ⚠️ Potential issue | 🟡 Minor

Clarify intentional disable of autoResumeSuspendedTools and remove commented-out code.

Two concerns on this defaultOptions block:

  1. autoResumeSuspendedTools is now effectively undefined (previously true). If any tool registered in researchAgentTools uses suspend/resume (e.g., for human-in-the-loop approvals), those workflows will stall at suspension instead of auto-resuming. Please confirm this is the intended behavior and not a regression, and document it near the option — otherwise re-enable it.
  2. Leaving commented-out options (autoResumeSuspendedTools, maxOutputTokens, stopSequences, cachedContent, labels) violates the coding guideline "Never comment out code; remove it instead and use version control history if needed."

Also note: serviceTier: 'flex' is a lower-priority Gemini tier with higher latency and best-effort availability — OK for background research but worth being aware of for user-facing paths.

♻️ Proposed cleanup
   defaultOptions: {
-        //autoResumeSuspendedTools: true,
         includeRawChunks: true,
         modelSettings: {
             temperature: 0.2,
-            //maxOutputTokens: 64000,
             topK: 40,
             topP: 0.95,
-            //stopSequences: ['\n\n'],
             maxRetries: 5,
         },
         providerOptions: {
         google: {
           responseModalities: ['TEXT', 'IMAGE'],
           thinkingConfig: {
             includeThoughts: true,
             thinkingLevel: 'medium',
           },
-          //cachedContent: "Use cached content when available to reduce latency and costs, but ensure freshness for time-sensitive queries. Prefer cached data for static information and use real-time fetches for news, trends, and financial data.",
           streamFunctionCallArguments: true,
           mediaResolution: "MEDIA_RESOLUTION_MEDIUM",
           threshold: 'OFF', // Set to 'OFF' to disable thresholding and allow all tool calls
-          //labels: "research-agent",
           serviceTier: 'flex',
         } satisfies GoogleLanguageModelOptions,
     },
   },

As per coding guidelines: "Never comment out code; remove it instead and use version control history if needed."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/agents/researchAgent.ts` around lines 393 - 419, The
defaultOptions block left autoResumeSuspendedTools commented-out which
effectively sets it undefined and may regress suspend/resume workflows (see
researchAgentTools); either restore autoResumeSuspendedTools: true in
defaultOptions (and add a one-line comment explaining intentional auto-resume
for human-in-the-loop tools) or explicitly document nearby that auto-resume is
intentionally disabled and why; also remove all other commented-out config keys
(maxOutputTokens, stopSequences, cachedContent, labels) rather than leaving them
in-place, and keep providerOptions.google typed as GoogleLanguageModelOptions
with a short inline note about serviceTier: 'flex' being lower-priority for
awareness.
src/mastra/config/logger.ts (1)

23-30: ⚠️ Potential issue | 🟠 Major

Gate debug log level by environment; risk of PII/secret leakage to logs/app.log.

Setting level: 'debug' unconditionally means every log.info in this file plus any log.debug across the codebase is persisted to logs/app.log via FileTransport. The helpers in this same file (logWorkflowStart, logWorkflowEnd, logStepStart, logStepEnd, logToolExecution, logAgentActivity, logError) log raw input/output/details/context objects — these can include user identifiers, prompts, API responses, and headers. Unlike the Observability pipeline in src/mastra/index.ts (which runs SensitiveDataFilter before export), PinoLogger output is NOT redacted, so this change materially increases the blast radius for sensitive data on disk.

Per coding guidelines: "Never include passwords, API keys, tokens, or personally identifiable information (PII) in code or logs", "Encrypt sensitive data at rest and in transit", and the logger-specific guideline to "Use structured logging with Pino … [and] transport configuration".

🛡️ Suggested fix
-    level: 'debug',
-    prettyPrint: true, // Set to false in production to disable pretty printing and output raw JSON
+    level: process.env.LOG_LEVEL ?? (process.env.NODE_ENV === 'production' ? 'info' : 'debug'),
+    prettyPrint: process.env.NODE_ENV !== 'production',

Additionally, consider adding Pino redact paths (e.g., ['*.password', '*.token', '*.apiKey', '*.authorization', 'input.email', 'details.email']) on the logger to reduce leakage risk independent of log level.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/config/logger.ts` around lines 23 - 30, The logger is currently
configured with level: 'debug' in the PinoLogger instantiation (symbol: log)
causing sensitive objects logged by helpers (logWorkflowStart, logWorkflowEnd,
logStepStart, logStepEnd, logToolExecution, logAgentActivity, logError) to be
written to FileTransport; change the config to gate debug behind an environment
variable (e.g., process.env.LOG_LEVEL or NODE_ENV) so production defaults to
'info' or higher and only enables 'debug' when explicitly set, and also add Pino
redaction paths (e.g., include keys like
'*.password','*.token','*.apiKey','*.authorization','input.*','details.*') to
the PinoLogger options so sensitive fields are redacted before being persisted
to the file transport.
src/mastra/workspaces.ts (1)

230-317: ⚠️ Potential issue | 🔴 Critical

mainWorkspace and helper functions operate on two different LocalSandbox instances.

Line 230 exports mainSandbox = new LocalSandbox(mainSandboxOptions), and every helper in this file (listWorkspaceProcesses, spawnWorkspaceProcess, spawnWorkspaceLspProcess, getWorkspaceProcessHandle, killWorkspaceProcess) defaults to that instance. At line 317, mainWorkspace is constructed with sandbox: new LocalSandbox(mainSandboxOptions) — a second LocalSandbox sharing the same id: 'sandbox' and workingDirectory.

Consequences:

  • Processes spawned through the exported helpers will not be visible to mainWorkspace (and vice versa); mainWorkspace.sandbox.processes.list() won't see them.
  • sandboxStartHook / sandboxStopHook fire for both instances, producing duplicate lifecycle logs with the same sandboxId.
  • Two sandboxes racing on the same working directory can produce non-deterministic file state during concurrent operations.
  • Any state cached on the helper-side mainSandbox (process registry, PTY handles) is invisible to the workspace — tool calls coming through the workspace won't find processes spawned via spawnWorkspaceProcess.
🛠 Proposed fix: reuse the single exported sandbox
 export const mainWorkspace = new Workspace({
     id: 'main-Workspace',
     name: 'MainWorkspace',
     filesystem: mainFilesystem,
-    sandbox:new LocalSandbox(mainSandboxOptions),
+    sandbox: mainSandbox,
     vectorStore: libsqlvector,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/workspaces.ts` around lines 230 - 317, The file creates two
separate LocalSandbox instances causing duplicated sandbox state and lifecycle
logs; fix by reusing the exported mainSandbox when constructing mainWorkspace
instead of creating a new LocalSandbox—replace sandbox: new
LocalSandbox(mainSandboxOptions) in the Workspace initializer with sandbox:
mainSandbox (or simply sandbox: mainSandbox variable), ensure mainSandbox is
declared before mainWorkspace, and remove any redundant LocalSandbox
instantiation so all helpers (listWorkspaceProcesses, spawnWorkspaceProcess,
spawnWorkspaceLspProcess, getWorkspaceProcessHandle, killWorkspaceProcess) and
mainWorkspace reference the same sandbox instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@memory-bank/progress.md`:
- Around line 9-16: The progress log currently contradicts itself by claiming
the swingtimer file was "Left ... untouched" while immediately documenting
multiple edits; update the memory-bank entry so it accurately reflects the
change set: remove or replace the phrase "Left
`src/mastra/public/workspace/swingtimer.md` untouched" with a summary that the
file was modified and list the key changes (switch to _G.GetTimePreciseSec with
GetTime fallback, seeded latency cache, removed duplicate latency helper, prefer
world connection for combat latency, UNIT_AURA rescale, added
PLAYER_TALENT_UPDATE resync, wired swing delta into reset/speed-change paths,
made main/off delta track observed swing error, and added ResetTimers() for
equipment changes) so the log is consistent and non-contradictory.

In `@package.json`:
- Around line 173-175: The dependency entry for "crawlee" currently pins a
pre-release v4 ("crawlee": "^4.0.0-beta.47") which is unstable; change the
package.json dependency for "crawlee" to a stable release (e.g., replace the
version string with a v3 stable like "^3.16.0") or, if you truly need v4
features, explicitly switch to the pre-release channel by using "crawlee":
"next" and document the risk in the PR notes; update the "crawlee" dependency
line accordingly and run your lockfile update (npm/yarn/pnpm) to regenerate the
lockfile.

In `@src/mastra/agents/compsio.ts`:
- Line 14: Change the default COMPOSIO user id and null-handling: update the
userId declaration (variable userId that reads process.env.COMPOSIO_USER_ID) to
use the nullish coalescing operator (??) instead of || and set the fallback
string to "agentstack-admin" (fixing the typo). Also consider renaming the
module file from compsio.ts to composio.ts for discoverability so
imports/reference points match the corrected service name.
- Around line 39-43: Remove the commented-out example invocation of
composioAgent.generate and the console.log lines (the dead code referencing
composioAgent.generate and the text variable) from src/mastra/agents/compsio.ts;
if you want to keep the example for documentation, add it to a README or a TSDoc
`@example` block for the composioAgent or the module instead of leaving it
commented in the source so the codebase contains no commented-out code.
- Around line 22-37: Add a TSDoc block above the exported composioAgent
describing its purpose as the Composio integration agent, listing its key
configuration (uses Agent with model 'opencode/minimax-m2.5-free', memory
LibsqlMemory, tools comptools, browser agentBrowser, and workspace
mainWorkspace), noting runtime constraints and required environment variables
(e.g., COMPOSIO_API_KEY and COMPOSIO_USER_ID), and briefly documenting any
important behavior such as maxRetries and tracingPolicy; reference the exported
symbol composioAgent and the Agent constructor so reviewers can find the comment
easily.
- Around line 9-20: Rename the file from compsio.ts to composio.ts and fix the
userId default string from 'agenstack-admin' to 'agentstack-admin'; remove any
commented-out code blocks (lines ~39–43). Do not call session.create() or
session.tools() at module scope — instead gate Composio initialization behind an
environment check for COMPOSIO_API_KEY and either lazy-initialize inside the
composioAgent handler (create the Composio instance, call create(userId, ...)
and tools() on demand) or wrap the top-level init in try/catch and provide a
safe fallback (e.g., empty tools object) so failure does not crash startup;
update the code references for Composio, composio, session, and comptools
accordingly. Finally add a TSDoc comment above composioAgent describing its
purpose, inputs, and outputs.

In `@src/mastra/index.ts`:
- Around line 187-194: Remove the dead commented imports and agent registration
and either delete them or replace with a single TODO comment referencing the
work (e.g., remove lines like the commented imports GoogleVoice and
composioAgent and the commented registration of composioAgent inside the
registration block), and update the stale sampling comment to match the actual
value (change the trailing comment near the probability: 0.75 usage so it reads
~75% sampling). Locate symbols/imports MastraEditor, ArcadeToolProvider,
ComposioToolProvider and the commented composioAgent registration to remove, and
update the comment adjacent to the probability setting to reflect 75% sampling
or adjust probability to match the comment.

In `@src/mastra/process-manager.ts`:
- Around line 1-49: Replace the placeholder runtime-trap by implementing or
clearly gating the spawn behavior and export/rename the classes: rename
MyProcessManager→LocalProcessManager and MySandbox→LocalSandbox, implement
LocalProcessManager.spawn (or if scaffolding, change the thrown value to a
specific TODO/NotImplementedError and guard construction with a feature flag),
update the LocalSandbox constructor to instantiate new LocalProcessManager(),
export both classes, and ensure any status helpers (setStatus, markRunning,
markStopped) remain intact and typed; this will remove the unexported dead
module and fix runtime crashes caused by the unimplemented spawn method.

In `@src/mastra/public/workspace/weavingapi.md`:
- Around line 1-22: Replace the H1 "# Weaving API" with "## Weaving API" and
demote the existing "## Overview" and "## Reference" headers to "### Overview"
and "### Reference"; add the required YAML front matter at the top including
post_title, author1, post_slug, microsoft_alias, featured_image, categories,
tags, ai_note, summary, and post_date; wrap any lines exceeding 80 characters
(e.g., the long sentence about spell IDs/intentional exclusions) to multiple
lines under 80 chars; if this file is actually source for an addon (not a
published doc), consider renaming to a non-.md extension or moving to a
lint-exempt path to avoid markdown rules firing.

In `@src/mastra/tools/composio-mcp.ts`:
- Around line 4-31: The composio-mcp setup uses composioKey
(process.env.COMPOSIO_API_KEY) without validation, hardcodes redirect URL,
embeds the API key in the MCPClient URL, and doesn't follow the
createTool/export conventions; update oauthProvider to read redirect URL from
process.env.COMPOSIO_OAUTH_REDIRECT_URL (fallback to NEXT_PUBLIC_APP_URL +
'/oauth/callback'), validate composioKey and throw if missing, construct the
MCPClient servers URL without exposing the raw key in logs/spans by redacting
composioKey before any logging or tracing (match the .replace(apiKey,
'[REDACTED]') pattern used in polygon-tools.ts), and either export composioMcp
or remove the file and refactor this setup into a createTool-based module (use
the createTool pattern and Zod schemas) to match other files in
src/mastra/tools; locate symbols oauthProvider, composioKey, composioMcp,
MCPClient, COMPOSIO_API_KEY, COMPOSIO_OAUTH_REDIRECT_URL and SensitiveDataFilter
while making these changes.

In `@src/mastra/tools/document-chunking.tool.ts`:
- Around line 761-769: The inline creation of AbortController (abortSignal: new
AbortController().signal) disconnects cancellation from the tool and is a no-op;
replace those inline signals with the tool's propagated signal (use
context.abortSignal) for all embed/embedMany calls (e.g., the call whose
functionId is 'document-chunking-tool-embedMany' and the other embed/embedMany
sites), remove the new AbortController() usage, and ensure the tool checks
context.abortSignal?.aborted early and records cancellations via span?.error()
before returning so cancellation propagates and is logged.
- Around line 1015-1017: libsqlChunker currently resolves embeddingModel from
inputData.embeddingModel but then calls embedMany with model: fastembed, so the
user-supplied embeddingModel is ignored; update the embedMany call(s) in
libsqlChunker (the call around embedMany at lines ~1227 and the block 1224-1236)
to pass the resolved embeddingModel variable (or wrap it with
ModelRouterEmbeddingModel like mdocumentChunker does) instead of hardcoding
fastembed, or alternatively remove/ignore embeddingModel from
CustomDocumentChunkingInputSchema if the tool must always use fastembed so
callers aren’t misled.

In `@src/mastra/workspaces.ts`:
- Around line 414-428: The embedder in agentFsWorkspace is using the same
telemetry functionId ('mainWorkspace-embedder') which will conflate metrics;
update the embedder definition inside agentFsWorkspace to use a distinct
functionId (e.g., 'agentFsWorkspace-embedder' or similar) in the
experimental_telemetry.functionId field so traces are separated from the
mainWorkspace embedder; locate the embedder async function in agentFsWorkspace
and change only the functionId string, leaving other telemetry flags and
parameters unchanged.
- Around line 377-390: Remove the dead commented-out LSP spawn block shown in
the diff (the inline spawn/StreamMessageReader/StreamMessageWriter code) and
rely on the existing spawnWorkspaceLspProcess helper instead; delete those
commented lines so there’s no leftover commented code in
src/mastra/workspaces.ts and ensure any needed logic is already covered by
spawnWorkspaceLspProcess (and its callers) so behavior does not change.
- Around line 205-218: The sandbox configuration (isolation, nativeSandbox,
readWritePaths, allowNetwork, allowSystemBinaries) is currently fully permissive
and has misleading inline comments; change the defaults to safe values and gate
any fully-permissive settings behind an explicit env toggle (e.g., check
NODE_ENV !== 'production' or a new SANDBOX_UNRESTRICTED env flag) before
applying isolation: 'none', allowNetwork: true, readWritePaths: ['*'], or
allowSystemBinaries: true in the nativeSandbox object used by
sandboxStartHook/sandboxStopHook; also update the inline comments to accurately
reflect the effective behavior (e.g., note that allowNetwork: true permits
network access and that readWritePaths: ['*'] grants global write access) so
production deployments never inherit an unrestricted sandbox by default.
- Around line 320-336: The embedder functions (embedder in both workspace
definitions) are wrong: change the model from bare fastembed to fastembed.base
to match the LibSQL vector index (768-dim) and avoid dimension mismatch, and
remove the per-call AbortController (abortSignal: new AbortController().signal)
or replace it with a lifecycle-scoped controller referenced outside the embedder
so you can actually call abort()—i.e., either drop the abortSignal field
entirely in embedder or wire it to a long-lived AbortController instance managed
by the workspace lifecycle.

---

Outside diff comments:
In `@src/mastra/agents/researchAgent.ts`:
- Around line 393-419: The defaultOptions block left autoResumeSuspendedTools
commented-out which effectively sets it undefined and may regress suspend/resume
workflows (see researchAgentTools); either restore autoResumeSuspendedTools:
true in defaultOptions (and add a one-line comment explaining intentional
auto-resume for human-in-the-loop tools) or explicitly document nearby that
auto-resume is intentionally disabled and why; also remove all other
commented-out config keys (maxOutputTokens, stopSequences, cachedContent,
labels) rather than leaving them in-place, and keep providerOptions.google typed
as GoogleLanguageModelOptions with a short inline note about serviceTier: 'flex'
being lower-priority for awareness.

In `@src/mastra/config/logger.ts`:
- Around line 23-30: The logger is currently configured with level: 'debug' in
the PinoLogger instantiation (symbol: log) causing sensitive objects logged by
helpers (logWorkflowStart, logWorkflowEnd, logStepStart, logStepEnd,
logToolExecution, logAgentActivity, logError) to be written to FileTransport;
change the config to gate debug behind an environment variable (e.g.,
process.env.LOG_LEVEL or NODE_ENV) so production defaults to 'info' or higher
and only enables 'debug' when explicitly set, and also add Pino redaction paths
(e.g., include keys like
'*.password','*.token','*.apiKey','*.authorization','input.*','details.*') to
the PinoLogger options so sensitive fields are redacted before being persisted
to the file transport.

In `@src/mastra/index.ts`:
- Around line 444-450: In the CORS config in src/mastra/index.ts (the cors
object), remove the literal '*' from allowHeaders so only explicit header names
remain (update the array used by allowHeaders in the cors config) and, if
browser clients need to read headers like x-user-id or Authorization, uncomment
and populate the exposeHeaders line to include those header names; ensure you
edit the cors block where allowHeaders and the commented exposeHeaders are
defined to make these changes.

In `@src/mastra/tools/document-chunking.tool.ts`:
- Around line 21-22: Remove the unused aliased import "libsqlvector as pgVector"
from the imports and keep only "libsqlvector" to avoid confusing references to
pgVector; update any stale references/comments that mention "PgVector" to
"LibSQL" — specifically search for and edit the comment that currently reads
"PGVector query accepts Mongo/Sift-style filter" and the description text for
documentRerankerTool (the block around documentRerankerTool) to replace
"PgVector"/"PGVector" with "LibSQL" so all call sites and docs consistently
reference libsqlvector and documentRerankerTool.
- Around line 256-274: The span types for the document-chunking tools must be
standardized: update the child-span creation in the tool factories
(mastraChunker, mdocumentChunker, libsqlChunker, and documentRerankerTool) to
use SpanType.TOOL_CALL and the tracing pattern
tracingContext?.currentSpan?.createChildSpan(...) instead of
SpanType.MODEL_CHUNK; locate the span creation calls inside each createTool()
implementation and replace the span type argument with SpanType.TOOL_CALL while
preserving the existing requestContext, input metadata and tracingContext usage.
- Around line 93-98: The schema default is using an object (fastembed.base)
where a string is required: change the embeddingModel z.string().default(...) to
provide a valid model-routing key string (e.g.
'google/gemini-embedding-2-preview') instead of fastembed.base, and update the
two fallback sites that use inputData.embeddingModel ?? fastembed to use the
same string literal fallback (or a named string constant) so
ModelRouterEmbeddingModel receives a proper string rather than the fastembed
object; target the symbols embeddingModel, fastembed.base,
ModelRouterEmbeddingModel and the two occurrences of inputData.embeddingModel ??
fastembed when making this change.

In `@src/mastra/workspaces.ts`:
- Around line 230-317: The file creates two separate LocalSandbox instances
causing duplicated sandbox state and lifecycle logs; fix by reusing the exported
mainSandbox when constructing mainWorkspace instead of creating a new
LocalSandbox—replace sandbox: new LocalSandbox(mainSandboxOptions) in the
Workspace initializer with sandbox: mainSandbox (or simply sandbox: mainSandbox
variable), ensure mainSandbox is declared before mainWorkspace, and remove any
redundant LocalSandbox instantiation so all helpers (listWorkspaceProcesses,
spawnWorkspaceProcess, spawnWorkspaceLspProcess, getWorkspaceProcessHandle,
killWorkspaceProcess) and mainWorkspace reference the same sandbox instance.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ee85f720-8560-4e84-b82c-a166ddc1ab29

📥 Commits

Reviewing files that changed from the base of the PR and between 43625bf and 54d4eb6.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • memory-bank/activeContext.md
  • memory-bank/progress.md
  • package.json
  • src/mastra/agents/compsio.ts
  • src/mastra/agents/researchAgent.ts
  • src/mastra/config/logger.ts
  • src/mastra/index.ts
  • src/mastra/process-manager.ts
  • src/mastra/public/workspace/weavingapi.md
  • src/mastra/tools/composio-mcp.ts
  • src/mastra/tools/document-chunking.tool.ts
  • src/mastra/workspaces.ts

Comment thread memory-bank/progress.md
Comment on lines +9 to +16
- Left `src/mastra/public/workspace/swingtimer.md` untouched.
- Hardened the shared spellcast handler so stop/interrupt events clear stale casting state, and untracked cast starts now emit an explicit clear update instead of leaving the weaving HUD stuck on a previous cast.

# Progress Update (2026-04-17 - swingtimer precise-clock and aura refresh)

- Updated `src/mastra/public/workspace/swingtimer.md` to use `_G.GetTimePreciseSec` (with `GetTime` fallback) for precise melee swing timing while keeping latency frame-cached, and bumped the swingtimer version/changelog to reflect the final delta-correction and reset-safe behavior.
- Seeded the latency cache on load, removed the duplicate shadowed latency helper path, and switched combat latency to prefer the world connection so swing timing tracks the combat channel first.
- Changed `UNIT_AURA` to rescale swing speed immediately, added `PLAYER_TALENT_UPDATE` so melee speed also resyncs after talent swaps, wired the swing delta event into the actual swing reset/speed-change paths, made the main/off delta correction track observed swing error instead of staying at zero and zero itself during equipment resets, and added a real `ResetTimers()` implementation for equipment changes while leaving the parry branch untouched.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Contradictory claims in the 2026-04-17 progress entries.

Line 9 of the weaving entry states "Left src/mastra/public/workspace/swingtimer.md untouched," but the very next entry (lines 12-16) describes substantive edits to swingtimer.md on the same date (precise-clock switch, latency cache seeding, UNIT_AURA rescaling, ResetTimers(), etc.). At least one of these statements is stale. Reconcile so the memory-bank log accurately reflects what was changed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@memory-bank/progress.md` around lines 9 - 16, The progress log currently
contradicts itself by claiming the swingtimer file was "Left ... untouched"
while immediately documenting multiple edits; update the memory-bank entry so it
accurately reflects the change set: remove or replace the phrase "Left
`src/mastra/public/workspace/swingtimer.md` untouched" with a summary that the
file was modified and list the key changes (switch to _G.GetTimePreciseSec with
GetTime fallback, seeded latency cache, removed duplicate latency helper, prefer
world connection for combat latency, UNIT_AURA rescale, added
PLAYER_TALENT_UPDATE resync, wired swing delta into reset/speed-change paths,
made main/off delta track observed swing error, and added ResetTimers() for
equipment changes) so the log is consistent and non-contradictory.

Comment thread package.json
Comment on lines +173 to +175
"convert-csv-to-json": "^4.36.0",
"convex": "^1.35.1",
"crawlee": "^4.0.0-beta.43",
"crawlee": "^4.0.0-beta.47",
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm marked 18.0.1 is published (or not) and crawlee 4 channel.
curl -s https://registry.npmjs.org/marked | jq '."dist-tags", (.versions | keys | map(select(startswith("18."))) )'
echo "---"
curl -s https://registry.npmjs.org/crawlee | jq '."dist-tags"'

Repository: ssdeanx/AgentStack

Length of output: 195


Replace crawlee@^4.0.0-beta.47 with a stable release.

crawlee@^4.0.0-beta.47 is pinned to a pre-release version under the v4 dist-tag, not the stable latest channel (which is 3.16.0). Using a pre-release in production dependencies introduces unstable breaking changes without a safety net. Per coding guidelines, dependencies should favor stable releases unless v4-specific features are required. Either upgrade to the next stable v3 release or use crawlee@next with explicit acknowledgment of pre-release risks.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` around lines 173 - 175, The dependency entry for "crawlee"
currently pins a pre-release v4 ("crawlee": "^4.0.0-beta.47") which is unstable;
change the package.json dependency for "crawlee" to a stable release (e.g.,
replace the version string with a v3 stable like "^3.16.0") or, if you truly
need v4 features, explicitly switch to the pre-release channel by using
"crawlee": "next" and document the risk in the PR notes; update the "crawlee"
dependency line accordingly and run your lockfile update (npm/yarn/pnpm) to
regenerate the lockfile.

Comment on lines +9 to +20
const composio = new Composio({
provider: new MastraProvider(),
apiKey: process.env.COMPOSIO_API_KEY,
});
// Create a session for your user
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';

const session = await composio.create(userId, {
manageConnections: true,
});

const comptools = await session.tools();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

Does @composio/core Composio.create() require the API key or does it fall back gracefully when apiKey is undefined?

💡 Result:

No, Composio.create (or new Composio) in @composio/core does not require the API key. The apiKey parameter is optional (apiKey?: string | null). It falls back gracefully by reading from the COMPOSIO_API_KEY environment variable via getSDKConfig, or proceeds with an empty/undefined key if neither is provided. Examples in official docs and AI code guidelines show new Composio without explicit apiKey, confirming it works without it if env var is set. Operations requiring API access (e.g., tools.execute) will fail without a valid key, but instantiation succeeds.

Citations:


🏁 Script executed:

# Check if the file exists and with what name
fd -e ts composio src/mastra/agents/

# Also check for compsio (typo variant)
fd -e ts compsio src/mastra/

Repository: ssdeanx/AgentStack

Length of output: 90


🏁 Script executed:

# Read the actual file to verify all concerns
git ls-files src/mastra/agents/ | grep -E "composio|compsio"

Repository: ssdeanx/AgentStack

Length of output: 90


🏁 Script executed:

# Get detailed content of the file
if [ -f "src/mastra/agents/compsio.ts" ]; then
  cat -n src/mastra/agents/compsio.ts
elif [ -f "src/mastra/agents/composio.ts" ]; then
  cat -n src/mastra/agents/composio.ts
fi

Repository: ssdeanx/AgentStack

Length of output: 1888


Remove top-level await and gate Composio initialization behind env check to prevent startup crashes.

Lines 16–20 execute session.create() and session.tools() at module scope. This blocks and crashes the entire application boot if COMPOSIO_API_KEY is missing, invalid, or the Composio API is unreachable—taking src/mastra/index.ts (and any importer) down with it. Per coding guidelines: "Gate optional channel adapters such as GitHub behind explicit environment checks so local/dev boots do not fail when webhook secrets or auth credentials are absent." Composio is an optional integration and must not be a hard boot dependency.

Lazy-initialize Composio tools only when the agent is invoked, or wrap initialization in try-catch with a fallback empty object.

Additional issues:

  • Line 1 (filename): Rename file from compsio.ts to composio.ts (typo).
  • Line 14: Fix userId default from 'agenstack-admin' to 'agentstack-admin'.
  • Lines 39–43: Remove commented-out code instead of leaving it in the file.
  • Line 22: Add TSDoc comment documenting composioAgent's purpose, inputs, and outputs.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/agents/compsio.ts` around lines 9 - 20, Rename the file from
compsio.ts to composio.ts and fix the userId default string from
'agenstack-admin' to 'agentstack-admin'; remove any commented-out code blocks
(lines ~39–43). Do not call session.create() or session.tools() at module scope
— instead gate Composio initialization behind an environment check for
COMPOSIO_API_KEY and either lazy-initialize inside the composioAgent handler
(create the Composio instance, call create(userId, ...) and tools() on demand)
or wrap the top-level init in try/catch and provide a safe fallback (e.g., empty
tools object) so failure does not crash startup; update the code references for
Composio, composio, session, and comptools accordingly. Finally add a TSDoc
comment above composioAgent describing its purpose, inputs, and outputs.

apiKey: process.env.COMPOSIO_API_KEY,
});
// Create a session for your user
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Typo in default userId: agenstack-adminagentstack-admin.

This default value becomes the Composio session identifier for self-hosted / local runs and, once it ships, migrating away without orphaning sessions is painful. Also note the filename itself is compsio.ts (missing the second o); consider renaming to composio.ts for discoverability before this module is referenced widely.

-const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';
+const userId = process.env.COMPOSIO_USER_ID ?? 'agentstack-admin';

Also prefer ?? over || so an explicit empty string in COMPOSIO_USER_ID is still treated as an empty value rather than silently falling through every truthy check.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const userId = process.env.COMPOSIO_USER_ID || 'agenstack-admin';
const userId = process.env.COMPOSIO_USER_ID ?? 'agentstack-admin';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/agents/compsio.ts` at line 14, Change the default COMPOSIO user id
and null-handling: update the userId declaration (variable userId that reads
process.env.COMPOSIO_USER_ID) to use the nullish coalescing operator (??)
instead of || and set the fallback string to "agentstack-admin" (fixing the
typo). Also consider renaming the module file from compsio.ts to composio.ts for
discoverability so imports/reference points match the corrected service name.

Comment on lines +22 to +37
export const composioAgent = new Agent({
id: "composio-agent",
name: "Composio Agent",
instructions: "You are a helpful assistant that can use tools to perform tasks for the user. Use the tools provided to you to complete the user's requests. Always use the tools when appropriate. If you don't know how to do something, use the tools to find out. Be concise and efficient in your responses.",
model: 'opencode/minimax-m2.5-free',
memory: LibsqlMemory,
tools: comptools,
browser: agentBrowser,
workspace: mainWorkspace,
maxRetries: 5,
options: {
tracingPolicy: {
internal: InternalSpans.AGENT,
},
},
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the model string is referenced elsewhere / resolvable by the current provider layer.
rg -nP "opencode/minimax" -C2
rg -nP "minimax-m2\.?5" -C2

Repository: ssdeanx/AgentStack

Length of output: 2531


🏁 Script executed:

# Check for provider configuration and model registry setup
fd -type f -name "*.ts" -o -name "*.js" | head -20 | xargs rg -l "provider|model" | head -10
rg "opencode" -t ts -t js
rg "openrouter\|google\.chat\|provider" -C1 | head -40

Repository: ssdeanx/AgentStack

Length of output: 700


🏁 Script executed:

# Check other agent files to see if they have TSDoc
fd -path "src/mastra/agents/*.ts" -type f | xargs head -30

Repository: ssdeanx/AgentStack

Length of output: 230


🏁 Script executed:

# Look for model configuration or provider setup files
fd -type f \( -name "*config*" -o -name "*provider*" -o -name "*model*" \) | grep -E "(ts|js|json|yaml|env)$"

Repository: ssdeanx/AgentStack

Length of output: 232


🏁 Script executed:

# List all agent files and check for TSDoc comments
ls -la src/mastra/agents/*.ts | head -20

Repository: ssdeanx/AgentStack

Length of output: 1807


🏁 Script executed:

# Check request-context.ts to understand opencode provider
cat src/mastra/agents/request-context.ts | head -50

Repository: ssdeanx/AgentStack

Length of output: 1704


🏁 Script executed:

# Check model-selector for valid models
rg "opencode|minimax" -A2 -B2

Repository: ssdeanx/AgentStack

Length of output: 7343


🏁 Script executed:

# Check if other agents have TSDoc comments
rg "/**" src/mastra/agents/ -A3 | head -50

Repository: ssdeanx/AgentStack

Length of output: 3322


Add TSDoc for the exported agent.

Per TypeScript coding guidelines, public API exports require TSDoc comments documenting purpose, parameters, return values, and runtime constraints. Add a comment block above composioAgent describing its role, the tools it uses (Composio integrations), and any environment requirements (e.g., COMPOSIO_API_KEY, COMPOSIO_USER_ID).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/agents/compsio.ts` around lines 22 - 37, Add a TSDoc block above
the exported composioAgent describing its purpose as the Composio integration
agent, listing its key configuration (uses Agent with model
'opencode/minimax-m2.5-free', memory LibsqlMemory, tools comptools, browser
agentBrowser, and workspace mainWorkspace), noting runtime constraints and
required environment variables (e.g., COMPOSIO_API_KEY and COMPOSIO_USER_ID),
and briefly documenting any important behavior such as maxRetries and
tracingPolicy; reference the exported symbol composioAgent and the Agent
constructor so reviewers can find the comment easily.

Comment on lines 1015 to 1017
const embeddingModel =
inputData.embeddingModel ?? fastembed.base
inputData.embeddingModel ?? fastembed
const embeddingBatchSize = inputData.embeddingBatchSize ?? 50
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

libsqlChunker silently ignores inputData.embeddingModel — pipeline always uses fastembed.

In libsqlChunker, line 1015–1016 resolves embeddingModel from inputData.embeddingModel ?? fastembed, but the subsequent embedMany call at line 1227 hardcodes model: fastembed and never uses the resolved embeddingModel. Users who supply a specific embedding model in the input schema will be silently overridden, which also diverges from mdocumentChunker (line 757–760) which wraps in ModelRouterEmbeddingModel(embeddingModel). This is a correctness bug and also means embeddingModel is effectively dead code in this tool.

🛠 Proposed fix
                         const result = await embedMany({
                             values: batch,
-                            model: fastembed,
+                            model: new ModelRouterEmbeddingModel(embeddingModel),
                             maxRetries: 3,

Or, if libsqlChunker is deliberately locked to fastembed for the 768-dim index, remove embeddingModel from CustomDocumentChunkingInputSchema (or override/ignore it explicitly) so callers don't get misled.

Also applies to: 1224-1236

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/tools/document-chunking.tool.ts` around lines 1015 - 1017,
libsqlChunker currently resolves embeddingModel from inputData.embeddingModel
but then calls embedMany with model: fastembed, so the user-supplied
embeddingModel is ignored; update the embedMany call(s) in libsqlChunker (the
call around embedMany at lines ~1227 and the block 1224-1236) to pass the
resolved embeddingModel variable (or wrap it with ModelRouterEmbeddingModel like
mdocumentChunker does) instead of hardcoding fastembed, or alternatively
remove/ignore embeddingModel from CustomDocumentChunkingInputSchema if the tool
must always use fastembed so callers aren’t misled.

Comment thread src/mastra/workspaces.ts
Comment on lines +205 to +218
isolation: 'none',
instructions: 'This is the main sandbox for the workspace. You can use this sandbox to execute commands and run processes as part of your tasks. Always be careful when executing commands and make sure to follow the instructions provided by the user',
nativeSandbox: {
allowNetwork: true, // Block network access (default)
readWritePaths: ['*'], // Additional writable paths
readOnlyPaths: [], // Additional read-only paths
allowSystemBinaries: true, // Allow access to system binaries (default: false)
},
onStart: sandboxStartHook,
onStop: sandboxStopHook,
env: {
PATH: sandboxPathEnv,
NODE_ENV: sandboxNodeEnv,
API_URL: process.env.API_URL ?? 'http://localhost:4111/api',
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Sandbox is effectively unisolated; inline comments are misleading.

The new sandbox options on lines 205-212 combine:

  • isolation: 'none'
  • allowNetwork: true
  • readWritePaths: ['*']
  • allowSystemBinaries: true

That is a fully-permissive sandbox: any agent-issued command can write anywhere the Node process can reach, call any system binary, and hit any network endpoint. If this is truly intended for local dev, it should at minimum be gated by NODE_ENV / an explicit env toggle so a production deployment doesn't inherit these defaults.

Separately, the inline comments on lines 208 and 210 are outdated and now contradict the values:

  • allowNetwork: true, // Block network access (default) — the comment says "Block" but the value allows.
  • readWritePaths: ['*'], // Additional writable paths'*' is not "additional", it's universal.

Per coding guidelines: "Keep comments accurate and update them when code changes to avoid outdated comments that no longer match the implementation."

🛡 Suggested tightening
     nativeSandbox: {
-        allowNetwork: true, // Block network access (default)
-        readWritePaths: ['*'], // Additional writable paths
-        readOnlyPaths: [], // Additional read-only paths
-        allowSystemBinaries: true, // Allow access to system binaries (default: false)
+        // Permissive by design for local dev; gate tighter defaults in production.
+        allowNetwork: process.env.SANDBOX_ALLOW_NETWORK !== 'false',
+        readWritePaths: [localWorkspacePath],
+        readOnlyPaths: [],
+        allowSystemBinaries: process.env.SANDBOX_ALLOW_SYSTEM_BINARIES === 'true',
     },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/workspaces.ts` around lines 205 - 218, The sandbox configuration
(isolation, nativeSandbox, readWritePaths, allowNetwork, allowSystemBinaries) is
currently fully permissive and has misleading inline comments; change the
defaults to safe values and gate any fully-permissive settings behind an
explicit env toggle (e.g., check NODE_ENV !== 'production' or a new
SANDBOX_UNRESTRICTED env flag) before applying isolation: 'none', allowNetwork:
true, readWritePaths: ['*'], or allowSystemBinaries: true in the nativeSandbox
object used by sandboxStartHook/sandboxStopHook; also update the inline comments
to accurately reflect the effective behavior (e.g., note that allowNetwork: true
permits network access and that readWritePaths: ['*'] grants global write
access) so production deployments never inherit an unrestricted sandbox by
default.

Comment thread src/mastra/workspaces.ts
Comment on lines 320 to 336
embedder: async (text: string) => {
const { embedding } = await embed({
model: fastembed.base,
model: fastembed,
value: text,
maxRetries: 3,
abortSignal: new AbortController().signal,
providerOptions: {
},
experimental_telemetry: {
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'mainWorkspace-embedder',
},
})
return embedding
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Does @mastra/fastembedexportfastembedas a callable/usable EmbeddingModel for the ai SDK's embed() function, or is.base (or another preset) required?

💡 Result:

Yes, @mastra/fastembed exports fastembed as a callable/usable EmbeddingModel directly compatible with the AI SDK's embed function. The default export fastembed (bge-small-en-v1.5 with v2 spec) can be passed as the model parameter without needing .base or another preset, though named exports like fastembed.base (bge-base-en-v1.5) are available for other models.

Citations:


🏁 Script executed:

#!/bin/bash
# Check what `@mastra/fastembed` actually exports for the 'fastembed' symbol.
fd -t f 'package.json' node_modules/@mastra/fastembed 2>/dev/null | head -1 | xargs -r cat
rg -nP '^\s*export\s+(const|function|default)?\s*(fastembed|base)\b' node_modules/@mastra/fastembed -g '*.d.ts' -g '*.ts' -C2 2>/dev/null | head -60

Repository: ssdeanx/AgentStack

Length of output: 44


🏁 Script executed:

# Check the actual file content at the specified lines
cat -n src/mastra/workspaces.ts | sed -n '315,340p'

Repository: ssdeanx/AgentStack

Length of output: 933


🏁 Script executed:

# Search for all workspace definitions and their embedder configurations
rg -n "embedder.*async.*text" src/mastra/workspaces.ts -A 15

Repository: ssdeanx/AgentStack

Length of output: 1032


🏁 Script executed:

# Search for vector index dimension configuration or references to 768
rg -n "768|dimension|fastembed\.base" src/mastra/ -i

Repository: ssdeanx/AgentStack

Length of output: 16616


🏁 Script executed:

# Check how fastembed is imported in this file
head -50 src/mastra/workspaces.ts | grep -n "import\|fastembed"

Repository: ssdeanx/AgentStack

Length of output: 77


Fix embedder model and abort signal handling in both workspace definitions.

Two issues in the embedder config (both workspaces at lines 320–336 and 414–428):

  1. abortSignal: new AbortController().signal allocates a controller on every embed call and discards the reference. The signal will never fire abort(), so this provides no cancellation. Either wire a real lifecycle-scoped controller or drop the field entirely.

  2. The embedder model uses bare fastembed instead of fastembed.base. The LibSQL vector index is explicitly configured to use fastembed.base with 768-dimension embeddings (src/mastra/config/libsql.ts lines 12–14). Bare fastembed is the bge-small-en-v1.5 model with 384 dimensions, creating a dimension mismatch that will fail at runtime when writing embeddings to the vector index.

Proposed fix
     embedder: async (text: string) => {
+    const controller = new AbortController();
     const { embedding } = await embed({
-      model: fastembed,
+      model: fastembed.base,
       value: text,
       maxRetries: 3,
-      abortSignal: new AbortController().signal,
-      providerOptions: {
-      },
+      abortSignal: controller.signal,
       experimental_telemetry: {
         isEnabled: true,
         recordInputs: true,
         recordOutputs: true,
         functionId: 'mainWorkspace-embedder',
         },
     })
     return embedding
     },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/workspaces.ts` around lines 320 - 336, The embedder functions
(embedder in both workspace definitions) are wrong: change the model from bare
fastembed to fastembed.base to match the LibSQL vector index (768-dim) and avoid
dimension mismatch, and remove the per-call AbortController (abortSignal: new
AbortController().signal) or replace it with a lifecycle-scoped controller
referenced outside the embedder so you can actually call abort()—i.e., either
drop the abortSignal field entirely in embedder or wire it to a long-lived
AbortController instance managed by the workspace lifecycle.

Comment thread src/mastra/workspaces.ts
Comment on lines +377 to +390
//const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', {
// cwd: '/',
// env: {
// ...process.env,
// NODE_ENV: 'development',
// },
// timeout: 60_000,
//})

//const connection = createMessageConnection(
// new StreamMessageReader(handle.reader),
// new StreamMessageWriter(handle.writer),
//)
//connection.listen()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove the commented-out LSP spawn block.

The previous inline LSP-server spawn has been replaced by the spawnWorkspaceLspProcess helper above; the commented-out copy (lines 377-390) should be deleted rather than kept as dead documentation.

-//const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', {
-//    cwd: '/',
-//    env: {
-//        ...process.env,
-//        NODE_ENV: 'development',
-//    },
-//    timeout: 60_000,
-//})
-
-//const connection = createMessageConnection(
-//  new StreamMessageReader(handle.reader),
-//  new StreamMessageWriter(handle.writer),
-//)
-//connection.listen()

As per coding guidelines: "Never comment out code; remove it instead and use version control history if needed."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', {
// cwd: '/',
// env: {
// ...process.env,
// NODE_ENV: 'development',
// },
// timeout: 60_000,
//})
//const connection = createMessageConnection(
// new StreamMessageReader(handle.reader),
// new StreamMessageWriter(handle.writer),
//)
//connection.listen()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/workspaces.ts` around lines 377 - 390, Remove the dead
commented-out LSP spawn block shown in the diff (the inline
spawn/StreamMessageReader/StreamMessageWriter code) and rely on the existing
spawnWorkspaceLspProcess helper instead; delete those commented lines so there’s
no leftover commented code in src/mastra/workspaces.ts and ensure any needed
logic is already covered by spawnWorkspaceLspProcess (and its callers) so
behavior does not change.

Comment thread src/mastra/workspaces.ts
Comment on lines 414 to 428
embedder: async (text: string) => {
const { embedding } = await embed({
model: fastembed.base,
model: fastembed,
value: text,
maxRetries: 3,
abortSignal: new AbortController().signal,
experimental_telemetry: {
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'mainWorkspace-embedder',
},
})
return embedding
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Copy-pasted functionId: 'mainWorkspace-embedder' in agentFsWorkspace.

The agentFsWorkspace embedder reports telemetry under the same functionId as mainWorkspace, which will conflate traces/metrics from two distinct workspaces under one identifier.

       experimental_telemetry: {
         isEnabled: true,
         recordInputs: true,
         recordOutputs: true,
-        functionId: 'mainWorkspace-embedder',
+        functionId: 'agentFsWorkspace-embedder',
         },

As per coding guidelines: "Observability hygiene (structured logs, right log levels, useful metrics) without behavior change."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
embedder: async (text: string) => {
const { embedding } = await embed({
model: fastembed.base,
model: fastembed,
value: text,
maxRetries: 3,
abortSignal: new AbortController().signal,
experimental_telemetry: {
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'mainWorkspace-embedder',
},
})
return embedding
},
embedder: async (text: string) => {
const { embedding } = await embed({
model: fastembed,
value: text,
maxRetries: 3,
abortSignal: new AbortController().signal,
experimental_telemetry: {
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'agentFsWorkspace-embedder',
},
})
return embedding
},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mastra/workspaces.ts` around lines 414 - 428, The embedder in
agentFsWorkspace is using the same telemetry functionId
('mainWorkspace-embedder') which will conflate metrics; update the embedder
definition inside agentFsWorkspace to use a distinct functionId (e.g.,
'agentFsWorkspace-embedder' or similar) in the experimental_telemetry.functionId
field so traces are separated from the mainWorkspace embedder; locate the
embedder async function in agentFsWorkspace and change only the functionId
string, leaving other telemetry flags and parameters unchanged.

@ssdeanx ssdeanx merged commit 89f7eb2 into main Apr 18, 2026
312 of 316 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants