@mastra/editor 0.10.0 → 0.10.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @mastra/editor
2
2
 
3
+ ## 0.10.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Added optional constructor argument support to `createBuilderAgent()` so callers can override agent defaults while the canonical `id`, `name`, and `description` are preserved. ([#17109](https://github.com/mastra-ai/mastra/pull/17109))
8
+
9
+ ```ts
10
+ // Before — could only use the built-in defaults
11
+ const builder = createBuilderAgent();
12
+
13
+ // After — pass overrides while keeping the canonical identity
14
+ const builder = createBuilderAgent({
15
+ model: openai('gpt-4o'),
16
+ instructions: 'Custom instructions for this deployment',
17
+ });
18
+ ```
19
+
20
+ - Updated dependencies [[`21db1a4`](https://github.com/mastra-ai/mastra/commit/21db1a4b8ac058d5a4fbe38b516cc1b81e526915)]:
21
+ - @mastra/core@1.37.1
22
+
23
+ ## 0.10.1-alpha.0
24
+
25
+ ### Patch Changes
26
+
27
+ - Added optional constructor argument support to `createBuilderAgent()` so callers can override agent defaults while the canonical `id`, `name`, and `description` are preserved. ([#17109](https://github.com/mastra-ai/mastra/pull/17109))
28
+
29
+ ```ts
30
+ // Before — could only use the built-in defaults
31
+ const builder = createBuilderAgent();
32
+
33
+ // After — pass overrides while keeping the canonical identity
34
+ const builder = createBuilderAgent({
35
+ model: openai('gpt-4o'),
36
+ instructions: 'Custom instructions for this deployment',
37
+ });
38
+ ```
39
+
3
40
  ## 0.10.0
4
41
 
5
42
  ### Minor Changes
package/dist/ee/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/ee/index.ts
@@ -135,12 +145,22 @@ var EditorAgentBuilder = class {
135
145
  // src/ee/agent-builder-agent.ts
136
146
  var import_agent = require("@mastra/core/agent");
137
147
  var import_memory = require("@mastra/memory");
138
- function createBuilderAgent() {
148
+ var import_workspace = require("@mastra/core/workspace");
149
+ var import_node_path = __toESM(require("path"), 1);
150
+ var import_node_url = require("url");
151
+ var import_meta = {};
152
+ var __filename = (0, import_node_url.fileURLToPath)(import_meta.url);
153
+ var __dirname = import_node_path.default.dirname(__filename);
154
+ var workspacePath = import_node_path.default.join(__dirname, "workspace");
155
+ var workspace = new import_workspace.Workspace({
156
+ filesystem: new import_workspace.LocalFilesystem({
157
+ basePath: workspacePath
158
+ }),
159
+ skills: ["skills"]
160
+ });
161
+ function createBuilderAgent(args) {
139
162
  const memory = new import_memory.Memory();
140
163
  return new import_agent.Agent({
141
- id: "builder-agent",
142
- name: "Agent Builder Agent",
143
- description: "An agent that can build agents",
144
164
  instructions: `You are the Agent Builder.
145
165
 
146
166
  Your job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.
@@ -270,7 +290,12 @@ The system prompt written into \`set-agent-instructions\` MUST include all of th
270
290
  - The final message to the user must be concise, friendly, and focused on what the configured agent can now do.
271
291
  - The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,
272
292
  model: "openai/gpt-5.5",
273
- memory
293
+ memory,
294
+ workspace,
295
+ ...args || {},
296
+ id: "builder-agent",
297
+ name: "Agent Builder Agent",
298
+ description: "An agent that can build agents"
274
299
  });
275
300
  }
276
301
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ee/index.ts","../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts"],"sourcesContent":["export { EditorAgentBuilder } from './agent-builder';\nexport { createBuilderAgent } from './agent-builder-agent';\n","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 { Memory } from '@mastra/memory';\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\nexport function createBuilderAgent(): Agent {\n const memory = new Memory();\n return new Agent({\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\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# 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\nBefore building the agent, define:\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\nCall \\`set-agent-name\\` and \\`set-agent-description\\` to set the agent's identity. Skip any whose feature is not available in the form snapshot.\n\n## Step C — Decide capabilities\n\nRead the form snapshot already injected into your context. It lists the user's current selections plus the available tools, agents, workflows, stored skills, models, and workspaces.\n\nThen:\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 from the form snapshot.\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 the run contract\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item:\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\n## Step E — Write the agent\n\nCall the capability tools. Skip any whose feature is not available in the form snapshot.\n\n1. \\`set-agent-model\\` — pick the best model for the use case from the available models list. Rules:\n - Choose only a model id that appears in the available models list. Never invent, assume, or copy example model ids.\n - For coding, reasoning-heavy, or planning agents, prefer the most capable available model.\n - For short, simple, structured, or high-volume tasks, prefer a lower-latency/lower-cost available model when quality will not materially suffer.\n - If several plausible models are available, choose the newest or strongest option based on the metadata visible in the snapshot.\n2. \\`set-agent-tools\\` — attach the minimum set chosen in Step C. Also use \\`set-agent-skills\\` and \\`set-agent-browser-enabled\\` only when applicable and supported by the snapshot.\n3. \\`set-agent-instructions\\` — write the new agent's system prompt from scratch, tailored to the user's specific outcome and the run contract from Step D.\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 present, concrete, and tool-aware.\n- Refusal / fallback path is present for missing integrations, credentials, permissions, workspace, or sources.\n- Final response format is specified.\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 include all of the following:\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 exact 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.\n10. **Worked example.** Include at least one short input → output example showing a complete successful run.\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 });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,gBAAiF;AAe1E,IAAM,qBAAN,MAAkD;AAAA,EAoBvD,YAAY,SAA+B;AAlB3C,SAAiB,sBAAgC,CAAC;AAGlD;AAAA,SAAiB,wBAAkC,CAAC;AAoBlD,UAAM,SAAS,WAAW,CAAC;AAC3B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,UAAU,OAAO,WACb;AAAA,Q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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgId,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/ee/index.ts","../../src/ee/agent-builder.ts","../../src/ee/agent-builder-agent.ts"],"sourcesContent":["export { EditorAgentBuilder } from './agent-builder';\nexport { createBuilderAgent } from './agent-builder-agent';\n","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 { Memory } from '@mastra/memory';\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\nexport function createBuilderAgent(\n args?: Partial<ConstructorParameters<typeof Agent<'builder-agent'>>[0]>,\n): Agent<'builder-agent'> {\n const memory = new Memory();\n\n return new Agent<'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# 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\nBefore building the agent, define:\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\nCall \\`set-agent-name\\` and \\`set-agent-description\\` to set the agent's identity. Skip any whose feature is not available in the form snapshot.\n\n## Step C — Decide capabilities\n\nRead the form snapshot already injected into your context. It lists the user's current selections plus the available tools, agents, workflows, stored skills, models, and workspaces.\n\nThen:\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 from the form snapshot.\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 the run contract\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item:\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\n## Step E — Write the agent\n\nCall the capability tools. Skip any whose feature is not available in the form snapshot.\n\n1. \\`set-agent-model\\` — pick the best model for the use case from the available models list. Rules:\n - Choose only a model id that appears in the available models list. Never invent, assume, or copy example model ids.\n - For coding, reasoning-heavy, or planning agents, prefer the most capable available model.\n - For short, simple, structured, or high-volume tasks, prefer a lower-latency/lower-cost available model when quality will not materially suffer.\n - If several plausible models are available, choose the newest or strongest option based on the metadata visible in the snapshot.\n2. \\`set-agent-tools\\` — attach the minimum set chosen in Step C. Also use \\`set-agent-skills\\` and \\`set-agent-browser-enabled\\` only when applicable and supported by the snapshot.\n3. \\`set-agent-instructions\\` — write the new agent's system prompt from scratch, tailored to the user's specific outcome and the run contract from Step D.\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 present, concrete, and tool-aware.\n- Refusal / fallback path is present for missing integrations, credentials, permissions, workspace, or sources.\n- Final response format is specified.\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 include all of the following:\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 exact 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.\n10. **Worked example.** Include at least one short input → output example showing a complete successful run.\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 id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,gBAAiF;AAe1E,IAAM,qBAAN,MAAkD;AAAA,EAoBvD,YAAY,SAA+B;AAlB3C,SAAiB,sBAAgC,CAAC;AAGlD;AAAA,SAAiB,wBAAkC,CAAC;AAoBlD,UAAM,SAAS,WAAW,CAAC;AAC3B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,UAAU,OAAO,WACb;AAAA,QACE,GAAG,OAAO;AAAA,QACV,OAAO,OAAO,SAAS,QAAQ,EAAE,GAAG,OAAO,SAAS,MAAM,IAAI;AAAA,MAChE,IACA;AAAA,IACN;AACA,SAAK,oBAAoB;AACzB,SAAK,sBAAsB;AAK3B,SAAK,mBAAmB;AAAA,MACtB,WAAO,gCAAqB,KAAK,QAAQ,UAAU,OAAO;AAAA,QACxD,kBAAkB,KAAK,sBAAsB;AAAA,MAC/C,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,IAAI,UAAmB;AACrB,WAAO,KAAK,QAAQ,YAAY;AAAA,EAClC;AAAA,EAEA,cAA+C;AAC7C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,mBAAyD;AACvD,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,gBAAmD;AACjD,WAAO,KAAK,QAAQ;AAAA,EACtB;A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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgId,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA,GAAI,QAAQ,CAAC;AAAA,IACb,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,EACf,CAAC;AACH;","names":["path"]}
@@ -72,6 +72,6 @@ declare class EditorAgentBuilder implements IAgentBuilder {
72
72
  * - set-agent-browser-enabled (gated by features.browser)
73
73
  * - createSkillTool (gated by features.skills) — only when a needed capability does not exist
74
74
  */
75
- declare function createBuilderAgent(): Agent;
75
+ declare function createBuilderAgent(args?: Partial<ConstructorParameters<typeof Agent<'builder-agent'>>[0]>): Agent<'builder-agent'>;
76
76
 
77
77
  export { EditorAgentBuilder, createBuilderAgent };
@@ -72,6 +72,6 @@ declare class EditorAgentBuilder implements IAgentBuilder {
72
72
  * - set-agent-browser-enabled (gated by features.browser)
73
73
  * - createSkillTool (gated by features.skills) — only when a needed capability does not exist
74
74
  */
75
- declare function createBuilderAgent(): Agent;
75
+ declare function createBuilderAgent(args?: Partial<ConstructorParameters<typeof Agent<'builder-agent'>>[0]>): Agent<'builder-agent'>;
76
76
 
77
77
  export { EditorAgentBuilder, createBuilderAgent };
package/dist/ee/index.js CHANGED
@@ -108,12 +108,21 @@ var EditorAgentBuilder = class {
108
108
  // src/ee/agent-builder-agent.ts
109
109
  import { Agent } from "@mastra/core/agent";
110
110
  import { Memory } from "@mastra/memory";
111
- function createBuilderAgent() {
111
+ import { Workspace, LocalFilesystem } from "@mastra/core/workspace";
112
+ import path from "path";
113
+ import { fileURLToPath } from "url";
114
+ var __filename = fileURLToPath(import.meta.url);
115
+ var __dirname = path.dirname(__filename);
116
+ var workspacePath = path.join(__dirname, "workspace");
117
+ var workspace = new Workspace({
118
+ filesystem: new LocalFilesystem({
119
+ basePath: workspacePath
120
+ }),
121
+ skills: ["skills"]
122
+ });
123
+ function createBuilderAgent(args) {
112
124
  const memory = new Memory();
113
125
  return new Agent({
114
- id: "builder-agent",
115
- name: "Agent Builder Agent",
116
- description: "An agent that can build agents",
117
126
  instructions: `You are the Agent Builder.
118
127
 
119
128
  Your job: turn a non-technical user's plain-language request into a fully configured, production-quality agent in a single turn.
@@ -243,7 +252,12 @@ The system prompt written into \`set-agent-instructions\` MUST include all of th
243
252
  - The final message to the user must be concise, friendly, and focused on what the configured agent can now do.
244
253
  - The final message should make clear that the agent starts with initial parameters and can be adjusted later.`,
245
254
  model: "openai/gpt-5.5",
246
- memory
255
+ memory,
256
+ workspace,
257
+ ...args || {},
258
+ id: "builder-agent",
259
+ name: "Agent Builder Agent",
260
+ description: "An agent that can build agents"
247
261
  });
248
262
  }
249
263
  export {
@@ -1 +1 @@
1
- {"version":3,"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 { Memory } from '@mastra/memory';\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\nexport function createBuilderAgent(): Agent {\n const memory = new Memory();\n return new Agent({\n id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\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# 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\nBefore building the agent, define:\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\nCall \\`set-agent-name\\` and \\`set-agent-description\\` to set the agent's identity. Skip any whose feature is not available in the form snapshot.\n\n## Step C — Decide capabilities\n\nRead the form snapshot already injected into your context. It lists the user's current selections plus the available tools, agents, workflows, stored skills, models, and workspaces.\n\nThen:\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 from the form snapshot.\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 the run contract\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item:\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\n## Step E — Write the agent\n\nCall the capability tools. Skip any whose feature is not available in the form snapshot.\n\n1. \\`set-agent-model\\` — pick the best model for the use case from the available models list. Rules:\n - Choose only a model id that appears in the available models list. Never invent, assume, or copy example model ids.\n - For coding, reasoning-heavy, or planning agents, prefer the most capable available model.\n - For short, simple, structured, or high-volume tasks, prefer a lower-latency/lower-cost available model when quality will not materially suffer.\n - If several plausible models are available, choose the newest or strongest option based on the metadata visible in the snapshot.\n2. \\`set-agent-tools\\` — attach the minimum set chosen in Step C. Also use \\`set-agent-skills\\` and \\`set-agent-browser-enabled\\` only when applicable and supported by the snapshot.\n3. \\`set-agent-instructions\\` — write the new agent's system prompt from scratch, tailored to the user's specific outcome and the run contract from Step D.\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 present, concrete, and tool-aware.\n- Refusal / fallback path is present for missing integrations, credentials, permissions, workspace, or sources.\n- Final response format is specified.\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 include all of the following:\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 exact 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.\n10. **Worked example.** Include at least one short input → output example showing a complete successful run.\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 parame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AAC1B,SAAO,IAAI,MAAM;AAAA,IACf,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,IACb,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgId,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"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 { Memory } from '@mastra/memory';\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\nexport function createBuilderAgent(\n args?: Partial<ConstructorParameters<typeof Agent<'builder-agent'>>[0]>,\n): Agent<'builder-agent'> {\n const memory = new Memory();\n\n return new Agent<'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# 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\nBefore building the agent, define:\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\nCall \\`set-agent-name\\` and \\`set-agent-description\\` to set the agent's identity. Skip any whose feature is not available in the form snapshot.\n\n## Step C — Decide capabilities\n\nRead the form snapshot already injected into your context. It lists the user's current selections plus the available tools, agents, workflows, stored skills, models, and workspaces.\n\nThen:\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 from the form snapshot.\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 the run contract\n\nBefore calling \\`set-agent-instructions\\`, privately write a concrete run contract for the produced agent. The system prompt must instantiate each item:\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\n## Step E — Write the agent\n\nCall the capability tools. Skip any whose feature is not available in the form snapshot.\n\n1. \\`set-agent-model\\` — pick the best model for the use case from the available models list. Rules:\n - Choose only a model id that appears in the available models list. Never invent, assume, or copy example model ids.\n - For coding, reasoning-heavy, or planning agents, prefer the most capable available model.\n - For short, simple, structured, or high-volume tasks, prefer a lower-latency/lower-cost available model when quality will not materially suffer.\n - If several plausible models are available, choose the newest or strongest option based on the metadata visible in the snapshot.\n2. \\`set-agent-tools\\` — attach the minimum set chosen in Step C. Also use \\`set-agent-skills\\` and \\`set-agent-browser-enabled\\` only when applicable and supported by the snapshot.\n3. \\`set-agent-instructions\\` — write the new agent's system prompt from scratch, tailored to the user's specific outcome and the run contract from Step D.\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 present, concrete, and tool-aware.\n- Refusal / fallback path is present for missing integrations, credentials, permissions, workspace, or sources.\n- Final response format is specified.\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 include all of the following:\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 exact 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.\n10. **Worked example.** Include at least one short input → output example showing a complete successful run.\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 id: 'builder-agent',\n name: 'Agent Builder Agent',\n description: 'An agent that can build agents',\n });\n}\n"],"mappings":";AACA,SAAS,4BAA4B,gBAAgB,4BAA4B;AAe1E,IAAM,qBAAN,MAAkD;AAAA,EAoBvD,YAAY,SAA+B;AAlB3C,SAAiB,sBAAgC,CAAC;AAGlD;AAAA,SAAiB,wBAAkC,CAAC;AAoBlD,UAAM,SAAS,WAAW,CAAC;AAC3B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,UAAU,OAAO,WACb;AAAA,QACE,GAAG,OAAO;AAAA,QACV,OAAO,OAAO,SAAS,QAAQ,EAAE,GAAG,OAAO,SAAS,MAAM,IAAI;AAAA,MAChE,IACA;AAAA,IACN;AACA,SAAK,oBAAoB;AACzB,SAAK,sBAAsB;AAK3B,SAAK,mBAAmB;AAAA,MACtB,OAAO,qBAAqB,KAAK,QAAQ,UAAU,OAAO;AAAA,QACxD,kBAAkB,KAAK,sBAAsB;AAAA,MAC/C,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,IAAI,UAAmB;AACrB,WAAO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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAgId,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA,GAAI,QAAQ,CAAC;AAAA,IACb,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,aAAa;AAAA,EACf,CAAC;AACH;","names":[]}
@@ -0,0 +1,126 @@
1
+ # Agent Builder — Authoring Skills
2
+
3
+ This directory holds the **builder agent's own playbooks**: opinionated guides the Agent Builder reads at runtime when it needs to produce a high-quality agent of a given archetype (a coding agent, a spreadsheet agent, a research agent, etc.).
4
+
5
+ ## Important: two different "skills"
6
+
7
+ The word "skills" means two things in this codebase. Don't conflate them:
8
+
9
+ 1. **Builder authoring skills (this directory).** Read-only Markdown playbooks that teach the builder agent _how to write a great system prompt_ for a given archetype. Loaded via the workspace skill tools (`skill`, `skill_search`, `skill_read`) wired up automatically because `agent-builder-agent.ts` configures a `Workspace` with `skills: ['skills']`.
10
+ 2. **User-attachable agent skills (the product feature).** Stored skills the end-user can attach to the agent they're building. Created via the `createSkillTool` client tool. Persisted to the editor's skill store; surfaced via `useAvailableSkills`. These are **not** what lives in this directory.
11
+
12
+ Builder authoring skills must never be attached to produced agents or mentioned to users. Produced agents can only reference user-facing capabilities that exist in the form snapshot.
13
+
14
+ ## How the builder uses these files
15
+
16
+ At runtime the builder agent receives three workspace tools:
17
+
18
+ - `skill_search` — find a skill by name/description.
19
+ - `skill` — activate a skill; returns the full `SKILL.md` content as a tool result.
20
+ - `skill_read` — read a specific file inside a skill directory (references, scripts, assets).
21
+
22
+ The builder's system prompt (see `../agent-builder-agent.ts`) instructs it to:
23
+
24
+ 1. Classify the user's outcome into one archetype.
25
+ 2. `skill_search` for that archetype.
26
+ 3. `skill` to activate it and load the playbook.
27
+ 4. Synthesize a concrete run contract.
28
+ 5. Use the playbook plus run contract to write the produced agent's name, description, model, capabilities, and system prompt.
29
+ 6. Self-audit the final prompt before writing it.
30
+
31
+ If classification is uncertain, the builder falls back to `agent-prompt-quality-bar` (universal rules) and then `generic-assistant`.
32
+
33
+ ## Run contract requirement
34
+
35
+ Every archetype skill must help the builder instantiate this contract for the produced agent:
36
+
37
+ 1. **Trigger / input** — what starts a run: a user message, schedule, webhook, file, row, ticket, document, or event.
38
+ 2. **Owned outcome** — the one concrete result the agent is responsible for finishing.
39
+ 3. **Available capabilities** — only tools, data sources, workflows, agents, or stored skills actually attached or available.
40
+ 4. **Missing-capability fallback** — what the agent does when a required integration, credential, workspace, permission, source, or input is absent.
41
+ 5. **Done criteria** — how the agent proves the job is complete: tool confirmation, read-back, tests, citations, delivery receipt, or an explicit not-run reason.
42
+ 6. **Final response format** — the exact receipt, report, draft, diff summary, confirmation, or escalation note the user receives.
43
+
44
+ Without a run contract, the produced prompt will sound good but fail to finish real work.
45
+
46
+ ## Final audit requirement
47
+
48
+ Before the builder writes a produced system prompt, the prompt must pass this audit:
49
+
50
+ - Role/outcome is single and concrete.
51
+ - Trigger/input is named.
52
+ - Tools/capabilities are described only if attached or available.
53
+ - Missing integration/credential/workspace/source behavior is explicit.
54
+ - Completion criteria are verifiable and tool-aware.
55
+ - Final answer/receipt format is specified.
56
+ - Refusal/escalation path is present.
57
+ - No placeholders remain (`<...>`, `TBD`, `TODO`, "policy here", "your tool").
58
+ - No internal tool ids, schemas, file paths, or authoring skill names leak.
59
+ - Worked example demonstrates a complete run.
60
+
61
+ ## Good completion criteria examples
62
+
63
+ Coding:
64
+
65
+ > Completion criteria: relevant files inspected; fix written; targeted test/typecheck run or explicit not-run reason; final response names changed files and behavior fixed.
66
+
67
+ Spreadsheet:
68
+
69
+ > Completion criteria: write succeeded; affected range verified by read-back or returned updated values; final receipt states sheet, tab, range, row count, and skipped rows.
70
+
71
+ Research:
72
+
73
+ > Completion criteria: current claims are searched; every finding has a citation; every numbered citation appears in the Sources list with date if available; "What I couldn't verify" is present.
74
+
75
+ Support:
76
+
77
+ > Completion criteria: ticket classified; reply drafted or action verified; every policy claim grounded; refunds verified by tool result before claimed; internal note records classification and action.
78
+
79
+ Ops automation:
80
+
81
+ > Completion criteria: idempotency key checked; action succeeded/skipped/failed/dry-run stopped; receipt includes idempotency key, affected resources, verification, status, and next run.
82
+
83
+ ## Good missing-integration refusals
84
+
85
+ - Spreadsheet: "I need access to your spreadsheet first. Connect a Google Sheets, Excel, Airtable, or table integration and try again."
86
+ - Current research: "I need a search or browsing tool to research current information. Connect one and try again."
87
+ - Repo editing: "I need a connected workspace before I can inspect files, edit code, or run tests."
88
+ - Support sending: "I can draft the reply, but I can't send it until a support inbox send action is connected."
89
+ - Ops action: "I need the Slack integration before I can post to the channel."
90
+
91
+ ## Internal template for every archetype skill
92
+
93
+ Every archetype `SKILL.md` follows this structure so the builder sees a consistent shape:
94
+
95
+ 1. **YAML frontmatter** — `name` (must match directory name; lowercase + hyphens), `description` (1024 chars max; includes the user-facing trigger words so `skill_search` ranks it correctly).
96
+ 2. **When to use** — trigger criteria.
97
+ 3. **Agent identity template** — name/description patterns.
98
+ 4. **Domain-specific policy** — mode selection, safety boundaries, freshness, action boundary, or missing-input rules.
99
+ 5. **System prompt template** — a fully-fleshed system prompt with placeholders the builder must instantiate.
100
+ 6. **Required behavioral rules** — decisiveness, output format, **completion criteria (the most important section)**, refusals.
101
+ 7. **Capabilities to prefer** — which tools/skills/sub-agents to attach for this archetype.
102
+ 8. **Anti-patterns** — concrete bad-prompt shapes to reject.
103
+ 9. **Worked example** — a full user request → produced agent example.
104
+
105
+ ## Adding a new archetype skill
106
+
107
+ 1. Create a new directory under this folder named `<archetype>-agent/` (kebab-case, matches the `name` frontmatter field).
108
+ 2. Add a `SKILL.md` following the internal template above.
109
+ 3. Make the `description` field include the **user-facing trigger words** that would appear in a builder request. `skill_search` ranks by description; vague descriptions get skipped.
110
+ 4. Define the run contract elements explicitly enough that the builder can instantiate them.
111
+ 5. Include explicit **completion criteria** in the produced system prompt template. This is the single most important rule — without it, agents do not finish their work.
112
+ 6. Include missing-capability fallbacks. Never let a generated agent imply access to tools, data, or integrations it may not have.
113
+ 7. No code changes needed — the workspace loads `*/SKILL.md` files at agent-build time via the static `skills: ['skills']` path in `agent-builder-agent.ts`.
114
+
115
+ ## Current archetypes
116
+
117
+ | Skill | When the builder picks it |
118
+ | -------------------------- | ------------------------------------------------------------ |
119
+ | `coding-agent` | Writes, edits, reviews, or refactors source code. |
120
+ | `spreadsheet-agent` | Reads or writes tabular data (Sheets, Excel, Airtable, CSV). |
121
+ | `research-agent` | Researches a topic and produces a citation-backed report. |
122
+ | `customer-support-agent` | Triages or replies to inbound support messages. |
123
+ | `content-writer-agent` | Drafts blog posts, social, newsletters, marketing copy. |
124
+ | `ops-automation-agent` | Runs recurring or event-driven internal automation. |
125
+ | `generic-assistant` | Fallback for general-purpose personal helpers. |
126
+ | `agent-prompt-quality-bar` | Meta-skill: universal run contract + final audit rubric. |