Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/chat/providers/chat-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export function ChatProvider({
id: selectedAgent,
messages: outgoingMessages,
parts: outgoingMessages.flatMap(
(m) => (m.parts ?? []) as UIMessage['parts']
(m) => (m.parts ?? [])
),
trigger,
messageId,
Expand Down
28 changes: 28 additions & 0 deletions lib/types/chat-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { z } from 'zod'

export const chatTransportRequestSchema = z
.object({
id: z.string().optional(),
messages: z.array(z.unknown()).default([]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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([]),

trigger: z.string().optional(),
messageId: z.string().optional(),
requestMetadata: z.unknown().optional(),
requestContext: z.record(z.string(), z.unknown()).optional(),
memory: z
.object({
thread: z.string().optional(),
resource: z.string().optional(),
})
.partial()
.optional(),
data: z
.object({
agentId: z.string().min(1).optional(),
input: z.string().optional(),
})
.loose()
.optional(),
})
.loose()

export type ChatTransportRequest = z.infer<typeof chatTransportRequestSchema>
58 changes: 58 additions & 0 deletions memory-bank/activeContext.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,61 @@
## Active Context Update (2026-03-17 - codingAgents explicit tool-generic cleanup)

- User flagged that `codingAgents.ts` still contained an explicit `new Agent<...>` constructor and that the per-agent tool objects had been disturbed.
- Fixed `src/mastra/agents/codingAgents.ts` by:
- removing the remaining explicit generic constructor from `codeReviewerAgent`
- restoring the local per-agent tool objects (`codeArchitectTools`, `codeReviewerTools`, `testEngineerTools`, `refactoringTools`) with concrete tool names
- normalizing `codeArchitectAgent` model selection back to shared request-context helper usage rather than raw string access
- removing the stray unused `scrapingSchedulerTool` import
- Validation:
- targeted `get_errors` on `src/mastra/agents/codingAgents.ts` returned **No errors found**
- folder-level `get_errors` on `src/mastra/agents` returned **No errors found**

## Active Context Update (2026-03-17 - networks/a2a nested-agent cleanup completed without ToolsInput adaptering)

- Completed the follow-up fix pass for the remaining `src/mastra/networks` and `src/mastra/a2a` nested child-agent assignment failures.
- User direction was explicit: do **not** rely on any shared adapter or `as Record<string, Agent>` cast, and do **not** introduce gratuitous `ToolsInput` typing into agents.
- Source-level fix applied across the remaining child agents by:
- removing narrowed `RequestContext<SpecificContext>` instruction callback annotations from public agent surfaces
- pinning affected child agents to public `new Agent<..., unknown>(...)` request-context generics
- keeping specialized runtime-context parsing local inside instruction bodies via explicit narrowing/constants
- removing the extra `ToolsInput` usage introduced in the touched agents; tool maps now use direct inferred object types (`typeof toolMap`) or `Record<string, never>` for tool-less agents
- Additional cleanup included:
- `codingAgents.ts` refactoring-tool typing cleanup
- `codingA2ACoordinator.ts` / `a2aCoordinatorAgent.ts` unused-parameter cleanup
- `codingTeamNetwork.ts` synchronous quality gate fix
- Source agents updated in this pass:
- `dataExportAgent.ts`
- `dataIngestionAgent.ts`
- `dataTransformationAgent.ts`
- `reportAgent.ts`
- `stockAnalysisAgent.ts`
- `recharts.ts`
- `researchPaperAgent.ts`
- `documentProcessingAgent.ts`
- `learningExtractionAgent.ts`
- `scriptWriterAgent.ts`
- `package-publisher.ts`
- plus cleanup in previously touched `editorAgent.ts`, `copywriterAgent.ts`, `knowledgeIndexingAgent.ts`, `researchAgent.ts`, `contentStrategistAgent.ts`, `evaluationAgent.ts`, and `codingAgents.ts`
- Validation result:
- targeted `get_errors` returned clean for all edited agent files
- targeted `get_errors` for `src/mastra/a2a` and `src/mastra/networks` no longer surfaced the earlier nested-agent assignment failures

## Active Context Update (2026-03-17 - nested agent typing without adapter)

- Resolved the `seoAgent.ts` nested child-agent type errors without using a shared adapter or local cast.
- Root cause: Mastra inferred narrower child `Agent<..., TRequestContext>` generics from `researchAgent`, `contentStrategistAgent`, and `evaluationAgent`, which made them fail assignment to parent `agents: Record<string, Agent<..., unknown>>` slots.
- Fix applied:
- centralized shared request-context keys in `src/mastra/agents/request-context.ts`
- replaced raw string usage in touched agents with declared constants/helpers
- explicitly pinned the public child-agent generic to `unknown` via `new Agent<..., unknown>(...)`
- kept runtime-safe parsing of specialized context values inside the agent instruction bodies
- Files updated:
- `src/mastra/agents/request-context.ts`
- `src/mastra/agents/researchAgent.ts`
- `src/mastra/agents/contentStrategistAgent.ts`
- `src/mastra/agents/evaluationAgent.ts`
- Validation: targeted `get_errors` is clean for all edited files and `src/mastra/agents/seoAgent.ts`.

## Active Context Update (2026-03-16 - use-mastra-query full client-js surface expansion)

- Expanded `lib/hooks/use-mastra-query.ts` beyond dataset/eval coverage to expose the remaining installed `@mastra/client-js` surfaces needed by the frontend hook factory.
Expand Down
38 changes: 38 additions & 0 deletions memory-bank/progress.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,41 @@
# 2026-03-17 codingAgents normalization

- Restored `codingAgents.ts` after a bad intermediate state:
- local tool objects are back in place by concrete tool name
- no explicit `new Agent<...>` tool generic remains in that file
- targeted validation for `codingAgents.ts` is clean
- Rechecked `src/mastra/agents` after the fix:
- ✅ **No errors found**

# 2026-03-17 full nested-agent source fix for networks/a2a

- 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.

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 (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.

Suggested change
- 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.

- Fixed adjacent diagnostics encountered during the pass:
- invalid `unknown` template interpolation in `knowledgeIndexingAgent.ts`
- `codingAgents.ts` unused import + `projectRoot` stringification issue
- unused `requestContext` / `userId` in A2A coordinators
- `codingTeamNetwork.ts` async/no-await quality-gate bug
- Validation:
- ✅ edited agent files clean
- ✅ `src/mastra/a2a` clean
- ✅ `src/mastra/networks` clean

# 2026-03-17 nested-agent typing fix without adapter

- Fixed the reported `seoAgent.ts` nested child-agent assignment failures for:
- `researchAgent`
- `contentStrategistAgent`
- `evaluationAgent`
- Kept the solution at the source rather than adding a parent-side adapter:
- shared request-context keys now come from `src/mastra/agents/request-context.ts`
- touched child agents parse specialized runtime context internally
- touched child agents now expose `unknown` as their public `Agent` request-context generic so direct parent registration compiles cleanly
- Validation:
- ✅ targeted `get_errors` on `request-context.ts`, `researchAgent.ts`, `contentStrategistAgent.ts`, `evaluationAgent.ts`, and `seoAgent.ts` returned clean
- ⚠️ folder-wide `get_errors` on `src/mastra/agents` still shows unrelated pre-existing diagnostics in `knowledgeIndexingAgent.ts`

# 2026-03-16 use-mastra-query full client-js hook expansion

- Completed the requested `@mastra/client-js` parity pass in `lib/hooks/use-mastra-query.ts` without replacing the file’s existing hook-factory pattern.
Expand Down
5 changes: 3 additions & 2 deletions src/mastra/a2a/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,16 @@ coordinate_a2a_task({

## Typing Note

- Parent coordinators that register child agents should use `@/src/mastra/agents/nestedAgents` for the `agents` config.
- This keeps the current Mastra nested-agent typing workaround isolated to one boundary while upstream typings remain restrictive.
- Do **not** rely on parent-side adapter helpers or `as Record<string, Agent>` casts for child-agent registration.
- Fix child agents at the source by exposing the public `Agent<..., unknown>` request-context generic and keeping any specialized runtime-context parsing inside the agent implementation.

---

## Change Log

| Version | Date (UTC) | Changes |
| ------- | ---------- | ----------------------------------------------- |
| 2.0.2 | 2026-03-17 | Updated guidance to use source-level public `unknown` request-context generics for child agents instead of adapter-based registration. |
| 2.0.1 | 2026-03-16 | Added note about `nestedAgents` boundary adapter for child-agent registration typing. |
| 2.0.0 | 2025-11-26 | Major update: documented all coordinated agents |
| 1.0.0 | 2025-11-14 | Initial A2A coordinator implementation |
7 changes: 3 additions & 4 deletions src/mastra/a2a/a2aCoordinatorAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
refactoringAgent,
testEngineerAgent,
} from '../agents/codingAgents'
import { asNestedAgents } from '@/src/mastra/agents/nestedAgents'
import { contentStrategistAgent } from '../agents/contentStrategistAgent'
import { copywriterAgent } from '../agents/copywriterAgent'
import { editorAgent } from '../agents/editorAgent'
Expand Down Expand Up @@ -40,7 +39,7 @@ export const a2aCoordinatorAgent = new Agent({
name: 'a2aCoordinator',
description:
'A2A Coordinator that orchestrates multiple specialized agents in parallel. Routes tasks dynamically, coordinates workflows, and synthesizes results using the A2A protocol.',
instructions: ({ requestContext }) => {
instructions: () => {
// const userId = requestContext.get('userId')
return {
role: 'system',
Expand Down Expand Up @@ -108,7 +107,7 @@ Use knowledgeIndexingAgent to provide semantic context for complex queries.
model: googleAI,
memory: pgMemory,
options: {},
agents: asNestedAgents({
agents: {
researchAgent,
knowledgeIndexingAgent,
editorAgent,
Expand All @@ -119,7 +118,7 @@ Use knowledgeIndexingAgent to provide semantic context for complex queries.
refactoringAgent,
contentStrategistAgent,
projectManagementAgent,
}),
},
workflows: {
researchSynthesisWorkflow,
repoIngestionWorkflow,
Expand Down
8 changes: 3 additions & 5 deletions src/mastra/a2a/codingA2ACoordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
refactoringAgent,
testEngineerAgent,
} from '../agents/codingAgents'
import { asNestedAgents } from '@/src/mastra/agents/nestedAgents'
import {
checkFileExists,
createDirectory,
Expand Down Expand Up @@ -59,8 +58,7 @@ export const codingA2ACoordinator = new Agent({
name: 'Coding A2A Coordinator',
description:
'A2A Coordinator that orchestrates multiple coding agents in parallel for complex development tasks like full feature development, comprehensive reviews, and refactoring with tests.',
instructions: ({ requestContext }) => {
const userId = requestContext.get('userId')
instructions: () => {
return {
role: 'system',
content: `You are a Coding A2A (Agent-to-Agent) Coordinator that orchestrates multi-agent coding workflows.
Expand Down Expand Up @@ -206,12 +204,12 @@ When a user's request requires prolonged, structured work across multiple subtas
model: googleAIFlashLite,
memory: pgMemory,

agents: asNestedAgents({
agents: {
codeArchitectAgent,
codeReviewerAgent,
testEngineerAgent,
refactoringAgent,
}),
},
workflows: {
researchSynthesisWorkflow,
financialReportWorkflow,
Expand Down
6 changes: 5 additions & 1 deletion src/mastra/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ This directory contains 22+ agent definitions that map use-case intents to seque
- **Logging**: Use the provided logger for consistent logging
- **Testing**: Write unit tests for all agent functionality
- **Documentation**: Document your agent's purpose, inputs, and outputs
- **Nested Agent Registration**: When an agent exposes child agents via the `agents` config, use `@/src/mastra/agents/nestedAgents` to adapt Mastra's current nested-agent typing without spreading one-off workarounds across files.
- **Nested Agent Registration**: Prefer fixing child-agent public generics at the source. If a child agent needs specialized runtime context internally, keep that parsing inside its instruction/helpers while pinning the public `Agent<..., unknown>` request-context generic so parent `agents` registration remains directly assignable.
- **Tool Typing**: Avoid adding `ToolsInput` annotations to agent definitions unless they are truly required. Prefer inferred tool maps (`const tools = { ... }`) with `typeof tools`, or `Record<string, never>` for tool-less agents.

## Execution & Testing

Expand Down Expand Up @@ -121,6 +122,9 @@ npm test src/mastra/__tests__/agents/your-agent.test.ts
| Version | Date (UTC) | Changes |
| ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| 2.2.0 | 2025-12-15 | Added 5 new specialized agents: socialMediaAgent, seoAgent, translationAgent, customerSupportAgent, projectManagementAgent. |
| 2.2.4 | 2026-03-17 | Normalized `codingAgents.ts` by restoring concrete per-agent tool maps and removing the last explicit `new Agent<...>` tool generic; `src/mastra/agents` now validates clean. |
| 2.2.3 | 2026-03-17 | Removed unnecessary `ToolsInput` usage from touched agents and completed the source-level `unknown` request-context fix for all remaining network/A2A child-agent registrations. |
| 2.2.2 | 2026-03-17 | Fixed direct nested-agent registration typing by centralizing request-context keys and pinning touched child agents to public `unknown` request-context generics instead of using an adapter in parent registrations. |
| 2.2.1 | 2026-03-16 | Added `nestedAgents.ts` boundary adapter for Mastra nested sub-agent typing and cleaned folder-level agent errors. |
| 2.1.0 | 2025-11-28 | Added 4 Financial Chart agents: chartTypeAdvisorAgent, chartDataProcessorAgent, chartGeneratorAgent, chartSupervisorAgent. |
| 2.0.0 | 2025-11-26 | Major update: 22 agents documented. Added data pipeline, research paper, document processing, knowledge indexing agents. |
Expand Down
10 changes: 3 additions & 7 deletions src/mastra/agents/academicResearchAgent.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { GoogleGenerativeAIProviderOptions } from '@ai-sdk/google'
import { Agent } from '@mastra/core/agent'
import type { RequestContext } from '@mastra/core/request-context'
import type { AgentRequestContext } from './request-context'

import { google } from '../config/google'
import { log } from '../config/logger'
Expand All @@ -18,14 +19,9 @@ import {
import { extractLearningsTool } from '../tools/extractLearningsTool'
import { InternalSpans } from '@mastra/core/observability'

type UserTier = 'free' | 'pro' | 'enterprise'

export interface AcademicResearchRuntimeContext {
'user-tier': UserTier
language: 'en' | 'es' | 'ja' | 'fr'
userId?: string
export type AcademicResearchRuntimeContext = AgentRequestContext<{
researchType?: 'quick' | 'deep' | 'systematic'
}
}>

log.info('Initializing Academic Research Agent...')

Expand Down
6 changes: 3 additions & 3 deletions src/mastra/agents/acpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ import type { RequestContext } from '@mastra/core/request-context'
import { PGVECTOR_PROMPT } from '@mastra/pg'
import { TokenLimiterProcessor } from '@mastra/core/processors'
import { InternalSpans } from '@mastra/core/observability'
import type { AgentRequestContext } from './request-context'

export interface ACPContext {
userId?: string
export type ACPContext = AgentRequestContext<{
userRole?: string
}
}>

export const acpAgent = new Agent({
id: 'acpAgent',
Expand Down
8 changes: 3 additions & 5 deletions src/mastra/agents/businessLegalAgents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
UnicodeNormalizer,
} from '@mastra/core/processors'
import type { RequestContext } from '@mastra/core/request-context'
import type { AgentRequestContext } from './request-context'
import {
createAnswerRelevancyScorer,
createToxicityScorer,
Expand Down Expand Up @@ -46,10 +47,7 @@ type Research = 'simple' | 'deep' | 'extensive' | 'extreme' | 'ultra' | 'insane'

type AnalysisConfig = 'summary' | 'detailed' | 'extensive' | 'full'

type UserTier = 'free' | 'pro' | 'enterprise'
export interface BusinessRuntimeContext {
'user-tier': UserTier
language: 'en' | 'es' | 'ja' | 'fr'
export type BusinessRuntimeContext = AgentRequestContext<{
responseFormat: 'json' | 'markdown'
research: {
depth: Research
Expand All @@ -59,7 +57,7 @@ export interface BusinessRuntimeContext {
depth: Research
scope: AnalysisConfig
}
}
}>

const isResearchConfig = (value: unknown): value is BusinessRuntimeContext['research'] => {
if (typeof value !== 'object' || value === null) {
Expand Down
5 changes: 2 additions & 3 deletions src/mastra/agents/calendarAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import { InternalSpans } from '@mastra/core/observability'
import { TokenLimiterProcessor } from '@mastra/core/processors'
import type { RequestContext } from '@mastra/core/request-context'
import { googleAIFlashLite, pgMemory } from '../config'
import type { AgentRequestContext } from './request-context'
import {
findFreeSlots,
getTodayEvents,
getUpcomingEvents,
listEvents,
} from '../tools/calendar-tool'

export interface CalendarContext {
userId?: string
}
export type CalendarContext = AgentRequestContext

export const calendarAgent = new Agent({
id: 'calendarAgent',
Expand Down
Loading
Loading