Repository navigation
Conversation
…itions - Introduced a new `request-context.ts` file to centralize request context management for agents. - Created a `BaseAgentRequestContext` interface to standardize user tier and language handling across agents. - Implemented utility functions `getUserTierFromContext` and `getLanguageFromContext` to simplify context retrieval. - Updated all agents (reportAgent, researchAgent, researchPaperAgent, scriptWriterAgent, seoAgent, socialMediaAgent, stockAnalysisAgent, translationAgent, weatherAgent, webResearchAgent) to use the new context handling methods, removing redundant code. - Replaced `asNestedAgents` usage in network definitions with direct agent assignments to improve type safety and clarity. - Added a new `chat-request.ts` file defining a schema for chat transport requests using Zod for validation. - Updated documentation in `AGENTS.md` to reflect changes in agent wiring and context handling. - Enhanced type definitions for agent contexts to support additional properties and improve type safety.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
Reviewer's GuideRefactors agent request-context handling into a shared request-context module, updates many agents and networks to consume the new helpers and unified AgentRequestContext typing, replaces nestedAgents adapter usage with direct child-agent registration, and introduces a validated chat transport request schema for frontend/backend integration. Sequence diagram for chat transport request handling with validated contextsequenceDiagram
actor Client
participant ChatAPI
participant chatTransportRequestSchema
participant request_context_module as request-context.ts
participant AgentInstance as Agent
Client->>ChatAPI: send ChatTransportRequest payload
ChatAPI->>chatTransportRequestSchema: parse(payload)
chatTransportRequestSchema-->>ChatAPI: validated_request or error
ChatAPI->>ChatAPI: extract requestContext, memory, data.agentId
ChatAPI->>request_context_module: buildSharedRequestContextPayload(sharedPayload)
request_context_module-->>ChatAPI: contextRecord
ChatAPI->>request_context_module: createAgentRequestContext(payload, identity)
request_context_module-->>ChatAPI: RequestContext_AgentRequestContext_
ChatAPI->>AgentInstance: invoke(messages, requestContext)
AgentInstance->>request_context_module: getUserTierFromContext(requestContext)
AgentInstance->>request_context_module: getLanguageFromContext(requestContext)
AgentInstance->>request_context_module: resolveTieredModelFromContext(requestContext, models)
request_context_module-->>AgentInstance: userTier, language, modelId
AgentInstance-->>ChatAPI: streaming or final response
ChatAPI-->>Client: response
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
🤖 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. |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (60)
Summary by CodeRabbit
WalkthroughThis PR refactors the MAStra agent system by introducing centralized request-context utilities, replacing agent runtime context interfaces with generic type aliases, removing the Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a significant refactoring of how request context is managed and utilized across the agent ecosystem. By centralizing context definitions and providing helper functions, it streamlines development, enhances type safety, and removes boilerplate code from individual agent implementations. The changes also improve the clarity and maintainability of agent and network configurations, alongside adding a new Zod schema for chat transport requests. Highlights
Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details. |
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- In several agents (e.g., customerSupportAgent, projectManagementAgent, socialMediaAgent, translationAgent) you're still casting the
agentsmap toRecord<string, Agent>; now that child agent generics have been normalized, consider removing these casts entirely and letting the types infer cleanly. - In editorAgent you manually read
USER_TIER_CONTEXT_KEYinside themodelfunction instead of usinggetUserTierFromContext; aligning this with the new helper would reduce duplication and keep fallback/validation behavior consistent with the rest of the agents.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In several agents (e.g., customerSupportAgent, projectManagementAgent, socialMediaAgent, translationAgent) you're still casting the `agents` map to `Record<string, Agent>`; now that child agent generics have been normalized, consider removing these casts entirely and letting the types infer cleanly.
- In editorAgent you manually read `USER_TIER_CONTEXT_KEY` inside the `model` function instead of using `getUserTierFromContext`; aligning this with the new helper would reduce duplication and keep fallback/validation behavior consistent with the rest of the agents.
## Individual Comments
### Comment 1
<location path="memory-bank/progress.md" line_range="14" />
<code_context>
+
+- Completed the remaining nested-agent typing cleanup the user requested across `src/mastra/networks` and `src/mastra/a2a`.
+- Removed the bad `ToolsInput` additions from the touched agent implementations.
+- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering.
+- Fixed adjacent diagnostics encountered during the pass:
+ - invalid `unknown` template interpolation in `knowledgeIndexingAgent.ts`
</code_context>
<issue_to_address>
**issue (typo):** The term "adaptering" here is unconventional; "adapting" would be clearer.
Consider updating the phrase to "casting/adapting" or "casting/adapter-based registration" to align with standard terminology.
```suggestion
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adapting.
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
|
|
||
| - Completed the remaining nested-agent typing cleanup the user requested across `src/mastra/networks` and `src/mastra/a2a`. | ||
| - Removed the bad `ToolsInput` additions from the touched agent implementations. | ||
| - Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering. |
There was a problem hiding this comment.
issue (typo): The term "adaptering" here is unconventional; "adapting" would be clearer.
Consider updating the phrase to "casting/adapting" or "casting/adapter-based registration" to align with standard terminology.
| - Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering. | |
| - Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adapting. |
There was a problem hiding this comment.
Pull request overview
This PR standardizes Mastra agent request-context handling by introducing a shared request-context.ts module, updating agents to use the shared helpers/types, and removing the previous nested-agent adapter approach in favor of direct agent registration.
Changes:
- Centralized request-context keys/types and added helpers for tier/language/model override resolution.
- Updated many agents to use the new context helpers and consolidated tool maps into named objects.
- Removed
nestedAgentsadapter usage across networks/A2A coordinators and added a Zod schema for chat transport requests.
Reviewed changes
Copilot reviewed 60 out of 60 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
| src/mastra/networks/securityNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/researchPipelineNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/reportGenerationNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/marketingAutomationNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/learningNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/index.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/financialIntelligenceNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/devopsNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/dataPipelineNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/contentCreationNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/codingTeamNetwork.ts | Fixes quality-check processor to be synchronous; removes asNestedAgents usage. |
| src/mastra/networks/businessIntelligenceNetwork.ts | Removes asNestedAgents usage; registers child agents directly. |
| src/mastra/networks/AGENTS.md | Updates guidance away from adapters/casts toward source-level agent typing. |
| src/mastra/agents/webResearchAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/weather-agent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/translationAgent.ts | Removes asNestedAgents import; uses direct child agents (still has a cast). |
| src/mastra/agents/stockAnalysisAgent.ts | Uses shared context helpers; consolidates tool map. |
| src/mastra/agents/socialMediaAgent.ts | Removes asNestedAgents import; uses direct child agents (still has a cast). |
| src/mastra/agents/seoAgent.ts | Removes asNestedAgents import; uses direct child agents. |
| src/mastra/agents/scriptWriterAgent.ts | Uses shared context helpers; consolidates tool map. |
| src/mastra/agents/researchPaperAgent.ts | Uses shared context helpers; consolidates tool map. |
| src/mastra/agents/researchAgent.ts | Uses shared context helpers; adds typed parsing for researchPhase; consolidates tool map. |
| src/mastra/agents/request-context.ts | New shared request-context keys/types/helpers (tier/language/model override, context creation). |
| src/mastra/agents/reportAgent.ts | Uses shared tier/language helpers in instructions; normalizes tools: {} placement. |
| src/mastra/agents/recharts.ts | Uses shared context helpers; adds typed parsing helpers for chart runtime keys; consolidates tool maps. |
| src/mastra/agents/projectManagementAgent.ts | Removes asNestedAgents import; uses direct child agents (still has a cast). |
| src/mastra/agents/package-publisher.ts | Uses shared context helpers; consolidates tool map. |
| src/mastra/agents/nestedAgents.ts | Deletes the nested-agent adapter helper. |
| src/mastra/agents/learningExtractionAgent.ts | Uses shared context keys/helpers; adds runtime narrowing for userId/researchPhase; sets tools: {}. |
| src/mastra/agents/knowledgeIndexingAgent.ts | Switches to shared request-context typing; adds constants and runtime narrowing; consolidates tool map. |
| src/mastra/agents/image_to_csv.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/image.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/graphingAgents.ts | Switches runtime context typing to shared AgentRequestContext; aligns tier key usage. |
| src/mastra/agents/financialAnalysisAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/excalidraw_validator.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/evaluationAgent.ts | Uses shared tier helper; sets tools: {}. |
| src/mastra/agents/editorAgent.ts | Uses shared tier/language helpers for instructions; updates runtime context type; sets tools: {}. |
| src/mastra/agents/documentProcessingAgent.ts | Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map. |
| src/mastra/agents/dataTransformationAgent.ts | Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map. |
| src/mastra/agents/dataProcessingAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/dataIngestionAgent.ts | Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map. |
| src/mastra/agents/dataExportAgent.ts | Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map. |
| src/mastra/agents/dane.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/customerSupportAgent.ts | Removes asNestedAgents import; uses direct child agents (still has a cast). |
| src/mastra/agents/csv_to_excalidraw.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/copywriterAgent.ts | Switches runtime context typing to shared AgentRequestContext; consolidates tool map; uses shared context keys. |
| src/mastra/agents/contentStrategistAgent.ts | Uses shared tier helper + shared keys; adds typed parsing helpers/constants; consolidates tool map. |
| src/mastra/agents/codingAgents.ts | Uses shared context helpers; consolidates per-agent tool maps; uses tiered model resolver. |
| src/mastra/agents/calendarAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/businessLegalAgents.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/acpAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/academicResearchAgent.ts | Switches runtime context typing to shared AgentRequestContext. |
| src/mastra/agents/AGENTS.md | Updates repo guidance toward source-level typing + inferred tool maps; changelog entry. |
| src/mastra/a2a/codingA2ACoordinator.ts | Removes asNestedAgents usage; registers child agents directly; removes unused requestContext usage. |
| src/mastra/a2a/a2aCoordinatorAgent.ts | Removes asNestedAgents usage; registers child agents directly; removes unused requestContext usage. |
| src/mastra/a2a/AGENTS.md | Updates A2A guidance away from adapters/casts toward source-level agent typing. |
| memory-bank/progress.md | Documents the typing cleanup/normalization work performed. |
| memory-bank/activeContext.md | Documents the typing cleanup/normalization work performed. |
| lib/types/chat-request.ts | Adds Zod schema/type for chat transport request payloads. |
| app/chat/providers/chat-context.tsx | Removes unnecessary type assertion when flattening message parts. |
Comments suppressed due to low confidence (1)
src/mastra/agents/copywriterAgent.ts:56
requestContext.get(USER_ID_CONTEXT_KEY)returnsunknown, but it’s interpolated into the system prompt directly. If a non-string value is ever present, this will produce confusing output (e.g.,[object Object]). Consider narrowing tostring(as several other agents do) and falling back to'anonymous'when the value isn’t a valid user id string.
instructions: ({ requestContext }) => {
const userId = requestContext.get(USER_ID_CONTEXT_KEY)
return {
role: 'system',
content: `
# Copywriter Agent
User: ${userId ?? 'anonymous'}
You can also share your feedback on Copilot code review. Take the survey.
| agents: { | ||
| copywriterAgent, | ||
| contentStrategistAgent, | ||
| researchAgent, | ||
| calendarAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
| agents: { | ||
| calendarAgent, | ||
| reportAgent, | ||
| evaluationAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
| evaluationAgent, | ||
| reportAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
| const userTier = | ||
| typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string' | ||
| ? requestContext.get(USER_TIER_CONTEXT_KEY) | ||
| : 'free' |
| import type { RequestContext } from '@mastra/core/request-context' | ||
| import { | ||
| USER_ID_CONTEXT_KEY, | ||
| USER_TIER_CONTEXT_KEY, |
| export function getModelOverrideFromContext( | ||
| requestContext: RequestContextReader | undefined | ||
| ): string | undefined { | ||
| const providerId = requestContext?.get(PROVIDER_ID_CONTEXT_KEY) | ||
| const modelId = requestContext?.get(MODEL_ID_CONTEXT_KEY) | ||
|
|
||
| if (typeof modelId !== 'string' || modelId.trim().length === 0) { | ||
| return undefined | ||
| } | ||
|
|
||
| if (modelId.includes('/')) { | ||
| return modelId.trim() | ||
| } | ||
|
|
||
| if (typeof providerId === 'string' && providerId.trim().length > 0) { | ||
| return `${providerId}/${modelId}` | ||
| } |
| agents: { | ||
| evaluationAgent, | ||
| researchAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
There was a problem hiding this comment.
Code Review
This pull request introduces a significant and valuable refactoring to centralize agent request context handling. The introduction of request-context.ts with shared types and helper functions is a great step towards improving type safety and maintainability across the agent ecosystem. The removal of the asNestedAgents helper and the move towards direct agent assignment is also a positive change. My review focuses on ensuring these new patterns are applied consistently and identifying a few areas where the new abstractions could be further leveraged. I've also noted some places where type safety could be further improved.
| export const chatTransportRequestSchema = z | ||
| .object({ | ||
| id: z.string().optional(), | ||
| messages: z.array(z.unknown()).default([]), |
There was a problem hiding this comment.
The schema for messages is currently using z.array(z.unknown()), which provides no type safety for the message objects. To improve validation and align with the goal of better type safety, consider defining a more specific schema for the message objects. Even a minimal schema would be an improvement.
For example, you could define a schema that validates the basic structure of a message:
const messagePartSchema = z.object({
type: z.string(),
}).passthrough();
const messageSchema = z.object({
id: z.string(),
role: z.enum(['user', 'assistant', 'system', 'tool']),
parts: z.array(messagePartSchema),
}).passthrough();
// ... in chatTransportRequestSchema
messages: z.array(messageSchema).default([]),| evaluationAgent, | ||
| reportAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
There was a problem hiding this comment.
The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".
The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.
| const userTier = | ||
| typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string' | ||
| ? requestContext.get(USER_TIER_CONTEXT_KEY) | ||
| : 'free' |
There was a problem hiding this comment.
For consistency and to fully leverage the new centralized context handling, it's better to use the getUserTierFromContext helper function here, just as it's used in the instructions function within the same agent. This avoids duplicating the logic for retrieving and providing a fallback for the user tier.
| const userTier = | |
| typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string' | |
| ? requestContext.get(USER_TIER_CONTEXT_KEY) | |
| : 'free' | |
| const userTier = getUserTierFromContext(requestContext) |
| }) => { | ||
| const lang = requestContext.get('language') ?? 'en' | ||
| const tier = requestContext.get('userTier') ?? 'free' | ||
| const tier = requestContext.get('user-tier') ?? 'free' |
There was a problem hiding this comment.
For consistency with the refactoring patterns introduced in this PR, consider using the getUserTierFromContext helper function from src/mastra/agents/request-context.ts to retrieve the user tier. This will centralize the logic and make the code more maintainable.
You'll need to import it first:
import { getUserTierFromContext } from './request-context'
| const tier = requestContext.get('user-tier') ?? 'free' | |
| const tier = getUserTierFromContext(requestContext) ?? 'free' |
| reportAgent, | ||
| evaluationAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
There was a problem hiding this comment.
The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".
The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.
| } | ||
|
|
||
| function isUserTier(value: unknown): value is UserTier { | ||
| return value === 'free' || value === 'pro' || value === 'enterprise' |
| } | ||
|
|
||
| function isSupportedLanguage(value: unknown): value is SupportedLanguage { | ||
| return value === 'en' || value === 'es' || value === 'ja' || value === 'fr' |
There was a problem hiding this comment.
| researchAgent, | ||
| calendarAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
There was a problem hiding this comment.
The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".
The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.
| evaluationAgent, | ||
| researchAgent, | ||
| }), | ||
| } as Record<string, Agent>, |
There was a problem hiding this comment.
The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".
The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.
…itions
request-context.tsfile to centralize request context management for agents.BaseAgentRequestContextinterface to standardize user tier and language handling across agents.getUserTierFromContextandgetLanguageFromContextto simplify context retrieval.asNestedAgentsusage in network definitions with direct agent assignments to improve type safety and clarity.chat-request.tsfile defining a schema for chat transport requests using Zod for validation.AGENTS.mdto reflect changes in agent wiring and context handling.Summary by Sourcery
Centralize agent request context handling and nested agent wiring, simplifying runtime context access and improving type safety across agents and networks.
New Features:
Enhancements:
Documentation:
Chores: