| name | agentforce-generate |
| description | Build, modify, optimize, debug, and deploy agents with Agentforce Agent Script. TRIGGER when: user creates, modifies, optimizes, or asks about .agent files or aiAuthoringBundle metadata; changes agent behavior, responses, or conversation logic; designs agent actions, tools, subagents, or flow control; writes or reviews an Agent Spec; wants to optimize, improve, or refactor an agent; previews, debugs, deploys, publishes, or tests agents; uses Agent Script CLI commands (sf agent generate/preview/publish/test). DO NOT TRIGGER when: Apex development, Flow building, Prompt Template authoring, Experience Cloud configuration, or general Salesforce CLI tasks unrelated to Agent Script. |
| compatibility | Requires Agentforce license, API v66.0+, Einstein Agent User |
| metadata | {"version":"0.9"} |
Agent Script Skill
What This Skill Is For
This skill is for developing Agentforce agents, primarily with Agent Script, Salesforce's scripting language for AI agents.
CRITICAL: Agent Script is NOT AppleScript, JavaScript, Python, or any other
language. Do NOT confuse Agent Script syntax or semantics with any other
language you have been trained on.
Agent Script agents are defined by AiAuthoringBundle metadata: a .agent file (agent behavior) plus bundle-meta.xml (bundle metadata). Actions can be implemented with invocable Apex, autolaunched Flows, Prompt Templates, and other supported types.
This skill covers the full Agent Script lifecycle: designing agents,
writing Agent Script code, validating and debugging, deploying and
publishing, and testing.
How to Use This Skill
This file maps user intent to task domains and relevant reference files in references/. Treat this file as the execution router for end-to-end agent development, and use references for deep detail.
Identify user intent from task descriptions. ALWAYS read indicated reference files BEFORE starting work.
Rules That Always Apply
-
Always --json. ALWAYS include --json on EVERY sf CLI command. Do NOT pipe CLI output through jq or 2>/dev/null. Read the full JSON response directly — LLMs parse JSON natively.
-
Verify target org. Before any org interaction, run sf config get target-org --json to confirm a target org is set. If none configured, ask the user to set one with sf config set target-org <alias>.
-
Diagnose before you fix. When validating/debugging agent behavior,
ALWAYS --use-live-actions to preview authoring bundles. Send utterances
then read resulting session traces to ground your understanding of the
agent's behavior. Trace files reveal subagent selection, action I/O, and
LLM reasoning. DO NOT modify .agent files or action implementations without
this grounding. See Validation & Debugging
for trace file locations and diagnostic patterns.
-
Spec approval is a hard gate. Never proceed past Agent Spec
creation without explicit user approval.
-
Don't stall. After a step completes successfully, announce the
next step and start it. Do not wait for the user to say "what's next"
or "ok, continue." The only checkpoints that require explicit user
approval are: (a) Agent Spec approval, (b) the pre-Publish CHECKPOINT,
(c) any A/B branch the skill explicitly surfaces (e.g., Data Cloud
not provisioned during ADL setup). Long-running async work like ADL
indexing should run in the background while the skill continues with
work that doesn't depend on the result.
-
Draft-first lifecycle. During normal authoring, stay in draft iteration:
edit .agent + action implementations, validate, deploy, and preview as many
times as needed. Do NOT publish/activate by default. Publish + activate are
explicit release actions that require the user to confirm they are ready to
commit the current draft to metadata and expose it to end users.
-
Default agentic, pin with cause. Use the most agentic posture that meets
each subagent's requirement, and add deterministic controls only for
regulation/trust gates or observed failures. For detailed posture rules, see
Posture & Determinism.
-
No nested if or else if. Agent Script only supports flat if/else blocks. No else if, no if inside else, no if inside if. For multi-branch logic, use sequential if statements or compound conditions (if A and B:). Nested structures cause silent compile failures.
-
Action implementation is a user decision. During planning/spec work,
default new actions to NEEDS STUB placeholders. Always ask the user whether
they want to scan org/project for existing implementations and/or generate
new Apex/Flow/Prompt implementations before taking either path.
Task Domains
Every task domain below has Required Steps. Follow verbatim, in order. The default path is: design -> draft implementation loop -> validation/preview loop -> explicit user-approved release.
Create an Agent
User wants to build new agent from scratch. ALWAYS use Agent Script. Work with User to understand the agent's purpose, subagents, and actions using plain language without Salesforce-specific terminology.
Required Steps
Read CLI for Agents for exact command syntax.
- Design — Read Design & Agent Spec to draft an Agent Spec. Default all new actions to
NEEDS STUB placeholders during planning. Ask the user which implementation path they want before implementation work:
- Path A: Keep placeholders only (no implementation now)
- Path B: Scan for existing actions to reuse
- Path C: Generate new actions
Only run scans (reading
sfdx-project.json, searching @InvocableMethod, AutoLaunchedFlow, prompt templates, external service registrations, standard invocable actions, and custom objects) if the user explicitly chooses Path B or C.
If the agent's purpose involves answering from documents (e.g., "answer customer questions from our product manual", "respond based on a policy guide", "FAQ from a PDF"), ask the user: "Will this agent answer questions from a document corpus (PDF/DOCX/TXT)? If so, what file path?" Capture the path in the Spec under a "Knowledge Grounding" section. Asking now — during requirements capture — is critical: ADL indexing takes minutes, so we want the file path captured pre-Spec-approval and provisioning kicked off as early as possible.
Always save Agent Spec as file.
- STOP for user approval of Agent Spec. Present to user (including the Knowledge Grounding section if present). Ask for approval or feedback. Do not proceed without approval. Once approved, proceed without stopping unless a step fails.
- Validate environment prerequisites — Read Design & Agent Spec, Section 3 (Environment Prerequisites). Based on agent type from design, validate org environment:
- Employee agent: Confirm config block does NOT include
connection messaging: or MessagingSession linked variables. Remove if present. Exception: If the agent has a knowledge: block (uses AnswerQuestionsWithKnowledge), default_agent_user IS required even for employee agents — the platform treats knowledge-grounded agents as requiring an Einstein Agent User context at runtime. Query for the agent user and include it. See Examples for a complete employee agent example.
- Service agent: Query org for Einstein Agent User. If one exists, confirm username with user. If none, guide user through creation. See CLI for Agents, Section 12 for creation steps and Agent User Setup for required permissions.
3b. Kick off ADL provisioning (only if the Spec has a Knowledge Grounding section). Read Data Library Reference. Run the Step 0 preflight:
SELECT COUNT() FROM DataKnowledgeSpace (DC provisioned check), then sf agent adl list (ADL service health check). If DC is not provisioned, present the A/B choice from that reference. If DC is provisioned but the ADL service returns 400 INTERNAL_ERROR, surface the "DC up, ADL broken" path and skip grounding for this run. If both checks pass, run sf agent adl create (reference Step 1) to capture libraryId. Compute rag_feature_config_id = "ARFPC_<libraryId>" from the libraryId alone — that's enough to author the bundle. Then start the upload + indexing flow (reference Steps 2–6) in the background while authoring continues. Per Rule 5, do not block on async indexing; retrieverId is only needed for runtime queries (gated in Step 8). Also kick off the Data Cloud permset assignment for the agent user — see Agent User Setup, Step 3b for the discovery-then-assign procedure, which now ends with Step 3b.5 pinned post-assignment verification (against the resolved running-user and Einstein Agent User IDs) so callers can treat "Step 3b passed" as an authoritative Data Cloud grounding gate without re-running inline SOQL.
Do not proceed to code generation until environment is validated (ADL provisioning may continue running in background).
- Generate authoring bundle —
sf agent generate authoring-bundle --json --no-spec --name "<Label>" --api-name <Developer_Name>
- Write code — Read Core Language for syntax, block structure, and anti-patterns. Read Instruction Resolution for instruction patterns, recommended instruction order, and anti-patterns (especially Anti-Pattern 7: prose-based conditional logic). Edit generated
.agent file using reference files and templates. Do not create .agent or bundle-meta.xml files manually. If Step 3b produced a libraryId, include the top-level knowledge: block and the AnswerQuestionsWithKnowledge action wiring per Data Library Reference, section "Wiring the ADL into Agent Script". The template at assets/agents/knowledge-grounded.agent is a copy-modify starting point.
- Validate compilation —
sf agent validate authoring-bundle --json --api-name <Developer_Name>
If validation fails, read Validation & Debugging to diagnose and fix, then re-validate. ALWAYS fix syntax and structural errors before generating action implementations.
- Generate action implementations (explicit user-requested path only) — Only run this step if the user explicitly asked to generate new implementations (Path C in Step 1). For each action marked NEEDS STUB:
sf template generate apex class --name <ClassName> --output-dir <PACKAGE_DIR>/main/default/classes
Replace class body with invocable pattern from Design & Agent Spec. ALWAYS deploy:
sf project deploy start --json --metadata ApexClass:<ClassName>
ALWAYS fix deploy errors BEFORE generating and deploying next stub.
- Validate behavior — Read Validation & Debugging for preview workflow and session trace analysis.
If Step 3b provisioned an ADL, before sending any grounded test utterances confirm the library is queryable: run
sf agent adl get -i $LIBRARY_ID and check that retrieverId is present (Data Library Reference, Step 6). If still null, wait and re-poll — do not preview yet, the agent will return empty knowledgeSummary and the anti-hallucination guard will refuse on every utterance.
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
If actions query data, ground test utterances with:
sf data query --json -q "SELECT <Relevant_Fields> FROM <SObject> LIMIT 100"
Send test utterances with:
sf agent preview send --json --authoring-bundle <Developer_Name> --session-id <ID> -u "<message>"
Smoke testing requirements (see Validation & Debugging, Utterance Derivation):
- Publish (explicit release step) — Only after the user confirms they are ready to commit this draft to metadata. Publish validates metadata structure, not agent behavior. Every publish creates permanent version number.
sf agent publish authoring-bundle --json --api-name <Developer_Name>
If publish fails, follow troubleshooting checklist in Metadata & Lifecycle, Section 5 before retrying.
- Activate (explicit release step) — Makes new version available to users after publish.
sf agent activate --json --api-name <Developer_Name>
- Verify published agent — Preview user-facing behavior AFTER activation with
sf agent preview start --json --api-name <Developer_Name>
Use --api-name, not --authoring-bundle.
- Configure end-user access — ONLY for employee agents. Read Agent Access Guide to configure perms and assign access.
Reference Files
- CLI for Agents — exact
command syntax for generate, validate, deploy, publish, activate;
Section 12 for Einstein Agent User creation
- Core Language — execution
model, syntax, block structure, anti-patterns
- Design & Agent Spec —
subagent graph design, flow control patterns, Agent Spec production,
action implementation analysis; Section 3 for environment prerequisites
- Subagent Map Diagrams —
Mermaid diagram conventions for visualizing the agent's subagent graph
- Posture & Determinism —
default agentic posture, deterministic controls with cause
- Agent User Setup & Permissions —
permission set assignment, object permissions, cross-subagent validation
- Metadata & Lifecycle —
directory structure, bundle metadata; publish troubleshooting
- Validation & Debugging —
validate the agent compiles, preview to confirm behavior
- Agent Access Guide — end-user
access permissions, visibility troubleshooting
- Known Issues — only load when errors
persist after code fixes
- Patterns by Requirement — scenario-to-pattern mapping for architecture and flow choices
- Architecture Patterns — router-first mechanics, verification gates, workflow-local linear patterns
- Complex Data Types — type mapping decision tree
- Safety Review — 7-category safety review
- Discover Reference — target discovery CLI
- Scaffold Reference — stub generation CLI
- Deploy Reference — deployment lifecycle, error recovery
- Data Library Reference — provision a SFDRIVE Agentforce Data Library and wire it into the
.agent via the knowledge: block + AnswerQuestionsWithKnowledge action
Comprehend an Existing Agent
User wants to understand Agent Script agent they didn't write or need to revisit. May point to AiAuthoringBundle directory or ask "what does this agent do?" or "I need to fix this agent but I don't understand how it works.".
Required Steps
- Locate agent — Read
sfdx-project.json to identify package directories. Find AiAuthoringBundle directory within them. Read .agent file and bundle-meta.xml.
- Read code — Read Core Language for syntax and execution model BEFORE parsing
.agent file.
- Map action implementations — For each action with
target, locate implementation (Apex class, Flow, Prompt Template) in project. Note input/output contracts.
- Reverse-engineer Agent Spec — Read Design & Agent Spec for Agent Spec structure. Produce Agent Spec from code and save as file.
- Produce Subagent Map diagram — Read Subagent Map Diagrams for Mermaid conventions. Generate flowchart of subagent graph showing transitions, gates, and action associations.
- Annotate source — Ask if user wants Agent Script source annotated with explanations. If requested, add inline comments to
.agent file explaining flow control decisions, gating rationale, and subagent relationships.
- Present to user — Share Agent Spec, Subagent Map, and annotated source if produced. Check Anti-Patterns section in Core Language reference and flag any matches found in code.
Reference Files
- Core Language — syntax,
execution model, anti-patterns
- Design & Agent Spec —
Agent Spec structure, flow control pattern recognition
- Subagent Map Diagrams —
Mermaid conventions for subagent graph visualization
- Metadata & Lifecycle —
directory conventions, bundle metadata
- Known Issues — only load when code
contains unexplained workaround patterns
Modify an Existing Agent
User wants to add, remove, or change subagents, actions, instructions, or flow control on existing agent. May describe change in plain language ("add a billing subagent") or reference specific Agent Script constructs.
Required Steps
Read CLI for Agents for exact command syntax.
- Comprehend — If no Agent Spec exists, reverse-engineer first by following "Comprehend an Existing Agent" workflow above.
- Update Agent Spec — Read Design & Agent Spec for flow control patterns and existing action analysis. Modify Agent Spec to reflect intended changes. Default new actions to
NEEDS STUB placeholders. Ask the user which path they want:
- Path A: Keep placeholders only
- Path B: Scan for existing actions to reuse
- Path C: Generate new actions
Only run scans if the user explicitly chooses Path B or C.
If the modification involves adding, replacing, or removing knowledge grounding, ask: "Will this agent answer questions from a document corpus (PDF/DOCX/TXT)? If so, what file path?" Capture the path in the updated Spec under a "Knowledge Grounding" section. Asking now — during Spec update — surfaces ADL changes for the user's approval and lets us kick off provisioning right after.
Always save updated Agent Spec as file.
- STOP for user approval of updated Agent Spec. Present to user (including the Knowledge Grounding section if present). Ask for approval or feedback. Do not proceed without approval. Once approved, proceed without stopping unless a step fails.
- Kick off ADL provisioning (only if the Spec has a Knowledge Grounding section).
- If the
.agent already has a knowledge: block with a populated rag_feature_config_id AND the user is keeping the same library, reuse it. Skip provisioning. (No need to confirm retrieverId here — that gate moves to Step 8.)
- If a new ADL is needed, follow the same flow as the create workflow: read Data Library Reference, run the Step 0 preflight (
sf agent adl list), and (if DC is ready) run sf agent adl create (Step 1) to capture libraryId. Compute rag_feature_config_id = "ARFPC_<libraryId>" from libraryId alone — that's enough to author the bundle. Start the upload + indexing flow (reference Steps 2–6) in the background while you continue to Step 5 (Edit code). Per Rule 5, do not block on async indexing. Also kick off the Data Cloud permset assignment for the agent user — see Agent User Setup, Step 3b, which now ends with Step 3b.5 pinned post-assignment verification (against the resolved running-user and Einstein Agent User IDs) so callers can treat "Step 3b passed" as an authoritative Data Cloud grounding gate without re-running inline SOQL.
- If grounding is not part of the modification, skip this step.
- Edit code — Read Core Language for syntax and anti-patterns. Edit
.agent file to implement approved changes. If Step 4 produced a libraryId, include or update the knowledge: block and the AnswerQuestionsWithKnowledge action per Data Library Reference.
- Validate compilation —
sf agent validate authoring-bundle --json --api-name <Developer_Name>
If validation fails, read Validation & Debugging to diagnose and fix, then re-validate.
- Generate new action implementations (explicit user-requested path only) — Only run this step if the user explicitly asked to generate new implementations (Path C in Step 2). For each new action marked NEEDS STUB:
sf template generate apex class --name <ClassName> --output-dir <PACKAGE_DIR>/main/default/classes
Replace class body with invocable pattern from Design & Agent Spec. ALWAYS deploy:
sf project deploy start --json --metadata ApexClass:<ClassName>
ALWAYS fix deploy errors BEFORE generating and deploying next stub. Skip if no new actions added.
- Validate behavior — Read Validation & Debugging for preview workflow and session trace analysis.
If Step 4 provisioned a new ADL, before sending any grounded test utterances confirm the library is queryable: run
sf agent adl get -i $LIBRARY_ID and check that retrieverId is present (Data Library Reference, Step 6). If still null, wait and re-poll — do not preview yet, the agent will return empty knowledgeSummary and the anti-hallucination guard will refuse on every utterance.
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
If actions query data, ground test utterances with:
sf data query --json -q "SELECT <Relevant_Fields> FROM <SObject> LIMIT 100"
Send test utterances with:
sf agent preview send --json --authoring-bundle <Developer_Name> --session-id <ID> -u "<message>"
Smoke testing requirements (see Validation & Debugging, Utterance Derivation):
- Publish (explicit release step) — Only after the user confirms they are ready to commit this draft to metadata. Publish validates metadata structure, not agent behavior. Every publish creates permanent version number.
sf agent publish authoring-bundle --json --api-name <Developer_Name>
If publish fails, follow troubleshooting checklist in Metadata & Lifecycle, Section 5 before retrying.
- Activate (explicit release step) — Makes new version available to users after publish.
sf agent activate --json --api-name <Developer_Name>
- Verify published agent — Preview user-facing behavior AFTER activation with
sf agent preview start --json --api-name <Developer_Name>
Use --api-name, not --authoring-bundle.
Reference Files
- CLI for Agents — exact
command syntax for validate, deploy, preview, publish, activate
- Core Language — syntax,
anti-patterns
- Design & Agent Spec —
Agent Spec updates, action implementation analysis
- Validation & Debugging —
compilation diagnosis, preview workflow, session trace analysis
- Data Library Reference —
provisioning and Agent Script wiring for ADL grounding
- Known Issues — only load when errors
persist after code fixes
Diagnose Compilation Errors
User has Agent Script that won't compile. Errors surface from sf agent validate or sf agent preview start, or User describes symptoms like "I'm getting a validation error."
Required Steps
Read CLI for Agents for exact command syntax.
- Capture concrete errors first, then reproduce — If the user already shared error output, extract and list the exact error messages first. Then run
sf agent validate authoring-bundle --json --api-name <Developer_Name>
to capture basic compile errors. If no errors, run
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
to capture complex compile errors. If reproduction differs from user-provided errors, call out both and continue with the current reproducible errors.
- Classify error — Read Validation & Debugging for error taxonomy. Map each exact error message to a root cause category.
- Locate fault — Read Core Language to understand correct syntax. Find specific line(s) in
.agent file that cause each error.
- Fix code — Apply targeted fixes. Check Anti-Patterns section in Core Language reference to ensure you're not introducing known bad pattern.
- Re-validate — Run
sf agent validate authoring-bundle --json --api-name <Developer_Name>
then run
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
Repeat steps 2–5 if errors persist.
- Explain fix — Tell user what was wrong and what you changed. Explain root cause in terms of Core Language agent execution model.
Reference Files
- Core Language — syntax,
block structure, anti-patterns
- Validation & Debugging —
error taxonomy, error-to-root-cause mapping
- Known Issues — only load when error
doesn't match user code; may be a platform bug
- Production Gotchas — only load
when error involves reserved keywords or lifecycle hook syntax
Diagnose Behavioral Issues
Agent compiles, preview can start and --use-live-actions, but agent does not behave as expected. User describes symptoms like "the agent keeps going to the wrong subagent" or "the action isn't being called." Fundamentally different from validate or preview start errors — code is valid but behavior is wrong.
Required Steps
Read CLI for Agents for exact command syntax.
- Establish baseline — Read Agent Spec. If no Agent Spec exists, follow Comprehend an Existing Agent workflow to reverse-engineer one, then continue.
- Form hypotheses — Read Core Language for execution model. Based on user's description, list candidate root causes. Think through: subagent routing, gating conditions, action availability, instruction clarity, variable state, and transition timing.
- Reproduce in preview — Read Validation & Debugging for preview workflow and session trace analysis. Start preview session:
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
then send test messages covering EACH subagent with sf agent preview send. One message is not enough — confirm behavior per subagent before proceeding.
- Analyze session traces — Examine trace output to confirm subagent selection, action availability/execution, LLM reasoning, and where behavior diverges from Agent Spec. Do NOT skip this step — preview output alone is insufficient for diagnosis.
- Identify root cause — Match trace evidence to hypotheses. Consult Core Language reference and Gating Patterns in Design & Agent Spec reference to confirm absence of anti-patterns.
- Fix code — Apply targeted fix. If fix involves flow control changes, update Agent Spec to match.
- Re-validate and re-preview — Repeat steps 3–6 until behavior matches Agent Spec or you confirm a platform limitation. Run
validate authoring-bundle, then preview start --use-live-actions to verify fix using same utterances. Then test adjacent paths that might be affected by your changes.
- Explain fix — Tell user what was wrong and what you changed. Explain root cause in terms of Core Language agent execution model.
Reference Files
- Core Language — execution
model, anti-patterns
- Design & Agent Spec —
Agent Spec as behavioral baseline, gating patterns
- Validation & Debugging —
preview workflow, session trace analysis
- Known Issues — only load when behavior
is wrong but code logic is correct
Deploy, Publish, and Activate
User wants to take working agent from local development to running state in Salesforce org. Involves deploying AiAuthoringBundle and its dependencies, publishing to commit version, then activating to make it live.
Required Steps
Read CLI for Agents for exact command syntax.
- Validate compilation —
sf agent validate authoring-bundle --json --api-name <Developer_Name>
Do not proceed if validation fails.
- Deploy bundle and dependencies — Read Metadata & Lifecycle for dependency management and deploy commands. Deploy
AiAuthoringBundle and all action implementations (Apex classes, Flows, Prompt Templates) and dependencies to org.
- Live preview — Read Validation & Debugging for preview workflow and session trace analysis.
sf agent preview start --json --use-live-actions --authoring-bundle <Developer_Name>
then send test utterances with:
sf agent preview send --json --authoring-bundle <Developer_Name> --session-id <ID> -u "<message>"
Test key conversation paths to validate agent behavior when backed by live actions.
CHECKPOINT — Do NOT proceed to Publish unless ALL are true:
validate authoring-bundle passes with zero errors
- Live preview (
--use-live-actions) tested with realistic utterances covering all routing branches
- Traces confirm correct subagent routing, action invocation (
FunctionStep present), and spec-compliant behavior
- User explicitly approves deployment
- Publish (explicit release step) — Publish validates metadata structure, not agent behavior. DO NOT publish as part of a dev/test inner loop. ONLY publish as the FINAL step after user confirmation to commit this draft and prior to activation.
sf agent publish authoring-bundle --json --api-name <Developer_Name>
If publish fails, follow Troubleshooting Publish Failures in Metadata & Lifecycle before retrying.
- Activate — Makes new version available to users.
sf agent activate --json --api-name <Developer_Name>
- Verify published agent — Preview user-facing behavior AFTER activation with
sf agent preview start --json --api-name <Developer_Name>
Use --api-name, not --authoring-bundle.
- Configure end-user access — ONLY for employee agents. Read Agent Access Guide to configure perms and assign access.
Reference Files
- CLI for Agents — exact
command syntax for deploy, publish, activate, deactivate
- Validation & Debugging —
compilation validation, preview workflow
- Metadata & Lifecycle —
dependency management, deploy commands; publish troubleshooting
- Agent Access Guide — end-user
access permissions, visibility troubleshooting
- Known Issues — only load when deploy
hangs, publish fails, or activate fails unexpectedly
Diagnose Production Issues
User's agent is published and active but experiencing issues not caught during preview. Includes credit overconsumption, token or size limit failures, loop guardrail interruptions, reserved keyword runtime errors, VS Code sync failures, or unexpected behavioral differences between preview and production.
Required Steps
Read CLI for Agents for exact command syntax.
- Classify issue — Determine whether this is billing/cost concern, runtime limit, naming conflict, tooling issue, or behavioral difference between preview and production.
- Check known production gotchas — Read Production Gotchas for credit consumption, token limits, loop guardrails, reserved keywords, lifecycle hooks, and VS Code workarounds.
- Compare preview vs production behavior — If issue is behavioral, preview published agent with
sf agent preview start --json --api-name <Developer_Name>
(not --authoring-bundle). Compare against live-actions authoring bundle preview --authoring-bundle <Developer_Name> --use-live-actions to isolate preview-vs-production differences.
- Check known issues — Read Known Issues for platform bugs that may explain production-only failures.
- Fix and republish — Apply fixes, validate, re-preview, publish, activate, verify. Follow Deploy, Publish, and Activate steps.
- Explain diagnosis — Tell user what was happening and what you changed. Explain root cause.
Reference Files
- Production Gotchas — credit
consumption, token limits, loop guardrails, reserved keywords,
lifecycle hooks, VS Code workarounds
- CLI for Agents — command
syntax for preview, publish, activate
- Validation & Debugging —
preview workflow, session trace analysis
- Known Issues — only load when issue may
be a platform bug
Delete or Rename an Agent
User wants to remove agent or change its name. Maintenance tasks complicated by AiAuthoringBundle versioning and published version dependencies.
Required Steps
Read CLI for Agents for exact command syntax.
- Understand current state — Read Metadata & Lifecycle for versioning, delete mechanics, and rename mechanics. Identify whether agent has been published, how many versions exist, and whether it's currently active.
- Deactivate if active —
sf agent deactivate --json --api-name <Developer_Name>
Active agent cannot be deleted or renamed.
- Execute operation — For delete: follow delete mechanics in Metadata & Lifecycle reference. For rename: follow rename mechanics in same reference.
- Clean up orphans — Check for and remove orphaned metadata: Bot, BotVersion, GenAiPlannerBundle, GenAiPlugin, GenAiFunction. Metadata & Lifecycle reference details what to look for.
- Validate — Confirm operation completed cleanly. For rename, validate new bundle compiles and preview to confirm behavior.
Reference Files
- CLI for Agents — exact
command syntax for delete, deactivate, retrieve
- Validation & Debugging —
compilation validation, preview workflow
- Metadata & Lifecycle —
delete mechanics, rename mechanics, orphan cleanup
Test an Agent
User wants to create automated tests for Agent Script agent. Involves writing AiEvaluationDefinition test specs in YAML format that define test scenarios, expected behaviors, and quality metrics.
Required Steps
Read CLI for Agents for exact command syntax.
- Establish coverage baseline — Read Agent Spec. If no Agent Spec exists, reverse-engineer first by following Comprehend steps. Map every subagent, action, and flow control path to identify what needs test coverage.
- Design test scenarios — For test design methodology, expectations, metrics, test spec YAML format, and templates, use agentforce-test skill. That skill owns all testing content. For each coverage target, write one or more test scenarios: user utterance, expected subagent routing, expected action invocations, and expected agent response. Include both happy paths and edge cases.
- Write test spec YAML — Use template and reference files from agentforce-test skill. Save to
specs/<Agent_API_Name>-testSpec.yaml in SFDX project.
- Create test metadata — Generate
AiEvaluationDefinition from test spec using CLI.
- Deploy test — Deploy
AiEvaluationDefinition to org.
- Run tests — Execute test run using CLI. Capture results.
- Analyze results — Compare actual outcomes against expectations. For failures, identify whether issue is in agent code, action implementations, or test spec itself.
- Iterate — Fix agent code or test spec as needed, redeploy, and re-run until coverage targets are met.
Reference Files
- CLI for Agents — exact
command syntax for test create, test run, test results
- Core Language — agent
structure for designing meaningful tests
- Design & Agent Spec —
Agent Spec as test coverage baseline
- agentforce-test skill — test spec YAML format, expectations,
metrics, test design methodology, and test spec template
Optimize an Agent
User wants to improve an existing Agent Script agent by scanning for common optimization patterns and applying fixes. May say "optimize my agent", "improve my agent", "clean up this agent", "refactor agent", or mention the agent feels inefficient or has redundancies. Also appropriate to suggest proactively after complex editing sessions with many incremental changes.
Required Steps
-
Read and analyze the agent file — Read the current .agent file. Read Core Language for syntax rules and valid constructs as validation reference during optimization.
-
Scan for optimization patterns — For EACH subagent in the agent file, systematically apply all 4 optimization patterns:
Pattern 1: Wire action outputs to consuming actions (missing data flow)
- Scan all
actions: definitions to identify which have outputs: (data producers)
- Scan all
reasoning.actions for any action with ... placeholder inputs (data consumers)
- For each
... placeholder, match it to a producer with compatible output name/type
- If match found, ALL THREE steps are mandatory: create mutable variable, add
set statement after producer, replace ... with @variables.X in consumer
- See Optimization Pattern 1 — Data Flow for detailed fix instructions
Pattern 2: Extract deterministic logic from natural language
- Look for deterministic action calls in instructions: "first do X", "do X before any action", "retrieve/get/call X"
- Look for variable conditionals: "If [variable] is [value], route/transition to [subagent]"
- Look for post-action logic: "If [action result]...", "After calling X, do Y..."
- Extract to explicit
if/run/set/transition constructs
- When extracting, create new mutable variables to store action outputs as needed
- See Optimization Pattern 2 — Deterministic Logic for detailed fix instructions
Pattern 3: Fix variable and action reference syntax in instructions
- Check for
@variables.X used directly in natural language instead of {!@variables.X}
- Check for actions mentioned by use case in instructions without
{!@actions.X} syntax
- Match phrases like "retrieve details", "get contact", "update status" to actual action names
- See Optimization Pattern 3 — Reference Syntax for detailed fix instructions
Pattern 4: Add proper escalation actions (only if escalation mentioned in instructions)
- ONLY apply if instructions explicitly mention "escalate to human", "transfer to live agent", "connect to support representative", or similar
- Verify a proper
@utils.transition to @subagent.escalation action exists
- Add
{!@actions.go_to_escalation} reference in instructions
- See Optimization Pattern 4 — Escalation for detailed fix instructions
-
Report findings — Present all findings concisely with actionable edit instructions:
## Optimization Report
I found [N] improvements for your agent:
1. **Wire orderRecord between actions** (OrderManagement subagent, lines 36-41)
- Add variable: `orderRecord: mutable object`
- Add `set @variables.orderRecord = @outputs.orderRecord` after GetOrderDetails action
- Replace `with orderRecord = ...` with `with orderRecord = @variables.orderRecord` in UpdateStatus action
2. **Extract user check to deterministic logic** (hotel_booking subagent, line 120)
- Add variables: `userRecord: mutable object`, `roomAvailable: boolean`
- Move "If user is not known" check to: `if @variables.userRecord is None: run @actions.identify_user_by_username`
- Store output: `set @variables.userRecord = @outputs.userRecord`
Would you like me to apply these [N] improvements?
-
STOP for user approval. Do not apply changes without explicit approval.
-
Apply improvements (if approved) — For each approved improvement, edit the .agent file directly applying the fix described in the report. Track successes and failures.
-
Validate compilation —
sf agent validate authoring-bundle --json --api-name <Developer_Name>
If validation fails, fix introduced errors and re-validate.
-
Report results — Summarize what was applied:
## Applied [X] of [N] improvements
- Improvement 1: Successfully applied
- Improvement 2: Successfully applied
- Improvement 3: Failed - [reason]
Reference Files
- Core Language — syntax rules,
valid constructs for validation during optimization
- Optimization Pattern 1 — Data Flow —
wiring action outputs to consuming actions via variables
- Optimization Pattern 2 — Deterministic Logic —
extracting procedural logic from natural language to explicit code
- Optimization Pattern 3 — Reference Syntax —
fixing variable and action references in instructions
- Optimization Pattern 4 — Escalation —
adding proper escalation action wiring
- Validation & Debugging —
compilation validation after applying optimizations
The Agent Spec
Agent Spec is the central artifact this skill produces and consumes. A structured design document representing agent purpose, user outcomes, subagent graph, actions and implementations, variables, subagent posture, deterministic controls (when needed), and behavioral intent.
Agent Specs evolve with the agent. Sparse during agent creation (purpose, use cases, planned placeholders). Fleshed out during agent build (flowchart, action implementations mapped, posture choices documented, deterministic controls added only where justified). Reverse-engineered when comprehending existing agents. Critical for advanced troubleshooting, providing reference to compare expected vs. actual behavior. During testing, test coverage maps against it.
Always produce or update Agent Spec as first step of any operation that changes or analyzes agent. It is consistent grounding to work from, and a durable artifact a developer can review.
Read Design & Agent Spec for Agent Spec structure and production methodology.
Assets
The assets/ directory contains templates and examples. Read when you need a starting point or a concrete reference for artifacts and source files.
-
assets/agent-spec-template.md — Agent Spec template with all sections and placeholder content. Copy to <AgentName>-AgentSpec.md in project directory, then fill in during design. Save Agent Spec as file — significant design artifact that benefits from proper rendering, especially Mermaid Subagent Map diagram.
-
assets/agents/local-info-agent-annotated.agent — Complete annotated example based on Local Info Agent, showing all major Agent Script constructs in context with inline comments explaining why each construct is used. Read when you need concrete reference for how concepts compose into working agent, or as fallback when focused examples in reference files aren't sufficient.
-
assets/agents/template-single-subagent.agent — Minimal agent with one subagent. Copy and modify for simple agents.
-
assets/agents/template-multi-subagent.agent — Minimal agent with multiple subagents and transitions. Copy and modify for complex agents.
-
assets/invocable-apex-template.cls — Reference for invocable Apex
classes. Copy and modify when complex Apex action implementations are desired.
Important Constraints
-
Use only Salesforce CLI and Salesforce org. Do not reference or depend on other skills, MCP servers, or external tooling. All commands use sf (Salesforce CLI).
-
Only certain implementation types are valid for actions. For example, only invocable Apex (not arbitrary Apex classes) can back an action. Similar constraints may apply to Flows and Prompt Templates. When wiring actions to implementations, consult Design & Agent Spec reference file for valid types and stubbing methodology.
-
sf agent generate test-spec is not for agentic use. It is interactive, REPL-style command designed for humans. When creating test specs, start from boilerplate template in assets instead.
Common Issues Quick Reference
Internal Error, try again later during publish:
Server-side compile failure. The 500 doesn't tell you which check failed — walk all four causes in order before asking the user what's wrong. Do NOT stop at cause 1.
- Agent type mismatch on
default_agent_user. Employee agent must NOT have default_agent_user; service agent MUST have it (and the user must hold an Einstein Agent license). See Design & Agent Spec, Section 3. Re-run the query — do not invent the username.
- Action definition missing
outputs: block. If any action has target: and inputs: but no outputs:, the server-side compiler can't generate return bindings. CLI validate and LSP both PASS — only publish fails. See Known Issues, Issue 15.
- Other structural drift in the
.agent file. Diff against a known-good bundle in the same org:
sf project retrieve start --metadata "AiAuthoringBundle:<known-working-agent>" --output-dir /tmp/diff-bundle --json
Compare keyword-by-keyword. Look for missing required-but-undocumented fields, block-ordering drift, or DSL keywords your bundle uses that aren't in the working one.
- Genuine transient backend error. If 1–3 are clean and the response
requestId differs across retries, wait 60 s and retry once.
Unable to access Salesforce Agent APIs... during preview:
default_agent_user lacks permissions. See Agent User Setup & Permissions. Do NOT publish as fix — --use-live-actions does not require published agent.
Permission error referencing different username than configured:
Same fix as above — error references org's default running user, but root cause is Einstein Agent User permissions.
Agent fails with permission error even though current subagent's actions work:
Planner validates ALL actions across ALL subagents at startup. One missing permission fails entire agent.
Apex action returns empty results in live preview but works in simulated:
WITH USER_MODE + missing object permissions = silent failure (0 rows, no error). See Agent User Setup & Permissions, Section 6.2.
Agent published, ADL indexed (retrieverId populated), but every grounded question returns empty knowledgeSummary / "I don't have that information":
The Einstein Agent User lacks Data Cloud access. Two things to check, in order:
- Permset/PSL not assigned. Run the verification queries from Agent User Setup, Step 3b.3. If no Data Cloud permset/PSL appears, run the discovery-then-assign procedure (priority:
GenieDataPlatformStarterPsl PSL → GenieUserEnhancedSecurity PS → DataCloudUser PS → DataCloudArchitect PS).
- Data Space scope not granted on the permset. Currently no API. Setup → Permission Sets → click the assigned permset → "Data Cloud Data Space Management" under Apps → Edit → add the ADL's data space (usually
default) → Save. See Agent User Setup, Step 3b.4.
Quick Links (Deep Detail Lives in References)