@mastra/editor 0.16.4-alpha.7 → 0.16.4-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/arcade.cjs.map +1 -1
- package/dist/ee/index.cjs +6 -4
- package/dist/ee/index.cjs.map +1 -1
- package/dist/ee/index.js +5 -3
- package/dist/ee/index.js.map +1 -1
- package/dist/index.cjs +30 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +30 -22
- package/dist/index.js.map +1 -1
- package/dist/storage/index.js +1 -2
- package/package.json +8 -8
package/dist/arcade.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"arcade.cjs","names":["Arcade","MASTRA_RESOURCE_ID_KEY","executeOrAuthorizeZodTool"],"sources":["../src/providers/arcade.ts"],"sourcesContent":["import type {\n ToolProvider,\n ToolProviderInfo,\n ToolProviderToolkit,\n ToolProviderToolInfo,\n ToolProviderListResult,\n ListToolProviderToolsOptions,\n ResolveToolProviderToolsOptions,\n} from '@mastra/core/tool-provider';\nimport type { ToolAction } from '@mastra/core/tools';\nimport type { StorageToolConfig } from '@mastra/core/storage';\nimport { MASTRA_RESOURCE_ID_KEY } from '@mastra/core/request-context';\n\nimport { Arcade } from '@arcadeai/arcadejs';\nimport type {\n ToolDefinition,\n ExecuteToolResponse,\n ToolListParams as ArcadeToolListParams,\n} from '@arcadeai/arcadejs/resources';\nimport { toZodToolSet, executeOrAuthorizeZodTool } from '@arcadeai/arcadejs/lib/index';\nimport type { ZodTool, ToolAuthorizationResponse } from '@arcadeai/arcadejs/lib/index';\n\nexport interface ArcadeToolProviderConfig {\n /** Arcade AI API key */\n apiKey: string;\n /** Base URL for the Arcade API (defaults to https://api.arcade.dev) */\n baseURL?: string;\n}\n\n/*\n * Pre-seeded catalog of known Arcade toolkits, sourced from the Arcade\n * integrations page and verified against the API. This avoids the need to\n * paginate through 7 000+ tools just to list toolkit names.\n *\n * The cache is updated at runtime when `listTools()` or `resolveTools()` encounters\n * a toolkit that isn't already present, so newly-added Arcade integrations are\n * picked up automatically.\n */\nconst KNOWN_TOOLKITS: readonly { slug: string; name: string; description?: string; category?: string }[] = [\n { slug: 'AirtableApi', name: 'Airtable API', category: 'productivity' },\n { slug: 'ArcadeEngineApi', name: 'Arcade Engine API', category: 'development' },\n { slug: 'Asana', name: 'Asana', category: 'productivity' },\n { slug: 'AsanaApi', name: 'Asana API', category: 'productivity' },\n { slug: 'AshbyApi', name: 'Ashby API', category: 'productivity' },\n { slug: 'Attio', name: 'Attio', category: 'sales' },\n { slug: 'BoxApi', name: 'Box API', category: 'productivity' },\n { slug: 'Brightdata', name: 'Bright Data', category: 'development' },\n { slug: 'CalendlyApi', name: 'Calendly API', category: 'productivity' },\n { slug: 'Clickup', name: 'ClickUp', category: 'productivity' },\n { slug: 'ClickupApi', name: 'ClickUp API', category: 'productivity' },\n { slug: 'Confluence', name: 'Confluence', category: 'productivity' },\n { slug: 'CursorAgentsApi', name: 'Cursor Agents API', category: 'development' },\n { slug: 'CustomerioApi', name: 'Customer.io API', category: 'customer-support' },\n { slug: 'CustomerioPipelinesApi', name: 'Customer.io Pipelines API', category: 'customer-support' },\n { slug: 'CustomerioTrackApi', name: 'Customer.io Track API', category: 'customer-support' },\n { slug: 'DatadogApi', name: 'Datadog API', category: 'development' },\n { slug: 'Dropbox', name: 'Dropbox', category: 'productivity' },\n { slug: 'E2b', name: 'E2B', category: 'development' },\n { slug: 'ExaApi', name: 'Exa API', category: 'search' },\n { slug: 'Figma', name: 'Figma', category: 'productivity' },\n { slug: 'FigmaApi', name: 'Figma API', category: 'productivity' },\n { slug: 'Firecrawl', name: 'Firecrawl', category: 'development' },\n { slug: 'FreshserviceApi', name: 'Freshservice API', category: 'customer-support' },\n { slug: 'Github', name: 'GitHub', category: 'development' },\n { slug: 'GithubApi', name: 'GitHub API', category: 'development' },\n { slug: 'Gmail', name: 'Gmail', category: 'productivity' },\n { slug: 'Google', name: 'Google', category: 'search' },\n { slug: 'GoogleCalendar', name: 'Google Calendar', category: 'productivity' },\n { slug: 'GoogleContacts', name: 'Google Contacts', category: 'productivity' },\n { slug: 'GoogleDocs', name: 'Google Docs', category: 'productivity' },\n { slug: 'GoogleDrive', name: 'Google Drive', category: 'productivity' },\n { slug: 'GoogleFinance', name: 'Google Finance', category: 'search' },\n { slug: 'GoogleFlights', name: 'Google Flights', category: 'search' },\n { slug: 'GoogleHotels', name: 'Google Hotels', category: 'search' },\n { slug: 'GoogleJobs', name: 'Google Jobs', category: 'search' },\n { slug: 'GoogleMaps', name: 'Google Maps', category: 'search' },\n { slug: 'GoogleNews', name: 'Google News', category: 'search' },\n { slug: 'GoogleSearch', name: 'Google Search', category: 'search' },\n { slug: 'GoogleSheets', name: 'Google Sheets', category: 'productivity' },\n { slug: 'GoogleShopping', name: 'Google Shopping', category: 'search' },\n { slug: 'GoogleSlides', name: 'Google Slides', category: 'productivity' },\n { slug: 'Hubspot', name: 'HubSpot', category: 'sales' },\n { slug: 'HubspotAutomationApi', name: 'HubSpot Automation API', category: 'sales' },\n { slug: 'HubspotCmsApi', name: 'HubSpot CMS API', category: 'sales' },\n { slug: 'HubspotConversationsApi', name: 'HubSpot Conversations API', category: 'sales' },\n { slug: 'HubspotCrmApi', name: 'HubSpot CRM API', category: 'sales' },\n { slug: 'HubspotEventsApi', name: 'HubSpot Events API', category: 'sales' },\n { slug: 'HubspotMarketingApi', name: 'HubSpot Marketing API', category: 'sales' },\n { slug: 'HubspotMeetingsApi', name: 'HubSpot Meetings API', category: 'sales' },\n { slug: 'HubspotUsersApi', name: 'HubSpot Users API', category: 'sales' },\n { slug: 'Imgflip', name: 'Imgflip', category: 'entertainment' },\n { slug: 'IntercomApi', name: 'Intercom API', category: 'customer-support' },\n { slug: 'Jira', name: 'Jira', category: 'productivity' },\n { slug: 'Linear', name: 'Linear', category: 'productivity' },\n { slug: 'Linkedin', name: 'LinkedIn', category: 'social' },\n { slug: 'LumaApi', name: 'Luma API', category: 'productivity' },\n { slug: 'MailchimpMarketingApi', name: 'Mailchimp API', category: 'productivity' },\n { slug: 'Math', name: 'Math', category: 'utility' },\n { slug: 'Microsoft', name: 'Microsoft', category: 'productivity' },\n { slug: 'MicrosoftOnedrive', name: 'Microsoft OneDrive', category: 'productivity' },\n { slug: 'MicrosoftTeams', name: 'Microsoft Teams', category: 'social' },\n { slug: 'MicrosoftWord', name: 'Microsoft Word', category: 'productivity' },\n { slug: 'MiroApi', name: 'Miro API', category: 'productivity' },\n { slug: 'NotionToolkit', name: 'Notion', category: 'productivity' },\n { slug: 'OutlookCalendar', name: 'Outlook Calendar', category: 'productivity' },\n { slug: 'OutlookMail', name: 'Outlook Mail', category: 'productivity' },\n { slug: 'Pagerduty', name: 'PagerDuty', category: 'development' },\n { slug: 'PagerdutyApi', name: 'PagerDuty API', category: 'development' },\n { slug: 'PosthogApi', name: 'PostHog API', category: 'development' },\n { slug: 'Pylon', name: 'Pylon', category: 'customer-support' },\n { slug: 'PylonApi', name: 'Pylon API', category: 'customer-support' },\n { slug: 'Reddit', name: 'Reddit', category: 'social' },\n { slug: 'Salesforce', name: 'Salesforce', category: 'sales' },\n { slug: 'Sharepoint', name: 'Microsoft SharePoint', category: 'productivity' },\n { slug: 'Slack', name: 'Slack', category: 'social' },\n { slug: 'SlackApi', name: 'Slack API', category: 'social' },\n { slug: 'Spotify', name: 'Spotify', category: 'entertainment' },\n { slug: 'SquareupApi', name: 'SquareUp API', category: 'productivity' },\n { slug: 'Stripe', name: 'Stripe', category: 'payments' },\n { slug: 'StripeApi', name: 'Stripe API', category: 'payments' },\n { slug: 'TicktickApi', name: 'TickTick API', category: 'productivity' },\n { slug: 'TrelloApi', name: 'Trello API', category: 'productivity' },\n { slug: 'Twilio', name: 'Twilio', category: 'social' },\n { slug: 'VercelApi', name: 'Vercel API', category: 'development' },\n { slug: 'Walmart', name: 'Walmart', category: 'search' },\n { slug: 'WeaviateApi', name: 'Weaviate API', category: 'development' },\n { slug: 'X', name: 'X', category: 'social' },\n { slug: 'XeroApi', name: 'Xero API', category: 'productivity' },\n { slug: 'Youtube', name: 'Youtube', category: 'search' },\n { slug: 'Zendesk', name: 'Zendesk', category: 'customer-support' },\n { slug: 'ZohoBooksApi', name: 'Zoho Books API', category: 'payments' },\n { slug: 'Zoom', name: 'Zoom', category: 'social' },\n] as const;\n\n/**\n * Arcade AI tool provider adapter.\n *\n * Uses `@arcadeai/arcadejs` SDK for discovery and runtime tool resolution.\n * The SDK is a static import and tree-shaken if this provider class isn't used.\n *\n * Arcade tools use `Toolkit.ToolName` naming (e.g., `Github.GetRepository`).\n * Each toolkit groups related tools and manages its own auth requirements.\n *\n * Discovery methods (`listToolkits`, `listTools`, `getToolSchema`) use the\n * standard `tools.list()` / `tools.get()` SDK methods.\n *\n * Runtime method (`resolveTools`) uses `toZodToolSet` from `@arcadeai/arcadejs/lib`\n * to get executable ZodTool objects, then converts them to Mastra's ToolAction format.\n */\nexport class ArcadeToolProvider implements ToolProvider {\n readonly info: ToolProviderInfo = {\n id: 'arcade',\n name: 'Arcade AI',\n description: 'Access 7,000+ tools from 130+ app integrations via Arcade AI',\n };\n\n private config: ArcadeToolProviderConfig;\n private toolkitCache: Map<string, ToolProviderToolkit>;\n private client: Arcade | null = null;\n\n constructor(config: ArcadeToolProviderConfig) {\n this.config = config;\n this.toolkitCache = new Map();\n for (const tk of KNOWN_TOOLKITS) {\n this.toolkitCache.set(tk.slug, {\n slug: tk.slug,\n name: tk.name,\n description: tk.description ?? `Arcade AI ${tk.name} tools`,\n icon: tk.category,\n });\n }\n }\n\n /**\n * Get or create an Arcade client.\n */\n private getClient(): Arcade {\n if (!this.client) {\n this.client = new Arcade({\n apiKey: this.config.apiKey,\n ...(this.config.baseURL ? { baseURL: this.config.baseURL } : {}),\n });\n }\n return this.client;\n }\n\n /**\n * Absorb toolkit metadata from a tool listing into the cache.\n * Returns true if any new toolkit was discovered.\n */\n private absorbToolkits(items: ToolDefinition[]): boolean {\n let discovered = false;\n for (const tool of items) {\n const tk = tool.toolkit;\n if (tk?.name && !this.toolkitCache.has(tk.name)) {\n this.toolkitCache.set(tk.name, {\n slug: tk.name,\n name: tk.name,\n description: tk.description ?? `Arcade AI ${tk.name} tools`,\n });\n discovered = true;\n }\n }\n return discovered;\n }\n\n /**\n * List toolkits.\n *\n * Returns the pre-seeded catalog merged with any toolkits discovered at\n * runtime via `listTools()` or `resolveTools()` calls.\n */\n async listToolkits(): Promise<ToolProviderListResult<ToolProviderToolkit>> {\n const data = [...this.toolkitCache.values()].sort((a, b) => a.name.localeCompare(b.name));\n return { data };\n }\n\n /**\n * List available tools with optional toolkit and pagination filters.\n * Uses `tools.list({ toolkit, limit, offset })`.\n */\n async listTools(options?: ListToolProviderToolsOptions): Promise<ToolProviderListResult<ToolProviderToolInfo>> {\n const client = this.getClient();\n\n const limit = options?.perPage ?? 50;\n const page = options?.page ?? 1;\n const offset = (page - 1) * limit;\n\n const query: ArcadeToolListParams = { limit, offset };\n if (options?.toolkit) query.toolkit = options.toolkit;\n\n const result = await client.tools.list(query);\n const items: ToolDefinition[] = result.items ?? [];\n\n // Update toolkit cache with any newly-discovered toolkits\n this.absorbToolkits(items);\n\n let filtered: ToolDefinition[] = items;\n if (options?.search) {\n const searchLower = options.search.toLowerCase();\n filtered = items.filter(\n t =>\n t.name?.toLowerCase().includes(searchLower) ||\n t.description?.toLowerCase().includes(searchLower) ||\n t.qualified_name?.toLowerCase().includes(searchLower),\n );\n }\n\n const data: ToolProviderToolInfo[] = filtered.map(tool => ({\n slug: tool.qualified_name ?? `${tool.toolkit?.name}.${tool.name}`,\n name: tool.name,\n description: tool.description,\n toolkit: tool.toolkit?.name,\n }));\n\n return {\n data,\n pagination: {\n page,\n perPage: limit,\n total: result.total_count,\n hasMore: offset + items.length < (result.total_count ?? 0),\n },\n };\n }\n\n /**\n * Get the JSON schema for a specific tool by its qualified name (e.g., `Github.GetRepository`).\n */\n async getToolSchema(toolSlug: string): Promise<Record<string, unknown> | null> {\n try {\n const client = this.getClient();\n const tool: ToolDefinition = await client.tools.get(toolSlug);\n if (!tool) return null;\n\n // Convert Arcade's parameter array to a JSON Schema-like object\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n\n for (const param of tool.input?.parameters ?? []) {\n properties[param.name] = {\n ...(param.value_schema ?? {}),\n description: param.description,\n };\n if (param.required) required.push(param.name);\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve executable tools in Mastra's ToolAction format.\n *\n * Uses `toZodToolSet` from `@arcadeai/arcadejs/lib` to create ZodTool objects\n * with Zod schemas and execute functions, then wraps them as ToolAction objects.\n */\n async resolveTools(\n toolSlugs: string[],\n toolConfigs?: Record<string, StorageToolConfig>,\n options?: ResolveToolProviderToolsOptions,\n ): Promise<Record<string, ToolAction<unknown, unknown>>> {\n if (toolSlugs.length === 0) return {};\n\n const client = this.getClient();\n const resourceId = options?.requestContext?.[MASTRA_RESOURCE_ID_KEY];\n const userId = typeof resourceId === 'string' ? resourceId : (options?.userId ?? 'default');\n\n // Fetch tool definitions for the requested slugs\n const toolDefs = await Promise.all(toolSlugs.map(slug => client.tools.get(slug).catch(() => null)));\n const validDefs: ToolDefinition[] = toolDefs.filter((d): d is ToolDefinition => d !== null);\n\n if (validDefs.length === 0) return {};\n\n // Update toolkit cache with any newly-discovered toolkits\n this.absorbToolkits(validDefs);\n\n // Convert to executable ZodTool objects using Arcade's helper\n const zodToolSet: Record<string, ZodTool<ExecuteToolResponse | ToolAuthorizationResponse>> = toZodToolSet({\n tools: validDefs,\n client,\n userId,\n executeFactory: executeOrAuthorizeZodTool,\n });\n\n // Convert ZodTool objects to Mastra ToolAction format\n const result: Record<string, ToolAction<unknown, unknown>> = {};\n\n // Build a lookup from normalized name (Github_GetRepository) to qualified name (Github.GetRepository)\n const normalizedToQualified = new Map<string, string>();\n for (const d of validDefs) {\n const qn = d.qualified_name ?? `${d.toolkit?.name}.${d.name}`;\n normalizedToQualified.set(qn.replace(/\\./g, '_'), qn);\n }\n\n for (const [key, zodTool] of Object.entries(zodToolSet)) {\n const qualifiedName = normalizedToQualified.get(key) ?? key;\n const descOverride = toolConfigs?.[qualifiedName]?.description ?? toolConfigs?.[key]?.description;\n\n // Arcade SDK bundles a different Zod minor version than Mastra, so the\n // schema types are structurally identical at runtime but nominally\n // incompatible in TS. Cast through `unknown` to bridge the gap.\n result[qualifiedName] = {\n id: qualifiedName,\n description: descOverride ?? zodTool.description ?? '',\n inputSchema: zodTool.parameters as unknown as ToolAction<unknown, unknown>['inputSchema'],\n outputSchema: zodTool.output as unknown as ToolAction<unknown, unknown>['outputSchema'],\n execute: async (input: unknown) => {\n return zodTool.execute(input);\n },\n };\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAsCA,MAAM,iBAAqG;CACzG;EAAE,MAAM;EAAe,MAAM;EAAgB,UAAU;CAAe;CACtE;EAAE,MAAM;EAAmB,MAAM;EAAqB,UAAU;CAAc;CAC9E;EAAE,MAAM;EAAS,MAAM;EAAS,UAAU;CAAe;CACzD;EAAE,MAAM;EAAY,MAAM;EAAa,UAAU;CAAe;CAChE;EAAE,MAAM;EAAY,MAAM;EAAa,UAAU;CAAe;CAChE;EAAE,MAAM;EAAS,MAAM;EAAS,UAAU;CAAQ;CAClD;EAAE,MAAM;EAAU,MAAM;EAAW,UAAU;CAAe;CAC5D;EAAE,MAAM;EAAc,MAAM;EAAe,UAAU;CAAc;CACnE;EAAE,MAAM;EAAe,MAAM;EAAgB,UAAU;CAAe;CACtE;EAAE,MAAM;EAAW,MAAM;EAAW,UAAU;CAAe;CAC7D;EAAE,MAAM;EAAc,MAAM;EAAe,UAAU;CAAe;CACpE;EAAE,MAAM;EAAc,MAAM;EAAc,UAAU;CAAe;CACnE;EAAE,MAAM;EAAmB,MAAM;EAAqB,UAAU;CAAc;CAC9E;EAAE,MAAM;EAAi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c,IAAI,EAAE,eAOvD,QAAQ,eAAe;IACpD,aAAa,QAAQ;IACrB,cAAc,QAAQ;IACtB,SAAS,OAAO,UAAmB;KACjC,OAAO,QAAQ,QAAQ,KAAK;IAC9B;GACF;EACF;EAEA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"arcade.cjs","names":["Arcade","MASTRA_RESOURCE_ID_KEY","toZodToolSet","executeOrAuthorizeZodTool"],"sources":["../src/providers/arcade.ts"],"sourcesContent":["import type {\n ToolProvider,\n ToolProviderInfo,\n ToolProviderToolkit,\n ToolProviderToolInfo,\n ToolProviderListResult,\n ListToolProviderToolsOptions,\n ResolveToolProviderToolsOptions,\n} from '@mastra/core/tool-provider';\nimport type { ToolAction } from '@mastra/core/tools';\nimport type { StorageToolConfig } from '@mastra/core/storage';\nimport { MASTRA_RESOURCE_ID_KEY } from '@mastra/core/request-context';\n\nimport { Arcade } from '@arcadeai/arcadejs';\nimport type {\n ToolDefinition,\n ExecuteToolResponse,\n ToolListParams as ArcadeToolListParams,\n} from '@arcadeai/arcadejs/resources';\nimport { toZodToolSet, executeOrAuthorizeZodTool } from '@arcadeai/arcadejs/lib/index';\nimport type { ZodTool, ToolAuthorizationResponse } from '@arcadeai/arcadejs/lib/index';\n\nexport interface ArcadeToolProviderConfig {\n /** Arcade AI API key */\n apiKey: string;\n /** Base URL for the Arcade API (defaults to https://api.arcade.dev) */\n baseURL?: string;\n}\n\n/*\n * Pre-seeded catalog of known Arcade toolkits, sourced from the Arcade\n * integrations page and verified against the API. This avoids the need to\n * paginate through 7 000+ tools just to list toolkit names.\n *\n * The cache is updated at runtime when `listTools()` or `resolveTools()` encounters\n * a toolkit that isn't already present, so newly-added Arcade integrations are\n * picked up automatically.\n */\nconst KNOWN_TOOLKITS: readonly { slug: string; name: string; description?: string; category?: string }[] = [\n { slug: 'AirtableApi', name: 'Airtable API', category: 'productivity' },\n { slug: 'ArcadeEngineApi', name: 'Arcade Engine API', category: 'development' },\n { slug: 'Asana', name: 'Asana', category: 'productivity' },\n { slug: 'AsanaApi', name: 'Asana API', category: 'productivity' },\n { slug: 'AshbyApi', name: 'Ashby API', category: 'productivity' },\n { slug: 'Attio', name: 'Attio', category: 'sales' },\n { slug: 'BoxApi', name: 'Box API', category: 'productivity' },\n { slug: 'Brightdata', name: 'Bright Data', category: 'development' },\n { slug: 'CalendlyApi', name: 'Calendly API', category: 'productivity' },\n { slug: 'Clickup', name: 'ClickUp', category: 'productivity' },\n { slug: 'ClickupApi', name: 'ClickUp API', category: 'productivity' },\n { slug: 'Confluence', name: 'Confluence', category: 'productivity' },\n { slug: 'CursorAgentsApi', name: 'Cursor Agents API', category: 'development' },\n { slug: 'CustomerioApi', name: 'Customer.io API', category: 'customer-support' },\n { slug: 'CustomerioPipelinesApi', name: 'Customer.io Pipelines API', category: 'customer-support' },\n { slug: 'CustomerioTrackApi', name: 'Customer.io Track API', category: 'customer-support' },\n { slug: 'DatadogApi', name: 'Datadog API', category: 'development' },\n { slug: 'Dropbox', name: 'Dropbox', category: 'productivity' },\n { slug: 'E2b', name: 'E2B', category: 'development' },\n { slug: 'ExaApi', name: 'Exa API', category: 'search' },\n { slug: 'Figma', name: 'Figma', category: 'productivity' },\n { slug: 'FigmaApi', name: 'Figma API', category: 'productivity' },\n { slug: 'Firecrawl', name: 'Firecrawl', category: 'development' },\n { slug: 'FreshserviceApi', name: 'Freshservice API', category: 'customer-support' },\n { slug: 'Github', name: 'GitHub', category: 'development' },\n { slug: 'GithubApi', name: 'GitHub API', category: 'development' },\n { slug: 'Gmail', name: 'Gmail', category: 'productivity' },\n { slug: 'Google', name: 'Google', category: 'search' },\n { slug: 'GoogleCalendar', name: 'Google Calendar', category: 'productivity' },\n { slug: 'GoogleContacts', name: 'Google Contacts', category: 'productivity' },\n { slug: 'GoogleDocs', name: 'Google Docs', category: 'productivity' },\n { slug: 'GoogleDrive', name: 'Google Drive', category: 'productivity' },\n { slug: 'GoogleFinance', name: 'Google Finance', category: 'search' },\n { slug: 'GoogleFlights', name: 'Google Flights', category: 'search' },\n { slug: 'GoogleHotels', name: 'Google Hotels', category: 'search' },\n { slug: 'GoogleJobs', name: 'Google Jobs', category: 'search' },\n { slug: 'GoogleMaps', name: 'Google Maps', category: 'search' },\n { slug: 'GoogleNews', name: 'Google News', category: 'search' },\n { slug: 'GoogleSearch', name: 'Google Search', category: 'search' },\n { slug: 'GoogleSheets', name: 'Google Sheets', category: 'productivity' },\n { slug: 'GoogleShopping', name: 'Google Shopping', category: 'search' },\n { slug: 'GoogleSlides', name: 'Google Slides', category: 'productivity' },\n { slug: 'Hubspot', name: 'HubSpot', category: 'sales' },\n { slug: 'HubspotAutomationApi', name: 'HubSpot Automation API', category: 'sales' },\n { slug: 'HubspotCmsApi', name: 'HubSpot CMS API', category: 'sales' },\n { slug: 'HubspotConversationsApi', name: 'HubSpot Conversations API', category: 'sales' },\n { slug: 'HubspotCrmApi', name: 'HubSpot CRM API', category: 'sales' },\n { slug: 'HubspotEventsApi', name: 'HubSpot Events API', category: 'sales' },\n { slug: 'HubspotMarketingApi', name: 'HubSpot Marketing API', category: 'sales' },\n { slug: 'HubspotMeetingsApi', name: 'HubSpot Meetings API', category: 'sales' },\n { slug: 'HubspotUsersApi', name: 'HubSpot Users API', category: 'sales' },\n { slug: 'Imgflip', name: 'Imgflip', category: 'entertainment' },\n { slug: 'IntercomApi', name: 'Intercom API', category: 'customer-support' },\n { slug: 'Jira', name: 'Jira', category: 'productivity' },\n { slug: 'Linear', name: 'Linear', category: 'productivity' },\n { slug: 'Linkedin', name: 'LinkedIn', category: 'social' },\n { slug: 'LumaApi', name: 'Luma API', category: 'productivity' },\n { slug: 'MailchimpMarketingApi', name: 'Mailchimp API', category: 'productivity' },\n { slug: 'Math', name: 'Math', category: 'utility' },\n { slug: 'Microsoft', name: 'Microsoft', category: 'productivity' },\n { slug: 'MicrosoftOnedrive', name: 'Microsoft OneDrive', category: 'productivity' },\n { slug: 'MicrosoftTeams', name: 'Microsoft Teams', category: 'social' },\n { slug: 'MicrosoftWord', name: 'Microsoft Word', category: 'productivity' },\n { slug: 'MiroApi', name: 'Miro API', category: 'productivity' },\n { slug: 'NotionToolkit', name: 'Notion', category: 'productivity' },\n { slug: 'OutlookCalendar', name: 'Outlook Calendar', category: 'productivity' },\n { slug: 'OutlookMail', name: 'Outlook Mail', category: 'productivity' },\n { slug: 'Pagerduty', name: 'PagerDuty', category: 'development' },\n { slug: 'PagerdutyApi', name: 'PagerDuty API', category: 'development' },\n { slug: 'PosthogApi', name: 'PostHog API', category: 'development' },\n { slug: 'Pylon', name: 'Pylon', category: 'customer-support' },\n { slug: 'PylonApi', name: 'Pylon API', category: 'customer-support' },\n { slug: 'Reddit', name: 'Reddit', category: 'social' },\n { slug: 'Salesforce', name: 'Salesforce', category: 'sales' },\n { slug: 'Sharepoint', name: 'Microsoft SharePoint', category: 'productivity' },\n { slug: 'Slack', name: 'Slack', category: 'social' },\n { slug: 'SlackApi', name: 'Slack API', category: 'social' },\n { slug: 'Spotify', name: 'Spotify', category: 'entertainment' },\n { slug: 'SquareupApi', name: 'SquareUp API', category: 'productivity' },\n { slug: 'Stripe', name: 'Stripe', category: 'payments' },\n { slug: 'StripeApi', name: 'Stripe API', category: 'payments' },\n { slug: 'TicktickApi', name: 'TickTick API', category: 'productivity' },\n { slug: 'TrelloApi', name: 'Trello API', category: 'productivity' },\n { slug: 'Twilio', name: 'Twilio', category: 'social' },\n { slug: 'VercelApi', name: 'Vercel API', category: 'development' },\n { slug: 'Walmart', name: 'Walmart', category: 'search' },\n { slug: 'WeaviateApi', name: 'Weaviate API', category: 'development' },\n { slug: 'X', name: 'X', category: 'social' },\n { slug: 'XeroApi', name: 'Xero API', category: 'productivity' },\n { slug: 'Youtube', name: 'Youtube', category: 'search' },\n { slug: 'Zendesk', name: 'Zendesk', category: 'customer-support' },\n { slug: 'ZohoBooksApi', name: 'Zoho Books API', category: 'payments' },\n { slug: 'Zoom', name: 'Zoom', category: 'social' },\n] as const;\n\n/**\n * Arcade AI tool provider adapter.\n *\n * Uses `@arcadeai/arcadejs` SDK for discovery and runtime tool resolution.\n * The SDK is a static import and tree-shaken if this provider class isn't used.\n *\n * Arcade tools use `Toolkit.ToolName` naming (e.g., `Github.GetRepository`).\n * Each toolkit groups related tools and manages its own auth requirements.\n *\n * Discovery methods (`listToolkits`, `listTools`, `getToolSchema`) use the\n * standard `tools.list()` / `tools.get()` SDK methods.\n *\n * Runtime method (`resolveTools`) uses `toZodToolSet` from `@arcadeai/arcadejs/lib`\n * to get executable ZodTool objects, then converts them to Mastra's ToolAction format.\n */\nexport class ArcadeToolProvider implements ToolProvider {\n readonly info: ToolProviderInfo = {\n id: 'arcade',\n name: 'Arcade AI',\n description: 'Access 7,000+ tools from 130+ app integrations via Arcade AI',\n };\n\n private config: ArcadeToolProviderConfig;\n private toolkitCache: Map<string, ToolProviderToolkit>;\n private client: Arcade | null = null;\n\n constructor(config: ArcadeToolProviderConfig) {\n this.config = config;\n this.toolkitCache = new Map();\n for (const tk of KNOWN_TOOLKITS) {\n this.toolkitCache.set(tk.slug, {\n slug: tk.slug,\n name: tk.name,\n description: tk.description ?? `Arcade AI ${tk.name} tools`,\n icon: tk.category,\n });\n }\n }\n\n /**\n * Get or create an Arcade client.\n */\n private getClient(): Arcade {\n if (!this.client) {\n this.client = new Arcade({\n apiKey: this.config.apiKey,\n ...(this.config.baseURL ? { baseURL: this.config.baseURL } : {}),\n });\n }\n return this.client;\n }\n\n /**\n * Absorb toolkit metadata from a tool listing into the cache.\n * Returns true if any new toolkit was discovered.\n */\n private absorbToolkits(items: ToolDefinition[]): boolean {\n let discovered = false;\n for (const tool of items) {\n const tk = tool.toolkit;\n if (tk?.name && !this.toolkitCache.has(tk.name)) {\n this.toolkitCache.set(tk.name, {\n slug: tk.name,\n name: tk.name,\n description: tk.description ?? `Arcade AI ${tk.name} tools`,\n });\n discovered = true;\n }\n }\n return discovered;\n }\n\n /**\n * List toolkits.\n *\n * Returns the pre-seeded catalog merged with any toolkits discovered at\n * runtime via `listTools()` or `resolveTools()` calls.\n */\n async listToolkits(): Promise<ToolProviderListResult<ToolProviderToolkit>> {\n const data = [...this.toolkitCache.values()].sort((a, b) => a.name.localeCompare(b.name));\n return { data };\n }\n\n /**\n * List available tools with optional toolkit and pagination filters.\n * Uses `tools.list({ toolkit, limit, offset })`.\n */\n async listTools(options?: ListToolProviderToolsOptions): Promise<ToolProviderListResult<ToolProviderToolInfo>> {\n const client = this.getClient();\n\n const limit = options?.perPage ?? 50;\n const page = options?.page ?? 1;\n const offset = (page - 1) * limit;\n\n const query: ArcadeToolListParams = { limit, offset };\n if (options?.toolkit) query.toolkit = options.toolkit;\n\n const result = await client.tools.list(query);\n const items: ToolDefinition[] = result.items ?? [];\n\n // Update toolkit cache with any newly-discovered toolkits\n this.absorbToolkits(items);\n\n let filtered: ToolDefinition[] = items;\n if (options?.search) {\n const searchLower = options.search.toLowerCase();\n filtered = items.filter(\n t =>\n t.name?.toLowerCase().includes(searchLower) ||\n t.description?.toLowerCase().includes(searchLower) ||\n t.qualified_name?.toLowerCase().includes(searchLower),\n );\n }\n\n const data: ToolProviderToolInfo[] = filtered.map(tool => ({\n slug: tool.qualified_name ?? `${tool.toolkit?.name}.${tool.name}`,\n name: tool.name,\n description: tool.description,\n toolkit: tool.toolkit?.name,\n }));\n\n return {\n data,\n pagination: {\n page,\n perPage: limit,\n total: result.total_count,\n hasMore: offset + items.length < (result.total_count ?? 0),\n },\n };\n }\n\n /**\n * Get the JSON schema for a specific tool by its qualified name (e.g., `Github.GetRepository`).\n */\n async getToolSchema(toolSlug: string): Promise<Record<string, unknown> | null> {\n try {\n const client = this.getClient();\n const tool: ToolDefinition = await client.tools.get(toolSlug);\n if (!tool) return null;\n\n // Convert Arcade's parameter array to a JSON Schema-like object\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n\n for (const param of tool.input?.parameters ?? []) {\n properties[param.name] = {\n ...(param.value_schema ?? {}),\n description: param.description,\n };\n if (param.required) required.push(param.name);\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve executable tools in Mastra's ToolAction format.\n *\n * Uses `toZodToolSet` from `@arcadeai/arcadejs/lib` to create ZodTool objects\n * with Zod schemas and execute functions, then wraps them as ToolAction objects.\n */\n async resolveTools(\n toolSlugs: string[],\n toolConfigs?: Record<string, StorageToolConfig>,\n options?: ResolveToolProviderToolsOptions,\n ): Promise<Record<string, ToolAction<unknown, unknown>>> {\n if (toolSlugs.length === 0) return {};\n\n const client = this.getClient();\n const resourceId = options?.requestContext?.[MASTRA_RESOURCE_ID_KEY];\n const userId = typeof resourceId === 'string' ? resourceId : (options?.userId ?? 'default');\n\n // Fetch tool definitions for the requested slugs\n const toolDefs = await Promise.all(toolSlugs.map(slug => client.tools.get(slug).catch(() => null)));\n const validDefs: ToolDefinition[] = toolDefs.filter((d): d is ToolDefinition => d !== null);\n\n if (validDefs.length === 0) return {};\n\n // Update toolkit cache with any newly-discovered toolkits\n this.absorbToolkits(validDefs);\n\n // Convert to executable ZodTool objects using Arcade's helper\n const zodToolSet: Record<string, ZodTool<ExecuteToolResponse | ToolAuthorizationResponse>> = toZodToolSet({\n tools: validDefs,\n client,\n userId,\n executeFactory: executeOrAuthorizeZodTool,\n });\n\n // Convert ZodTool objects to Mastra ToolAction format\n const result: Record<string, ToolAction<unknown, unknown>> = {};\n\n // Build a lookup from normalized name (Github_GetRepository) to qualified name (Github.GetRepository)\n const normalizedToQualified = new Map<string, string>();\n for (const d of validDefs) {\n const qn = d.qualified_name ?? `${d.toolkit?.name}.${d.name}`;\n normalizedToQualified.set(qn.replace(/\\./g, '_'), qn);\n }\n\n for (const [key, zodTool] of Object.entries(zodToolSet)) {\n const qualifiedName = normalizedToQualified.get(key) ?? key;\n const descOverride = toolConfigs?.[qualifiedName]?.description ?? toolConfigs?.[key]?.description;\n\n // Arcade SDK bundles a different Zod minor version than Mastra, so the\n // schema types are structurally identical at runtime but nominally\n // incompatible in TS. Cast through `unknown` to bridge the gap.\n result[qualifiedName] = {\n id: qualifiedName,\n description: descOverride ?? zodTool.description ?? '',\n inputSchema: zodTool.parameters as unknown as ToolAction<unknown, unknown>['inputSchema'],\n outputSchema: zodTool.output as unknown as ToolAction<unknown, unknown>['outputSchema'],\n execute: async (input: unknown) => {\n return zodTool.execute(input);\n },\n };\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAsCA,MAAM,iBAAqG;CACzG;EAAE,MAAM;EAAe,MAAM;EAAgB,UAAU;CAAe;CACtE;EAAE,MAAM;EAAmB,MAAM;EAAqB,UAAU;CAAc;CAC9E;EAAE,MAAM;EAAS,MAAM;EAAS,UAAU;CAAe;CACzD;EAAE,MAAM;EAAY,MAAM;EAAa,UAAU;CAAe;CAChE;EAAE,MAAM;EAAY,MAAM;EAAa,UAAU;CAAe;CAChE;EAAE,MAAM;EAAS,MAAM;EAAS,UAAU;CAAQ;CAClD;EAAE,MAAM;EAAU,MAAM;EAAW,UAAU;CAAe;CAC5D;EAAE,MAAM;EAAc,MAAM;EAAe,UAAU;CAAc;CACnE;EAAE,MAAM;EAAe,MAAM;EAAgB,UAAU;CAAe;CACtE;EAAE,MAAM;EAAW,MAAM;EAAW,UAAU;CAAe;CAC7D;EAAE,MAAM;EAAc,MAAM;EAAe,UAAU;CAAe;CACpE;EAAE,MAAM;EAAc,MAAM;EAAc,UAAU;CAAe;CACnE;EAAE,MAAM;EAAmB,MAAM;EAAqB,UAAU;CAAc;CAC9E;EAAE,MAAM;EAAiB,MAAM;EAAmB,UAAU;CAAmB;CAC/E;EAAE,MAAM;EAA0B,MAAM;EAA6B,UAAU;CAAmB;CAClG;EAAE,MAAM;EAAsB,MAAM;EAAyB,UAAU;CAAmB;CAC1F;EAAE,MAAM;EAAc,MAAM;EAAe,UAAU;CAAc;CACnE;EAAE,MAAM;EAAW,MAAM;EAAW,UAAU;CAAe;CAC7D;EAAE,MAAM;EAAO,MAAM;EAAO,UAAU;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|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
@@ -133,8 +133,9 @@ var EditorAgentBuilder = class {
|
|
|
133
133
|
//#region src/ee/agent-builder-agent.ts
|
|
134
134
|
const __filename$1 = (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
|
|
135
135
|
const __dirname$1 = path.default.dirname(__filename$1);
|
|
136
|
+
const workspacePath = path.default.join(__dirname$1, "workspace");
|
|
136
137
|
const workspace = new _mastra_core_workspace.Workspace({
|
|
137
|
-
filesystem: new _mastra_core_workspace.LocalFilesystem({ basePath:
|
|
138
|
+
filesystem: new _mastra_core_workspace.LocalFilesystem({ basePath: workspacePath }),
|
|
138
139
|
skills: ["skills"]
|
|
139
140
|
});
|
|
140
141
|
/**
|
|
@@ -188,7 +189,7 @@ function createBuilderAgent(args) {
|
|
|
188
189
|
const memory = new _mastra_memory.Memory();
|
|
189
190
|
const callerErrorProcessors = args?.errorProcessors;
|
|
190
191
|
const errorProcessors = args?.errorProcessorDefaults === false ? callerErrorProcessors : Array.isArray(callerErrorProcessors) ? [...DEFAULT_BUILDER_ERROR_PROCESSORS.map((processor) => callerErrorProcessors.find((caller) => caller.id === processor.id) ?? processor), ...callerErrorProcessors.filter((caller) => !DEFAULT_BUILDER_ERROR_PROCESSORS.some((processor) => processor.id === caller.id))] : callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS;
|
|
191
|
-
|
|
192
|
+
const config = {
|
|
192
193
|
instructions: `You are the Agent Builder.
|
|
193
194
|
|
|
194
195
|
Your job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.
|
|
@@ -324,7 +325,8 @@ Keep this to 2–4 focused paragraphs or compact bullet groups. Do not include w
|
|
|
324
325
|
id: "builder-agent",
|
|
325
326
|
name: "Agent Builder Agent",
|
|
326
327
|
description: "An agent that can build agents"
|
|
327
|
-
}
|
|
328
|
+
};
|
|
329
|
+
return new _mastra_core_agent.Agent(config);
|
|
328
330
|
}
|
|
329
331
|
function createWorkflowBuilderAgent(model, lastMessages = 100) {
|
|
330
332
|
return (0, _mastra_core_workflows_builder.createWorkflowBuilderAgent)({
|
package/dist/ee/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["__filename","__dirname","Workspace","LocalFilesystem","ProviderHistoryCompat","PrefillErrorHandler","StreamErrorRetryProcessor","Memory","Agent","Memory"],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"sourcesContent":["import type { AgentBuilderOptions, AgentFeatures, IAgentBuilder } from '@mastra/core/agent-builder/ee';\nimport { isBuilderModelPolicyActive, isModelAllowed, resolveAgentFeatures } from '@mastra/core/agent-builder/ee';\n\n/**\n * Concrete implementation of the Agent Builder EE feature.\n * Instantiated by MastraEditor.resolveBuilder() when builder config is enabled.\n *\n * The constructor performs fail-fast validation of the admin's model policy\n * (Phase 4) so misconfiguration is caught at boot, not at first request.\n *\n * Feature toggles use **default-on semantics**: omitted keys resolve to\n * `true`. Admins opt out by setting a key to `false`. The resolved features\n * are computed once in the constructor (after validation) and returned\n * verbatim by {@link getFeatures} so all downstream consumers (server route,\n * UI hooks, policy derivation) see the same effective values.\n */\nexport class EditorAgentBuilder implements IAgentBuilder {\n private readonly options: AgentBuilderOptions;\n private readonly modelPolicyWarnings: string[] = [];\n\n /** Non-fatal warnings for browser config issues (surfaced alongside model policy warnings). */\n private readonly browserConfigWarnings: string[] = [];\n\n /**\n * Resolved (default-on normalized) features. Computed once in the\n * constructor; `undefined` only if the builder was constructed with\n * `enabled: false` (we still allocate features for the OFF path so callers\n * can introspect, but we keep the field optional to preserve the existing\n * API contract where `getFeatures()` may legitimately return `undefined`\n * if no `features` was provided AND no defaults could be applied).\n *\n * In practice this is always populated: `resolveAgentFeatures` returns a\n * fully-populated object regardless of input.\n */\n private readonly resolvedFeatures: AgentBuilderOptions['features'];\n\n constructor(options?: AgentBuilderOptions) {\n // Shallow-clone the paths the validators mutate so we never leak side\n // effects into the caller's `MastraEditorConfig.builder` object.\n // `validateBrowserConfig` writes to `features.agent.browser`; nothing\n // else is mutated, so `configuration` and `registries` stay aliased.\n const source = options ?? {};\n this.options = {\n ...source,\n features: source.features\n ? {\n ...source.features,\n agent: source.features.agent ? { ...source.features.agent } : undefined,\n }\n : undefined,\n };\n this.validateModelPolicy();\n this.validateBrowserConfig();\n // Resolve features AFTER browser-config validation so that an explicit\n // `browser: true` with bad config is already mutated to `false` on\n // `this.options.features.agent.browser`. The resolver then sees the\n // downgraded value and returns it as-is.\n this.resolvedFeatures = {\n agent: resolveAgentFeatures(this.options.features?.agent, {\n hasBrowserConfig: this.hasValidBrowserConfig(),\n }),\n };\n }\n\n get enabled(): boolean {\n return this.options.enabled !== false;\n }\n\n getFeatures(): AgentBuilderOptions['features'] {\n return this.resolvedFeatures;\n }\n\n getConfiguration(): AgentBuilderOptions['configuration'] {\n return this.options.configuration;\n }\n\n getRegistries(): AgentBuilderOptions['registries'] {\n return this.options.registries;\n }\n\n getModelPolicyWarnings(): string[] {\n return [...this.modelPolicyWarnings, ...this.browserConfigWarnings];\n }\n\n /**\n * True when `configuration.agent.browser` declares a provider. The\n * EditorAgentBuilder does NOT verify the provider is registered with the\n * Mastra instance — that cross-validation lives in `MastraEditor.resolveBuilder`\n * because only the editor knows the registered browser providers.\n */\n private hasValidBrowserConfig(): boolean {\n const browserConfig = this.options.configuration?.agent?.browser;\n return Boolean(browserConfig?.config?.provider);\n }\n\n /**\n * Browser config validation only runs for **explicit** `browser: true`.\n * With default-on semantics, an omitted `browser` no longer means \"admin\n * opted in\" — it means \"admin didn't opt out\". The default-on path is\n * resolved later by `resolveAgentFeatures`, which already gates `browser`\n * on `hasValidBrowserConfig`. We don't want to spam every default-config\n * deployment with warnings.\n */\n private validateBrowserConfig(): void {\n const explicitBrowser = this.options.features?.agent?.browser;\n if (explicitBrowser !== true) return;\n\n const browserConfig = this.options.configuration?.agent?.browser;\n if (!browserConfig) {\n const warning =\n 'Agent Builder browser feature is enabled but no default browser config was provided. ' +\n 'Set `editor.builder.configuration.agent.browser` to a valid browser config ' +\n '(e.g. `{ type: \"inline\", config: { provider: \"stagehand\" } }`). ' +\n 'The browser toggle will be hidden until a default is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n // Downgrade so the resolved feature ends up `false`.\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n return;\n }\n\n if (!browserConfig.config?.provider) {\n const warning =\n 'Agent Builder browser config is missing a `provider` field. ' +\n 'Set `editor.builder.configuration.agent.browser.config.provider` ' +\n '(e.g. `\"stagehand\"`). The browser toggle will be hidden until a provider is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n }\n }\n\n private validateModelPolicy(): void {\n const enabled = this.options.enabled !== false;\n // Locked-mode is only triggered by an explicit `model: false` from the\n // admin. With default-on semantics, an omitted `model` resolves to\n // `true` (picker visible), which is open mode and has no\n // locked-mode-default invariant.\n const explicitModel = this.options.features?.agent?.model;\n const pickerVisible = explicitModel !== false;\n const models = this.options.configuration?.agent?.models;\n const allowed = models?.allowed;\n const defaultModel = models?.default;\n\n const active = isBuilderModelPolicyActive({\n enabled,\n pickerVisible,\n allowed,\n default: defaultModel,\n });\n\n if (!active) return;\n\n // Locked mode (picker hidden) requires an admin-pinned default. Phase 3's\n // create-path decision matrix relies on this invariant: a locked policy\n // without a default is unreachable. Only fires when the admin has\n // explicitly opted out of the picker.\n if (explicitModel === false && defaultModel === undefined) {\n throw new Error(\n 'Agent Builder model policy is active in locked mode but no default was set. ' +\n 'Set `editor.builder.configuration.agent.models.default`, or remove ' +\n '`editor.builder.features.agent.model = false` to allow end-users to pick a model.',\n );\n }\n\n // When an allowlist is set, the default (if any) must satisfy it. An\n // empty `allowed: []` means \"unrestricted\" so we skip this check.\n if (defaultModel !== undefined && allowed !== undefined && allowed.length > 0) {\n if (!isModelAllowed(allowed, defaultModel)) {\n throw new Error(\n 'Agent Builder default model is not in the allowlist. ' +\n 'Either add it to `editor.builder.configuration.agent.models.allowed` ' +\n 'or change `editor.builder.configuration.agent.models.default`.',\n );\n }\n }\n }\n}\n\n// AgentFeatures imported for documentation reference in this file's jsdoc.\nexport type { AgentFeatures };\n","import { Agent } from '@mastra/core/agent';\nimport type { AgentConfig } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor } from '@mastra/core/processors';\nimport { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst workspacePath = path.join(__dirname, 'workspace');\n\nconst workspace = new Workspace({\n filesystem: new LocalFilesystem({\n basePath: workspacePath,\n }),\n skills: ['skills'],\n});\n\n/**\n * Agent Builder Agent\n *\n * Audience: non-technical users (Product, founders, operators, business stakeholders).\n * Goal: turn a plain-language description of a desired outcome into a fully\n * configured, production-quality agent — name, description, model, capabilities,\n * and system prompt — without asking the user follow-up questions.\n *\n * Capability tools the playground UI injects as client tools:\n * - set-agent-name, set-agent-description, set-agent-instructions, set-agent-workspace-id (always on)\n * - set-agent-tools (gated by features.tools)\n * - set-agent-skills (gated by features.skills + skills available)\n * - set-agent-model (gated by features.model + models available)\n * - set-agent-browser-enabled (gated by features.browser)\n * - createSkillTool (gated by features.skills) — only when a needed capability does not exist\n */\n\n/**\n * Default error processors wired into every builder agent. These each fix a\n * class of provider-side correctness bug that builder workloads tend to hit:\n *\n * - `StreamErrorRetryProcessor` — retries OpenAI's transient stream errors\n * (`server_error`, `rate_limit`, `internal_error`, `timeout`, `overloaded`,\n * etc.) that surface on long, tool-heavy turns.\n * - `PrefillErrorHandler` — recovers from Anthropic's\n * `does not support assistant message prefill` 400 by appending a\n * `system-reminder` continue message and retrying.\n * - `ProviderHistoryCompat` — applies provider-history-shape fixes\n * (anthropic tool-id format, cerebras reasoning-content strip, anthropic\n * foreign-reasoning strip) so model swaps don't break history.\n *\n * Same three processors, same order, as the shared stability defaults in\n * `@mastra/core/processors`. `createBuilderAgent` passes this list explicitly\n * rather than relying on the framework defaults: the peer range allows older\n * cores that have no defaults, and bumping the range would be a breaking\n * change, so the builder brings its own stack and behaves the same on every\n * core version.\n *\n * Exported so callers can compose a custom processor list that keeps the\n * subset they want. Pass it with `errorProcessorDefaults: false`, or the\n * builder merges the omitted defaults back in:\n * `createBuilderAgent({ errorProcessors: [...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom], errorProcessorDefaults: false })`.\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new ProviderHistoryCompat(),\n new PrefillErrorHandler(),\n new StreamErrorRetryProcessor(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge the builder's stability processors with any caller-supplied list:\n // the peer range allows cores that predate the framework defaults, so\n // relying on the resolver to add them would silently drop this stack on\n // older cores. A caller instance with a default's id replaces that default\n // at its position, so repairs keep running ahead of retries; caller\n // processors with other ids run after the defaults so they can observe or\n // extend retries the defaults trigger. An empty array merges like any other,\n // matching core; `errorProcessorDefaults: false` is the only opt-out and\n // passes the caller's list through as given (the flag is also forwarded, so\n // newer cores add nothing either). A function-typed override\n // (DynamicArgument) is passed through unchanged — callers using the dynamic\n // form manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors =\n args?.errorProcessorDefaults === false\n ? callerErrorProcessors\n : Array.isArray(callerErrorProcessors)\n ? [\n ...DEFAULT_BUILDER_ERROR_PROCESSORS.map(\n processor => callerErrorProcessors.find(caller => caller.id === processor.id) ?? processor,\n ),\n ...callerErrorProcessors.filter(\n caller => !DEFAULT_BUILDER_ERROR_PROCESSORS.some(processor => processor.id === caller.id),\n ),\n ]\n : (callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS);\n\n const config: AgentConfig<'builder-agent'> = {\n instructions: `You are the Agent Builder.\n\nYour job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.\n\n# Non-negotiables\n\n- Never ask the user follow-up questions. Make the most reasonable assumption and move forward.\n- Never expose internal names, tool ids, file paths, schemas, code, or jargon to the user.\n- Speak only in user-facing capability terms.\n- Always finish the build in the same turn as the request — configure the agent end-to-end and deliver a short summary.\n- Always define the new agent's name, description, model, and system prompt yourself. Do not ask the user for any of these.\n\nExamples of communication style:\n- Bad: \"Added weatherTool to agent-yzx capabilities.\"\n- Good: \"Your new agent can now check the weather for you.\"\n- Bad: \"Calling set-agent-tools with [weatherTool].\"\n- Good: \"Checking what capabilities to bring to your agent…\"\n- Bad: \"Agent created with weatherTool and recipeWorkflow attached.\"\n- Good: \"Your agent can check the weather and suggest recipes that match the day's conditions.\"\n\n# Form snapshot\n\nA \"Current agent configuration (authoritative)\" block is injected into your context every turn. It lists every form field with its current value AND a directive telling you exactly which setter to call (or skip) for that field. Treat the snapshot as the single source of truth for what is and isn't already set — do not try to infer state from anywhere else, and do not re-call setters for fields whose directive says \"already set\".\n\n# Authoring loop\n\nFollow these five steps in order, every time:\n\n## Step A — Understand the real outcome\n\nAnalyze what the user actually wants to achieve. Focus on the final result, not just the literal wording of the request.\n\nAsk yourself:\n- What should the agent help the user accomplish?\n- Who will use this agent?\n- What decisions should the agent make on its own?\n- What kind of output should the agent produce?\n- What recurring tasks, reasoning, or actions does the agent need to perform?\n\n## Step B — Define the agent's identity\n\nDecide on:\n- Agent name: short, memorable, anchored to the outcome. Never \"Agent X\" or generic labels.\n- Description: exactly one sentence in plain user-facing language explaining what the agent helps with.\n\nThe snapshot will tell you whether to call \\`set-agent-name\\` and \\`set-agent-description\\` or skip them.\n\n## Step C — Decide capabilities\n\nThe form snapshot lists what's currently attached. Use it together with the available tools, agents, workflows, stored skills, and models listed in the corresponding tool descriptions to decide:\n\n- Pick the *minimum* set of existing tools/agents/workflows/stored skills that satisfies the outcome. Adding irrelevant capabilities makes the agent worse, not better.\n- Prefer existing tools, workflows, agents, and stored skills before creating anything new.\n- \\`set-agent-skills\\` attaches user-available stored skills.\n- Only call \\`createSkillTool\\` when (a) no existing stored skill matches reusable operating instructions the produced agent needs, AND (b) that operating instruction is genuinely needed for the outcome. Do not use stored skills as a substitute for missing integrations or tools.\n- If a specific external connection is required (e.g. a sheet tool for a spreadsheet-driven outcome) and none is available, the new agent's system prompt must instruct it to refuse cleanly and explain what the user needs to connect.\n\n## Step D — Synthesize concise operating instructions\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item, but keep each item brief:\n\n1. **Trigger / input** — what user request, schedule, event, file, row, ticket, or message starts a run.\n2. **Owned outcome** — the exact result the produced agent is responsible for finishing.\n3. **Available capabilities** — only capabilities actually attached or already available from the form snapshot, described in user-facing outcome terms.\n4. **Missing-capability fallback** — what the produced agent does when a required integration, workspace, credential, or source is absent.\n5. **Done criteria** — verifiable conditions that prove the job is finished, including tool confirmation or an explicit \"not run\" reason when verification is impossible.\n6. **Final response format** — the receipt, summary, draft, diff summary, report, or confirmation the user receives.\n\nWrite the final system prompt as 2–4 short paragraphs or compact bullet groups. Target 1,200–2,000 characters and stay under 2,500 characters. Do not include worked examples, FAQs, long edge-case lists, or exhaustive policies unless the user's request explicitly requires them. Prefer one clear default over several branches.\n\n## Step E — Write the agent\n\nRead the per-field directives in the form snapshot. Call only the setters the snapshot tells you to call, each at most once, with the final value. Skip every field marked \"already set\" or \"no setter\". Skip any field that isn't listed at all (its feature is disabled).\n\nBefore calling \\`set-agent-instructions\\`, self-audit the draft. It must pass every check:\n- No placeholders remain (no \\`<...>\\`, \"TBD\", \"TODO\", \"your tool\", or generic policy gaps).\n- No internal tool ids, file paths, schemas, or builder-only terms appear.\n- No generic \"helpful assistant\" identity remains.\n- No unsupported capabilities are promised.\n- Completion criteria are concrete.\n- Missing-access fallback is included when relevant.\n- Final response expectations are clear.\n- The prompt is specific to the agent's outcome and under 2,500 characters.\n\n## Step F — Confirm the agent configuration to the user\n\nEnd your turn with one short, friendly paragraph confirming that the agent has been configured and is ready to use.\n\nUse this shape:\n\n\"Your agent, [Agent Name], has been configured with its initial parameters. It can now [plain-language outcome]. You can adjust its instructions, inputs, or connected capabilities whenever your needs change.\"\n\nDo not mention internal capability names, tools, workflows, skills, or configuration steps.\n\nGood:\n\"Your agent, Sales Drop Watcher, has been configured with its initial parameters. It can now review your weekly sales sheet, flag accounts that dropped more than 10%, and prepare follow-up drafts for each one. You can adjust its instructions, thresholds, or connected data sources whenever your needs change.\"\n\nBad:\n\"Agent created with sheetsTool, scoringWorkflow, and emailSkill attached.\"\n\nBad:\n\"I configured the sheets integration and called set-agent-instructions.\"\n\n# Quality bar for the produced agent's system prompt\n\nThe system prompt written into \\`set-agent-instructions\\` MUST be short, concrete, and useful. It should cover all of the following, but each item should usually be one sentence or a compact bullet:\n\n1. **Role and outcome.** Define what the agent is and the concrete result it owns.\n2. **Trigger and input.** Define what starts a run and what input the agent expects.\n3. **Decision rules.** Explain how the agent resolves ambiguity, what defaults it should apply, and what it should skip without asking the user.\n4. **Capability awareness.** Describe only the tools, integrations, workspaces, or data sources the agent actually has, phrased in terms of what they let the agent accomplish.\n5. **Missing-capability fallback.** Explain what the agent should do when a required integration, credential, permission, workspace, or source is unavailable.\n6. **Completion criteria.** Define exactly when the task is done in observable, verifiable terms.\n7. **Final response format.** Specify the shape of the agent's final answer, report, draft, receipt, or confirmation.\n8. **Communication style.** Require plain language, short answers, no jargon, and structure only when useful.\n9. **Refusal rules.** State what the agent must refuse and how it should explain the refusal clearly.\n\nKeep this to 2–4 focused paragraphs or compact bullet groups. Do not include worked examples, FAQs, or exhaustive edge-case lists by default.\n\n# Hard rules\n\n- If the user's request requires CLI or local-machine actions and no workspace is connected, refuse in plain language and tell the user they need to connect a workspace first.\n- Never reveal that you are calling configuration tools. Describe progress only in terms of the user's intended outcome.\n- Never produce a system prompt without explicit completion criteria.\n- Never attach a capability \"just in case.\" Every tool, agent, workflow, or skill must directly support the requested outcome.\n- The final message to the user must be concise, friendly, and focused on what the configured agent can now do.\n- The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,\n model: 'openai/gpt-5.5',\n memory,\n workspace,\n // Newer cores warn once per agent because this list has no explicit\n // retry budget; that warning is accurate, and setting\n // `maxProcessorRetries` just to silence it would also convert\n // input/output processor `abort({ retry: true })` from abort into retry,\n // so the warning stays.\n ...(args || {}),\n errorProcessors,\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n };\n\n return new Agent<'builder-agent'>(config);\n}\n","import type { Mastra } from '@mastra/core';\nimport type { Agent } from '@mastra/core/agent';\nimport type { IWorkflowBuilder, WorkflowBuilderOptions } from '@mastra/core/editor';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { createWorkflowBuilderAgent as createSharedWorkflowBuilderAgent } from '@mastra/core/workflows/builder';\nimport { Memory } from '@mastra/memory';\n\nexport const DEFAULT_WORKFLOW_BUILDER_MODEL = 'openai/gpt-5.5';\n\n/**\n * Authoring turns are tool-heavy: a single request can persist dozens of\n * inspection and submission records. The memory default of 10 evicts the user's\n * original request long before the workflow is finished, which reads as the\n * agent forgetting what it was asked to build.\n */\nexport const DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES = 100;\n\nexport function createWorkflowBuilderAgent(\n model?: MastraModelConfig,\n lastMessages: number = DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES,\n): Agent<'workflow-builder-agent'> {\n return createSharedWorkflowBuilderAgent({\n id: 'workflow-builder-agent',\n name: 'Workflow Builder',\n description: 'Builds persisted workflow definitions through constrained client tools',\n model: model ?? DEFAULT_WORKFLOW_BUILDER_MODEL,\n memory: new Memory({ options: { lastMessages } }),\n surfaceInstructions: `# Studio authoring policy\n\nTurn the user's request into a complete canonical workflow definition using the registered agent, tool, and workflow catalogs. Treat the current unsaved authoring state, accepted definition, candidate definition, and validation issues injected in each turn as authoritative. Never describe schemas, mapping form, graph shape, lifecycle, or persistence state from memory—read the authoritative Studio state and catalogs first.\n\nThe three shared listing tools behave here as the shared playbook describes, with one Studio specific: \\`list-available-workflows\\` reports \\`catalog-unavailable\\` when this user lacks workflow read permission. Agents and tools stay listable in that case, so compose without nested workflow references rather than treating discovery as blocked.\n\n# Studio execution and response protocol\n\n1. Complete discovery, composition, and the shared pre-action check before calling \\`submit-workflow-draft\\`.\n2. Call \\`submit-workflow-draft\\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.\n When the definition nests helper workflows that the catalog does not have yet, put those complete helper definitions in the same submission's \\`dependencies\\` array. Never submit a helper on its own turn or in a separate call — the whole set travels as one submission, goes Ready as one unit, and the user's Save persists it as one unit. Only add a helper the composition genuinely requires, give it a real id and description because the user will see it as its own workflow, and tell the user in your summary which helpers Save will create.\n3. Wait for the submission result before deciding what to do next. A successful submission makes the returned accepted definition the authoritative Ready draft. Stop calling tools after success and never resubmit that Ready definition in the same turn.\n4. If the submission is rejected with validation diagnostics, do not claim success. Correct every returned issue against authoritative inspection, rerun the shared pre-action check, and make one sequential corrected complete submission.\n5. If the result is \\`already-ready\\`, the returned accepted definition is authoritative. Do not retry or replace it in the same turn; summarize it and wait for a new user turn.\n6. If the result is \\`superseded\\`, an earlier submission in the turn won. Do not apologize, retry, or claim the workflow is broken. Inspect the authoritative state before making any claim.\n7. Ready is not persisted. Never persist directly, never call a server-side \\`save-workflow\\` tool, and never claim persistence. Only the user's explicit Studio Save action may persist the finalized draft.\n8. After Ready success, follow the shared summary rules and end by telling the user to review the authoritative draft and use the explicit Studio Save action.`,\n });\n}\n\nexport class EditorWorkflowBuilder implements IWorkflowBuilder {\n readonly enabled: boolean;\n private readonly agent;\n private readonly modelPolicy: WorkflowBuilderOptions['modelPolicy'];\n\n constructor(options: WorkflowBuilderOptions = {}, mastra?: Mastra) {\n this.enabled = options.enabled !== false;\n this.modelPolicy = options.modelPolicy;\n this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);\n if (mastra) {\n this.agent.__registerMastra(mastra);\n this.agent.__registerPrimitives({ logger: mastra.getLogger(), storage: mastra.getStorage() });\n }\n }\n\n getAgent() {\n return this.agent;\n }\n\n getModelPolicy() {\n return this.modelPolicy;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,qBAAb,MAAyD;CAoBvD,YAAY,SAA+B;EAlBM,KAAA,sBAAA,CAAC;EAGC,KAAA,wBAAA,CAAC;EAoBlD,MAAM,SAAS,WAAW,CAAC;EAC3B,KAAK,UAAU;GACb,GAAG;GACH,UAAU,OAAO,WACb;IACE,GAAG,OAAO;IACV,OAAO,OAAO,SAAS,QAAQ,EAAE,GAAG,OAAO,SAAS,MAAM,IAAI,KAAA;GAChE,IACA,KAAA;EACN;EACA,KAAK,oBAAoB;EACzB,KAAK,sBAAsB;EAK3B,KAAK,mBAAmB,EACtB,QAAA,GAAA,8BAAA,qBAAA,CAA4B,KAAK,QAAQ,UAAU,OAAO,EACxD,kBAAkB,KAAK,sBAAsB,EAC/C,CAAC,EACH;CACF;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,QAAQ,YAAY;CAClC;CAEA,cAA+C;EAC7C,OAAO,KAAK;CACd;CAEA,mBA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AC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CAGwB,CAAC;AAC1C;ACnOA,SAAgB,2BACd,OACA,eAAA,KACiC;CACjC,QAAA,GAAA,+BAAA,2BAAA,CAAwC;EACtC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,OAAO,SAAA;EACP,QAAQ,IAAIC,eAAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC;EAChD,qBAAqB;;;;;;;;;;;;;;;;;CAiBvB,CAAC;AACH;AAEA,IAAa,wBAAb,MAA+D;CAK7D,YAAY,UAAkC,CAAC,GAAG,QAAiB;EACjE,KAAK,UAAU,QAAQ,YAAY;EACnC,KAAK,cAAc,QAAQ;EAC3B,KAAK,QAAQ,2BAA2B,QAAQ,OAAO,QAAQ,YAAY;EAC3E,IAAI,QAAQ;GACV,KAAK,MAAM,iBAAiB,MAAM;GAClC,KAAK,MAAM,qBAAqB;IAAE,QAAQ,OAAO,UAAU;IAAG,SAAS,OAAO,WAAW;GAAE,CAAC;EAC9F;CACF;CAEA,WAAW;EACT,OAAO,KAAK;CACd;CAEA,iBAAiB;EACf,OAAO,KAAK;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["resolveAgentFeatures","isBuilderModelPolicyActive","isModelAllowed","__filename","fileURLToPath","__dirname","Workspace","LocalFilesystem","ProviderHistoryCompat","PrefillErrorHandler","StreamErrorRetryProcessor","Memory","Agent","createSharedWorkflowBuilderAgent","Memory"],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"sourcesContent":["import type { AgentBuilderOptions, AgentFeatures, IAgentBuilder } from '@mastra/core/agent-builder/ee';\nimport { isBuilderModelPolicyActive, isModelAllowed, resolveAgentFeatures } from '@mastra/core/agent-builder/ee';\n\n/**\n * Concrete implementation of the Agent Builder EE feature.\n * Instantiated by MastraEditor.resolveBuilder() when builder config is enabled.\n *\n * The constructor performs fail-fast validation of the admin's model policy\n * (Phase 4) so misconfiguration is caught at boot, not at first request.\n *\n * Feature toggles use **default-on semantics**: omitted keys resolve to\n * `true`. Admins opt out by setting a key to `false`. The resolved features\n * are computed once in the constructor (after validation) and returned\n * verbatim by {@link getFeatures} so all downstream consumers (server route,\n * UI hooks, policy derivation) see the same effective values.\n */\nexport class EditorAgentBuilder implements IAgentBuilder {\n private readonly options: AgentBuilderOptions;\n private readonly modelPolicyWarnings: string[] = [];\n\n /** Non-fatal warnings for browser config issues (surfaced alongside model policy warnings). */\n private readonly browserConfigWarnings: string[] = [];\n\n /**\n * Resolved (default-on normalized) features. Computed once in the\n * constructor; `undefined` only if the builder was constructed with\n * `enabled: false` (we still allocate features for the OFF path so callers\n * can introspect, but we keep the field optional to preserve the existing\n * API contract where `getFeatures()` may legitimately return `undefined`\n * if no `features` was provided AND no defaults could be applied).\n *\n * In practice this is always populated: `resolveAgentFeatures` returns a\n * fully-populated object regardless of input.\n */\n private readonly resolvedFeatures: AgentBuilderOptions['features'];\n\n constructor(options?: AgentBuilderOptions) {\n // Shallow-clone the paths the validators mutate so we never leak side\n // effects into the caller's `MastraEditorConfig.builder` object.\n // `validateBrowserConfig` writes to `features.agent.browser`; nothing\n // else is mutated, so `configuration` and `registries` stay aliased.\n const source = options ?? {};\n this.options = {\n ...source,\n features: source.features\n ? {\n ...source.features,\n agent: source.features.agent ? { ...source.features.agent } : undefined,\n }\n : undefined,\n };\n this.validateModelPolicy();\n this.validateBrowserConfig();\n // Resolve features AFTER browser-config validation so that an explicit\n // `browser: true` with bad config is already mutated to `false` on\n // `this.options.features.agent.browser`. The resolver then sees the\n // downgraded value and returns it as-is.\n this.resolvedFeatures = {\n agent: resolveAgentFeatures(this.options.features?.agent, {\n hasBrowserConfig: this.hasValidBrowserConfig(),\n }),\n };\n }\n\n get enabled(): boolean {\n return this.options.enabled !== false;\n }\n\n getFeatures(): AgentBuilderOptions['features'] {\n return this.resolvedFeatures;\n }\n\n getConfiguration(): AgentBuilderOptions['configuration'] {\n return this.options.configuration;\n }\n\n getRegistries(): AgentBuilderOptions['registries'] {\n return this.options.registries;\n }\n\n getModelPolicyWarnings(): string[] {\n return [...this.modelPolicyWarnings, ...this.browserConfigWarnings];\n }\n\n /**\n * True when `configuration.agent.browser` declares a provider. The\n * EditorAgentBuilder does NOT verify the provider is registered with the\n * Mastra instance — that cross-validation lives in `MastraEditor.resolveBuilder`\n * because only the editor knows the registered browser providers.\n */\n private hasValidBrowserConfig(): boolean {\n const browserConfig = this.options.configuration?.agent?.browser;\n return Boolean(browserConfig?.config?.provider);\n }\n\n /**\n * Browser config validation only runs for **explicit** `browser: true`.\n * With default-on semantics, an omitted `browser` no longer means \"admin\n * opted in\" — it means \"admin didn't opt out\". The default-on path is\n * resolved later by `resolveAgentFeatures`, which already gates `browser`\n * on `hasValidBrowserConfig`. We don't want to spam every default-config\n * deployment with warnings.\n */\n private validateBrowserConfig(): void {\n const explicitBrowser = this.options.features?.agent?.browser;\n if (explicitBrowser !== true) return;\n\n const browserConfig = this.options.configuration?.agent?.browser;\n if (!browserConfig) {\n const warning =\n 'Agent Builder browser feature is enabled but no default browser config was provided. ' +\n 'Set `editor.builder.configuration.agent.browser` to a valid browser config ' +\n '(e.g. `{ type: \"inline\", config: { provider: \"stagehand\" } }`). ' +\n 'The browser toggle will be hidden until a default is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n // Downgrade so the resolved feature ends up `false`.\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n return;\n }\n\n if (!browserConfig.config?.provider) {\n const warning =\n 'Agent Builder browser config is missing a `provider` field. ' +\n 'Set `editor.builder.configuration.agent.browser.config.provider` ' +\n '(e.g. `\"stagehand\"`). The browser toggle will be hidden until a provider is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n }\n }\n\n private validateModelPolicy(): void {\n const enabled = this.options.enabled !== false;\n // Locked-mode is only triggered by an explicit `model: false` from the\n // admin. With default-on semantics, an omitted `model` resolves to\n // `true` (picker visible), which is open mode and has no\n // locked-mode-default invariant.\n const explicitModel = this.options.features?.agent?.model;\n const pickerVisible = explicitModel !== false;\n const models = this.options.configuration?.agent?.models;\n const allowed = models?.allowed;\n const defaultModel = models?.default;\n\n const active = isBuilderModelPolicyActive({\n enabled,\n pickerVisible,\n allowed,\n default: defaultModel,\n });\n\n if (!active) return;\n\n // Locked mode (picker hidden) requires an admin-pinned default. Phase 3's\n // create-path decision matrix relies on this invariant: a locked policy\n // without a default is unreachable. Only fires when the admin has\n // explicitly opted out of the picker.\n if (explicitModel === false && defaultModel === undefined) {\n throw new Error(\n 'Agent Builder model policy is active in locked mode but no default was set. ' +\n 'Set `editor.builder.configuration.agent.models.default`, or remove ' +\n '`editor.builder.features.agent.model = false` to allow end-users to pick a model.',\n );\n }\n\n // When an allowlist is set, the default (if any) must satisfy it. An\n // empty `allowed: []` means \"unrestricted\" so we skip this check.\n if (defaultModel !== undefined && allowed !== undefined && allowed.length > 0) {\n if (!isModelAllowed(allowed, defaultModel)) {\n throw new Error(\n 'Agent Builder default model is not in the allowlist. ' +\n 'Either add it to `editor.builder.configuration.agent.models.allowed` ' +\n 'or change `editor.builder.configuration.agent.models.default`.',\n );\n }\n }\n }\n}\n\n// AgentFeatures imported for documentation reference in this file's jsdoc.\nexport type { AgentFeatures };\n","import { Agent } from '@mastra/core/agent';\nimport type { AgentConfig } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor } from '@mastra/core/processors';\nimport { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst workspacePath = path.join(__dirname, 'workspace');\n\nconst workspace = new Workspace({\n filesystem: new LocalFilesystem({\n basePath: workspacePath,\n }),\n skills: ['skills'],\n});\n\n/**\n * Agent Builder Agent\n *\n * Audience: non-technical users (Product, founders, operators, business stakeholders).\n * Goal: turn a plain-language description of a desired outcome into a fully\n * configured, production-quality agent — name, description, model, capabilities,\n * and system prompt — without asking the user follow-up questions.\n *\n * Capability tools the playground UI injects as client tools:\n * - set-agent-name, set-agent-description, set-agent-instructions, set-agent-workspace-id (always on)\n * - set-agent-tools (gated by features.tools)\n * - set-agent-skills (gated by features.skills + skills available)\n * - set-agent-model (gated by features.model + models available)\n * - set-agent-browser-enabled (gated by features.browser)\n * - createSkillTool (gated by features.skills) — only when a needed capability does not exist\n */\n\n/**\n * Default error processors wired into every builder agent. These each fix a\n * class of provider-side correctness bug that builder workloads tend to hit:\n *\n * - `StreamErrorRetryProcessor` — retries OpenAI's transient stream errors\n * (`server_error`, `rate_limit`, `internal_error`, `timeout`, `overloaded`,\n * etc.) that surface on long, tool-heavy turns.\n * - `PrefillErrorHandler` — recovers from Anthropic's\n * `does not support assistant message prefill` 400 by appending a\n * `system-reminder` continue message and retrying.\n * - `ProviderHistoryCompat` — applies provider-history-shape fixes\n * (anthropic tool-id format, cerebras reasoning-content strip, anthropic\n * foreign-reasoning strip) so model swaps don't break history.\n *\n * Same three processors, same order, as the shared stability defaults in\n * `@mastra/core/processors`. `createBuilderAgent` passes this list explicitly\n * rather than relying on the framework defaults: the peer range allows older\n * cores that have no defaults, and bumping the range would be a breaking\n * change, so the builder brings its own stack and behaves the same on every\n * core version.\n *\n * Exported so callers can compose a custom processor list that keeps the\n * subset they want. Pass it with `errorProcessorDefaults: false`, or the\n * builder merges the omitted defaults back in:\n * `createBuilderAgent({ errorProcessors: [...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom], errorProcessorDefaults: false })`.\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new ProviderHistoryCompat(),\n new PrefillErrorHandler(),\n new StreamErrorRetryProcessor(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge the builder's stability processors with any caller-supplied list:\n // the peer range allows cores that predate the framework defaults, so\n // relying on the resolver to add them would silently drop this stack on\n // older cores. A caller instance with a default's id replaces that default\n // at its position, so repairs keep running ahead of retries; caller\n // processors with other ids run after the defaults so they can observe or\n // extend retries the defaults trigger. An empty array merges like any other,\n // matching core; `errorProcessorDefaults: false` is the only opt-out and\n // passes the caller's list through as given (the flag is also forwarded, so\n // newer cores add nothing either). A function-typed override\n // (DynamicArgument) is passed through unchanged — callers using the dynamic\n // form manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors =\n args?.errorProcessorDefaults === false\n ? callerErrorProcessors\n : Array.isArray(callerErrorProcessors)\n ? [\n ...DEFAULT_BUILDER_ERROR_PROCESSORS.map(\n processor => callerErrorProcessors.find(caller => caller.id === processor.id) ?? processor,\n ),\n ...callerErrorProcessors.filter(\n caller => !DEFAULT_BUILDER_ERROR_PROCESSORS.some(processor => processor.id === caller.id),\n ),\n ]\n : (callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS);\n\n const config: AgentConfig<'builder-agent'> = {\n instructions: `You are the Agent Builder.\n\nYour job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.\n\n# Non-negotiables\n\n- Never ask the user follow-up questions. Make the most reasonable assumption and move forward.\n- Never expose internal names, tool ids, file paths, schemas, code, or jargon to the user.\n- Speak only in user-facing capability terms.\n- Always finish the build in the same turn as the request — configure the agent end-to-end and deliver a short summary.\n- Always define the new agent's name, description, model, and system prompt yourself. Do not ask the user for any of these.\n\nExamples of communication style:\n- Bad: \"Added weatherTool to agent-yzx capabilities.\"\n- Good: \"Your new agent can now check the weather for you.\"\n- Bad: \"Calling set-agent-tools with [weatherTool].\"\n- Good: \"Checking what capabilities to bring to your agent…\"\n- Bad: \"Agent created with weatherTool and recipeWorkflow attached.\"\n- Good: \"Your agent can check the weather and suggest recipes that match the day's conditions.\"\n\n# Form snapshot\n\nA \"Current agent configuration (authoritative)\" block is injected into your context every turn. It lists every form field with its current value AND a directive telling you exactly which setter to call (or skip) for that field. Treat the snapshot as the single source of truth for what is and isn't already set — do not try to infer state from anywhere else, and do not re-call setters for fields whose directive says \"already set\".\n\n# Authoring loop\n\nFollow these five steps in order, every time:\n\n## Step A — Understand the real outcome\n\nAnalyze what the user actually wants to achieve. Focus on the final result, not just the literal wording of the request.\n\nAsk yourself:\n- What should the agent help the user accomplish?\n- Who will use this agent?\n- What decisions should the agent make on its own?\n- What kind of output should the agent produce?\n- What recurring tasks, reasoning, or actions does the agent need to perform?\n\n## Step B — Define the agent's identity\n\nDecide on:\n- Agent name: short, memorable, anchored to the outcome. Never \"Agent X\" or generic labels.\n- Description: exactly one sentence in plain user-facing language explaining what the agent helps with.\n\nThe snapshot will tell you whether to call \\`set-agent-name\\` and \\`set-agent-description\\` or skip them.\n\n## Step C — Decide capabilities\n\nThe form snapshot lists what's currently attached. Use it together with the available tools, agents, workflows, stored skills, and models listed in the corresponding tool descriptions to decide:\n\n- Pick the *minimum* set of existing tools/agents/workflows/stored skills that satisfies the outcome. Adding irrelevant capabilities makes the agent worse, not better.\n- Prefer existing tools, workflows, agents, and stored skills before creating anything new.\n- \\`set-agent-skills\\` attaches user-available stored skills.\n- Only call \\`createSkillTool\\` when (a) no existing stored skill matches reusable operating instructions the produced agent needs, AND (b) that operating instruction is genuinely needed for the outcome. Do not use stored skills as a substitute for missing integrations or tools.\n- If a specific external connection is required (e.g. a sheet tool for a spreadsheet-driven outcome) and none is available, the new agent's system prompt must instruct it to refuse cleanly and explain what the user needs to connect.\n\n## Step D — Synthesize concise operating instructions\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item, but keep each item brief:\n\n1. **Trigger / input** — what user request, schedule, event, file, row, ticket, or message starts a run.\n2. **Owned outcome** — the exact result the produced agent is responsible for finishing.\n3. **Available capabilities** — only capabilities actually attached or already available from the form snapshot, described in user-facing outcome terms.\n4. **Missing-capability fallback** — what the produced agent does when a required integration, workspace, credential, or source is absent.\n5. **Done criteria** — verifiable conditions that prove the job is finished, including tool confirmation or an explicit \"not run\" reason when verification is impossible.\n6. **Final response format** — the receipt, summary, draft, diff summary, report, or confirmation the user receives.\n\nWrite the final system prompt as 2–4 short paragraphs or compact bullet groups. Target 1,200–2,000 characters and stay under 2,500 characters. Do not include worked examples, FAQs, long edge-case lists, or exhaustive policies unless the user's request explicitly requires them. Prefer one clear default over several branches.\n\n## Step E — Write the agent\n\nRead the per-field directives in the form snapshot. Call only the setters the snapshot tells you to call, each at most once, with the final value. Skip every field marked \"already set\" or \"no setter\". Skip any field that isn't listed at all (its feature is disabled).\n\nBefore calling \\`set-agent-instructions\\`, self-audit the draft. It must pass every check:\n- No placeholders remain (no \\`<...>\\`, \"TBD\", \"TODO\", \"your tool\", or generic policy gaps).\n- No internal tool ids, file paths, schemas, or builder-only terms appear.\n- No generic \"helpful assistant\" identity remains.\n- No unsupported capabilities are promised.\n- Completion criteria are concrete.\n- Missing-access fallback is included when relevant.\n- Final response expectations are clear.\n- The prompt is specific to the agent's outcome and under 2,500 characters.\n\n## Step F — Confirm the agent configuration to the user\n\nEnd your turn with one short, friendly paragraph confirming that the agent has been configured and is ready to use.\n\nUse this shape:\n\n\"Your agent, [Agent Name], has been configured with its initial parameters. It can now [plain-language outcome]. You can adjust its instructions, inputs, or connected capabilities whenever your needs change.\"\n\nDo not mention internal capability names, tools, workflows, skills, or configuration steps.\n\nGood:\n\"Your agent, Sales Drop Watcher, has been configured with its initial parameters. It can now review your weekly sales sheet, flag accounts that dropped more than 10%, and prepare follow-up drafts for each one. You can adjust its instructions, thresholds, or connected data sources whenever your needs change.\"\n\nBad:\n\"Agent created with sheetsTool, scoringWorkflow, and emailSkill attached.\"\n\nBad:\n\"I configured the sheets integration and called set-agent-instructions.\"\n\n# Quality bar for the produced agent's system prompt\n\nThe system prompt written into \\`set-agent-instructions\\` MUST be short, concrete, and useful. It should cover all of the following, but each item should usually be one sentence or a compact bullet:\n\n1. **Role and outcome.** Define what the agent is and the concrete result it owns.\n2. **Trigger and input.** Define what starts a run and what input the agent expects.\n3. **Decision rules.** Explain how the agent resolves ambiguity, what defaults it should apply, and what it should skip without asking the user.\n4. **Capability awareness.** Describe only the tools, integrations, workspaces, or data sources the agent actually has, phrased in terms of what they let the agent accomplish.\n5. **Missing-capability fallback.** Explain what the agent should do when a required integration, credential, permission, workspace, or source is unavailable.\n6. **Completion criteria.** Define exactly when the task is done in observable, verifiable terms.\n7. **Final response format.** Specify the shape of the agent's final answer, report, draft, receipt, or confirmation.\n8. **Communication style.** Require plain language, short answers, no jargon, and structure only when useful.\n9. **Refusal rules.** State what the agent must refuse and how it should explain the refusal clearly.\n\nKeep this to 2–4 focused paragraphs or compact bullet groups. Do not include worked examples, FAQs, or exhaustive edge-case lists by default.\n\n# Hard rules\n\n- If the user's request requires CLI or local-machine actions and no workspace is connected, refuse in plain language and tell the user they need to connect a workspace first.\n- Never reveal that you are calling configuration tools. Describe progress only in terms of the user's intended outcome.\n- Never produce a system prompt without explicit completion criteria.\n- Never attach a capability \"just in case.\" Every tool, agent, workflow, or skill must directly support the requested outcome.\n- The final message to the user must be concise, friendly, and focused on what the configured agent can now do.\n- The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,\n model: 'openai/gpt-5.5',\n memory,\n workspace,\n // Newer cores warn once per agent because this list has no explicit\n // retry budget; that warning is accurate, and setting\n // `maxProcessorRetries` just to silence it would also convert\n // input/output processor `abort({ retry: true })` from abort into retry,\n // so the warning stays.\n ...(args || {}),\n errorProcessors,\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n };\n\n return new Agent<'builder-agent'>(config);\n}\n","import type { Mastra } from '@mastra/core';\nimport type { Agent } from '@mastra/core/agent';\nimport type { IWorkflowBuilder, WorkflowBuilderOptions } from '@mastra/core/editor';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { createWorkflowBuilderAgent as createSharedWorkflowBuilderAgent } from '@mastra/core/workflows/builder';\nimport { Memory } from '@mastra/memory';\n\nexport const DEFAULT_WORKFLOW_BUILDER_MODEL = 'openai/gpt-5.5';\n\n/**\n * Authoring turns are tool-heavy: a single request can persist dozens of\n * inspection and submission records. The memory default of 10 evicts the user's\n * original request long before the workflow is finished, which reads as the\n * agent forgetting what it was asked to build.\n */\nexport const DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES = 100;\n\nexport function createWorkflowBuilderAgent(\n model?: MastraModelConfig,\n lastMessages: number = DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES,\n): Agent<'workflow-builder-agent'> {\n return createSharedWorkflowBuilderAgent({\n id: 'workflow-builder-agent',\n name: 'Workflow Builder',\n description: 'Builds persisted workflow definitions through constrained client tools',\n model: model ?? DEFAULT_WORKFLOW_BUILDER_MODEL,\n memory: new Memory({ options: { lastMessages } }),\n surfaceInstructions: `# Studio authoring policy\n\nTurn the user's request into a complete canonical workflow definition using the registered agent, tool, and workflow catalogs. Treat the current unsaved authoring state, accepted definition, candidate definition, and validation issues injected in each turn as authoritative. Never describe schemas, mapping form, graph shape, lifecycle, or persistence state from memory—read the authoritative Studio state and catalogs first.\n\nThe three shared listing tools behave here as the shared playbook describes, with one Studio specific: \\`list-available-workflows\\` reports \\`catalog-unavailable\\` when this user lacks workflow read permission. Agents and tools stay listable in that case, so compose without nested workflow references rather than treating discovery as blocked.\n\n# Studio execution and response protocol\n\n1. Complete discovery, composition, and the shared pre-action check before calling \\`submit-workflow-draft\\`.\n2. Call \\`submit-workflow-draft\\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.\n When the definition nests helper workflows that the catalog does not have yet, put those complete helper definitions in the same submission's \\`dependencies\\` array. Never submit a helper on its own turn or in a separate call — the whole set travels as one submission, goes Ready as one unit, and the user's Save persists it as one unit. Only add a helper the composition genuinely requires, give it a real id and description because the user will see it as its own workflow, and tell the user in your summary which helpers Save will create.\n3. Wait for the submission result before deciding what to do next. A successful submission makes the returned accepted definition the authoritative Ready draft. Stop calling tools after success and never resubmit that Ready definition in the same turn.\n4. If the submission is rejected with validation diagnostics, do not claim success. Correct every returned issue against authoritative inspection, rerun the shared pre-action check, and make one sequential corrected complete submission.\n5. If the result is \\`already-ready\\`, the returned accepted definition is authoritative. Do not retry or replace it in the same turn; summarize it and wait for a new user turn.\n6. If the result is \\`superseded\\`, an earlier submission in the turn won. Do not apologize, retry, or claim the workflow is broken. Inspect the authoritative state before making any claim.\n7. Ready is not persisted. Never persist directly, never call a server-side \\`save-workflow\\` tool, and never claim persistence. Only the user's explicit Studio Save action may persist the finalized draft.\n8. After Ready success, follow the shared summary rules and end by telling the user to review the authoritative draft and use the explicit Studio Save action.`,\n });\n}\n\nexport class EditorWorkflowBuilder implements IWorkflowBuilder {\n readonly enabled: boolean;\n private readonly agent;\n private readonly modelPolicy: WorkflowBuilderOptions['modelPolicy'];\n\n constructor(options: WorkflowBuilderOptions = {}, mastra?: Mastra) {\n this.enabled = options.enabled !== false;\n this.modelPolicy = options.modelPolicy;\n this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);\n if (mastra) {\n this.agent.__registerMastra(mastra);\n this.agent.__registerPrimitives({ logger: mastra.getLogger(), storage: mastra.getStorage() });\n }\n }\n\n getAgent() {\n return this.agent;\n }\n\n getModelPolicy() {\n return this.modelPolicy;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,qBAAb,MAAyD;CAoBvD,YAAY,SAA+B;EAlBM,KAAA,sBAAA,CAAC;EAGC,KAAA,wBAAA,CAAC;EAoBlD,MAAM,SAAS,WAAW,CAAC;EAC3B,KAAK,UAAU;GACb,GAAG;GACH,UAAU,OAAO,WACb;IACE,GAAG,OAAO;IACV,OAAO,OAAO,SAAS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const __filename = fileURLToPath(import.meta.url);
|
|
111
111
|
const __dirname = path.dirname(__filename);
|
|
112
|
+
const workspacePath = path.join(__dirname, "workspace");
|
|
112
113
|
const workspace = new Workspace({
|
|
113
|
-
filesystem: new LocalFilesystem({ basePath:
|
|
114
|
+
filesystem: new LocalFilesystem({ basePath: workspacePath }),
|
|
114
115
|
skills: ["skills"]
|
|
115
116
|
});
|
|
116
117
|
/**
|
|
@@ -164,7 +165,7 @@ function createBuilderAgent(args) {
|
|
|
164
165
|
const memory = new Memory();
|
|
165
166
|
const callerErrorProcessors = args?.errorProcessors;
|
|
166
167
|
const errorProcessors = args?.errorProcessorDefaults === false ? callerErrorProcessors : Array.isArray(callerErrorProcessors) ? [...DEFAULT_BUILDER_ERROR_PROCESSORS.map((processor) => callerErrorProcessors.find((caller) => caller.id === processor.id) ?? processor), ...callerErrorProcessors.filter((caller) => !DEFAULT_BUILDER_ERROR_PROCESSORS.some((processor) => processor.id === caller.id))] : callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS;
|
|
167
|
-
|
|
168
|
+
const config = {
|
|
168
169
|
instructions: `You are the Agent Builder.
|
|
169
170
|
|
|
170
171
|
Your job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.
|
|
@@ -300,7 +301,8 @@ Keep this to 2–4 focused paragraphs or compact bullet groups. Do not include w
|
|
|
300
301
|
id: "builder-agent",
|
|
301
302
|
name: "Agent Builder Agent",
|
|
302
303
|
description: "An agent that can build agents"
|
|
303
|
-
}
|
|
304
|
+
};
|
|
305
|
+
return new Agent(config);
|
|
304
306
|
}
|
|
305
307
|
function createWorkflowBuilderAgent(model, lastMessages = 100) {
|
|
306
308
|
return createWorkflowBuilderAgent$1({
|
package/dist/ee/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["createSharedWorkflowBuilderAgent"],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"sourcesContent":["import type { AgentBuilderOptions, AgentFeatures, IAgentBuilder } from '@mastra/core/agent-builder/ee';\nimport { isBuilderModelPolicyActive, isModelAllowed, resolveAgentFeatures } from '@mastra/core/agent-builder/ee';\n\n/**\n * Concrete implementation of the Agent Builder EE feature.\n * Instantiated by MastraEditor.resolveBuilder() when builder config is enabled.\n *\n * The constructor performs fail-fast validation of the admin's model policy\n * (Phase 4) so misconfiguration is caught at boot, not at first request.\n *\n * Feature toggles use **default-on semantics**: omitted keys resolve to\n * `true`. Admins opt out by setting a key to `false`. The resolved features\n * are computed once in the constructor (after validation) and returned\n * verbatim by {@link getFeatures} so all downstream consumers (server route,\n * UI hooks, policy derivation) see the same effective values.\n */\nexport class EditorAgentBuilder implements IAgentBuilder {\n private readonly options: AgentBuilderOptions;\n private readonly modelPolicyWarnings: string[] = [];\n\n /** Non-fatal warnings for browser config issues (surfaced alongside model policy warnings). */\n private readonly browserConfigWarnings: string[] = [];\n\n /**\n * Resolved (default-on normalized) features. Computed once in the\n * constructor; `undefined` only if the builder was constructed with\n * `enabled: false` (we still allocate features for the OFF path so callers\n * can introspect, but we keep the field optional to preserve the existing\n * API contract where `getFeatures()` may legitimately return `undefined`\n * if no `features` was provided AND no defaults could be applied).\n *\n * In practice this is always populated: `resolveAgentFeatures` returns a\n * fully-populated object regardless of input.\n */\n private readonly resolvedFeatures: AgentBuilderOptions['features'];\n\n constructor(options?: AgentBuilderOptions) {\n // Shallow-clone the paths the validators mutate so we never leak side\n // effects into the caller's `MastraEditorConfig.builder` object.\n // `validateBrowserConfig` writes to `features.agent.browser`; nothing\n // else is mutated, so `configuration` and `registries` stay aliased.\n const source = options ?? {};\n this.options = {\n ...source,\n features: source.features\n ? {\n ...source.features,\n agent: source.features.agent ? { ...source.features.agent } : undefined,\n }\n : undefined,\n };\n this.validateModelPolicy();\n this.validateBrowserConfig();\n // Resolve features AFTER browser-config validation so that an explicit\n // `browser: true` with bad config is already mutated to `false` on\n // `this.options.features.agent.browser`. The resolver then sees the\n // downgraded value and returns it as-is.\n this.resolvedFeatures = {\n agent: resolveAgentFeatures(this.options.features?.agent, {\n hasBrowserConfig: this.hasValidBrowserConfig(),\n }),\n };\n }\n\n get enabled(): boolean {\n return this.options.enabled !== false;\n }\n\n getFeatures(): AgentBuilderOptions['features'] {\n return this.resolvedFeatures;\n }\n\n getConfiguration(): AgentBuilderOptions['configuration'] {\n return this.options.configuration;\n }\n\n getRegistries(): AgentBuilderOptions['registries'] {\n return this.options.registries;\n }\n\n getModelPolicyWarnings(): string[] {\n return [...this.modelPolicyWarnings, ...this.browserConfigWarnings];\n }\n\n /**\n * True when `configuration.agent.browser` declares a provider. The\n * EditorAgentBuilder does NOT verify the provider is registered with the\n * Mastra instance — that cross-validation lives in `MastraEditor.resolveBuilder`\n * because only the editor knows the registered browser providers.\n */\n private hasValidBrowserConfig(): boolean {\n const browserConfig = this.options.configuration?.agent?.browser;\n return Boolean(browserConfig?.config?.provider);\n }\n\n /**\n * Browser config validation only runs for **explicit** `browser: true`.\n * With default-on semantics, an omitted `browser` no longer means \"admin\n * opted in\" — it means \"admin didn't opt out\". The default-on path is\n * resolved later by `resolveAgentFeatures`, which already gates `browser`\n * on `hasValidBrowserConfig`. We don't want to spam every default-config\n * deployment with warnings.\n */\n private validateBrowserConfig(): void {\n const explicitBrowser = this.options.features?.agent?.browser;\n if (explicitBrowser !== true) return;\n\n const browserConfig = this.options.configuration?.agent?.browser;\n if (!browserConfig) {\n const warning =\n 'Agent Builder browser feature is enabled but no default browser config was provided. ' +\n 'Set `editor.builder.configuration.agent.browser` to a valid browser config ' +\n '(e.g. `{ type: \"inline\", config: { provider: \"stagehand\" } }`). ' +\n 'The browser toggle will be hidden until a default is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n // Downgrade so the resolved feature ends up `false`.\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n return;\n }\n\n if (!browserConfig.config?.provider) {\n const warning =\n 'Agent Builder browser config is missing a `provider` field. ' +\n 'Set `editor.builder.configuration.agent.browser.config.provider` ' +\n '(e.g. `\"stagehand\"`). The browser toggle will be hidden until a provider is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n }\n }\n\n private validateModelPolicy(): void {\n const enabled = this.options.enabled !== false;\n // Locked-mode is only triggered by an explicit `model: false` from the\n // admin. With default-on semantics, an omitted `model` resolves to\n // `true` (picker visible), which is open mode and has no\n // locked-mode-default invariant.\n const explicitModel = this.options.features?.agent?.model;\n const pickerVisible = explicitModel !== false;\n const models = this.options.configuration?.agent?.models;\n const allowed = models?.allowed;\n const defaultModel = models?.default;\n\n const active = isBuilderModelPolicyActive({\n enabled,\n pickerVisible,\n allowed,\n default: defaultModel,\n });\n\n if (!active) return;\n\n // Locked mode (picker hidden) requires an admin-pinned default. Phase 3's\n // create-path decision matrix relies on this invariant: a locked policy\n // without a default is unreachable. Only fires when the admin has\n // explicitly opted out of the picker.\n if (explicitModel === false && defaultModel === undefined) {\n throw new Error(\n 'Agent Builder model policy is active in locked mode but no default was set. ' +\n 'Set `editor.builder.configuration.agent.models.default`, or remove ' +\n '`editor.builder.features.agent.model = false` to allow end-users to pick a model.',\n );\n }\n\n // When an allowlist is set, the default (if any) must satisfy it. An\n // empty `allowed: []` means \"unrestricted\" so we skip this check.\n if (defaultModel !== undefined && allowed !== undefined && allowed.length > 0) {\n if (!isModelAllowed(allowed, defaultModel)) {\n throw new Error(\n 'Agent Builder default model is not in the allowlist. ' +\n 'Either add it to `editor.builder.configuration.agent.models.allowed` ' +\n 'or change `editor.builder.configuration.agent.models.default`.',\n );\n }\n }\n }\n}\n\n// AgentFeatures imported for documentation reference in this file's jsdoc.\nexport type { AgentFeatures };\n","import { Agent } from '@mastra/core/agent';\nimport type { AgentConfig } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor } from '@mastra/core/processors';\nimport { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst workspacePath = path.join(__dirname, 'workspace');\n\nconst workspace = new Workspace({\n filesystem: new LocalFilesystem({\n basePath: workspacePath,\n }),\n skills: ['skills'],\n});\n\n/**\n * Agent Builder Agent\n *\n * Audience: non-technical users (Product, founders, operators, business stakeholders).\n * Goal: turn a plain-language description of a desired outcome into a fully\n * configured, production-quality agent — name, description, model, capabilities,\n * and system prompt — without asking the user follow-up questions.\n *\n * Capability tools the playground UI injects as client tools:\n * - set-agent-name, set-agent-description, set-agent-instructions, set-agent-workspace-id (always on)\n * - set-agent-tools (gated by features.tools)\n * - set-agent-skills (gated by features.skills + skills available)\n * - set-agent-model (gated by features.model + models available)\n * - set-agent-browser-enabled (gated by features.browser)\n * - createSkillTool (gated by features.skills) — only when a needed capability does not exist\n */\n\n/**\n * Default error processors wired into every builder agent. These each fix a\n * class of provider-side correctness bug that builder workloads tend to hit:\n *\n * - `StreamErrorRetryProcessor` — retries OpenAI's transient stream errors\n * (`server_error`, `rate_limit`, `internal_error`, `timeout`, `overloaded`,\n * etc.) that surface on long, tool-heavy turns.\n * - `PrefillErrorHandler` — recovers from Anthropic's\n * `does not support assistant message prefill` 400 by appending a\n * `system-reminder` continue message and retrying.\n * - `ProviderHistoryCompat` — applies provider-history-shape fixes\n * (anthropic tool-id format, cerebras reasoning-content strip, anthropic\n * foreign-reasoning strip) so model swaps don't break history.\n *\n * Same three processors, same order, as the shared stability defaults in\n * `@mastra/core/processors`. `createBuilderAgent` passes this list explicitly\n * rather than relying on the framework defaults: the peer range allows older\n * cores that have no defaults, and bumping the range would be a breaking\n * change, so the builder brings its own stack and behaves the same on every\n * core version.\n *\n * Exported so callers can compose a custom processor list that keeps the\n * subset they want. Pass it with `errorProcessorDefaults: false`, or the\n * builder merges the omitted defaults back in:\n * `createBuilderAgent({ errorProcessors: [...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom], errorProcessorDefaults: false })`.\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new ProviderHistoryCompat(),\n new PrefillErrorHandler(),\n new StreamErrorRetryProcessor(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge the builder's stability processors with any caller-supplied list:\n // the peer range allows cores that predate the framework defaults, so\n // relying on the resolver to add them would silently drop this stack on\n // older cores. A caller instance with a default's id replaces that default\n // at its position, so repairs keep running ahead of retries; caller\n // processors with other ids run after the defaults so they can observe or\n // extend retries the defaults trigger. An empty array merges like any other,\n // matching core; `errorProcessorDefaults: false` is the only opt-out and\n // passes the caller's list through as given (the flag is also forwarded, so\n // newer cores add nothing either). A function-typed override\n // (DynamicArgument) is passed through unchanged — callers using the dynamic\n // form manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors =\n args?.errorProcessorDefaults === false\n ? callerErrorProcessors\n : Array.isArray(callerErrorProcessors)\n ? [\n ...DEFAULT_BUILDER_ERROR_PROCESSORS.map(\n processor => callerErrorProcessors.find(caller => caller.id === processor.id) ?? processor,\n ),\n ...callerErrorProcessors.filter(\n caller => !DEFAULT_BUILDER_ERROR_PROCESSORS.some(processor => processor.id === caller.id),\n ),\n ]\n : (callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS);\n\n const config: AgentConfig<'builder-agent'> = {\n instructions: `You are the Agent Builder.\n\nYour job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.\n\n# Non-negotiables\n\n- Never ask the user follow-up questions. Make the most reasonable assumption and move forward.\n- Never expose internal names, tool ids, file paths, schemas, code, or jargon to the user.\n- Speak only in user-facing capability terms.\n- Always finish the build in the same turn as the request — configure the agent end-to-end and deliver a short summary.\n- Always define the new agent's name, description, model, and system prompt yourself. Do not ask the user for any of these.\n\nExamples of communication style:\n- Bad: \"Added weatherTool to agent-yzx capabilities.\"\n- Good: \"Your new agent can now check the weather for you.\"\n- Bad: \"Calling set-agent-tools with [weatherTool].\"\n- Good: \"Checking what capabilities to bring to your agent…\"\n- Bad: \"Agent created with weatherTool and recipeWorkflow attached.\"\n- Good: \"Your agent can check the weather and suggest recipes that match the day's conditions.\"\n\n# Form snapshot\n\nA \"Current agent configuration (authoritative)\" block is injected into your context every turn. It lists every form field with its current value AND a directive telling you exactly which setter to call (or skip) for that field. Treat the snapshot as the single source of truth for what is and isn't already set — do not try to infer state from anywhere else, and do not re-call setters for fields whose directive says \"already set\".\n\n# Authoring loop\n\nFollow these five steps in order, every time:\n\n## Step A — Understand the real outcome\n\nAnalyze what the user actually wants to achieve. Focus on the final result, not just the literal wording of the request.\n\nAsk yourself:\n- What should the agent help the user accomplish?\n- Who will use this agent?\n- What decisions should the agent make on its own?\n- What kind of output should the agent produce?\n- What recurring tasks, reasoning, or actions does the agent need to perform?\n\n## Step B — Define the agent's identity\n\nDecide on:\n- Agent name: short, memorable, anchored to the outcome. Never \"Agent X\" or generic labels.\n- Description: exactly one sentence in plain user-facing language explaining what the agent helps with.\n\nThe snapshot will tell you whether to call \\`set-agent-name\\` and \\`set-agent-description\\` or skip them.\n\n## Step C — Decide capabilities\n\nThe form snapshot lists what's currently attached. Use it together with the available tools, agents, workflows, stored skills, and models listed in the corresponding tool descriptions to decide:\n\n- Pick the *minimum* set of existing tools/agents/workflows/stored skills that satisfies the outcome. Adding irrelevant capabilities makes the agent worse, not better.\n- Prefer existing tools, workflows, agents, and stored skills before creating anything new.\n- \\`set-agent-skills\\` attaches user-available stored skills.\n- Only call \\`createSkillTool\\` when (a) no existing stored skill matches reusable operating instructions the produced agent needs, AND (b) that operating instruction is genuinely needed for the outcome. Do not use stored skills as a substitute for missing integrations or tools.\n- If a specific external connection is required (e.g. a sheet tool for a spreadsheet-driven outcome) and none is available, the new agent's system prompt must instruct it to refuse cleanly and explain what the user needs to connect.\n\n## Step D — Synthesize concise operating instructions\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item, but keep each item brief:\n\n1. **Trigger / input** — what user request, schedule, event, file, row, ticket, or message starts a run.\n2. **Owned outcome** — the exact result the produced agent is responsible for finishing.\n3. **Available capabilities** — only capabilities actually attached or already available from the form snapshot, described in user-facing outcome terms.\n4. **Missing-capability fallback** — what the produced agent does when a required integration, workspace, credential, or source is absent.\n5. **Done criteria** — verifiable conditions that prove the job is finished, including tool confirmation or an explicit \"not run\" reason when verification is impossible.\n6. **Final response format** — the receipt, summary, draft, diff summary, report, or confirmation the user receives.\n\nWrite the final system prompt as 2–4 short paragraphs or compact bullet groups. Target 1,200–2,000 characters and stay under 2,500 characters. Do not include worked examples, FAQs, long edge-case lists, or exhaustive policies unless the user's request explicitly requires them. Prefer one clear default over several branches.\n\n## Step E — Write the agent\n\nRead the per-field directives in the form snapshot. Call only the setters the snapshot tells you to call, each at most once, with the final value. Skip every field marked \"already set\" or \"no setter\". Skip any field that isn't listed at all (its feature is disabled).\n\nBefore calling \\`set-agent-instructions\\`, self-audit the draft. It must pass every check:\n- No placeholders remain (no \\`<...>\\`, \"TBD\", \"TODO\", \"your tool\", or generic policy gaps).\n- No internal tool ids, file paths, schemas, or builder-only terms appear.\n- No generic \"helpful assistant\" identity remains.\n- No unsupported capabilities are promised.\n- Completion criteria are concrete.\n- Missing-access fallback is included when relevant.\n- Final response expectations are clear.\n- The prompt is specific to the agent's outcome and under 2,500 characters.\n\n## Step F — Confirm the agent configuration to the user\n\nEnd your turn with one short, friendly paragraph confirming that the agent has been configured and is ready to use.\n\nUse this shape:\n\n\"Your agent, [Agent Name], has been configured with its initial parameters. It can now [plain-language outcome]. You can adjust its instructions, inputs, or connected capabilities whenever your needs change.\"\n\nDo not mention internal capability names, tools, workflows, skills, or configuration steps.\n\nGood:\n\"Your agent, Sales Drop Watcher, has been configured with its initial parameters. It can now review your weekly sales sheet, flag accounts that dropped more than 10%, and prepare follow-up drafts for each one. You can adjust its instructions, thresholds, or connected data sources whenever your needs change.\"\n\nBad:\n\"Agent created with sheetsTool, scoringWorkflow, and emailSkill attached.\"\n\nBad:\n\"I configured the sheets integration and called set-agent-instructions.\"\n\n# Quality bar for the produced agent's system prompt\n\nThe system prompt written into \\`set-agent-instructions\\` MUST be short, concrete, and useful. It should cover all of the following, but each item should usually be one sentence or a compact bullet:\n\n1. **Role and outcome.** Define what the agent is and the concrete result it owns.\n2. **Trigger and input.** Define what starts a run and what input the agent expects.\n3. **Decision rules.** Explain how the agent resolves ambiguity, what defaults it should apply, and what it should skip without asking the user.\n4. **Capability awareness.** Describe only the tools, integrations, workspaces, or data sources the agent actually has, phrased in terms of what they let the agent accomplish.\n5. **Missing-capability fallback.** Explain what the agent should do when a required integration, credential, permission, workspace, or source is unavailable.\n6. **Completion criteria.** Define exactly when the task is done in observable, verifiable terms.\n7. **Final response format.** Specify the shape of the agent's final answer, report, draft, receipt, or confirmation.\n8. **Communication style.** Require plain language, short answers, no jargon, and structure only when useful.\n9. **Refusal rules.** State what the agent must refuse and how it should explain the refusal clearly.\n\nKeep this to 2–4 focused paragraphs or compact bullet groups. Do not include worked examples, FAQs, or exhaustive edge-case lists by default.\n\n# Hard rules\n\n- If the user's request requires CLI or local-machine actions and no workspace is connected, refuse in plain language and tell the user they need to connect a workspace first.\n- Never reveal that you are calling configuration tools. Describe progress only in terms of the user's intended outcome.\n- Never produce a system prompt without explicit completion criteria.\n- Never attach a capability \"just in case.\" Every tool, agent, workflow, or skill must directly support the requested outcome.\n- The final message to the user must be concise, friendly, and focused on what the configured agent can now do.\n- The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,\n model: 'openai/gpt-5.5',\n memory,\n workspace,\n // Newer cores warn once per agent because this list has no explicit\n // retry budget; that warning is accurate, and setting\n // `maxProcessorRetries` just to silence it would also convert\n // input/output processor `abort({ retry: true })` from abort into retry,\n // so the warning stays.\n ...(args || {}),\n errorProcessors,\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n };\n\n return new Agent<'builder-agent'>(config);\n}\n","import type { Mastra } from '@mastra/core';\nimport type { Agent } from '@mastra/core/agent';\nimport type { IWorkflowBuilder, WorkflowBuilderOptions } from '@mastra/core/editor';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { createWorkflowBuilderAgent as createSharedWorkflowBuilderAgent } from '@mastra/core/workflows/builder';\nimport { Memory } from '@mastra/memory';\n\nexport const DEFAULT_WORKFLOW_BUILDER_MODEL = 'openai/gpt-5.5';\n\n/**\n * Authoring turns are tool-heavy: a single request can persist dozens of\n * inspection and submission records. The memory default of 10 evicts the user's\n * original request long before the workflow is finished, which reads as the\n * agent forgetting what it was asked to build.\n */\nexport const DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES = 100;\n\nexport function createWorkflowBuilderAgent(\n model?: MastraModelConfig,\n lastMessages: number = DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES,\n): Agent<'workflow-builder-agent'> {\n return createSharedWorkflowBuilderAgent({\n id: 'workflow-builder-agent',\n name: 'Workflow Builder',\n description: 'Builds persisted workflow definitions through constrained client tools',\n model: model ?? DEFAULT_WORKFLOW_BUILDER_MODEL,\n memory: new Memory({ options: { lastMessages } }),\n surfaceInstructions: `# Studio authoring policy\n\nTurn the user's request into a complete canonical workflow definition using the registered agent, tool, and workflow catalogs. Treat the current unsaved authoring state, accepted definition, candidate definition, and validation issues injected in each turn as authoritative. Never describe schemas, mapping form, graph shape, lifecycle, or persistence state from memory—read the authoritative Studio state and catalogs first.\n\nThe three shared listing tools behave here as the shared playbook describes, with one Studio specific: \\`list-available-workflows\\` reports \\`catalog-unavailable\\` when this user lacks workflow read permission. Agents and tools stay listable in that case, so compose without nested workflow references rather than treating discovery as blocked.\n\n# Studio execution and response protocol\n\n1. Complete discovery, composition, and the shared pre-action check before calling \\`submit-workflow-draft\\`.\n2. Call \\`submit-workflow-draft\\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.\n When the definition nests helper workflows that the catalog does not have yet, put those complete helper definitions in the same submission's \\`dependencies\\` array. Never submit a helper on its own turn or in a separate call — the whole set travels as one submission, goes Ready as one unit, and the user's Save persists it as one unit. Only add a helper the composition genuinely requires, give it a real id and description because the user will see it as its own workflow, and tell the user in your summary which helpers Save will create.\n3. Wait for the submission result before deciding what to do next. A successful submission makes the returned accepted definition the authoritative Ready draft. Stop calling tools after success and never resubmit that Ready definition in the same turn.\n4. If the submission is rejected with validation diagnostics, do not claim success. Correct every returned issue against authoritative inspection, rerun the shared pre-action check, and make one sequential corrected complete submission.\n5. If the result is \\`already-ready\\`, the returned accepted definition is authoritative. Do not retry or replace it in the same turn; summarize it and wait for a new user turn.\n6. If the result is \\`superseded\\`, an earlier submission in the turn won. Do not apologize, retry, or claim the workflow is broken. Inspect the authoritative state before making any claim.\n7. Ready is not persisted. Never persist directly, never call a server-side \\`save-workflow\\` tool, and never claim persistence. Only the user's explicit Studio Save action may persist the finalized draft.\n8. After Ready success, follow the shared summary rules and end by telling the user to review the authoritative draft and use the explicit Studio Save action.`,\n });\n}\n\nexport class EditorWorkflowBuilder implements IWorkflowBuilder {\n readonly enabled: boolean;\n private readonly agent;\n private readonly modelPolicy: WorkflowBuilderOptions['modelPolicy'];\n\n constructor(options: WorkflowBuilderOptions = {}, mastra?: Mastra) {\n this.enabled = options.enabled !== false;\n this.modelPolicy = options.modelPolicy;\n this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);\n if (mastra) {\n this.agent.__registerMastra(mastra);\n this.agent.__registerPrimitives({ logger: mastra.getLogger(), storage: mastra.getStorage() });\n }\n }\n\n getAgent() {\n return this.agent;\n }\n\n getModelPolicy() {\n return this.modelPolicy;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;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AU,EAAE,KAAK,SACnF,GACA,GAAG,sBAAsB,QACvB,WAAU,CAAC,iCAAiC,MAAK,cAAa,UAAU,OAAO,OAAO,EAAE,CAC1F,CACF,IACC,yBAAyB;CAiJlC,OAAO,IAAI,MAAuB;EA9IhC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Hd,OAAO;EACP;EACA;EAMA,GAAI,QAAQ,CAAC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CAGwB,CAAC;AAC1C;ACnOA,SAAgB,2BACd,OACA,eAAA,KACiC;CACjC,OAAOA,6BAAiC;EACtC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,OAAO,SAAA;EACP,QAAQ,IAAI,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC;EAChD,qBAAqB;;;;;;;;;;;;;;;;;CAiBvB,CAAC;AACH;AAEA,IAAa,wBAAb,MAA+D;CAK7D,YAAY,UAAkC,CAAC,GAAG,QAAiB;EACjE,KAAK,UAAU,QAAQ,YAAY;EACnC,KAAK,cAAc,QAAQ;EAC3B,KAAK,QAAQ,2BAA2B,QAAQ,OAAO,QAAQ,YAAY;EAC3E,IAAI,QAAQ;GACV,KAAK,MAAM,iBAAiB,MAAM;GAClC,KAAK,MAAM,qBAAqB;IAAE,QAAQ,OAAO,UAAU;IAAG,SAAS,OAAO,WAAW;GAAE,CAAC;EAC9F;CACF;CAEA,WAAW;EACT,OAAO,KAAK;CACd;CAEA,iBAAiB;EACf,OAAO,KAAK;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["createSharedWorkflowBuilderAgent"],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"sourcesContent":["import type { AgentBuilderOptions, AgentFeatures, IAgentBuilder } from '@mastra/core/agent-builder/ee';\nimport { isBuilderModelPolicyActive, isModelAllowed, resolveAgentFeatures } from '@mastra/core/agent-builder/ee';\n\n/**\n * Concrete implementation of the Agent Builder EE feature.\n * Instantiated by MastraEditor.resolveBuilder() when builder config is enabled.\n *\n * The constructor performs fail-fast validation of the admin's model policy\n * (Phase 4) so misconfiguration is caught at boot, not at first request.\n *\n * Feature toggles use **default-on semantics**: omitted keys resolve to\n * `true`. Admins opt out by setting a key to `false`. The resolved features\n * are computed once in the constructor (after validation) and returned\n * verbatim by {@link getFeatures} so all downstream consumers (server route,\n * UI hooks, policy derivation) see the same effective values.\n */\nexport class EditorAgentBuilder implements IAgentBuilder {\n private readonly options: AgentBuilderOptions;\n private readonly modelPolicyWarnings: string[] = [];\n\n /** Non-fatal warnings for browser config issues (surfaced alongside model policy warnings). */\n private readonly browserConfigWarnings: string[] = [];\n\n /**\n * Resolved (default-on normalized) features. Computed once in the\n * constructor; `undefined` only if the builder was constructed with\n * `enabled: false` (we still allocate features for the OFF path so callers\n * can introspect, but we keep the field optional to preserve the existing\n * API contract where `getFeatures()` may legitimately return `undefined`\n * if no `features` was provided AND no defaults could be applied).\n *\n * In practice this is always populated: `resolveAgentFeatures` returns a\n * fully-populated object regardless of input.\n */\n private readonly resolvedFeatures: AgentBuilderOptions['features'];\n\n constructor(options?: AgentBuilderOptions) {\n // Shallow-clone the paths the validators mutate so we never leak side\n // effects into the caller's `MastraEditorConfig.builder` object.\n // `validateBrowserConfig` writes to `features.agent.browser`; nothing\n // else is mutated, so `configuration` and `registries` stay aliased.\n const source = options ?? {};\n this.options = {\n ...source,\n features: source.features\n ? {\n ...source.features,\n agent: source.features.agent ? { ...source.features.agent } : undefined,\n }\n : undefined,\n };\n this.validateModelPolicy();\n this.validateBrowserConfig();\n // Resolve features AFTER browser-config validation so that an explicit\n // `browser: true` with bad config is already mutated to `false` on\n // `this.options.features.agent.browser`. The resolver then sees the\n // downgraded value and returns it as-is.\n this.resolvedFeatures = {\n agent: resolveAgentFeatures(this.options.features?.agent, {\n hasBrowserConfig: this.hasValidBrowserConfig(),\n }),\n };\n }\n\n get enabled(): boolean {\n return this.options.enabled !== false;\n }\n\n getFeatures(): AgentBuilderOptions['features'] {\n return this.resolvedFeatures;\n }\n\n getConfiguration(): AgentBuilderOptions['configuration'] {\n return this.options.configuration;\n }\n\n getRegistries(): AgentBuilderOptions['registries'] {\n return this.options.registries;\n }\n\n getModelPolicyWarnings(): string[] {\n return [...this.modelPolicyWarnings, ...this.browserConfigWarnings];\n }\n\n /**\n * True when `configuration.agent.browser` declares a provider. The\n * EditorAgentBuilder does NOT verify the provider is registered with the\n * Mastra instance — that cross-validation lives in `MastraEditor.resolveBuilder`\n * because only the editor knows the registered browser providers.\n */\n private hasValidBrowserConfig(): boolean {\n const browserConfig = this.options.configuration?.agent?.browser;\n return Boolean(browserConfig?.config?.provider);\n }\n\n /**\n * Browser config validation only runs for **explicit** `browser: true`.\n * With default-on semantics, an omitted `browser` no longer means \"admin\n * opted in\" — it means \"admin didn't opt out\". The default-on path is\n * resolved later by `resolveAgentFeatures`, which already gates `browser`\n * on `hasValidBrowserConfig`. We don't want to spam every default-config\n * deployment with warnings.\n */\n private validateBrowserConfig(): void {\n const explicitBrowser = this.options.features?.agent?.browser;\n if (explicitBrowser !== true) return;\n\n const browserConfig = this.options.configuration?.agent?.browser;\n if (!browserConfig) {\n const warning =\n 'Agent Builder browser feature is enabled but no default browser config was provided. ' +\n 'Set `editor.builder.configuration.agent.browser` to a valid browser config ' +\n '(e.g. `{ type: \"inline\", config: { provider: \"stagehand\" } }`). ' +\n 'The browser toggle will be hidden until a default is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n // Downgrade so the resolved feature ends up `false`.\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n return;\n }\n\n if (!browserConfig.config?.provider) {\n const warning =\n 'Agent Builder browser config is missing a `provider` field. ' +\n 'Set `editor.builder.configuration.agent.browser.config.provider` ' +\n '(e.g. `\"stagehand\"`). The browser toggle will be hidden until a provider is configured.';\n this.browserConfigWarnings.push(warning);\n // eslint-disable-next-line no-console\n console.warn(`[mastra:editor:builder] ${warning}`);\n if (this.options.features?.agent) {\n this.options.features.agent.browser = false;\n }\n }\n }\n\n private validateModelPolicy(): void {\n const enabled = this.options.enabled !== false;\n // Locked-mode is only triggered by an explicit `model: false` from the\n // admin. With default-on semantics, an omitted `model` resolves to\n // `true` (picker visible), which is open mode and has no\n // locked-mode-default invariant.\n const explicitModel = this.options.features?.agent?.model;\n const pickerVisible = explicitModel !== false;\n const models = this.options.configuration?.agent?.models;\n const allowed = models?.allowed;\n const defaultModel = models?.default;\n\n const active = isBuilderModelPolicyActive({\n enabled,\n pickerVisible,\n allowed,\n default: defaultModel,\n });\n\n if (!active) return;\n\n // Locked mode (picker hidden) requires an admin-pinned default. Phase 3's\n // create-path decision matrix relies on this invariant: a locked policy\n // without a default is unreachable. Only fires when the admin has\n // explicitly opted out of the picker.\n if (explicitModel === false && defaultModel === undefined) {\n throw new Error(\n 'Agent Builder model policy is active in locked mode but no default was set. ' +\n 'Set `editor.builder.configuration.agent.models.default`, or remove ' +\n '`editor.builder.features.agent.model = false` to allow end-users to pick a model.',\n );\n }\n\n // When an allowlist is set, the default (if any) must satisfy it. An\n // empty `allowed: []` means \"unrestricted\" so we skip this check.\n if (defaultModel !== undefined && allowed !== undefined && allowed.length > 0) {\n if (!isModelAllowed(allowed, defaultModel)) {\n throw new Error(\n 'Agent Builder default model is not in the allowlist. ' +\n 'Either add it to `editor.builder.configuration.agent.models.allowed` ' +\n 'or change `editor.builder.configuration.agent.models.default`.',\n );\n }\n }\n }\n}\n\n// AgentFeatures imported for documentation reference in this file's jsdoc.\nexport type { AgentFeatures };\n","import { Agent } from '@mastra/core/agent';\nimport type { AgentConfig } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor } from '@mastra/core/processors';\nimport { Workspace, LocalFilesystem } from '@mastra/core/workspace';\n\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst workspacePath = path.join(__dirname, 'workspace');\n\nconst workspace = new Workspace({\n filesystem: new LocalFilesystem({\n basePath: workspacePath,\n }),\n skills: ['skills'],\n});\n\n/**\n * Agent Builder Agent\n *\n * Audience: non-technical users (Product, founders, operators, business stakeholders).\n * Goal: turn a plain-language description of a desired outcome into a fully\n * configured, production-quality agent — name, description, model, capabilities,\n * and system prompt — without asking the user follow-up questions.\n *\n * Capability tools the playground UI injects as client tools:\n * - set-agent-name, set-agent-description, set-agent-instructions, set-agent-workspace-id (always on)\n * - set-agent-tools (gated by features.tools)\n * - set-agent-skills (gated by features.skills + skills available)\n * - set-agent-model (gated by features.model + models available)\n * - set-agent-browser-enabled (gated by features.browser)\n * - createSkillTool (gated by features.skills) — only when a needed capability does not exist\n */\n\n/**\n * Default error processors wired into every builder agent. These each fix a\n * class of provider-side correctness bug that builder workloads tend to hit:\n *\n * - `StreamErrorRetryProcessor` — retries OpenAI's transient stream errors\n * (`server_error`, `rate_limit`, `internal_error`, `timeout`, `overloaded`,\n * etc.) that surface on long, tool-heavy turns.\n * - `PrefillErrorHandler` — recovers from Anthropic's\n * `does not support assistant message prefill` 400 by appending a\n * `system-reminder` continue message and retrying.\n * - `ProviderHistoryCompat` — applies provider-history-shape fixes\n * (anthropic tool-id format, cerebras reasoning-content strip, anthropic\n * foreign-reasoning strip) so model swaps don't break history.\n *\n * Same three processors, same order, as the shared stability defaults in\n * `@mastra/core/processors`. `createBuilderAgent` passes this list explicitly\n * rather than relying on the framework defaults: the peer range allows older\n * cores that have no defaults, and bumping the range would be a breaking\n * change, so the builder brings its own stack and behaves the same on every\n * core version.\n *\n * Exported so callers can compose a custom processor list that keeps the\n * subset they want. Pass it with `errorProcessorDefaults: false`, or the\n * builder merges the omitted defaults back in:\n * `createBuilderAgent({ errorProcessors: [...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom], errorProcessorDefaults: false })`.\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new ProviderHistoryCompat(),\n new PrefillErrorHandler(),\n new StreamErrorRetryProcessor(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge the builder's stability processors with any caller-supplied list:\n // the peer range allows cores that predate the framework defaults, so\n // relying on the resolver to add them would silently drop this stack on\n // older cores. A caller instance with a default's id replaces that default\n // at its position, so repairs keep running ahead of retries; caller\n // processors with other ids run after the defaults so they can observe or\n // extend retries the defaults trigger. An empty array merges like any other,\n // matching core; `errorProcessorDefaults: false` is the only opt-out and\n // passes the caller's list through as given (the flag is also forwarded, so\n // newer cores add nothing either). A function-typed override\n // (DynamicArgument) is passed through unchanged — callers using the dynamic\n // form manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors =\n args?.errorProcessorDefaults === false\n ? callerErrorProcessors\n : Array.isArray(callerErrorProcessors)\n ? [\n ...DEFAULT_BUILDER_ERROR_PROCESSORS.map(\n processor => callerErrorProcessors.find(caller => caller.id === processor.id) ?? processor,\n ),\n ...callerErrorProcessors.filter(\n caller => !DEFAULT_BUILDER_ERROR_PROCESSORS.some(processor => processor.id === caller.id),\n ),\n ]\n : (callerErrorProcessors ?? DEFAULT_BUILDER_ERROR_PROCESSORS);\n\n const config: AgentConfig<'builder-agent'> = {\n instructions: `You are the Agent Builder.\n\nYour job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.\n\n# Non-negotiables\n\n- Never ask the user follow-up questions. Make the most reasonable assumption and move forward.\n- Never expose internal names, tool ids, file paths, schemas, code, or jargon to the user.\n- Speak only in user-facing capability terms.\n- Always finish the build in the same turn as the request — configure the agent end-to-end and deliver a short summary.\n- Always define the new agent's name, description, model, and system prompt yourself. Do not ask the user for any of these.\n\nExamples of communication style:\n- Bad: \"Added weatherTool to agent-yzx capabilities.\"\n- Good: \"Your new agent can now check the weather for you.\"\n- Bad: \"Calling set-agent-tools with [weatherTool].\"\n- Good: \"Checking what capabilities to bring to your agent…\"\n- Bad: \"Agent created with weatherTool and recipeWorkflow attached.\"\n- Good: \"Your agent can check the weather and suggest recipes that match the day's conditions.\"\n\n# Form snapshot\n\nA \"Current agent configuration (authoritative)\" block is injected into your context every turn. It lists every form field with its current value AND a directive telling you exactly which setter to call (or skip) for that field. Treat the snapshot as the single source of truth for what is and isn't already set — do not try to infer state from anywhere else, and do not re-call setters for fields whose directive says \"already set\".\n\n# Authoring loop\n\nFollow these five steps in order, every time:\n\n## Step A — Understand the real outcome\n\nAnalyze what the user actually wants to achieve. Focus on the final result, not just the literal wording of the request.\n\nAsk yourself:\n- What should the agent help the user accomplish?\n- Who will use this agent?\n- What decisions should the agent make on its own?\n- What kind of output should the agent produce?\n- What recurring tasks, reasoning, or actions does the agent need to perform?\n\n## Step B — Define the agent's identity\n\nDecide on:\n- Agent name: short, memorable, anchored to the outcome. Never \"Agent X\" or generic labels.\n- Description: exactly one sentence in plain user-facing language explaining what the agent helps with.\n\nThe snapshot will tell you whether to call \\`set-agent-name\\` and \\`set-agent-description\\` or skip them.\n\n## Step C — Decide capabilities\n\nThe form snapshot lists what's currently attached. Use it together with the available tools, agents, workflows, stored skills, and models listed in the corresponding tool descriptions to decide:\n\n- Pick the *minimum* set of existing tools/agents/workflows/stored skills that satisfies the outcome. Adding irrelevant capabilities makes the agent worse, not better.\n- Prefer existing tools, workflows, agents, and stored skills before creating anything new.\n- \\`set-agent-skills\\` attaches user-available stored skills.\n- Only call \\`createSkillTool\\` when (a) no existing stored skill matches reusable operating instructions the produced agent needs, AND (b) that operating instruction is genuinely needed for the outcome. Do not use stored skills as a substitute for missing integrations or tools.\n- If a specific external connection is required (e.g. a sheet tool for a spreadsheet-driven outcome) and none is available, the new agent's system prompt must instruct it to refuse cleanly and explain what the user needs to connect.\n\n## Step D — Synthesize concise operating instructions\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item, but keep each item brief:\n\n1. **Trigger / input** — what user request, schedule, event, file, row, ticket, or message starts a run.\n2. **Owned outcome** — the exact result the produced agent is responsible for finishing.\n3. **Available capabilities** — only capabilities actually attached or already available from the form snapshot, described in user-facing outcome terms.\n4. **Missing-capability fallback** — what the produced agent does when a required integration, workspace, credential, or source is absent.\n5. **Done criteria** — verifiable conditions that prove the job is finished, including tool confirmation or an explicit \"not run\" reason when verification is impossible.\n6. **Final response format** — the receipt, summary, draft, diff summary, report, or confirmation the user receives.\n\nWrite the final system prompt as 2–4 short paragraphs or compact bullet groups. Target 1,200–2,000 characters and stay under 2,500 characters. Do not include worked examples, FAQs, long edge-case lists, or exhaustive policies unless the user's request explicitly requires them. Prefer one clear default over several branches.\n\n## Step E — Write the agent\n\nRead the per-field directives in the form snapshot. Call only the setters the snapshot tells you to call, each at most once, with the final value. Skip every field marked \"already set\" or \"no setter\". Skip any field that isn't listed at all (its feature is disabled).\n\nBefore calling \\`set-agent-instructions\\`, self-audit the draft. It must pass every check:\n- No placeholders remain (no \\`<...>\\`, \"TBD\", \"TODO\", \"your tool\", or generic policy gaps).\n- No internal tool ids, file paths, schemas, or builder-only terms appear.\n- No generic \"helpful assistant\" identity remains.\n- No unsupported capabilities are promised.\n- Completion criteria are concrete.\n- Missing-access fallback is included when relevant.\n- Final response expectations are clear.\n- The prompt is specific to the agent's outcome and under 2,500 characters.\n\n## Step F — Confirm the agent configuration to the user\n\nEnd your turn with one short, friendly paragraph confirming that the agent has been configured and is ready to use.\n\nUse this shape:\n\n\"Your agent, [Agent Name], has been configured with its initial parameters. It can now [plain-language outcome]. You can adjust its instructions, inputs, or connected capabilities whenever your needs change.\"\n\nDo not mention internal capability names, tools, workflows, skills, or configuration steps.\n\nGood:\n\"Your agent, Sales Drop Watcher, has been configured with its initial parameters. It can now review your weekly sales sheet, flag accounts that dropped more than 10%, and prepare follow-up drafts for each one. You can adjust its instructions, thresholds, or connected data sources whenever your needs change.\"\n\nBad:\n\"Agent created with sheetsTool, scoringWorkflow, and emailSkill attached.\"\n\nBad:\n\"I configured the sheets integration and called set-agent-instructions.\"\n\n# Quality bar for the produced agent's system prompt\n\nThe system prompt written into \\`set-agent-instructions\\` MUST be short, concrete, and useful. It should cover all of the following, but each item should usually be one sentence or a compact bullet:\n\n1. **Role and outcome.** Define what the agent is and the concrete result it owns.\n2. **Trigger and input.** Define what starts a run and what input the agent expects.\n3. **Decision rules.** Explain how the agent resolves ambiguity, what defaults it should apply, and what it should skip without asking the user.\n4. **Capability awareness.** Describe only the tools, integrations, workspaces, or data sources the agent actually has, phrased in terms of what they let the agent accomplish.\n5. **Missing-capability fallback.** Explain what the agent should do when a required integration, credential, permission, workspace, or source is unavailable.\n6. **Completion criteria.** Define exactly when the task is done in observable, verifiable terms.\n7. **Final response format.** Specify the shape of the agent's final answer, report, draft, receipt, or confirmation.\n8. **Communication style.** Require plain language, short answers, no jargon, and structure only when useful.\n9. **Refusal rules.** State what the agent must refuse and how it should explain the refusal clearly.\n\nKeep this to 2–4 focused paragraphs or compact bullet groups. Do not include worked examples, FAQs, or exhaustive edge-case lists by default.\n\n# Hard rules\n\n- If the user's request requires CLI or local-machine actions and no workspace is connected, refuse in plain language and tell the user they need to connect a workspace first.\n- Never reveal that you are calling configuration tools. Describe progress only in terms of the user's intended outcome.\n- Never produce a system prompt without explicit completion criteria.\n- Never attach a capability \"just in case.\" Every tool, agent, workflow, or skill must directly support the requested outcome.\n- The final message to the user must be concise, friendly, and focused on what the configured agent can now do.\n- The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,\n model: 'openai/gpt-5.5',\n memory,\n workspace,\n // Newer cores warn once per agent because this list has no explicit\n // retry budget; that warning is accurate, and setting\n // `maxProcessorRetries` just to silence it would also convert\n // input/output processor `abort({ retry: true })` from abort into retry,\n // so the warning stays.\n ...(args || {}),\n errorProcessors,\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n };\n\n return new Agent<'builder-agent'>(config);\n}\n","import type { Mastra } from '@mastra/core';\nimport type { Agent } from '@mastra/core/agent';\nimport type { IWorkflowBuilder, WorkflowBuilderOptions } from '@mastra/core/editor';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { createWorkflowBuilderAgent as createSharedWorkflowBuilderAgent } from '@mastra/core/workflows/builder';\nimport { Memory } from '@mastra/memory';\n\nexport const DEFAULT_WORKFLOW_BUILDER_MODEL = 'openai/gpt-5.5';\n\n/**\n * Authoring turns are tool-heavy: a single request can persist dozens of\n * inspection and submission records. The memory default of 10 evicts the user's\n * original request long before the workflow is finished, which reads as the\n * agent forgetting what it was asked to build.\n */\nexport const DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES = 100;\n\nexport function createWorkflowBuilderAgent(\n model?: MastraModelConfig,\n lastMessages: number = DEFAULT_WORKFLOW_BUILDER_LAST_MESSAGES,\n): Agent<'workflow-builder-agent'> {\n return createSharedWorkflowBuilderAgent({\n id: 'workflow-builder-agent',\n name: 'Workflow Builder',\n description: 'Builds persisted workflow definitions through constrained client tools',\n model: model ?? DEFAULT_WORKFLOW_BUILDER_MODEL,\n memory: new Memory({ options: { lastMessages } }),\n surfaceInstructions: `# Studio authoring policy\n\nTurn the user's request into a complete canonical workflow definition using the registered agent, tool, and workflow catalogs. Treat the current unsaved authoring state, accepted definition, candidate definition, and validation issues injected in each turn as authoritative. Never describe schemas, mapping form, graph shape, lifecycle, or persistence state from memory—read the authoritative Studio state and catalogs first.\n\nThe three shared listing tools behave here as the shared playbook describes, with one Studio specific: \\`list-available-workflows\\` reports \\`catalog-unavailable\\` when this user lacks workflow read permission. Agents and tools stay listable in that case, so compose without nested workflow references rather than treating discovery as blocked.\n\n# Studio execution and response protocol\n\n1. Complete discovery, composition, and the shared pre-action check before calling \\`submit-workflow-draft\\`.\n2. Call \\`submit-workflow-draft\\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.\n When the definition nests helper workflows that the catalog does not have yet, put those complete helper definitions in the same submission's \\`dependencies\\` array. Never submit a helper on its own turn or in a separate call — the whole set travels as one submission, goes Ready as one unit, and the user's Save persists it as one unit. Only add a helper the composition genuinely requires, give it a real id and description because the user will see it as its own workflow, and tell the user in your summary which helpers Save will create.\n3. Wait for the submission result before deciding what to do next. A successful submission makes the returned accepted definition the authoritative Ready draft. Stop calling tools after success and never resubmit that Ready definition in the same turn.\n4. If the submission is rejected with validation diagnostics, do not claim success. Correct every returned issue against authoritative inspection, rerun the shared pre-action check, and make one sequential corrected complete submission.\n5. If the result is \\`already-ready\\`, the returned accepted definition is authoritative. Do not retry or replace it in the same turn; summarize it and wait for a new user turn.\n6. If the result is \\`superseded\\`, an earlier submission in the turn won. Do not apologize, retry, or claim the workflow is broken. Inspect the authoritative state before making any claim.\n7. Ready is not persisted. Never persist directly, never call a server-side \\`save-workflow\\` tool, and never claim persistence. Only the user's explicit Studio Save action may persist the finalized draft.\n8. After Ready success, follow the shared summary rules and end by telling the user to review the authoritative draft and use the explicit Studio Save action.`,\n });\n}\n\nexport class EditorWorkflowBuilder implements IWorkflowBuilder {\n readonly enabled: boolean;\n private readonly agent;\n private readonly modelPolicy: WorkflowBuilderOptions['modelPolicy'];\n\n constructor(options: WorkflowBuilderOptions = {}, mastra?: Mastra) {\n this.enabled = options.enabled !== false;\n this.modelPolicy = options.modelPolicy;\n this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);\n if (mastra) {\n this.agent.__registerMastra(mastra);\n this.agent.__registerPrimitives({ logger: mastra.getLogger(), storage: mastra.getStorage() });\n }\n }\n\n getAgent() {\n return this.agent;\n }\n\n getModelPolicy() {\n return this.modelPolicy;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,qBAAb,MAAyD;CAoBvD,YAAY,SAA+B;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,QACvB,WAAU,CAAC,iCAAiC,MAAK,cAAa,UAAU,OAAO,OAAO,EAAE,CAC1F,CACF,IACC,yBAAyB;CAElC,MAAM,SAAuC;EAC3C,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Hd,OAAO;EACP;EACA;EAMA,GAAI,QAAQ,CAAC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CACf;CAEA,OAAO,IAAI,MAAuB,MAAM;AAC1C;ACnOA,SAAgB,2BACd,OACA,eAAA,KACiC;CACjC,OAAOA,6BAAiC;EACtC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,OAAO,SAAA;EACP,QAAQ,IAAI,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC;EAChD,qBAAqB;;;;;;;;;;;;;;;;;CAiBvB,CAAC;AACH;AAEA,IAAa,wBAAb,MAA+D;CAK7D,YAAY,UAAkC,CAAC,GAAG,QAAiB;EACjE,KAAK,UAAU,QAAQ,YAAY;EACnC,KAAK,cAAc,QAAQ;EAC3B,KAAK,QAAQ,2BAA2B,QAAQ,OAAO,QAAQ,YAAY;EAC3E,IAAI,QAAQ;GACV,KAAK,MAAM,iBAAiB,MAAM;GAClC,KAAK,MAAM,qBAAqB;IAAE,QAAQ,OAAO,UAAU;IAAG,SAAS,OAAO,WAAW;GAAE,CAAC;EAC9F;CACF;CAEA,WAAW;EACT,OAAO,KAAK;CACd;CAEA,iBAAiB;EACf,OAAO,KAAK;CACd;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1004,7 +1004,8 @@ var EditorAgentNamespace = class extends CrudEditorNamespace {
|
|
|
1004
1004
|
const mcpTools = await this.resolveStoredMCPTools(resolvedMCPClientsConfig, requestContext);
|
|
1005
1005
|
const resolvedIntegrationToolsConfig = hasConditionalIntegrationTools ? this.accumulateObjectVariants(storedConfig.integrationTools, ctx) : storedConfig.integrationTools;
|
|
1006
1006
|
const integrationTools = await this.resolveStoredIntegrationTools(resolvedIntegrationToolsConfig, requestContext);
|
|
1007
|
-
const
|
|
1007
|
+
const resolvedToolProvidersConfig = hasConditionalToolProviders ? this.accumulateObjectVariants(storedConfig.toolProviders, ctx) : storedConfig.toolProviders;
|
|
1008
|
+
const providerTools = await (0, _mastra_core_tool_provider.resolveStoredToolProviders)(resolvedToolProvidersConfig, (providerId) => this.editor.getToolProviderOrThrow(providerId), {
|
|
1008
1009
|
requestContext,
|
|
1009
1010
|
authorId: storedConfig.authorId,
|
|
1010
1011
|
logger: this.logger
|
|
@@ -1030,17 +1031,19 @@ var EditorAgentNamespace = class extends CrudEditorNamespace {
|
|
|
1030
1031
|
...integrationTools
|
|
1031
1032
|
});
|
|
1032
1033
|
}
|
|
1033
|
-
} else if (toolDescriptionsEditable && hasStoredTools)
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
const
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1034
|
+
} else if (toolDescriptionsEditable && hasStoredTools) {
|
|
1035
|
+
if (this.isConditionalVariants(storedConfig.tools)) {
|
|
1036
|
+
const originalTools = agent.listTools.bind(agent);
|
|
1037
|
+
const toolsFn = async ({ requestContext }) => {
|
|
1038
|
+
const codeTools = await originalTools({ requestContext });
|
|
1039
|
+
const resolvedToolsConfig = this.accumulateObjectVariants(storedConfig.tools, requestContext.toJSON());
|
|
1040
|
+
return this.applyStoredToolDescriptions(codeTools, resolvedToolsConfig);
|
|
1041
|
+
};
|
|
1042
|
+
fork.__setTools(toolsFn);
|
|
1043
|
+
} else {
|
|
1044
|
+
const codeTools = await fork.listTools();
|
|
1045
|
+
fork.__setTools(this.applyStoredToolDescriptions(codeTools, storedConfig.tools));
|
|
1046
|
+
}
|
|
1044
1047
|
}
|
|
1045
1048
|
if (storedConfig.resolvedVersionId) {
|
|
1046
1049
|
const existing = fork.toRawConfig() ?? {};
|
|
@@ -1147,7 +1150,8 @@ var EditorAgentNamespace = class extends CrudEditorNamespace {
|
|
|
1147
1150
|
const mcpTools = await this.resolveStoredMCPTools(resolvedMCPClientsConfig, requestContext);
|
|
1148
1151
|
const resolvedIntegrationToolsConfig = hasConditionalIntegrationTools ? this.accumulateObjectVariants(storedAgent.integrationTools, ctx) : storedAgent.integrationTools;
|
|
1149
1152
|
const integrationTools = await this.resolveStoredIntegrationTools(resolvedIntegrationToolsConfig, requestContext);
|
|
1150
|
-
const
|
|
1153
|
+
const resolvedToolProvidersConfig = hasConditionalToolProviders ? this.accumulateObjectVariants(storedAgent.toolProviders, ctx) : storedAgent.toolProviders;
|
|
1154
|
+
const providerTools = await (0, _mastra_core_tool_provider.resolveStoredToolProviders)(resolvedToolProvidersConfig, (providerId) => this.editor.getToolProviderOrThrow(providerId), {
|
|
1151
1155
|
requestContext,
|
|
1152
1156
|
authorId: storedAgent.authorId,
|
|
1153
1157
|
logger: this.logger
|
|
@@ -1566,21 +1570,23 @@ var EditorAgentNamespace = class extends CrudEditorNamespace {
|
|
|
1566
1570
|
...options,
|
|
1567
1571
|
semanticRecall: false
|
|
1568
1572
|
};
|
|
1569
|
-
|
|
1573
|
+
const sharedConfig = {
|
|
1570
1574
|
storage: this.mastra.getStorage(),
|
|
1571
1575
|
vector,
|
|
1572
1576
|
options: adjustedOptions,
|
|
1573
1577
|
embedder: memoryConfig.embedder,
|
|
1574
1578
|
embedderOptions: memoryConfig.embedderOptions
|
|
1575
|
-
}
|
|
1579
|
+
};
|
|
1580
|
+
return new _mastra_memory.Memory(sharedConfig);
|
|
1576
1581
|
}
|
|
1577
|
-
|
|
1582
|
+
const sharedConfig = {
|
|
1578
1583
|
storage: this.mastra.getStorage(),
|
|
1579
1584
|
vector,
|
|
1580
1585
|
options,
|
|
1581
1586
|
embedder: memoryConfig.embedder,
|
|
1582
1587
|
embedderOptions: memoryConfig.embedderOptions
|
|
1583
|
-
}
|
|
1588
|
+
};
|
|
1589
|
+
return new _mastra_memory.Memory(sharedConfig);
|
|
1584
1590
|
} catch (error) {
|
|
1585
1591
|
this.logger?.error("Failed to resolve memory from config", { error });
|
|
1586
1592
|
return;
|
|
@@ -2268,11 +2274,13 @@ var EditorWorkspaceNamespace = class extends CrudEditorNamespace {
|
|
|
2268
2274
|
async snapshotFromWorkspace(workspace) {
|
|
2269
2275
|
const snapshot = { name: workspace.name };
|
|
2270
2276
|
const fs = workspace.filesystem;
|
|
2271
|
-
if (fs)
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2277
|
+
if (fs) {
|
|
2278
|
+
if (fs instanceof _mastra_core_workspace.CompositeFilesystem) {
|
|
2279
|
+
const mounts = {};
|
|
2280
|
+
for (const [mountPath, mountedFs] of fs.mounts) mounts[mountPath] = await this.serializeFilesystem(mountedFs);
|
|
2281
|
+
snapshot.mounts = mounts;
|
|
2282
|
+
} else snapshot.filesystem = await this.serializeFilesystem(fs);
|
|
2283
|
+
}
|
|
2276
2284
|
const sandbox = workspace.sandbox;
|
|
2277
2285
|
if (sandbox) {
|
|
2278
2286
|
const info = typeof sandbox.getInfo === "function" ? await sandbox.getInfo() : void 0;
|