@mastra/editor 0.14.6-alpha.2 → 0.15.0-alpha.4
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/ee/index.cjs +49 -0
- package/dist/ee/index.cjs.map +1 -1
- package/dist/ee/index.d.cts +15 -1
- package/dist/ee/index.d.cts.map +1 -1
- package/dist/ee/index.d.ts +15 -1
- package/dist/ee/index.d.ts.map +1 -1
- package/dist/ee/index.js +48 -1
- package/dist/ee/index.js.map +1 -1
- package/dist/index.cjs +56 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +9 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +56 -10
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/ee/index.cjs
CHANGED
|
@@ -29,6 +29,7 @@ let _mastra_core_agent_builder_ee = require("@mastra/core/agent-builder/ee");
|
|
|
29
29
|
let path = require("path");
|
|
30
30
|
path = __toESM(path, 1);
|
|
31
31
|
let url = require("url");
|
|
32
|
+
let _mastra_core_workflows_builder = require("@mastra/core/workflows/builder");
|
|
32
33
|
//#region src/ee/agent-builder.ts
|
|
33
34
|
/**
|
|
34
35
|
* Concrete implementation of the Agent Builder EE feature.
|
|
@@ -316,8 +317,56 @@ Keep this to 2–4 focused paragraphs or compact bullet groups. Do not include w
|
|
|
316
317
|
description: "An agent that can build agents"
|
|
317
318
|
});
|
|
318
319
|
}
|
|
320
|
+
function createWorkflowBuilderAgent(model, lastMessages = 100) {
|
|
321
|
+
return (0, _mastra_core_workflows_builder.createWorkflowBuilderAgent)({
|
|
322
|
+
id: "workflow-builder-agent",
|
|
323
|
+
name: "Workflow Builder",
|
|
324
|
+
description: "Builds persisted workflow definitions through constrained client tools",
|
|
325
|
+
model: model ?? "openai/gpt-5.5",
|
|
326
|
+
memory: new _mastra_memory.Memory({ options: { lastMessages } }),
|
|
327
|
+
surfaceInstructions: `# Studio authoring policy
|
|
328
|
+
|
|
329
|
+
Turn 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.
|
|
330
|
+
|
|
331
|
+
The 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.
|
|
332
|
+
|
|
333
|
+
# Studio execution and response protocol
|
|
334
|
+
|
|
335
|
+
1. Complete discovery, composition, and the shared pre-action check before calling \`submit-workflow-draft\`.
|
|
336
|
+
2. Call \`submit-workflow-draft\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.
|
|
337
|
+
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.
|
|
338
|
+
3. 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.
|
|
339
|
+
4. 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.
|
|
340
|
+
5. 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.
|
|
341
|
+
6. 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.
|
|
342
|
+
7. 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.
|
|
343
|
+
8. 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.`
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
var EditorWorkflowBuilder = class {
|
|
347
|
+
constructor(options = {}, mastra) {
|
|
348
|
+
this.enabled = options.enabled !== false;
|
|
349
|
+
this.modelPolicy = options.modelPolicy;
|
|
350
|
+
this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);
|
|
351
|
+
if (mastra) {
|
|
352
|
+
this.agent.__registerMastra(mastra);
|
|
353
|
+
this.agent.__registerPrimitives({
|
|
354
|
+
logger: mastra.getLogger(),
|
|
355
|
+
storage: mastra.getStorage()
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
getAgent() {
|
|
360
|
+
return this.agent;
|
|
361
|
+
}
|
|
362
|
+
getModelPolicy() {
|
|
363
|
+
return this.modelPolicy;
|
|
364
|
+
}
|
|
365
|
+
};
|
|
319
366
|
//#endregion
|
|
320
367
|
exports.EditorAgentBuilder = EditorAgentBuilder;
|
|
368
|
+
exports.EditorWorkflowBuilder = EditorWorkflowBuilder;
|
|
321
369
|
exports.createBuilderAgent = createBuilderAgent;
|
|
370
|
+
exports.createWorkflowBuilderAgent = createWorkflowBuilderAgent;
|
|
322
371
|
|
|
323
372
|
//# sourceMappingURL=index.cjs.map
|
package/dist/ee/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["__filename","__dirname","Workspace","LocalFilesystem","StreamErrorRetryProcessor","PrefillErrorHandler","ProviderHistoryCompat","Memory","Agent"],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.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 * Exported so callers can compose a custom processor list that keeps the\n * subset they want (e.g. `[...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom]`).\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new StreamErrorRetryProcessor(),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge defaults with any caller-supplied processors. Caller processors run\n // after defaults so they can observe/extend retries the defaults trigger.\n // A function-typed override (DynamicArgument) is passed through unchanged —\n // callers using the dynamic form are assumed to manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors = Array.isArray(callerErrorProcessors)\n ? [...DEFAULT_BUILDER_ERROR_PROCESSORS, ...callerErrorProcessors]\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 ...(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"],"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,mBAAyD;EACvD,OAAO,KAAK,QAAQ;CACtB;CAEA,gBAAmD;EACjD,OAAO,KAAK,QAAQ;CACtB;CAEA,yBAAmC;EACjC,OAAO,CAAC,GAA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,MAAMA,gBAAAA,GAAAA,IAAAA,cAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,IAA0C;AAChD,MAAMC,cAAY,KAAA,QAAK,QAAQD,YAAU;AAIzC,MAAM,YAAY,IAAIE,uBAAAA,UAAU;CAC9B,YAAY,IAAIC,uBAAAA,gBAAgB,EAC9B,UAJkB,KAAA,QAAK,KAAKF,aAAW,WAIjB,EACxB,CAAC;CACD,QAAQ,CAAC,QAAQ;AACnB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCD,MAAa,mCAAmC;CAC9C,IAAIG,wBAAAA,0BAA0B;CAC9B,IAAIC,wBAAAA,oBAAoB;CACxB,IAAIC,wBAAAA,sBAAsB;AAC5B;AAEA,SAAgB,mBAAmB,MAAsE;CACvG,MAAM,SAAS,IAAIC,eAAAA,OAAO;CAM1B,MAAM,wBAAwB,MAAM;CACpC,MAAM,kBAAkB,MAAM,QAAQ,qBAAqB,IACvD,CAAC,GAAG,kCAAkC,GAAG,qBAAqB,IAC7D,yBAAyB;CA4I9B,OAAO,IAAIC,mBAAAA,MAAuB;EAzIhC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Hd,OAAO;EACP;EACA;EACA,GAAI,QAAQ,CAAC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CAGwB,CAAC;AAC1C"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["__filename","__dirname","Workspace","LocalFilesystem","StreamErrorRetryProcessor","PrefillErrorHandler","ProviderHistoryCompat","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 * Exported so callers can compose a custom processor list that keeps the\n * subset they want (e.g. `[...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom]`).\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new StreamErrorRetryProcessor(),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge defaults with any caller-supplied processors. Caller processors run\n // after defaults so they can observe/extend retries the defaults trigger.\n // A function-typed override (DynamicArgument) is passed through unchanged —\n // callers using the dynamic form are assumed to manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors = Array.isArray(callerErrorProcessors)\n ? [...DEFAULT_BUILDER_ERROR_PROCESSORS, ...callerErrorProcessors]\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 ...(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,mBAAyD;EACvD,OAAO,KAAK,QAAQ;CACtB;CAEA,gBAAmD;EACjD,OAAO,KAAK,QAAQ;CACtB;CAEA,yBAAmC;EACjC,OAAO,CAAC,GAAG,KAAK,qBAAqB,GAAG,KAAK,qBAAqB;CACpE;;;;;;;CAQ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AAkC,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/ee/index.d.cts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { AgentBuilderOptions, IAgentBuilder } from "@mastra/core/agent-builder/ee";
|
|
2
2
|
import { Agent, AgentConfig } from "@mastra/core/agent";
|
|
3
3
|
import "@mastra/core/processors";
|
|
4
|
+
import { Mastra } from "@mastra/core";
|
|
5
|
+
import { IWorkflowBuilder, WorkflowBuilderOptions } from "@mastra/core/editor";
|
|
6
|
+
import { MastraModelConfig } from "@mastra/core/llm";
|
|
4
7
|
//#region src/ee/agent-builder.d.ts
|
|
5
8
|
/**
|
|
6
9
|
* Concrete implementation of the Agent Builder EE feature.
|
|
@@ -60,5 +63,16 @@ declare class EditorAgentBuilder implements IAgentBuilder {
|
|
|
60
63
|
//#region src/ee/agent-builder-agent.d.ts
|
|
61
64
|
declare function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'>;
|
|
62
65
|
//#endregion
|
|
63
|
-
|
|
66
|
+
//#region src/ee/workflow-builder.d.ts
|
|
67
|
+
declare function createWorkflowBuilderAgent(model?: MastraModelConfig, lastMessages?: number): Agent<'workflow-builder-agent'>;
|
|
68
|
+
declare class EditorWorkflowBuilder implements IWorkflowBuilder {
|
|
69
|
+
readonly enabled: boolean;
|
|
70
|
+
private readonly agent;
|
|
71
|
+
private readonly modelPolicy;
|
|
72
|
+
constructor(options?: WorkflowBuilderOptions, mastra?: Mastra);
|
|
73
|
+
getAgent(): Agent<"workflow-builder-agent", import("@mastra/core/agent").ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
|
|
74
|
+
getModelPolicy(): import("@mastra/core/agent-builder/ee").BuilderModelPolicy | undefined;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
export { EditorAgentBuilder, EditorWorkflowBuilder, createBuilderAgent, createWorkflowBuilderAgent };
|
|
64
78
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/ee/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cAgBa,8BAA8B;mBACxB;mBACA;;mBAGA;;;;;;;;;;;;mBAaA;EAEjB,YAAY,UAAU;MA4BlB;EAIJ,eAAe;EAIf,oBAAoB;EAIpB,iBAAiB;EAIjB;;;;;;;UAUQ;;;;;;;;;UAaA;UAmCA;;;;iBC7EM,mBAAmB,OAAO,QAAQ,gCAAgC;;;iBC5ClE,2BACd,QAAQ,mBACR,wBACC;cA2BU,iCAAiC;WACnC;mBACQ;mBACA;EAEjB,YAAY,UAAS,wBAA6B,SAAS;EAU3D,YAAQ,6DAAA,yDAAA;EAIR,0DAAc"}
|
package/dist/ee/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Agent, AgentConfig } from "@mastra/core/agent";
|
|
2
2
|
import { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor } from "@mastra/core/processors";
|
|
3
3
|
import { AgentBuilderOptions, IAgentBuilder } from "@mastra/core/agent-builder/ee";
|
|
4
|
+
import { Mastra } from "@mastra/core";
|
|
5
|
+
import { IWorkflowBuilder, WorkflowBuilderOptions } from "@mastra/core/editor";
|
|
6
|
+
import { MastraModelConfig } from "@mastra/core/llm";
|
|
4
7
|
//#region src/ee/agent-builder.d.ts
|
|
5
8
|
/**
|
|
6
9
|
* Concrete implementation of the Agent Builder EE feature.
|
|
@@ -60,5 +63,16 @@ declare class EditorAgentBuilder implements IAgentBuilder {
|
|
|
60
63
|
//#region src/ee/agent-builder-agent.d.ts
|
|
61
64
|
declare function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'>;
|
|
62
65
|
//#endregion
|
|
63
|
-
|
|
66
|
+
//#region src/ee/workflow-builder.d.ts
|
|
67
|
+
declare function createWorkflowBuilderAgent(model?: MastraModelConfig, lastMessages?: number): Agent<'workflow-builder-agent'>;
|
|
68
|
+
declare class EditorWorkflowBuilder implements IWorkflowBuilder {
|
|
69
|
+
readonly enabled: boolean;
|
|
70
|
+
private readonly agent;
|
|
71
|
+
private readonly modelPolicy;
|
|
72
|
+
constructor(options?: WorkflowBuilderOptions, mastra?: Mastra);
|
|
73
|
+
getAgent(): Agent<"workflow-builder-agent", import("@mastra/core/agent").ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
|
|
74
|
+
getModelPolicy(): import("@mastra/core/agent-builder/ee").BuilderModelPolicy | undefined;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
export { EditorAgentBuilder, EditorWorkflowBuilder, createBuilderAgent, createWorkflowBuilderAgent };
|
|
64
78
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/ee/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts","../../src/ee/workflow-builder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cAgBa,8BAA8B;mBACxB;mBACA;;mBAGA;;;;;;;;;;;;mBAaA;EAEjB,YAAY,UAAU;MA4BlB;EAIJ,eAAe;EAIf,oBAAoB;EAIpB,iBAAiB;EAIjB;;;;;;;UAUQ;;;;;;;;;UAaA;UAmCA;;;;iBC7EM,mBAAmB,OAAO,QAAQ,gCAAgC;;;iBC5ClE,2BACd,QAAQ,mBACR,wBACC;cA2BU,iCAAiC;WACnC;mBACQ;mBACA;EAEjB,YAAY,UAAS,wBAA6B,SAAS;EAU3D,YAAQ,6DAAA,yDAAA;EAIR,0DAAc"}
|
package/dist/ee/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { PrefillErrorHandler, ProviderHistoryCompat, StreamErrorRetryProcessor }
|
|
|
5
5
|
import { isBuilderModelPolicyActive, isModelAllowed, resolveAgentFeatures } from "@mastra/core/agent-builder/ee";
|
|
6
6
|
import path from "path";
|
|
7
7
|
import { fileURLToPath } from "url";
|
|
8
|
+
import { createWorkflowBuilderAgent as createWorkflowBuilderAgent$1 } from "@mastra/core/workflows/builder";
|
|
8
9
|
//#region src/ee/agent-builder.ts
|
|
9
10
|
/**
|
|
10
11
|
* Concrete implementation of the Agent Builder EE feature.
|
|
@@ -292,7 +293,53 @@ Keep this to 2–4 focused paragraphs or compact bullet groups. Do not include w
|
|
|
292
293
|
description: "An agent that can build agents"
|
|
293
294
|
});
|
|
294
295
|
}
|
|
296
|
+
function createWorkflowBuilderAgent(model, lastMessages = 100) {
|
|
297
|
+
return createWorkflowBuilderAgent$1({
|
|
298
|
+
id: "workflow-builder-agent",
|
|
299
|
+
name: "Workflow Builder",
|
|
300
|
+
description: "Builds persisted workflow definitions through constrained client tools",
|
|
301
|
+
model: model ?? "openai/gpt-5.5",
|
|
302
|
+
memory: new Memory({ options: { lastMessages } }),
|
|
303
|
+
surfaceInstructions: `# Studio authoring policy
|
|
304
|
+
|
|
305
|
+
Turn 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.
|
|
306
|
+
|
|
307
|
+
The 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.
|
|
308
|
+
|
|
309
|
+
# Studio execution and response protocol
|
|
310
|
+
|
|
311
|
+
1. Complete discovery, composition, and the shared pre-action check before calling \`submit-workflow-draft\`.
|
|
312
|
+
2. Call \`submit-workflow-draft\` with one complete canonical definition. Do not submit incremental fragments, speculative alternatives, or parallel attempts.
|
|
313
|
+
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.
|
|
314
|
+
3. 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.
|
|
315
|
+
4. 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.
|
|
316
|
+
5. 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.
|
|
317
|
+
6. 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.
|
|
318
|
+
7. 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.
|
|
319
|
+
8. 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.`
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
var EditorWorkflowBuilder = class {
|
|
323
|
+
constructor(options = {}, mastra) {
|
|
324
|
+
this.enabled = options.enabled !== false;
|
|
325
|
+
this.modelPolicy = options.modelPolicy;
|
|
326
|
+
this.agent = createWorkflowBuilderAgent(options.model, options.lastMessages);
|
|
327
|
+
if (mastra) {
|
|
328
|
+
this.agent.__registerMastra(mastra);
|
|
329
|
+
this.agent.__registerPrimitives({
|
|
330
|
+
logger: mastra.getLogger(),
|
|
331
|
+
storage: mastra.getStorage()
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
getAgent() {
|
|
336
|
+
return this.agent;
|
|
337
|
+
}
|
|
338
|
+
getModelPolicy() {
|
|
339
|
+
return this.modelPolicy;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
295
342
|
//#endregion
|
|
296
|
-
export { EditorAgentBuilder, createBuilderAgent };
|
|
343
|
+
export { EditorAgentBuilder, EditorWorkflowBuilder, createBuilderAgent, createWorkflowBuilderAgent };
|
|
297
344
|
|
|
298
345
|
//# sourceMappingURL=index.js.map
|
package/dist/ee/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.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 * Exported so callers can compose a custom processor list that keeps the\n * subset they want (e.g. `[...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom]`).\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new StreamErrorRetryProcessor(),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge defaults with any caller-supplied processors. Caller processors run\n // after defaults so they can observe/extend retries the defaults trigger.\n // A function-typed override (DynamicArgument) is passed through unchanged —\n // callers using the dynamic form are assumed to manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors = Array.isArray(callerErrorProcessors)\n ? [...DEFAULT_BUILDER_ERROR_PROCESSORS, ...callerErrorProcessors]\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 ...(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"],"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,OAAO,qBAAqB,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,mBAAyD;EACvD,OAAO,KAAK,QAAQ;CACtB;CAEA,gBAAmD;EACjD,OAAO,KAAK,QAAQ;CACtB;CAEA,yBAAmC;EACjC,OAAO,CAAC,GAAG,KAAK,qBAAqB,GAAG,KAAK,qBAAqB;CACpE;;;;;;;CAQA,wBAAyC;EACvC,MAAM,gBAAgB,KAAK,QAAQ,eAAe,OAAO;EACzD,OAAO,QAAQ,eAAe,QAAQ,QAAQ;CAChD;;;;;;;;;CAUA,wBAAsC;EAEpC,IADwB,KAAK,QAAQ,UAAU,OAAO,YAC9B,MAAM;EAE9B,MAAM,gBAAgB,KAAK,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AA0B;CAC9B,IAAI,oBAAoB;CACxB,IAAI,sBAAsB;AAC5B;AAEA,SAAgB,mBAAmB,MAAsE;CACvG,MAAM,SAAS,IAAI,OAAO;CAM1B,MAAM,wBAAwB,MAAM;CACpC,MAAM,kBAAkB,MAAM,QAAQ,qBAAqB,IACvD,CAAC,GAAG,kCAAkC,GAAG,qBAAqB,IAC7D,yBAAyB;CA4I9B,OAAO,IAAI,MAAuB;EAzIhC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Hd,OAAO;EACP;EACA;EACA,GAAI,QAAQ,CAAC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CAGwB,CAAC;AAC1C"}
|
|
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 * Exported so callers can compose a custom processor list that keeps the\n * subset they want (e.g. `[...DEFAULT_BUILDER_ERROR_PROCESSORS.filter(p => p.id !== 'stream-error-retry-processor'), myCustom]`).\n */\nexport const DEFAULT_BUILDER_ERROR_PROCESSORS = [\n new StreamErrorRetryProcessor(),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n];\n\nexport function createBuilderAgent(args?: Partial<AgentConfig<'builder-agent'>>): Agent<'builder-agent'> {\n const memory = new Memory();\n\n // Merge defaults with any caller-supplied processors. Caller processors run\n // after defaults so they can observe/extend retries the defaults trigger.\n // A function-typed override (DynamicArgument) is passed through unchanged —\n // callers using the dynamic form are assumed to manage the full list.\n const callerErrorProcessors = args?.errorProcessors;\n const errorProcessors = Array.isArray(callerErrorProcessors)\n ? [...DEFAULT_BUILDER_ERROR_PROCESSORS, ...callerErrorProcessors]\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 ...(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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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+Hd,OAAO;EACP;EACA;EACA,GAAI,QAAQ,CAAC;EACb;EACA,IAAI;EACJ,MAAM;EACN,aAAa;CAGwB,CAAC;AAC1C;ACnMA,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
|
@@ -1945,7 +1945,7 @@ var EditorPromptNamespace = class extends CrudEditorNamespace {
|
|
|
1945
1945
|
//#region src/namespaces/scorer.ts
|
|
1946
1946
|
var EditorScorerNamespace = class extends CrudEditorNamespace {
|
|
1947
1947
|
onCacheEvict(id) {
|
|
1948
|
-
this.mastra?.removeScorer(id);
|
|
1948
|
+
if (this.mastra?.listScorers()?.[id]?.source === "stored") this.mastra.removeScorer(id);
|
|
1949
1949
|
}
|
|
1950
1950
|
/**
|
|
1951
1951
|
* Hydrate a stored scorer definition into a runtime MastraScorer instance
|
|
@@ -2049,6 +2049,33 @@ Explain your reasoning for this score in a clear, concise paragraph.`;
|
|
|
2049
2049
|
}
|
|
2050
2050
|
};
|
|
2051
2051
|
//#endregion
|
|
2052
|
+
//#region src/workspace-tools-config.ts
|
|
2053
|
+
function toRuntimeWorkspaceToolsConfig(stored) {
|
|
2054
|
+
const config = {};
|
|
2055
|
+
if (stored.enabled !== void 0) config.enabled = stored.enabled;
|
|
2056
|
+
if (stored.requireApproval !== void 0) config.requireApproval = stored.requireApproval;
|
|
2057
|
+
return {
|
|
2058
|
+
...config,
|
|
2059
|
+
...stored.tools
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
function toStorageWorkspaceToolsConfig(config) {
|
|
2063
|
+
const stored = {};
|
|
2064
|
+
if (typeof config.enabled === "boolean") stored.enabled = config.enabled;
|
|
2065
|
+
if (typeof config.requireApproval === "boolean") stored.requireApproval = config.requireApproval;
|
|
2066
|
+
const tools = {};
|
|
2067
|
+
for (const [name, value] of Object.entries(config)) {
|
|
2068
|
+
if (!name.startsWith("mastra_workspace_") || !value || typeof value !== "object") continue;
|
|
2069
|
+
const tool = {};
|
|
2070
|
+
if ("enabled" in value && typeof value.enabled === "boolean") tool.enabled = value.enabled;
|
|
2071
|
+
if ("requireApproval" in value && typeof value.requireApproval === "boolean") tool.requireApproval = value.requireApproval;
|
|
2072
|
+
if ("requireReadBeforeWrite" in value && typeof value.requireReadBeforeWrite === "boolean") tool.requireReadBeforeWrite = value.requireReadBeforeWrite;
|
|
2073
|
+
if (Object.keys(tool).length > 0) tools[name] = tool;
|
|
2074
|
+
}
|
|
2075
|
+
if (Object.keys(tools).length > 0) stored.tools = tools;
|
|
2076
|
+
return Object.keys(stored).length > 0 ? stored : void 0;
|
|
2077
|
+
}
|
|
2078
|
+
//#endregion
|
|
2052
2079
|
//#region src/namespaces/workspace.ts
|
|
2053
2080
|
var EditorWorkspaceNamespace = class extends CrudEditorNamespace {
|
|
2054
2081
|
onCacheEvict(_id) {}
|
|
@@ -2086,7 +2113,7 @@ var EditorWorkspaceNamespace = class extends CrudEditorNamespace {
|
|
|
2086
2113
|
config.skillSource = options.skillSource;
|
|
2087
2114
|
config.skills = ["."];
|
|
2088
2115
|
} else if (snapshot.skills && snapshot.skills.length > 0) config.skills = snapshot.skills;
|
|
2089
|
-
if (snapshot.tools) config.tools = snapshot.tools;
|
|
2116
|
+
if (snapshot.tools) config.tools = toRuntimeWorkspaceToolsConfig(snapshot.tools);
|
|
2090
2117
|
if (snapshot.autoSync !== void 0) config.autoSync = snapshot.autoSync;
|
|
2091
2118
|
if (snapshot.operationTimeout !== void 0) config.operationTimeout = snapshot.operationTimeout;
|
|
2092
2119
|
return new _mastra_core_workspace.Workspace(config);
|
|
@@ -2114,10 +2141,8 @@ var EditorWorkspaceNamespace = class extends CrudEditorNamespace {
|
|
|
2114
2141
|
}
|
|
2115
2142
|
const tools = workspace.getToolsConfig();
|
|
2116
2143
|
if (tools) {
|
|
2117
|
-
const storageTools =
|
|
2118
|
-
if (
|
|
2119
|
-
if (typeof tools.requireApproval === "boolean") storageTools.requireApproval = tools.requireApproval;
|
|
2120
|
-
if (Object.keys(storageTools).length > 0) snapshot.tools = storageTools;
|
|
2144
|
+
const storageTools = toStorageWorkspaceToolsConfig(tools);
|
|
2145
|
+
if (storageTools) snapshot.tools = storageTools;
|
|
2121
2146
|
}
|
|
2122
2147
|
return snapshot;
|
|
2123
2148
|
}
|
|
@@ -2417,6 +2442,7 @@ function snapshotsMatch(stored, runtime) {
|
|
|
2417
2442
|
var MastraEditor = class {
|
|
2418
2443
|
constructor(config) {
|
|
2419
2444
|
this.__builderResolved = false;
|
|
2445
|
+
this.__workflowBuilderResolved = false;
|
|
2420
2446
|
this.__logger = config?.logger;
|
|
2421
2447
|
this.__toolProviders = config?.toolProviders ?? {};
|
|
2422
2448
|
this.__processorProviders = {
|
|
@@ -2447,6 +2473,7 @@ var MastraEditor = class {
|
|
|
2447
2473
|
this.skill = new EditorSkillNamespace(this);
|
|
2448
2474
|
this.favorites = new EditorFavoritesNamespace(this);
|
|
2449
2475
|
this.__builderConfig = config?.builder;
|
|
2476
|
+
this.__workflowBuilderConfig = config?.workflowBuilder;
|
|
2450
2477
|
}
|
|
2451
2478
|
/**
|
|
2452
2479
|
* Register this editor with a Mastra instance.
|
|
@@ -2558,6 +2585,24 @@ var MastraEditor = class {
|
|
|
2558
2585
|
}
|
|
2559
2586
|
}
|
|
2560
2587
|
}
|
|
2588
|
+
/** Sync. OSS-safe. Does NOT import @mastra/editor/ee. */
|
|
2589
|
+
hasEnabledWorkflowBuilderConfig() {
|
|
2590
|
+
if (!this.__workflowBuilderConfig) return false;
|
|
2591
|
+
return this.__workflowBuilderConfig.enabled !== false;
|
|
2592
|
+
}
|
|
2593
|
+
/** Resolve the hidden workflow builder without adding its agent to Mastra. */
|
|
2594
|
+
async resolveWorkflowBuilder() {
|
|
2595
|
+
if (this.__workflowBuilderResolved) return this.__workflowBuilderInstance;
|
|
2596
|
+
if (!this.hasEnabledWorkflowBuilderConfig()) {
|
|
2597
|
+
this.__workflowBuilderResolved = true;
|
|
2598
|
+
return;
|
|
2599
|
+
}
|
|
2600
|
+
await this.assertBuilderLicensed("Workflow Builder");
|
|
2601
|
+
const { EditorWorkflowBuilder } = await Promise.resolve().then(() => require("./ee/index.cjs"));
|
|
2602
|
+
this.__workflowBuilderInstance = new EditorWorkflowBuilder(this.__workflowBuilderConfig, this.__mastra);
|
|
2603
|
+
this.__workflowBuilderResolved = true;
|
|
2604
|
+
return this.__workflowBuilderInstance;
|
|
2605
|
+
}
|
|
2561
2606
|
/**
|
|
2562
2607
|
* Sync. OSS-safe. Does NOT import @mastra/editor/ee.
|
|
2563
2608
|
* Returns true if builder config is present and enabled.
|
|
@@ -2576,7 +2621,7 @@ var MastraEditor = class {
|
|
|
2576
2621
|
this.__builderResolved = true;
|
|
2577
2622
|
return;
|
|
2578
2623
|
}
|
|
2579
|
-
await this.
|
|
2624
|
+
await this.assertBuilderLicensed("Agent Builder");
|
|
2580
2625
|
const { EditorAgentBuilder } = await Promise.resolve().then(() => require("./ee/index.cjs"));
|
|
2581
2626
|
this.__builderInstance = new EditorAgentBuilder(this.__builderConfig);
|
|
2582
2627
|
const browserRef = this.__builderInstance.getConfiguration()?.agent?.browser;
|
|
@@ -2598,13 +2643,14 @@ var MastraEditor = class {
|
|
|
2598
2643
|
* builder cannot be instantiated outside the server boot path without a
|
|
2599
2644
|
* valid EE license. Dev environments bypass via `isEEEnabled()`.
|
|
2600
2645
|
*/
|
|
2601
|
-
async
|
|
2646
|
+
async assertBuilderLicensed(builderName) {
|
|
2602
2647
|
try {
|
|
2603
2648
|
const { isEEEnabled } = await import("@mastra/core/auth/ee");
|
|
2604
|
-
if (!isEEEnabled()) throw new Error(
|
|
2649
|
+
if (!isEEEnabled()) throw new Error(`[mastra/auth-ee] ${builderName} is configured but no valid EE license was found.\n${builderName} requires a Mastra Enterprise License for production use.\nSet the MASTRA_EE_LICENSE environment variable with your license key.
|
|
2650
|
+
Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE`);
|
|
2605
2651
|
} catch (err) {
|
|
2606
2652
|
if (err instanceof Error && err.message.startsWith("[mastra/auth-ee]")) throw err;
|
|
2607
|
-
throw new Error(
|
|
2653
|
+
throw new Error(`[mastra/auth-ee] ${builderName} is configured but the EE module (@mastra/core/auth/ee) could not be loaded.\nEnsure @mastra/core is updated to a version that includes EE support.`);
|
|
2608
2654
|
}
|
|
2609
2655
|
}
|
|
2610
2656
|
/** Returns the editor's configured source, or undefined if unset. */
|