Sf ai agentscript
Agent Script DSL for deterministic Agentforce agents. TRIGGER when: user writes or edits .agent files, builds FSM-based agents, uses Agent Script CLI (sf agent generate authoring-bundle, sf agent validate authoring-bundle, sf agent preview, sf agent publish authoring-bundle, sf agent activate), or asks about deterministic agent patterns, slot filling, or instruction resolution. DO NOT TRIGGER when: Builder metadata work (use sf-ai-agentforce), agent testing (use sf-ai-agentforce-testing), or persona design (use sf-ai-agentforce-persona).
By- name:
- sf-ai-agentscript
- description:
- Agent Script DSL for deterministic Agentforce agents. TRIGGER when: user writes or edits .agent files, builds FSM-based agents, uses Agent Script CLI (sf agent generate authoring-bundle, sf agent validate authoring-bundle, sf agent preview, sf agent publish authoring-bundle, sf agent activate), or asks about deterministic agent patterns, slot filling, or instruction resolution. DO NOT TRIGGER when: Builder metadata work (use sf-ai-agentforce), agent testing (use sf-ai-agentforce-testing), or persona design (use sf-ai-agentforce-persona).
SF-AI-AgentScript Skill
Agent Script is the code-first path for deterministic Agentforce agents. Use this skill when the user is authoring .agent files, building finite-state topic flows, or needs repeatable control over routing, variables, actions, and publish behavior.
Start with the shortest guide first: references/activation-checklist.md
Migrating from the Builder UI? Use references/migration-guide.md
When This Skill Owns the Task
Use sf-ai-agentscript when the work involves:
- creating or editing
.agentfiles - deterministic topic routing, guards, and transitions
- Agent Script CLI workflows (
sf agent generate authoring-bundle,sf agent validate authoring-bundle,sf agent preview,sf agent publish authoring-bundle,sf agent activate) - slot filling, instruction resolution, post-action loops, or FSM design
Delegate elsewhere when the user is:
- maintaining Builder metadata agents (
GenAiFunction,GenAiPlugin,GenAiPromptTemplate, Models API, custom Lightning types) → sf-ai-agentforce - designing persona / tone / voice → sf-ai-agentforce-persona
- building formal test plans or coverage loops → sf-ai-agentforce-testing
If the user is in Builder Script / Canvas view but the outcome is a .agent authoring bundle, keep the work in sf-ai-agentscript.
Right-Size Determinism
- Determinism is a dial, not a destination.
- Use Agent Script when “mostly right” is not acceptable: gates, mandatory sequencing, explicit state transitions, compliance, or drift control.
- If a workflow is fully static and linear, use Flow or Apex instead of scripting the conversation.
- Prefer a deterministic envelope: deterministic entry/gate → flexible middle → deterministic closeout.
- More determinism is not automatically better. Start minimal, then harden only the parts that show routing drift, sequencing failures, or compliance risk.
Required Context to Gather First
Ask for or infer:
- agent purpose and whether Agent Script is truly the right fit
- Service Agent vs Employee Agent
- target org and publish intent
- expected actions / targets (Flow, Apex, PromptTemplate, etc.)
- whether the request is authoring, validation, preview, or publish troubleshooting
Activation Checklist
Before you author or fix any .agent file, verify these first:
- Exactly one
start_agentblock - No mixed tabs and spaces
- Booleans are
True/False - No
else ifand no nestedif - No top-level
actions:block - No
@inputsinsetexpressions linkedvariables have no defaultslinkedvariables do not useobject/listtypes- Use explicit
agent_type - Use
@actions.prefixes consistently - Use
run @actions.Xonly whenXis a topic-level action definition withtarget: - Do not branch directly on raw
@system_variables.user_input contains/startswith/endswithfor intent routing - On prompt-template outputs, prefer
is_displayable: False+is_used_by_planner: True - Do not assume
@outputs.Xis scalar — inspect the output schema before branching or assignment
For the expanded version, use references/activation-checklist.md.
Non-Negotiable Rules
1) Service Agent vs Employee Agent
| Agent type | Required | Forbidden / caution |
|---|---|---|
AgentforceServiceAgent |
Valid default_agent_user, correct permissions, target-org checks, prefer sf org create agent-user |
Publishing without a real Einstein Agent User |
AgentforceEmployeeAgent |
Explicit agent_type |
Supplying default_agent_user |
Full details: references/agent-user-setup.md
2) Recommended top-level block convention
Use this order for consistency in this skill's examples and reviews:
config:
variables:
system:
connection:
knowledge:
language:
start_agent:
topic:
Official Salesforce materials present top-level blocks in differing sequences, and local validation evidence indicates multiple orderings compile. Treat this as a style convention, not a standalone correctness or publish blocker.
3) Critical config fields
| Field | Rule |
|---|---|
developer_name |
Must match folder / bundle name |
description |
Public docs/examples should use this config field |
agent_type |
Set explicitly every time |
default_agent_user |
Service Agents only |
Local tooling also accepts agent_description: for compatibility, but this skill's public docs and examples should prefer description:.
4) Syntax blockers you should treat as immediate failures
else if- nested
if - comment-only
ifbodies - top-level
actions: - invocation-level
inputs:/outputs:blocks - reserved variable / field names like
descriptionandlabel
Canonical rule set: references/syntax-reference.md and references/validator-rule-catalog.md
Recommended Workflow
Recommended Authoring Workflow
Phase 1 — design the agent
- decide whether the problem is actually deterministic enough for Agent Script
- model topics as states and transitions as edges
- define only the variables you truly need
Phase 2 — author the .agent
- create
config,system,start_agent, and topics first - add target-backed actions with full
inputs:andoutputs: - use
available whenfor deterministic tool visibility - normalize raw intent/validation signals into booleans or enums before branching; avoid direct substring checks on raw user utterances for critical control flow
- keep post-action checks at the top of
instructions: ->
Default authoring stance
- Default to direct
.agentauthoring and edits in source control. - Use
sf agent generate authoring-bundle --no-speconly when the user wants local bundle scaffolding. - Treat
sf agent generate agent-specas optional ideation / topic bootstrap, not the default workflow. - Do not route Agent Script users toward
sf agent createorsf agent generate template.
Phase 3 — validate continuously
Validation already runs automatically on write/edit. Use the CLI before publish:
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
The validator covers structure, runtime gotchas, target readiness, and org-aware Service Agent checks. Rule IDs live in references/validator-rule-catalog.md.
Phase 4 — preview smoke test
Use the preview loop before publish:
- derive 3–5 smoke utterances
- start preview with the
start/send/endsubcommands, not baresf agent preview - if you use
--authoring-bundle, always choose a mode explicitly:--simulate-actionsor--use-live-actions - inspect topic routing / action invocation / safety / grounding
- fix and rerun up to 3 times
Full loop: references/preview-test-loop.md
Phase 5 — publish and activate
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# Manual activation
sf agent activate --api-name MyAgent -o TARGET_ORG
# CI / deterministic activation of a known BotVersion
sf agent activate --api-name MyAgent --version <n> -o TARGET_ORG --json
Publishing does not activate the agent.
For automation, prefer --version <n> --json so activation is deterministic and machine-readable.
Deterministic Building Blocks
These execute as code, not suggestions:
- conditionals
available whenguards- variable checks
- direct
set/transition to run @actions.Xonly whenXis a topic-level action definition withtarget:- variable injection into LLM-facing text
Important distinction:
- Deterministic:
set,transition to, andrun @actions.Xfor a target-backed topic action - LLM-directed:
reasoning.actions:utilities / delegations such as@utils.setVariables,@utils.transition, and{!@actions.X}instruction references
If you need deterministic behavior for something that is currently modeled as a reasoning-level utility, either:
- rewrite it as direct
set/transition to, or - promote it to a topic-level target-backed action and
runthat action
See references/instruction-resolution.md and references/architecture-patterns.md.
Cross-Skill Integration
Cross-Skill Orchestration
| Task | Delegate to | Why |
|---|---|---|
Build flow:// targets |
sf-flow | Flow creation / validation |
| Build Apex action targets | sf-apex | @InvocableMethod and business logic |
| Test topic routing / actions | sf-ai-agentforce-testing | Formal test specs and fix loops |
| Deploy / publish | sf-deploy | Deployment orchestration |
High-Signal Failure Patterns
| Symptom | Likely cause | Read next |
|---|---|---|
Internal Error during publish |
invalid Service Agent user or missing action I/O | references/agent-user-setup.md, references/actions-reference.md |
invalid input/output parameters on prompt template action |
Target template is in Draft status — activate it first | references/action-prompt-templates.md |
| Parser rejects conditionals | else if, nested if, empty if body |
references/syntax-reference.md |
| Action target issues | missing Flow / Apex target, inactive Flow, bad schemas | references/actions-reference.md |
| Prompt template runs but user sees blank response | prompt output marked is_displayable: True |
references/production-gotchas.md, references/action-prompt-templates.md |
| Prompt action runs but planner behaves like output is missing | output hidden from direct display but not planner-visible | references/production-gotchas.md, references/actions-reference.md |
ACTION_NOT_IN_SCOPE on run @actions.X |
run points at a utility / delegation / unresolved action instead of a topic-level target-backed definition |
references/syntax-reference.md, references/instruction-resolution.md |
| Deterministic cancel / revise / URL checks behave inconsistently | raw @system_variables.user_input matching or string-method guards are being used as control-flow-critical validation |
references/syntax-reference.md, references/production-gotchas.md |
@outputs.X comparisons or assignments behave unexpectedly |
the action output is structured/wrapped, not a plain scalar | references/actions-reference.md, references/syntax-reference.md |
| Preview and runtime disagree | linked vars / context / known platform issues | references/known-issues.md |
| Validate passes but publish fails | org-specific user / permission / retrieve-back issue | references/production-gotchas.md, references/cli-guide.md |
Reference Map
Start here
Publish / runtime safety
- references/agent-user-setup.md
- references/production-gotchas.md
- references/customer-web-client.md
- references/known-issues.md
Architecture / reasoning
- references/architecture-patterns.md
- references/instruction-resolution.md
- references/fsm-architecture.md
- references/patterns-quick-ref.md
Validation / testing / debugging
- references/preview-test-loop.md
- references/testing-guide.md
- references/debugging-guide.md
- references/validator-rule-catalog.md
Examples / scaffolds
- references/minimal-examples.md
- references/migration-guide.md
- assets/
- assets/agents/
- assets/patterns/
Project documentation
Score Guide
| Score | Meaning |
|---|---|
| 90+ | Deploy with confidence |
| 75–89 | Good, review warnings |
| 60–74 | Needs focused revision |
| < 60 | Block publish |
Full rubric: references/scoring-rubric.md
Official Resources
<!-- Modified by Automation Skills on 2026-11-24: relative links to files that were not copied now point to the original repository. -->Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Advanced Action Patterns
Context-aware descriptions, instruction references, and binding strategies
Related: SKILL.md — Action Chaining | action-prompt-templates.md
1. Context-Aware Action Descriptions
The same underlying action can have different descriptions across topics. This improves LLM action selection by matching the description to the user's expertise level or business context.
Beginner vs. Advanced Mode
topic beginner_help:
reasoning:
actions:
search_help: @actions.search_knowledge_base
description: "Search for help articles"
topic advanced_help:
reasoning:
actions:
search_help: @actions.search_knowledge_base
description: "Execute knowledge base query with advanced filters (type, date range, tags). Returns paginated results with relevance scoring. Supports Boolean operators and wildcards."
Result: Beginner users see simple language; advanced users see technical capabilities.
available when + Description Override
Combine conditional availability with contextual descriptions for stronger control:
topic business_hours:
reasoning:
actions:
create_case: @actions.create_support_case
available when @variables.during_business_hours == True
description: "Create a support case for immediate assignment to available agents"
topic after_hours:
reasoning:
actions:
create_case: @actions.create_support_case
available when @variables.during_business_hours == False
description: "Create a support case for next-business-day follow-up"
When to use description overrides
| Scenario | Use Override? |
|---|---|
| Same action serves different user expertise levels | ✅ Yes |
| Same action has different context in different topics | ✅ Yes |
| Action is always used the same way | ❌ No — single description suffices |
| Action name alone is already clear | ❌ No — don't over-engineer |
2. Instruction Action References
The {!@actions.action_name} syntax embeds a reference to the full action definition (not just the name) into reasoning instructions. This gives the LLM richer context about the action's inputs, outputs, and purpose — improving selection accuracy when multiple actions could apply.
Basic Syntax
topic business_hours_routing:
data:
@variables.next_open_time: ...
reasoning:
instructions: ->
if @variables.next_open_time:
| We are currently OUTSIDE business hours.
The next available time is {!@variables.next_open_time}.
Create a support case using {!@actions.create_case} to ensure
follow-up during business hours.
else:
| We are currently WITHIN business hours.
Connect the customer to live support using {!@actions.transfer_to_agent}.
Conditional Instruction Patterns
Guide the LLM toward specific actions based on state:
topic identity_verification:
reasoning:
instructions: ->
if @variables.verification_attempts < 3:
| Verify identity using {!@actions.verify_email_code}
or {!@actions.verify_phone_code}.
else:
| Maximum attempts reached. Escalate using {!@actions.escalate_to_security}.
topic order_inquiry:
reasoning:
instructions: ->
if @variables.order_status == "shipped":
| Track shipment using {!@actions.get_tracking_info}.
if @variables.order_status == "processing":
| Check status using {!@actions.get_fulfillment_status}.
if @variables.order_status == "cancelled":
| Process refund using {!@actions.initiate_refund}.
Combining with available when
For maximum control, use both instruction references AND deterministic guards:
topic secure_operations:
reasoning:
instructions: ->
if @variables.verified == True:
| You can now access sensitive operations using {!@actions.view_account_details}.
else:
| Please verify your identity first.
actions:
view_account_details: @actions.get_account_info
available when @variables.verified == True
description: "View sensitive account information"
Result: Instruction guidance steers the LLM, while available when provides a deterministic safety net.
Descriptions vs. References: When to Use Which
| Approach | When to Use |
|---|---|
| Description overrides | Action needs different descriptions per topic/context |
| Instruction references | Need to explicitly guide LLM toward an action in instructions |
| Both | Maximum control — override description AND reference in instructions |
3. Input Binding Decision Matrix
Agent Script supports four input binding approaches. Use this matrix to choose:
| Binding | Syntax | Use When | Example |
|---|---|---|---|
| LLM slot-filling | ... |
User provides the value in conversation | with query=... |
| Variable binding | @variables.X |
Data exists from prior turns or actions | with id=@variables.customer_id |
| Fixed value | literal | System constant or business rule | with format="pdf" |
| Mixed | combination | Complex actions needing multiple sources | See below |
Mixed Binding Example
process_refund: @actions.process_refund_request
with order_id=@variables.order_id # Variable — from previous action
reason=... # Slot-fill — user explains why
amount=@variables.order_total # Variable — stored value
refund_method="original_payment" # Fixed — business rule
require_approval=True # Fixed — policy constant
Combined Pattern: Capture → Reuse → Extend
# Step 1: Capture data from first action
search: @actions.search_products
with query=...
set @variables.product_id = @outputs.top_result_id
# Step 2: Reuse captured value + collect new input
add_to_cart: @actions.add_to_cart
with product_id=@variables.product_id # Reuse from step 1
quantity=... # New user input
apply_discount=True # Business rule
4. Callback Behavior Notes
These supplement the "Action Chaining with run Keyword" section in SKILL.md.
Callbacks only execute if the parent action succeeds
verify_payment: @actions.verify_payment_method
with payment_method_id=...
set @variables.verified = @outputs.success
run @actions.process_payment # Only runs if verify succeeds
with payment_method_id=...
If verify_payment_method fails (Flow error, Apex exception), process_payment will not execute. Design your conversation flow to handle the failure case separately.
Flatten, don't nest
# ❌ WRONG — nested callbacks (not allowed)
action1: @actions.first
run @actions.second
run @actions.third # ERROR: Nested callbacks not supported
# ✅ CORRECT — sequential callbacks (flat structure)
action1: @actions.first
run @actions.second
run @actions.third
Practical callback chain: Create → Notify → Log
create_case: @actions.create_support_case
with subject=...
description=...
priority=@variables.priority
set @variables.case_id = @outputs.id
run @actions.notify_team
with case_id=@variables.case_id
priority=@variables.priority
run @actions.log_case_creation
with case_id=@variables.case_id
5. Additional Error Patterns
These supplement the "Common Issues" table in SKILL.md.
| Error | Cause | Fix |
|---|---|---|
| Missing colon after action name | my_action instead of my_action: |
Add colon: my_action: |
| Missing type annotation on input | email: with no type |
Add type: email: string |
| Wrong target protocol | flows://MyFlow |
Use flow://MyFlow (no trailing s) |
Input: without quotes |
with Input:email=... |
Quote it: with "Input:email"=... |
... as variable default |
my_var: mutable string = ... |
Use "" for defaults; ... is slot-filling only |
| Vague action description | description: "Does a search" |
Be specific: description: "Searches KB for articles matching the query" |
6. JSON Parsing Pattern
Agent Script cannot parse JSON strings inline. When an action returns a JSON string that needs to be decomposed into individual fields, use a Flow or Apex action to parse it.
Problem
# This will NOT work - cannot parse JSON inline in Agent Script
set @variables.name = @outputs.json_response["name"] # Not supported
set @variables.email = @outputs.json_response.email # May work for objects, not JSON strings
Solution: Flow/Apex JSON Parser
# Step 1: Call the action that returns JSON
get_data: @actions.fetch_external_data
with endpoint = "customer_profile"
set @variables.raw_json = @outputs.response_body
# Step 2: Pass JSON to a parser action (Flow or Apex)
parse: @actions.parse_json_response
with json_string = @variables.raw_json
set @variables.customer_name = @outputs.name
set @variables.customer_email = @outputs.email
set @variables.customer_tier = @outputs.tier
Apex Parser Example
public class JsonParserAction {
public class ParseRequest {
@InvocableVariable(required=true)
public String jsonString;
}
public class ParseResult {
@InvocableVariable public String name;
@InvocableVariable public String email;
@InvocableVariable public String tier;
}
@InvocableMethod(label='Parse Customer JSON')
public static List<ParseResult> parse(List<ParseRequest> requests) {
List<ParseResult> results = new List<ParseResult>();
for (ParseRequest req : requests) {
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(req.jsonString);
ParseResult result = new ParseResult();
result.name = (String) parsed.get('name');
result.email = (String) parsed.get('email');
result.tier = (String) parsed.get('tier');
results.add(result);
}
return results;
}
}
Tip: For complex nested JSON, create typed Apex wrapper classes instead of using
deserializeUntyped.
Consolidated from @kunello's PR #20 research on Agent Script Recipes action configuration patterns.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Prompt Template Actions
Invoking Salesforce Prompt Templates as actions within Agent Script
Related: SKILL.md — Action Target Protocols | action-patterns.md
Overview
Prompt Template Actions let agents invoke Salesforce Prompt Builder templates via either the prompt:// shorthand or the equivalent generatePromptResponse:// protocol. The agent passes structured inputs to the template and receives a generated promptResponse output — keeping content generation in the template while the agent manages conversation flow.
Terminology: in Setup, users usually say Prompt Template. In source metadata, the current metadata type is
GenAiPromptTemplate.
When to use: Personalized responses, summarization, content generation, recommendations — anything where an LLM prompt template produces better output than static Flow logic.
Action Definition
Whether you author the action through Setup or directly in an .agent file, the key prompt-template rules are the same:
actions:
Generate_Personalized_Schedule:
description: "Generate a personalized schedule using a prompt template"
inputs:
"Input:email": string
description: "User's email address"
is_required: True
"Input:preferences": string
description: "User's scheduling preferences"
is_required: False
outputs:
promptResponse: string
description: "The personalized schedule generated by the template"
is_displayable: False
is_used_by_planner: True
target: "prompt://Generate_Personalized_Schedule"
Critical syntax rules
| Rule | Example |
|---|---|
| Preferred target protocol | "prompt://TemplateName" |
| Also valid | "generatePromptResponse://TemplateName" |
| Input names must be quoted | "Input:email" not Input:email |
Input prefix is Input: |
Matches the template's input field API name |
Output field is always promptResponse |
Single string output from the template |
Both target protocols compile to the same runtime target. Prefer
prompt://for brevity in new authoring.
Prompt Template Gotchas
1) Quote every Input:... binding
Parameter names that include : must stay quoted in both the action definition and the invocation.
# ✅ Correct
inputs:
"Input:email": string
is_required: True
# ❌ Wrong
inputs:
Input:email: string
2) ... belongs to LLM-invoked actions, not deterministic inline run
# ❌ Wrong — deterministic run cannot slot-fill
reasoning:
instructions: ->
run @actions.Generate_Order_Summary
with "Input:orderId" = ...
# ✅ Correct — let the LLM invoke the action and fill the input
reasoning:
instructions: ->
| Ask for the order number, then call {!@actions.generate_summary}.
actions:
generate_summary: @actions.Generate_Order_Summary
description: "Generate a summary for the requested order"
with "Input:orderId" = ...
set @variables.summary = @outputs.promptResponse
If you need a later deterministic run, capture the user input first with @utils.setVariables (or another LLM-invoked action), then reference the saved variable.
3) Prompt outputs usually belong to the planner, not direct display
For most prompt-template actions, the safest output pattern remains:
outputs:
promptResponse: string
is_displayable: False
is_used_by_planner: True
Recommended output flags
For prompt targets, treat promptResponse as planner input rather than raw UI output:
outputs:
promptResponse: string
description: "Generated response text"
is_displayable: False
is_used_by_planner: True
Why:
is_displayable: Trueon prompt outputs is a known blank-response trap- if the output is hidden but not planner-visible, the action may run but the response can still feel "missing"
filter_from_agent: Trueis not the best substitute when the planner needs the prompt output, becausefilter_from_agentandis_used_by_plannercannot safely share the same field in this runtime
Agent Script Invocation
Reference the action definition in your .agent file:
topic schedule_generation:
reasoning:
actions:
generate_schedule: @actions.Generate_Personalized_Schedule
with "Input:email"=@variables.user_email
"Input:preferences"=...
set @variables.schedule = @outputs.promptResponse
Input binding patterns (same as regular actions):
@variables.user_email— variable binding (data from prior turns)...— LLM slot-filling (extract from conversation)"professional"— fixed value (business rule constant)
Grounded Data Integration
Templates can include data providers (Apex classes, Flows) that supply contextual data for personalized responses. The grounding happens inside the template — Agent Script only needs to pass the lookup key:
actions:
Get_Product_Recommendations:
description: "Generate personalized product recommendations based on purchase history"
inputs:
"Input:customerId": string
description: "Customer ID for personalization"
is_required: True
outputs:
promptResponse: string
description: "Personalized recommendations grounded in customer data"
is_displayable: False
is_used_by_planner: True
target: "prompt://Product_Recommender"
The template itself (configured in Prompt Builder) includes:
- Data Provider: Apex class fetching customer purchase history
- Grounding: Recent orders, preferences, browsing history
- Template instructions: How to format recommendations using the grounded data
Common Patterns
Pattern 1: Content Generation
generate_email: @actions.Generate_Email_Response
with "Input:customerMessage"=@variables.user_message
"Input:tone"="professional"
"Input:context"=@variables.case_context
set @variables.email_draft = @outputs.promptResponse
Pattern 2: Summarization
summarize: @actions.Summarize_Conversation
with "Input:conversationHistory"=@variables.chat_history
"Input:maxLength"="500"
set @variables.summary = @outputs.promptResponse
Pattern 3: Personalized Recommendations
recommend: @actions.Get_Product_Recommendations
with "Input:customerId"=@variables.customer_id
"Input:category"=...
set @variables.recommendations = @outputs.promptResponse
Known Limitation: run Keyword with Prompt Templates
Chained actions using run may not properly map "Input:X" parameters:
# ❌ MAY NOT WORK — run + prompt template input binding:
process: @actions.create_order
with customer_id=@variables.customer_id
run @actions.Generate_Order_Summary
with "Input:orderId"=@variables.order_id # Input binding may fail
# ✅ WORKAROUND — call as primary action instead:
generate_summary: @actions.Generate_Order_Summary
with "Input:orderId"=@variables.order_id # Works as primary action
set @variables.summary = @outputs.promptResponse
See SKILL.md "Action Chaining with
runKeyword" for the full known bug description.
<a id="draft-template-publish-errors"></a>
Draft Template Publish Errors (Critical)
If your
generatePromptResponse://action fails to publish, check the template status FIRST. A Draft template produces a cascade of misleading errors — none of which mention the template status.
When the target prompt template is in Draft status, sf agent publish authoring-bundle reports different errors depending on which I/O blocks are present. All are caused by the same root cause:
| Agent Script State | Error Message | Actually Means |
|---|---|---|
Full I/O (inputs: + outputs:) |
invalid input parameters found: 'Input:query' |
Template can't be resolved (Draft) |
outputs: only |
invalid output parameters found: 'promptResponse' |
Template can't be resolved (Draft) |
| Bare definition (no I/O) | Metadata API request failed: Metadata retrieval failed: |
Template can't be resolved (Draft) |
| Bare definition (retry) | Internal Error, try again later |
Template can't be resolved (Draft) |
sf agent validate authoring-bundle passes regardless of template status — it does not check whether the target template is published / active. This gives false confidence before publish.
Fix: Publish or activate the template in Setup > Prompt Builder before publishing the agent. The original Agent Script syntax (with "Input:X" inputs and promptResponse output) is correct — it will publish successfully once the template is available for runtime use.
Pre-publish check:
sf project retrieve start --metadata GenAiPromptTemplate:YourTemplateName -o TARGET_ORG --json
# Then inspect the retrieved XML for <status>Published</status> or <status>Active</status>
# Draft status = publish will fail with misleading errors
See known-issues.md Issue 40 for the full bug report.
Common Errors
| Error | Cause | Fix |
|---|---|---|
SyntaxError on input binding |
Missing quotes on parameter name | Use "Input:email" not Input:email |
| Template not found | Wrong protocol or template name | Verify prompt://ExactTemplateName (or the equivalent generatePromptResponse://ExactTemplateName) |
Empty promptResponse |
Template not published / active, or missing required inputs | Publish the template in Setup, check all is_required: True inputs are bound |
| Blank agent reply even though template ran | is_displayable: True on promptResponse |
Set is_displayable: False and let the planner synthesize the reply |
| Planner behaves like the prompt output is missing | Output is hidden but not planner-visible | Set is_used_by_planner: True on the output that should drive the reply or routing |
| Input not mapped | API name mismatch | Input field name after Input: must exactly match template's input API name |
invalid input/output parameters found |
Target template is in Draft status | Publish the template in Setup > Prompt Builder — see "Draft Template Publish Errors" above |
Internal Error with bare action definition |
Missing I/O blocks AND/OR Draft template | Add inputs:/outputs: blocks and ensure the template is published / active |
Checklist
- Template exists in org and is published / active (Draft templates cause misleading publish errors)
- Input field API names match template configuration exactly
- All
is_required: Trueinputs are bound (via...,@variables, or fixed) -
promptResponseoutput is captured withset -
promptResponseusesis_displayable: False+is_used_by_planner: Truewhen the planner should synthesize the reply - Template response quality tested with representative inputs
- If using grounded data: data provider returns expected records
Consolidated from repository prompt-template integration research and validated action configuration patterns.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Actions Reference
Migrated from the former
sf-ai-agentforce-legacy/references/actions-reference.mdon 2026-02-07. For context-aware descriptions, instruction references, and input binding patterns, see action-patterns.md. For prompt template actions (generatePromptResponse://), see action-prompt-templates.md.
Complete guide to Agent Actions in Agentforce: Flow, Apex, API actions, escalation routing, and GenAiFunction metadata.
Action Properties Reference
All actions in Agent Script support these properties:
Action Definition Properties
| Property | Type | Required | Description | TDD |
|---|---|---|---|---|
target |
String | Yes | Executable target (see Action Target Types below) | v1.3.0 |
description |
String | Yes | Explains behavior for LLM decision-making | v1.3.0 |
label |
String | No | Display name in UI (valid on action definitions, topics, and I/O fields) | v2.2.0 |
inputs |
Object | No | Input parameters and requirements | v1.3.0 |
outputs |
Object | No | Return parameters | v1.3.0 |
available_when |
Expression | No | Conditional availability for the LLM | v1.3.0 |
require_user_confirmation |
Boolean | No | Ask user to confirm before execution (compiles; runtime no-op per Issue 6) | v2.2.0 |
include_in_progress_indicator |
Boolean | No | Show progress indicator during execution | v2.2.0 |
progress_indicator_message |
String | No | Custom message shown during execution (e.g., "Processing your request...") | v2.2.0 |
Note:
label,require_user_confirmation,include_in_progress_indicator, andprogress_indicator_messageare valid on action definitions withtarget:but NOT on@utils.transitionutility actions (see Val_Action_Properties vs Val_Action_Meta_Props).
Input Properties
| Property | Type | Description | TDD |
|---|---|---|---|
description |
String | Explains the input parameter to LLM | v1.3.0 |
label |
String | Display name in UI | v2.2.0 |
is_required |
Boolean | Marks input as mandatory for the LLM | v2.2.0 |
is_user_input |
Boolean | LLM extracts value from conversation context | v2.2.0 |
complex_data_type_name |
String | Lightning data type mapping | v2.1.0 |
Output Properties
| Property | Type | Description | TDD |
|---|---|---|---|
description |
String | Explains the output parameter | v1.3.0 |
label |
String | Display name in UI | v2.2.0 |
filter_from_agent |
Boolean | True = hide from user display (GA standard name) |
v1.3.0 |
is_displayable |
Boolean | False = hide from user (compile-valid alias for filter_from_agent). Prefer this on prompt outputs when the planner still needs the value |
v2.2.0 |
is_used_by_planner |
Boolean | True = LLM can reason about this value for routing decisions |
v2.2.0 |
developer_name |
String | Overrides the parameter's developer name | — |
complex_data_type_name |
String | Lightning data type mapping | v2.1.0 |
filter_from_agentvsis_displayable: Both control the same behavior.filter_from_agent: Trueis the GA standard name (used in official documentation).is_displayable: Falseis a compile-valid alias that achieves the same result.
⚠️ Prompt-template exception: On
prompt:///generatePromptResponse://targets, preferis_displayable: False+is_used_by_planner: Truewhen the planner should synthesize the reply.is_displayable: Trueis a blank-response trap for prompt outputs.
⚠️
filter_from_agentandis_used_by_plannerare mutually exclusive: Do NOT use both on the same output field. The combination causesInvalidFormatErrorwhich invalidates the entire action definition, triggering cascadingACTION_NOT_IN_SCOPEerrors on every reference to that action. Usefilter_from_agent: Truealone to hide outputs from the customer. See known-issues.md Issue 40.
Output Access Follows the Output Schema
Do not assume @outputs.X is always a scalar.
# Scalar output
set @variables.status = @outputs.status
# Structured/wrapper output
set @variables.raw_result = @outputs.output
set @variables.result_text = @outputs.output.value # only if the schema exposes 'value'
Guidance:
- Direct assignment is safe for scalar outputs (
string,number,boolean). - If an action returns
objector another structured type, inspect the output schema before comparing or assigning it. .valueis a common wrapper field, but not a universal rule.- When a deterministic branch depends on the result, flatten the Flow/Apex output so the agent receives an explicit scalar.
Example with All Properties
actions:
process_payment:
description: "Processes payment for the order"
require_user_confirmation: True # Ask user before executing
include_in_progress_indicator: True
inputs:
amount: number
description: "Payment amount"
card_token: string
description: "Tokenized card number"
outputs:
transaction_id: string
description: "Transaction reference"
card_last_four: string
description: "Last 4 digits of card"
filter_from_agent: True # Hide from direct customer display
target: "flow://Process_Payment"
available_when: @variables.cart_total > 0
Action Target Types (Complete Reference)
AgentScript supports 22+ action target types. Use the correct protocol for your integration:
| Short Name | Long Name | Description | Use Case |
|---|---|---|---|
flow |
flow |
Salesforce Flow | Most common — Autolaunched Flows |
apex |
apex |
Apex Class | Custom business logic |
prompt |
generatePromptResponse |
Prompt Template | AI-generated responses |
standardInvocableAction |
standardInvocableAction |
Built-in Salesforce actions | Send email, create task, etc. |
externalService |
externalService |
External API via OpenAPI schema | External system calls |
quickAction |
quickAction |
Object-specific quick actions | Log call, create related record |
api |
api |
REST API calls | Direct API invocation |
apexRest |
apexRest |
Custom REST endpoints | Custom @RestResource classes |
serviceCatalog |
createCatalogItemRequest |
Service Catalog | Service catalog requests |
integrationProcedureAction |
executeIntegrationProcedure |
OmniStudio Integration | Industry Cloud procedures |
expressionSet |
runExpressionSet |
Expression calculations | Decision matrix, calculations |
cdpMlPrediction |
cdpMlPrediction |
CDP ML predictions | Data Cloud predictions |
externalConnector |
externalConnector |
External system connector | Pre-built connectors |
slack |
slack |
Slack integration | Slack messaging |
namedQuery |
namedQuery |
Predefined queries | Saved SOQL queries |
auraEnabled |
auraEnabled |
Lightning component methods | @AuraEnabled Apex methods |
mcpTool |
mcpTool |
Model Context Protocol | MCP tool integrations |
retriever |
retriever |
Knowledge retrieval | RAG/knowledge base queries |
Target Format: <type>://<DeveloperName> (e.g., flow://Get_Account_Info, standardInvocableAction://sendEmail)
💡
prompt://is the official shorthand forgeneratePromptResponse://. Both forms resolve to the same target.
Common Examples:
# Flow action (most common)
target: "flow://Get_Customer_Orders"
# Apex action
target: "apex://CustomerServiceController"
# Prompt template
target: "generatePromptResponse://Email_Draft_Template"
# Standard invocable action (built-in Salesforce)
target: "standardInvocableAction://sendEmail"
# External service (API call)
target: "externalService://Stripe_Payment_API"
Tip: Before creating a custom Flow, check if a standardInvocableAction:// already exists for your use case.
Pre-Publish Target Validation
Before sf agent publish, verify action targets exist and are active:
| Target Protocol | Validation Query |
|---|---|
flow://X |
SELECT ApiName FROM FlowDefinitionView WHERE ApiName = 'X' AND IsActive = true |
apex://X |
SELECT Name FROM ApexClass WHERE Name = 'X' |
retriever://X |
SELECT DeveloperName FROM DataCloudRetriever WHERE DeveloperName = 'X' |
externalService://X |
SELECT DeveloperName FROM ExternalServiceRegistration WHERE DeveloperName = 'X' |
generatePromptResponse://X |
SELECT DeveloperName FROM PromptTemplate WHERE DeveloperName = 'X' AND Status IN ('Active', 'Published') |
Run these via: sf data query -q "QUERY" -o ORG --json
Prompt template note: the queryable object name may still appear as
PromptTemplate, while the current source metadata type isGenAiPromptTemplate.
Direct Action Invocation (Debugging)
Test action targets outside the agent context via REST API:
- Flow:
POST /services/data/v66.0/actions/custom/flow/{FlowApiName} - Apex:
POST /services/data/v66.0/actions/custom/apex/{ClassName}
Useful for isolating whether failures are in the action target or the agent framework.
Action Invocation Methods
| Method | Syntax | Behavior | AiAuthoringBundle | GenAiPlannerBundle |
|---|---|---|---|---|
| Actions Block | actions: in reasoning: |
LLM chooses which to execute | ✅ Works | ✅ Works |
| Deterministic | run @actions.name |
Always executes when code path is reached if name resolves to a topic-level target-backed action definition |
⚠️ Partial (see below) | ✅ Works |
Deployment Method Capabilities
run keyword IS supported in reasoning.actions: post-action blocks and instructions: -> blocks (Validated Jan 2026)
# ✅ WORKS — run in reasoning.actions post-action block
create: @actions.create_order
with customer_id = @variables.customer_id
run @actions.send_confirmation # ✅ Chains after create_order
set @variables.order_id = @outputs.id
# ✅ WORKS — run in instructions: -> block
reasoning:
instructions: ->
run @actions.load_customer
with id = @variables.customer_id
set @variables.name = @outputs.name
# ❌ DOES NOT WORK — run in before_reasoning (no LLM context)
before_reasoning:
run @actions.log_turn # ❌ May not execute as expected
Note: The Dec 2025 finding that
runwas "NOT supported" has been superseded. As of Jan 2026,runworks in post-action chains and procedural instruction blocks when it targets a topic-level action definition withtarget:. It does NOT work reliably inbefore_reasoning:. Do not userunfor utilities / delegations (@utils.setVariables,@utils.transition,@topic.X) even if they are written under anactions:block — those are not deterministicruntargets.
{!@actions.name} interpolation in instructions (Updated Feb 2026)
The {!@actions.action_name} syntax embeds a reference to the full action definition into reasoning instructions. This gives the LLM richer context about available actions.
# ✅ WORKS — reference action in instructions for guided selection
reasoning:
instructions: ->
| To look up an order, use {!@actions.get_order}.
| To check shipping status, use {!@actions.track_shipment}.
Note: The Dec 2025 finding that this was broken has been superseded. See action-patterns.md for detailed usage patterns and examples.
Correct Approach: Use reasoning.actions Block
The LLM automatically selects appropriate actions from those defined in the reasoning.actions block:
topic order_management:
description: "Handles order inquiries"
actions:
get_order:
description: "Retrieves order information"
inputs:
order_id: string
description: "The order ID"
outputs:
status: string
description: "Order status"
target: "flow://Get_Order_Details"
reasoning:
instructions: ->
| Help the customer with their order.
| When they ask about an order, look it up.
actions:
# LLM automatically selects this when appropriate
lookup: @actions.get_order
with order_id=...
set @variables.order_status = @outputs.status
Action Type 1: Flow Actions
When to Use
- Standard Salesforce data operations (CRUD)
- Business logic that can be expressed in Flow
- Screen flows for guided user experiences
- Approval processes
Implementation
actions:
create_case:
description: "Creates a new support case for the customer"
inputs:
subject:
type: string
description: "Case subject line"
description:
type: string
description: "Detailed case description"
priority:
type: string
description: "Case priority (Low, Medium, High, Urgent)"
outputs:
caseNumber:
type: string
description: "Created case number"
caseId:
type: string
description: "Case record ID"
target: "flow://Create_Support_Case"
Flow Requirements
For an action to work with agents, the Flow must:
- Be Autolaunched —
processType: AutoLaunchedFlow - Have Input Variables — Marked as
isInput: true - Have Output Variables — Marked as
isOutput: true - Be Active —
status: Active
Flow Variable Example:
<variables>
<name>subject</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
Best Practices
| Practice | Description |
|---|---|
| Descriptive names | Use clear Flow API names that describe the action |
| Error handling | Include fault paths in your Flow |
| Bulkification | Design Flows to handle multiple records |
| Governor limits | Avoid SOQL/DML in loops |
Action Type 2: Apex Actions
When to Use
- Complex calculations or algorithms
- Custom integrations requiring Apex
- Operations not possible in Flow
- Bulk data processing
- When you need full control over execution
Two Deployment Paths (CRITICAL DISTINCTION)
| Deployment Method | How Apex Actions Work | GenAiFunction Required? |
|---|---|---|
| AiAuthoringBundle (.agent file) | apex://ClassName target in topic actions block |
NO |
| Agent Builder UI (GenAiPlannerBundle) | GenAiFunction metadata wraps the Apex class | YES |
⚠️ The official agent-script-recipes repo uses
apex://ClassNamedirectly with ZERO GenAiFunction metadata. GenAiFunction is only needed when configuring agents through the Agent Builder UI or deploying via GenAiPlannerBundle.
Path A: AiAuthoringBundle (Agent Script — RECOMMENDED)
Step 1: Create Apex Class with @InvocableMethod
public with sharing class CalculateDiscountAction {
public class DiscountRequest {
@InvocableVariable(label='Order Amount' required=true)
public Decimal orderAmount;
@InvocableVariable(label='Customer Tier' required=true)
public String customerTier;
}
public class DiscountResult {
@InvocableVariable(label='Discount Percentage')
public Decimal discountPercentage;
@InvocableVariable(label='Final Amount')
public Decimal finalAmount;
}
@InvocableMethod(
label='Calculate Discount'
description='Calculates discount based on order amount and customer tier'
)
public static List<DiscountResult> calculateDiscount(List<DiscountRequest> requests) {
List<DiscountResult> results = new List<DiscountResult>();
for (DiscountRequest req : requests) {
DiscountResult result = new DiscountResult();
result.discountPercentage = getTierDiscount(req.customerTier);
result.finalAmount = req.orderAmount * (1 - result.discountPercentage / 100);
results.add(result);
}
return results;
}
private static Decimal getTierDiscount(String tier) {
Map<String, Decimal> tierDiscounts = new Map<String, Decimal>{
'Bronze' => 5, 'Silver' => 10, 'Gold' => 15, 'Platinum' => 20
};
return tierDiscounts.containsKey(tier) ? tierDiscounts.get(tier) : 0;
}
}
Step 2: Reference DIRECTLY in Agent Script via apex://
topic discount_calculator:
description: "Calculates discount for customer order"
# Level 1: Action DEFINITION with target
actions:
calculate_discount:
description: "Calculates discount based on order amount and customer tier"
inputs:
orderAmount: number
description: "The total order amount before discount"
customerTier: string
description: "Customer membership tier"
outputs:
discountPercentage: number
description: "Applied discount percentage"
finalAmount: number
description: "Final order amount after discount"
target: "apex://CalculateDiscountAction" # Direct Apex — NO GenAiFunction needed!
reasoning:
instructions: |
Help the customer calculate their discount.
# Level 2: Action INVOCATION referencing the Level 1 definition
actions:
calc: @actions.calculate_discount
with orderAmount=...
with customerTier=@variables.tier
set @variables.final_amount = @outputs.finalAmount
✅ No GenAiFunction, no GenAiPlugin, no metadata deployment beyond the Apex class itself. The
apex://ClassNametarget auto-discovers the@InvocableMethodon the class.
I/O Name Matching Rules (TDD Validated v2.1.0)
Action inputs: and outputs: names in Agent Script must exactly match the @InvocableVariable field names in the Apex class:
| Agent Script I/O Name | Apex @InvocableVariable Field | Result |
|---|---|---|
orderAmount |
public Decimal orderAmount |
✅ Publishes |
order_amount |
public Decimal orderAmount |
❌ invalid input 'order_amount' |
wrong_name |
public String outputText |
❌ invalid output 'wrong_name' |
| (subset of outputs) | (declares fewer than all) | ✅ Publishes (partial is valid) |
Partial Output Pattern: You can declare a subset of the target's outputs in your action definition — you don't need to map every output parameter. This is useful when you only need one field from a multi-output action.
Bare @InvocableMethod Pattern (NOT Compatible)
⚠️ TDD Finding (v2.1.0): Apex classes using bare
List<String>parameters (no@InvocableVariablewrapper classes) are incompatible with Agent Script actions. The framework cannot discover bindable parameter names without@InvocableVariableannotations.
// ❌ INCOMPATIBLE with Agent Script — bare parameters, no wrappers
public class BareAction {
@InvocableMethod(label='Bare Action')
public static List<String> execute(List<String> inputs) {
return inputs;
}
}
// ✅ COMPATIBLE — wrapper classes with @InvocableVariable
public class WrappedAction {
public class Request {
@InvocableVariable(label='Input Text' required=true)
public String inputText; // ← This field name becomes the I/O name
}
public class Response {
@InvocableVariable(label='Output Text')
public String outputText; // ← This field name becomes the I/O name
}
@InvocableMethod(label='Wrapped Action')
public static List<Response> execute(List<Request> requests) { ... }
}
Rule: Always use @InvocableVariable wrapper classes when your Apex action will be called from Agent Script.
⚠️ Namespace Warning (Unresolved): In namespaced packages,
apex://ClassNamemay fail at publish time with "invocable action does not exist," even when the Apex class is confirmed deployed via SOQL. It is unclear whether namespace prefix syntax is required (e.g.,apex://ns__ClassName). If you encounter this in a namespaced org, try: (1)apex://ns__ClassNameformat, (2) wrapping the Apex in a Flow and usingflow://instead. See known-issues.md for tracking.
Path B: Agent Builder UI (GenAiPlannerBundle — Legacy)
If you're NOT using Agent Script and are building agents through the Agent Builder UI, you need GenAiFunction metadata to wrap the Apex class. See the assets/metadata/genai-function-apex.xml template for the XML format.
Note: GenAiFunction XML (API v66.0) only supports these elements:
masterLabel,description,invocationTarget,invocationTargetType,isConfirmationRequired. Input/output schemas are defined viainput/schema.jsonandoutput/schema.jsonbundle files, NOT inline XML elements.
Action Type 3: API Actions (External System Integration)
Architecture
┌─────────────────────────────────────────────────────────────┐
│ API ACTION ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ Agent Script │
│ │ │
│ ▼ │
│ flow://HTTP_Callout_Flow │
│ │ │
│ ▼ │
│ HTTP Callout Action (in Flow) │
│ │ │
│ ▼ │
│ Named Credential (Authentication) │
│ │ │
│ ▼ │
│ External API │
└─────────────────────────────────────────────────────────────┘
Implementation Steps
- Create Named Credential (via sf-integration skill)
- Create HTTP Callout Flow wrapping the external call
- Reference Flow in Agent Script with
flow://target
Security Considerations
| Consideration | Implementation |
|---|---|
| Authentication | Always use Named Credentials (never hardcode secrets) |
| Permissions | Use Permission Sets to grant Named Principal access |
| Error handling | Implement fault paths in Flow |
| Logging | Log callout details for debugging |
| Timeouts | Set appropriate timeout values |
Connection Block (Escalation Routing)
The connection block enables escalation to human agents via Omni-Channel. Use connection messaging: (singular). The plural connections: wrapper is invalid — see known-issues.md.
Basic Syntax
# Messaging channel (most common)
connection messaging:
outbound_route_type: "OmniChannelFlow"
outbound_route_name: "Support_Queue_Flow"
escalation_message: "Transferring you to a human agent..."
adaptive_response_allowed: True
Multiple Channels
⚠️ The plural
connections:wrapper block is invalid (see known-issues.md Issue 16). Use separateconnection <channel>:blocks:
# Each channel gets its own top-level connection block
connection messaging:
escalation_message: "Transferring to messaging agent..."
outbound_route_type: "OmniChannelFlow"
outbound_route_name: "flow://Agent_Support_Flow"
adaptive_response_allowed: True
Connection Block Properties
| Property | Type | Required | Description |
|---|---|---|---|
outbound_route_type |
String | Yes | "OmniChannelFlow" is the only TDD-validated value. SKILL.md mentions "Queue" and "Skill" but the connections: block itself is not GA (see known-issues.md Issue 16). |
outbound_route_name |
String | Yes | API name of Omni-Channel Flow (must exist in org) |
escalation_message |
String | Yes | Message shown to user during transfer |
adaptive_response_allowed |
Boolean | No | Allow agent to adapt responses during escalation (default: False) |
Supported Channels
| Channel | Description | Use Case |
|---|---|---|
messaging |
Chat/messaging channels | Enhanced Chat, Web Chat, In-App |
telephony |
Voice/phone channels | Service Cloud Voice, phone support |
CRITICAL: Values like "queue", "skill", "agent" for outbound_route_type cause validation errors!
Escalation Action
# AiAuthoringBundle - basic escalation
actions:
transfer_to_human: @utils.escalate
description: "Transfer to human agent"
# GenAiPlannerBundle - with reason parameter
actions:
transfer_to_human: @utils.escalate with reason="Customer requested"
Prerequisites for Escalation
- Omni-Channel configured in Salesforce
- Omni-Channel Flow created and deployed
- Connection block in agent script
- Messaging channel active (Enhanced Chat, etc.)
GenAiFunction Metadata Summary (Agent Builder UI / GenAiPlannerBundle ONLY)
⚠️ NOT needed for AiAuthoringBundle (Agent Script). If you're writing
.agentfiles, usetarget: "apex://ClassName"ortarget: "flow://FlowName"directly. See Action Type 2 above.
GenAiFunction wraps Apex, Flows, or Prompts as Agent Actions for the Agent Builder UI path.
<!-- Minimal valid GenAiFunction XML (API v66.0) -->
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<description>What this action does</description>
<invocationTarget>FlowOrApexName</invocationTarget>
<invocationTargetType>flow|apex|prompt</invocationTargetType>
<isConfirmationRequired>false</isConfirmationRequired>
<masterLabel>Display Name</masterLabel>
</GenAiFunction>
Input/Output Schemas: Use input/schema.json and output/schema.json files in the GenAiFunction bundle directory. Do NOT use inline XML elements like <genAiFunctionInputs>, <genAiFunctionOutputs>, <genAiFunctionParameters>, or <capability> — these are NOT valid in the Metadata API XML schema (API v66.0).
Prompt Builder Template Types
| Current metadata value | Typical use case |
|---|---|
einstein_gpt__flex |
General purpose, maximum flexibility |
einstein_gpt__salesEmail |
Sales-oriented generated content |
einstein_gpt__fieldCompletion |
Suggest field values |
einstein_gpt__recordSummary |
Summarize record data |
Template Variable Types
| Variable Type | Description |
|---|---|
freeText |
User-provided text input |
recordField |
Bound to specific record field |
relatedList |
Data from related records |
resource |
Static resource content |
Cross-Skill Integration
Orchestration Order for API Actions
When building agents with external API integrations, follow this order:
┌─────────────────────────────────────────────────────────────┐
│ INTEGRATION + AGENTFORCE ORCHESTRATION ORDER │
├─────────────────────────────────────────────────────────────┤
│ 1. sf-connected-apps → Connected App (if OAuth needed) │
│ 2. sf-integration → Named Credential + External Service │
│ 3. sf-apex → @InvocableMethod (if custom logic) │
│ 4. sf-flow → Flow wrapper (HTTP Callout / Apex) │
│ 5. sf-deploy → Deploy all metadata to org │
│ 6. sf-ai-agentscript → Agent with flow:// target │
│ 7. sf-deploy → Publish (sf agent publish │
│ authoring-bundle) │
└─────────────────────────────────────────────────────────────┘
Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
Tool target 'X' is not an action definition |
Action not defined in topic actions: block, or target doesn't exist in org |
Define action with target: in topic-level actions: block; ensure Apex class/Flow is deployed |
invalid input 'X' or invalid output 'X' |
I/O name doesn't match @InvocableVariable field name in Apex |
Use exact field names from the Apex wrapper class (case-sensitive) |
Internal Error with inputs-only action |
Action has inputs: but no outputs: block |
Add outputs: block — the server-side compiler requires it (see known-issues.md Issue 15) |
Internal Error with bare @InvocableMethod |
Apex uses List<String> without @InvocableVariable wrappers |
Refactor Apex to use wrapper classes with @InvocableVariable annotations |
apex:// target not found |
Apex class not deployed or missing @InvocableMethod |
Deploy class first, ensure it has @InvocableMethod annotation |
| Flow action fails | Flow not active or not Autolaunched | Activate the Flow; ensure it's Autolaunched (not Screen) |
| API action timeout | External system slow | Increase timeout, add retry logic |
| Permission denied | Missing Named Principal access | Grant Permission Set |
| Action not appearing in Agent Builder UI | GenAiFunction not deployed (UI path only) | Deploy GenAiFunction metadata (only needed for Agent Builder UI, not Agent Script) |
Debugging Tips
- Check deployment status:
sf project deploy report - Verify GenAiFunction deployment:
sf org list metadata -m GenAiFunction - Test Flow independently: Use Flow debugger in Setup with sample inputs
- Check agent logs: Agent Builder → Logs
Related Documentation
- action-patterns.md — Context-aware descriptions, instruction references, binding strategies
- action-prompt-templates.md — Prompt template invocation (
generatePromptResponse://) - fsm-architecture.md — FSM design and node patterns
Open this reference as its own page
Agent Script Activation Checklist
Use this file when sf-ai-agentscript is already active and you need the shortest possible pre-authoring / pre-publish checklist.
1. Route correctly
Use sf-ai-agentscript for:
.agentfiles- deterministic topic/state/action design
- Agent Script CLI workflows (
sf agent generate/publish)
Do not use it for:
- Setup UI / Agent Builder maintenance → use
sf-ai-agentforce - agent testing strategy → use
sf-ai-agentforce-testing - persona design → use
sf-ai-agentforce-persona
2. Blockers to check before editing
- Exactly one
start_agent - No mixed tabs and spaces
True/Falseonly- No
else if - No nested
if - No top-level
actions:block - No
@inputsinsideset - No default values on
linkedvariables - No
object/listlinked variables - Use explicit
agent_type - Use
run @actions.Xonly for topic-level action definitions that declaretarget: - Do not branch directly on raw
@system_variables.user_input contains/startswith/endswith - Do not treat
contains/startswith/endswithas the sole gate for critical routing or validation - On prompt template outputs, prefer
is_displayable: False+is_used_by_planner: True - Do not assume
@outputs.Xis scalar; inspect the output schema before comparing or assigning it
3. Service Agent publish safety
For AgentforceServiceAgent:
default_agent_usermust exist- user must be active
- user must not be
AutomatedProcess Profile.Namemust beEinstein Agent User- target-backed actions usually require a custom
{AgentName}_Accesspermission set
For AgentforceEmployeeAgent:
- omit
default_agent_user
Full details:
4. Minimal authoring workflow
- Define
config,system,start_agent, and topics - Add
variablesonly when state is needed - Define target-backed actions with complete
inputs:andoutputs: - Add deterministic guards with
available when - Validate on save
- Run preview smoke tests
- Publish, then activate
5. Canonical deep references
- Syntax rules: syntax-reference.md
- Actions and target protocols: actions-reference.md
- Production and runtime gotchas: production-gotchas.md
- Preview loop: preview-test-loop.md
- Debugging: debugging-guide.md
- Validator rules: validator-rule-catalog.md
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Agent User Setup & Permission Model
Complete provisioning workflow for Einstein Agent Users and permission sets. Validated against representative Service Agent and Employee Agent scenarios.
Preferred GA path: provision the Service Agent running user with
sf org create agent-user. Use manual user creation only when you need custom user fields or the command is unavailable in the target org/tooling version.
License Requirement: PID_DigitalAgent (typically included with Agentforce licenses)
Agent Type Decision Matrix
| Aspect | AgentforceServiceAgent | AgentforceEmployeeAgent |
|---|---|---|
| Use Case | Customer-facing, external users | Internal employees |
| Runs As | Dedicated Einstein Agent User | Logged-in user |
| Einstein Agent User? | Required | Not needed |
System PS (AgentforceServiceAgentBase, AgentforceServiceAgentUser, EinsteinGPTPromptTemplateUser) |
Required | Not needed |
Custom PS ({AgentName}_Access) |
Assigned to agent user | Assigned to employees |
default_agent_user in config |
Required | Omit entirely |
| Respects Sharing Rules | No (consistent permissions) | Yes (user's data access) |
| Preferred setup path | sf org create agent-user |
Permission-set visibility via <agentAccesses> |
How to check agent type: Look at the
agent_typefield in theconfig:block of your.agentfile, or query:sf data query --query "SELECT DeveloperName, Type FROM BotDefinition WHERE DeveloperName = 'AgentName'" -o TARGET_ORG --json
CLI Fast Track: Complete Workflow
Preferred CLI-first workflow (tested: ~8 minutes total):
# Step 1: Create the native Service Agent user
sf org create agent-user --target-org TARGET_ORG --json
# Optional: custom display name
sf org create agent-user \
--first-name Service \
--last-name Agent \
--target-org TARGET_ORG --json
# Optional: custom username base
sf org create agent-user \
--base-username service-agent@corp.com \
--target-org TARGET_ORG --json
# Step 2: Verify the native system assignments
sf data query \
--query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '<agent-username>' ORDER BY PermissionSet.Name" \
-o TARGET_ORG --json
# Expected: AgentforceServiceAgentBase + AgentforceServiceAgentUser + EinsteinGPTPromptTemplateUser
# Step 3: Deploy custom Permission Set for agent-specific Apex / data access
sf project deploy start \
--metadata PermissionSet:<AgentName>_Access \
-o TARGET_ORG --json
# Step 4: Assign custom Permission Set
sf org assign permset \
--name <AgentName>_Access \
--on-behalf-of <agent-username> \
-o TARGET_ORG --json
# If assignment fails, inspect the full JSON payload.
# Current CLI versions surface multiple assignment errors in --json output,
# which is much more useful than retrying blindly.
# Step 5: Verify all Permission Sets for the running user
sf data query \
--query "SELECT PermissionSet.Name, PermissionSet.Label FROM PermissionSetAssignment WHERE Assignee.Username = '<agent-username>' ORDER BY PermissionSet.Name" \
-o TARGET_ORG --json
# Expected: AgentforceServiceAgentBase + AgentforceServiceAgentUser + EinsteinGPTPromptTemplateUser + <AgentName>_Access
# Step 6: Set default_agent_user in the .agent config to the returned username
# Step 7: Validate and smoke-test before publish
sf agent validate authoring-bundle --api-name <AgentName> -o TARGET_ORG --json
SESSION_ID=$(sf agent preview start --authoring-bundle <AgentName> --simulate-actions -o TARGET_ORG --json | jq -r '.result.sessionId')
sf agent preview send --session-id "$SESSION_ID" --authoring-bundle <AgentName> --utterance "hello" -o TARGET_ORG --json
sf agent preview end --session-id "$SESSION_ID" --authoring-bundle <AgentName> -o TARGET_ORG --json
# Step 8: Publish and activate
sf agent publish authoring-bundle --api-name <AgentName> -o TARGET_ORG --json
sf agent activate --api-name <AgentName> --version <n> -o TARGET_ORG --json
Critical Notes:
sf org create agent-useris the preferred GA path for Service Agent running-user setup.- The native command auto-assigns the standard system profile and permission sets.
- Always test with preview BEFORE publishing to avoid version management overhead.
- Publishing does NOT activate — you must run
sf agent activateseparately.
Manual fallback (only if native agent-user creation can't be used)
Step 1: Create Einstein Agent User
Service agents need a dedicated service account with consistent permissions.
Get Org ID first (needed for username format):
sf org display -o TARGET_ORG --json | jq -r '.result.id'
Query existing Einstein Agent Users (skip creation if one exists):
sf data query --query "SELECT Id, Username, IsActive FROM User WHERE Profile.Name = 'Einstein Agent User' AND IsActive = true" -o TARGET_ORG --json
Create the user (if none exists):
Get the Einstein Agent User profile ID:
sf data query --query "SELECT Id FROM Profile WHERE Name = 'Einstein Agent User'" -o TARGET_ORG --jsonCreate a user definition file (
config/einstein-agent-user.json):{ "Username": "{agent_name}_agent@{orgId}.ext", "LastName": "{AgentName} Agent", "Email": "placeholder@example.com", "Alias": "agntuser", "ProfileId": "<profile-id-from-step-1>", "TimeZoneSidKey": "America/Los_Angeles", "LocaleSidKey": "en_US", "EmailEncodingKey": "UTF-8", "LanguageLocaleKey": "en_US", "UserPermissionsKnowledgeUser": true }Create the user:
Option A: Scratch Org (Definition File)
sf org create user \ --definition-file config/einstein-agent-user.json \ -o TARGET_ORGOption B: Production/Sandbox (Direct Record Creation)
# Get Profile ID first PROFILE_ID=$(sf data query \ --query "SELECT Id FROM Profile WHERE Name = 'Einstein Agent User'" \ -o TARGET_ORG --json | jq -r '.result.records[0].Id') # Create user directly sf data create record --sobject User --values \ "Username='{agent_name}_agent@{orgId}.ext' LastName='{AgentName} Agent' Email='placeholder@example.com' Alias='agntuser' ProfileId='${PROFILE_ID}' TimeZoneSidKey='America/Los_Angeles' LocaleSidKey='en_US' EmailEncodingKey='UTF-8' LanguageLocaleKey='en_US'" \ -o TARGET_ORG --jsonsf org create useronly works in scratch orgs. For production/sandbox, usesf data create record. Attemptingsf org create userin a non-scratch org fails with an authorization error.Verify creation:
sf data query --query "SELECT Id, Username, IsActive FROM User WHERE Username = '{agent_name}_agent@{orgId}.ext'" -o TARGET_ORG --json
Username format:
{agent_name}_agent@{orgId}.ext(production) or{agent_name}.{suffix}@{orgfarm}.salesforce.com(dev/scratch). Always query the target org to confirm the exact format.
Step 2: Assign Native System Permission Sets
CRITICAL: If you are not using sf org create agent-user, you must mirror the native system assignments BEFORE publishing the agent. Without them, publish or runtime execution can fail with generic errors.
Assign these system permission sets:
AgentforceServiceAgentBaseAgentforceServiceAgentUserEinsteinGPTPromptTemplateUser
Via Setup UI:
- Setup > Permission Sets > assign
AgentforceServiceAgentBase - Setup > Permission Sets > assign
AgentforceServiceAgentUser - Setup > Permission Sets > assign
EinsteinGPTPromptTemplateUser
Via CLI:
sf org assign permset --name AgentforceServiceAgentBase --on-behalf-of "{agent_name}_agent@{orgId}.ext" -o TARGET_ORG --json
sf org assign permset --name AgentforceServiceAgentUser --on-behalf-of "{agent_name}_agent@{orgId}.ext" -o TARGET_ORG --json
sf org assign permset --name EinsteinGPTPromptTemplateUser --on-behalf-of "{agent_name}_agent@{orgId}.ext" -o TARGET_ORG --json
Verify assignments:
sf data query --query "SELECT Id, PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '{agent_name}_agent@{orgId}.ext' AND PermissionSet.Name IN ('AgentforceServiceAgentBase', 'AgentforceServiceAgentUser', 'EinsteinGPTPromptTemplateUser')" -o TARGET_ORG --json
Step 3: Create Custom Permission Set for Apex Classes
The custom PS grants the agent user permission to execute your Apex invocable actions.
Naming convention: {AgentName}_Access (e.g., CustomerSupport_Access)
File: force-app/main/default/permissionsets/{AgentName}_Access.permissionset-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<description>Grants access to {AgentName} Agent Apex classes</description>
<hasActivationRequired>false</hasActivationRequired>
<label>{AgentName} Access</label>
<!-- Add one entry per Apex class the agent calls -->
<classAccesses>
<apexClass>YourApexClassName</apexClass>
<enabled>true</enabled>
</classAccesses>
<!-- Repeat for ALL Apex classes referenced via apex:// in agent script -->
</PermissionSet>
Key rule: Include EVERY Apex class referenced via apex:// in your agent script. Missing even one causes "invocable action does not exist" at runtime.
Deploy the permission set:
sf project deploy start --source-dir force-app/main/default/permissionsets/{AgentName}_Access.permissionset-meta.xml -o TARGET_ORG --json
Step 4: Assign Custom Permission Set to Agent User
Via CLI:
sf org assign permset --name {AgentName}_Access --on-behalf-of "{agent_name}_agent@{orgId}.ext" -o TARGET_ORG --json
Verify both permission sets are assigned:
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '{agent_name}_agent@{orgId}.ext'" -o TARGET_ORG --json
Expected output should include all of these:
AgentforceServiceAgentBase(system)AgentforceServiceAgentUser(system)EinsteinGPTPromptTemplateUser(system){AgentName}_Access(custom)
Step 5: Set default_agent_user in Agent Config
In your .agent file:
config:
developer_name: "AgentName"
description: "Your agent description"
agent_type: "AgentforceServiceAgent"
default_agent_user: "{agent_name}_agent@{orgId}.ext" # Service agents ONLY
Official docs may describe
default_agent_useras an API name or ID. In this skill, the standard operational path is to store the concrete username returned bysf org create agent-user, because that is the easiest value to verify in org queries and publish troubleshooting.
Before publishing, verify the actual user object — not just the username string:
sf data query --query "
SELECT Username, IsActive, UserType, Profile.Name
FROM User
WHERE Username = '{agent_name}_agent@{orgId}.ext'
LIMIT 1
" -o TARGET_ORG --json
A valid Service Agent user must satisfy all of these:
- user exists
IsActive = trueUserType != AutomatedProcessProfile.Name = 'Einstein Agent User'
This catches cases where sf agent validate passes but sf agent publish later fails because the configured user is missing, inactive, AutomatedProcess, or not on the Einstein Agent User profile.
Recommended native sequence:
sf agent validate authoring-bundle --api-name <AgentName> -o TARGET_ORG --json- Run the exact
sf data queryabove fordefault_agent_user - Smoke-test with
sf agent preview start/send/end - Publish with
sf agent publish authoring-bundle - If publish fails after validate + preview pass, retry with
--skip-retrieve
Step 6: Deploy, Test, Publish & Activate
Validated workflow pattern: Deploy as unpublished metadata, test with preview, then publish only when tests pass. This avoids version management overhead during iteration.
6.1: Deploy Agent Bundle (Unpublished)
sf project deploy start \
--source-dir force-app/main/default/aiAuthoringBundles/<AgentName> \
-o TARGET_ORG --json
This deploys the agent as unpublished metadata — you can edit freely without version management.
6.2: Test with Preview (Before Publishing)
SESSION_ID=$(sf agent preview start \
--authoring-bundle <AgentName> \
--use-live-actions \
-o TARGET_ORG --json | jq -r '.result.sessionId')
sf agent preview send \
--session-id "$SESSION_ID" \
--authoring-bundle <AgentName> \
--utterance "hello" \
-o TARGET_ORG --json
sf agent preview end \
--session-id "$SESSION_ID" \
--authoring-bundle <AgentName> \
-o TARGET_ORG --json
What to test:
- All topics trigger correctly
- All Apex actions execute without "Insufficient Privileges" errors
- Agent responds with expected data
- No compilation errors
If testing reveals problems, edit your agent script or Apex classes, redeploy, and test again — no publish required.
See preview-test-loop.md for the complete smoke test workflow with
jqtrace analysis recipes.
6.3: Publish Agent
Only publish after all tests pass.
# First try the standard publish path
sf agent publish authoring-bundle \
--api-name <AgentName> \
-o TARGET_ORG --json
# If that fails after validate/preview pass, retry without retrieve-back
sf agent publish authoring-bundle \
--api-name <AgentName> \
-o TARGET_ORG --skip-retrieve --json
Publishing does NOT activate. The new BotVersion is created as
Inactive. You must explicitly activate.Why
--skip-retrievematters: In org-backed testing, some publishes succeeded in the org but the CLI failed in the retrieve/deploy-back phase.--skip-retrieveisolates that tooling issue.
6.4: Activate Agent
# Manual activation
sf agent activate \
--api-name <AgentName> \
-o TARGET_ORG
# CI / deterministic activation of a known BotVersion
sf agent activate \
--api-name <AgentName> \
--version <n> \
-o TARGET_ORG --json
sf agent activatenow supports--json. If you use--jsonwithout--version, the CLI activates the latest agent version. Prefer--versionfor CI/CD and reproducible rollouts.
6.5: Verify Activation
sf data query \
--query "SELECT Id, DeveloperName, Status FROM BotVersion WHERE BotDefinition.DeveloperName = '<AgentName>' ORDER BY CreatedDate DESC LIMIT 1" \
-o TARGET_ORG --json
Expected: Status = 'Active'
After publish: Any further changes require version management. Test thoroughly before publishing.
Employee Agent Setup
Employee agents run as the logged-in user. The permission model is simpler.
What You DO NOT Need
- No Einstein Agent User creation
- No native Service Agent system permission sets (
AgentforceServiceAgentBase,AgentforceServiceAgentUser,EinsteinGPTPromptTemplateUser) - No
default_agent_userin agent config
What You DO Need
Custom permission set(s) assigned to employees who will use the agent.
Step 1: Create Custom Permission Set
Same XML template as Step 3 above. Include <classAccesses> for all Apex classes the agent calls.
Step 2: Assign to Employees
Assign the custom PS to employees (not to a service account):
sf org assign permset --name {AgentName}_Access --on-behalf-of "employee@company.com" -o TARGET_ORG --json
Or use Permission Set Groups for role-based access.
Step 3: Configure Agent Script (No default_agent_user)
config:
developer_name: "Employee_Agent"
description: "Internal employee assistant"
agent_type: "AgentforceEmployeeAgent"
# NO default_agent_user — agent runs as logged-in user
Step 4: Publish
sf agent publish authoring-bundle --api-name Employee_Agent -o TARGET_ORG --json
Common Mistakes with Employee Agents
| Mistake | Symptom | Fix |
|---|---|---|
Including default_agent_user |
HTTP 500 on publish | Remove the field entirely |
Omitting agent_type |
Defaults to Service Agent, then fails if no agent user | Set agent_type: "AgentforceEmployeeAgent" explicitly |
| Including Messaging-linked variables | Unnecessary bloat, may cause errors if Messaging not configured | Remove EndUserId, RoutableId, ContactId linked vars |
Including connection messaging: block |
Service Agent only -- causes errors for Employee Agent | Remove the entire connection block |
Including language: block |
Not required for Employee agents | Optional -- remove to keep minimal |
Auto-Generated Permission Set Warning
Salesforce auto-generates NextGen_{AgentName}_Permissions when an agent is published. Do NOT rely on this PS. It is often incomplete.
Representative example:
- Agent script referenced 4 Apex classes:
IdentityVerificationService,RiskScoringService,OrderLookupService,ShipmentTrackingService - Auto-generated
NextGen_Support_Agent_Permissionsonly included 3 classes (missingShipmentTrackingService) - Runtime error: "invocable action track_delivery does not exist"
- Fix: Created custom
Support_Agent_Accesswith all 4 classes — no errors
Best practice: Always create your own custom {AgentName}_Access PS with explicit <classAccesses> for every Apex class. Ignore the auto-generated PS.
End-to-End Verification Checklist
Run this combined query to verify all setup steps for a Service Agent:
# 1. Einstein Agent User exists and is active
sf data query --query "SELECT Id, Username, IsActive, Profile.Name FROM User WHERE Username = '{agent_name}_agent@{orgId}.ext'" -o TARGET_ORG --json
# 2. Native system PS assigned
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '{agent_name}_agent@{orgId}.ext' AND PermissionSet.Name IN ('AgentforceServiceAgentBase', 'AgentforceServiceAgentUser', 'EinsteinGPTPromptTemplateUser')" -o TARGET_ORG --json
# 3. Custom PS assigned
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '{agent_name}_agent@{orgId}.ext' AND PermissionSet.Name = '{AgentName}_Access'" -o TARGET_ORG --json
# 4. All permission sets for user (combined view)
sf data query --query "SELECT PermissionSet.Name, PermissionSet.Label FROM PermissionSetAssignment WHERE Assignee.Username = '{agent_name}_agent@{orgId}.ext'" -o TARGET_ORG --json
# 5. Agent config has default_agent_user
# Check your .agent file's config: block
# 6. Agent publishes successfully
sf agent publish authoring-bundle --api-name AgentName -o TARGET_ORG --json
Checklist:
- Einstein Agent User created and active (
IsActive = true) - Profile is "Einstein Agent User" (or "Minimum Access - Salesforce")
-
AgentforceServiceAgentBase,AgentforceServiceAgentUser, andEinsteinGPTPromptTemplateUsersystem PS assigned - Custom
{AgentName}_AccessPS deployed with ALL Apex classes - Custom PS assigned to the agent user
-
default_agent_userset in.agentconfig block - Agent tested with preview before publishing
- Agent publishes without error
- Agent activated (publish does NOT auto-activate)
Common Pitfalls (Validated)
1. "Internal Error" on First Publish
- Cause: Publishing before the native Service Agent system assignments are in place
- Prevention: Prefer
sf org create agent-user, or manually assign all Step 2 system permission sets before publishing (Step 6.3) - Result: First-time publish success (no retries needed)
2. "Insufficient Privileges" on Apex Actions
- Cause: Missing
<classAccesses>in custom permission set - Prevention: Custom PS template includes all Apex classes (Step 3)
- Result: All actions execute without permission errors
3. Testing After Publishing
- Cause: Publishing before testing, then needing version management for fixes
- Prevention: Deploy → Test → Publish workflow (Step 6.1-6.3)
- Result: No version management overhead during development
4. Wrong User Creation Command
- Cause: Using
sf org create userin non-scratch orgs - Prevention: Step 1 provides correct commands for each org type (Option A vs B)
- Result: User created successfully without authorization errors
5. Auto-Generated Permission Set Gaps
- Cause: Relying on
NextGen_{AgentName}_Permissions(often incomplete) - Prevention: Custom PS with explicit Apex access (Step 3)
- Result: All Apex classes accessible from the start
6. Forgot to Activate After Publish
- Cause: Assuming publish automatically activates
- Prevention: Step 6 splits publish and activate into separate steps with verification
- Result: Agent is both published AND activated
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
| "Internal Error" on publish | One or more native Service Agent system permission sets missing | Prefer sf org create agent-user, or assign Step 2 system PS manually, wait 2-3 min, retry publish |
| "Insufficient Privileges" at runtime | Custom PS missing or incomplete <classAccesses> |
Verify custom PS includes ALL Apex classes, redeploy + reassign |
| "invocable action does not exist" | Apex class not in custom PS (auto-generated PS incomplete) | Create custom {AgentName}_Access with all <classAccesses> (Step 3) |
| "Invalid default_agent_user" | Username typo or user not active | Query Einstein Agent Users, verify exact username + IsActive = true |
| Agent runs but returns wrong data | Employee agent using wrong user context | Verify agent_type — Service agents use dedicated user, Employee agents use logged-in user |
sf org create user fails |
Used in production/sandbox org | Use sf data create record instead (Step 1, Option B) |
| Native system behavior differs from local assumptions | Running user was created manually instead of with the native command | Re-check with sf org create agent-user --help and verify AgentforceServiceAgentBase, AgentforceServiceAgentUser, and EinsteinGPTPromptTemplateUser assignments |
Permission Set XML Template (Complete Example)
CustomerSupport agent (5 Apex classes):
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<description>Grants access to Automotive Support Agent Apex classes</description>
<hasActivationRequired>false</hasActivationRequired>
<label>Automotive Support Access</label>
<classAccesses>
<apexClass>VehicleLookupService</apexClass>
<enabled>true</enabled>
</classAccesses>
<classAccesses>
<apexClass>ErrorCodeDiagnosticsService</apexClass>
<enabled>true</enabled>
</classAccesses>
<classAccesses>
<apexClass>CheckEngineDiagnosticsService</apexClass>
<enabled>true</enabled>
</classAccesses>
<classAccesses>
<apexClass>BehaviorAnalysisService</apexClass>
<enabled>true</enabled>
</classAccesses>
<classAccesses>
<apexClass>ServiceSchedulerService</apexClass>
<enabled>true</enabled>
</classAccesses>
</PermissionSet>
Validated against representative Service Agent and Employee Agent scenarios. Last validated: 2026-03-07.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Architecture Patterns
Use these patterns when deciding how much should be deterministic, how much should be LLM-directed, and how to split work across topics.
Control Heuristic
- Start with the minimum deterministic control needed.
- Script only where “mostly right” is unacceptable.
- Keep high-variance conversation LLM-directed when possible.
- If the workflow has no real reasoning need, use Flow or Apex.
Pattern 0: Deterministic Sandwich
Apply hard control at the edges and leave the middle flexible.
gate / triage / auth → flexible worker topic(s) → deterministic closeout
Use when:
- auth or verification must happen first
- compliance text or closeout steps must always run
- the middle still benefits from flexible reasoning
Anti-pattern: scripting the whole conversation when only the edges need guarantees. If the middle is also fixed, use Flow or Apex.
Pattern 1: Hub and Spoke
Central router (hub) to specialized topics (spokes). Use for multi-purpose agents.
┌─────────────┐
│ router │
│ (hub) │
└──────┬──────┘
┌─────────┼─────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│refunds │ │ orders │ │support │
└────────┘ └────────┘ └────────┘
Use when: the first turn is mostly classification and each downstream topic owns a distinct capability.
Routing note: keep spoke descriptions semantically non-overlapping. If one utterance plausibly fits two spokes, merge, split, or rename them.
Pattern 2: Verification Gate
Security gate before protected topics. Mandatory for sensitive data.
┌─────────┐ ┌──────────┐ ┌───────────┐
│ entry │ ──▶ │ VERIFY │ ──▶ │ protected │
└─────────┘ │ (GATE) │ │ topics │
└────┬─────┘ └───────────┘
│ 3 fails
▼
┌──────────┐
│ lockout │
└──────────┘
Use when: account access, protected updates, regulated data, or irreversible actions require a hard precondition.
Pattern 3: Post-Action Loop
Topic re-resolves after action completes — put completion checks at the top.
topic refund:
reasoning:
instructions: ->
# POST-ACTION CHECK (at TOP - triggers on next loop)
if @variables.refund_status == "Approved":
run @actions.create_crm_case
transition to @topic.success
# PRE-LLM DATA LOADING
run @actions.check_churn_risk
set @variables.risk = @outputs.score
# DYNAMIC INSTRUCTIONS FOR LLM
if @variables.risk >= 80:
| Offer full refund to retain customer.
else:
| Offer $10 credit instead.
Use when: an action updates state and the next deterministic branch depends on that updated state.
Pattern 4: Staged Multi-Turn Workflow
When a workflow naturally spans multiple user turns, model each phase as its own topic instead of keeping a single topic with step = 1 / 2 / 3 flags.
variables:
lookup_id: mutable string = ""
lookup_result: mutable string = ""
topic collect_lookup_id:
description: "Collect the identifier needed for the lookup"
reasoning:
instructions: ->
if @variables.lookup_id == "":
| Ask the user for the identifier, then call {!@actions.save_lookup_id}.
else:
transition to @topic.run_lookup
actions:
save_lookup_id: @utils.setVariables
description: "Save the identifier for the next stage"
with lookup_id = ...
topic run_lookup:
description: "Run the lookup after the identifier is known"
reasoning:
instructions: ->
if @variables.lookup_result != "":
transition to @topic.present_lookup_result
run @actions.lookup_record
with lookup_id = @variables.lookup_id
set @variables.lookup_result = @outputs.result
topic present_lookup_result:
description: "Present the lookup result"
reasoning:
instructions: |
Share {!@variables.lookup_result} with the user.
Why this pattern is safer:
- user input capture stays LLM-directed
- deterministic work only runs after required state exists
- each turn boundary is explicit
- transitions are easier to debug than step counters
Anti-pattern to avoid: one large topic that increments a step variable and accidentally triggers step 2 in the same turn that finished step 1.
Pattern 5: Multi-Intent Orchestration
If a user can ask about more than one independent intent in the same utterance, decide the architecture based on the desired response style.
| Scenario | Recommended pattern |
|---|---|
| User may ask about several independent tasks in one message | Expose specialist topics/capabilities as delegated tools and let the orchestrator route between them |
| One business process spans multiple turns in sequence | Use staged topics with explicit transitions |
| Only the final stage should produce the user-facing answer | Use intermediate work topics, then transition to a final presentation topic |
Lightweight router example:
start_agent router:
description: "Route to the right specialist"
reasoning:
instructions: |
Determine which specialist capability is needed.
actions:
handle_shipping: @topic.shipping_status
description: "Handle shipping status questions"
handle_returns: @topic.returns
description: "Handle return questions"
handle_billing: @topic.billing
description: "Handle billing questions"
Guidance:
- For genuine multi-intent handling, prefer specialist tools/topics over building a queue string in one monolithic topic.
- For single-intent chained workflows, prefer
after_reasoningor explicit topic transitions. - If the orchestrator should not answer directly, let worker topics do the work and transition to one final response topic.
Quick Decision Guide
| Need | Prefer |
|---|---|
| Hard gating before sensitive actions | Verification Gate |
| Critical gate + flexible middle + must-run closeout | Deterministic Sandwich |
| Deterministic branch after action result | Post-Action Loop |
| Multi-turn data collection then deterministic execution | Staged Multi-Turn Workflow |
| Multiple specialist capabilities | Hub and Spoke |
| Several possible intents in one utterance | Multi-Intent Orchestration |
| Fully fixed workflow with no real reasoning need | Flow or Apex instead of full Agent Script |
Open this reference as its own page
Asset Validation Profiles
The assets/ directory intentionally mixes three kinds of .agent files:
- Standalone examples/templates — complete files that should validate as full agents.
- Org fixtures — structurally valid files that may block only because the currently resolved org is missing referenced users/Flows/classes.
- Partial snippets/patterns — reusable building blocks that intentionally omit top-level blocks or rely on surrounding context.
Because of that mix, a single "every .agent file must have 0 blocking findings" rule creates false failures.
Profile Manifest
Source of truth:
assets/validation-profiles.json
Validation harness:
scripts/validate-asset-profiles.py
How the Harness Works
The harness runs the main validator (hooks/scripts/agentscript-syntax-validator.py) against every assets/**/*.agent file, then checks the results against the profile manifest.
Profile types
1. standalone_examples
These are expected to be complete agents/templates.
Policy:
- No blocking findings allowed
- Only explicitly allowlisted warning IDs may appear
- Typical intentional warning classes here are template/demo reminders (
ASV-CFG-007) and teaching-pattern advisories such as planner-hint warnings (ASV-RUN-007)
2. org_fixtures
These are complete files, but the current local org may not contain all referenced metadata.
Policy:
- Only explicitly allowlisted org-dependent blocking IDs may appear
- Only explicitly allowlisted warning IDs may appear
- Current example:
ASV-ORG-007for missing outbound route Flows in the resolved org
3. partial_snippets
These are partial fragments or pattern files that are not intended to be published directly.
Policy:
- Only explicitly allowlisted completeness/snippet-related blocking IDs may appear
- Only explicitly allowlisted warning IDs may appear
- Any new unexpected blocker or warning still fails the harness
Run It
python3 skills/sf-ai-agentscript/scripts/validate-asset-profiles.py
Expected success shape:
Asset validation profile summary
-------------------------------
- standalone_examples: ...
- org_fixtures: ...
- partial_snippets: ...
✅ All asset files matched their configured validation profile expectations.
Why This Is Better Than Ignoring Failures
This profile-based approach keeps the validator strict without pretending every asset file is the same kind of artifact.
It gives us:
- strict validation for complete examples
- explicit documentation of intentional partials
- controlled tolerance for org-dependent fixtures
- failure on newly introduced unexpected blockers
- failure on newly introduced unexpected warnings that are not part of the file/profile's documented teaching intent
Maintenance Rules
When you add a new file under assets/:
- Decide whether it is a standalone example, org fixture, or partial snippet.
- Add it to
assets/validation-profiles.json. - If you allow blocking IDs or warning IDs for it, document why in the PR or commit.
- Re-run:
python3 skills/sf-ai-agentscript/scripts/validate-asset-profiles.py
If the harness fails, either:
- fix the asset, or
- update the profile manifest intentionally.
Do not silently broaden allowlists without explaining why.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Agent Script CLI Quick Reference
Pro-Code Lifecycle: Git, CI/CD, and CLI for Agent Development
The sf agent Commands
| Command | Purpose | Example |
|---|---|---|
sf project retrieve start |
Pull agent from org | sf project retrieve start --metadata Agent:MyAgent --target-org sandbox |
sf org create agent-user |
Create native Service Agent running user | sf org create agent-user --target-org TARGET_ORG --json |
sf agent validate authoring-bundle |
Check syntax before deploy | sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG |
sf agent publish authoring-bundle |
Publish agent to org | sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json |
sf agent test run |
Run batch tests | sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json |
sf agent create |
Create non-Agent Script agent from spec file (legacy / not default for this skill) | sf agent create --name "My Agent" --api-name MyAgent --spec agent-spec.yaml -o TARGET_ORG --json |
sf agent generate agent-spec |
Generate agent specification | sf agent generate agent-spec --type customer --role "Service Rep" --output-file agent-spec.yaml |
sf agent generate authoring-bundle |
Scaffold authoring bundle | sf agent generate authoring-bundle --no-spec --name "My Agent" -o TARGET_ORG --json |
sf agent activate |
Activate agent (make live) | sf agent activate --api-name MyAgent --version <n> -o TARGET_ORG --json |
sf agent deactivate |
Deactivate agent (take offline) | sf agent deactivate --api-name MyAgent -o TARGET_ORG --json |
sf agent preview start |
Start programmatic preview session | sf agent preview start --authoring-bundle MyAgent --simulate-actions -o TARGET_ORG --json (or --api-name MyAgent) |
sf agent preview send |
Send utterance to preview session | sf agent preview send --session-id <id> --authoring-bundle MyAgent --utterance "Hello" -o TARGET_ORG --json |
sf agent preview end |
End preview session | sf agent preview end --session-id <id> --authoring-bundle MyAgent -o TARGET_ORG --json |
sf org open agent |
Open Agent Builder in browser | sf org open agent --api-name MyAgent -o TARGET_ORG |
sf org open authoring-bundle |
Open Agentforce Studio list view | sf org open authoring-bundle -o TARGET_ORG |
⚠️ CRITICAL: Use
sf agent publish authoring-bundlefor Agent Script deployment, NOTsf project deploy start. The metadata API deploy will fail with "Required fields are missing: [BundleType]".Default workflow for this skill: edit or generate the
.agentbundle directly. Usesf agent generate agent-speconly when the user explicitly wants LLM-assisted topic ideation.ℹ️ Managed packaging note:
sf agent generate templatetargets Bot / BotVersion metadata and is not a packaging path for Agent Script.agentbundles. See known-issues.md for the current Agent Script packaging limitation.
Create Service Agent User (GA)
sf org create agent-user --target-org TARGET_ORG --json
sf org create agent-user --first-name Service --last-name Agent --target-org TARGET_ORG --json
sf org create agent-user --base-username service-agent@corp.com --target-org TARGET_ORG --json
The native command assigns the standard Service Agent profile and system permission sets automatically. Use the returned username as the default_agent_user value.
Authoring Bundle Structure
⚠️ CRITICAL NAMING CONVENTION: File must be named
AgentName.bundle-meta.xml, NOTAgentName.aiAuthoringBundle-meta.xml. The metadata API expects.bundle-meta.xmlsuffix.
force-app/main/default/aiAuthoringBundles/
└── MyAgent/
├── MyAgent.agent # Your Agent Script (REQUIRED)
└── MyAgent.bundle-meta.xml # Metadata XML (REQUIRED)
AgentName.bundle-meta.xml Content
<?xml version="1.0" encoding="UTF-8"?>
<AiAuthoringBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<bundleType>AGENT</bundleType>
</AiAuthoringBundle>
⚠️ COMMON ERROR: Using
<BundleType>(PascalCase) instead of<bundleType>(camelCase) will NOT cause errors, but the field name in the XML element isbundleType(lowercase b).
Bundle Naming Rules
| Component | Convention | Example |
|---|---|---|
| Folder name | PascalCase or snake_case | MyAgent/ or My_Agent/ |
| Agent script | Same as folder + .agent |
MyAgent.agent |
| Metadata XML | Same as folder + .bundle-meta.xml |
MyAgent.bundle-meta.xml |
Deployment Command (NOT sf project deploy!)
# ✅ CORRECT: Use sf agent publish authoring-bundle
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG
# ❌ WRONG: Do NOT use sf project deploy start
# This will fail with "Required fields are missing: [BundleType]"
Pro-Code Workflow
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1 Retrieve │ → │ 2 Edit │ → │ 3 Validate │ → │ 4 Deploy │
│ Pull agent │ │ CLI/editor │ │ Check syntax│ │ Push to prod│
│ from org │ │ + Claude │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
Step 1: Retrieve
# Retrieve from sandbox
sf project retrieve start --metadata Agent:MyAgent --target-org sandbox --json
⚠️ Flow Version Mismatch Warning:
sf project retrieve start --metadata Flow:FlowNameretrieves the latest Flow version, which may be Draft or Obsolete — NOT necessarily the active version. The Agent Script publisher validates action I/O against the active Flow version's inputs/outputs. If the latest version has different I/O than the active version (e.g., a renamed input parameter), your action definition will compile locally but fail on publish.How to verify the active Flow version's inputs:
# 1. Find the active version ID sf data query --query "SELECT ActiveVersionId, LatestVersionId FROM FlowDefinitionView WHERE ApiName = 'My_Flow_Name' LIMIT 1" -o TARGET_ORG --json # 2. If ActiveVersionId != LatestVersionId, inspect the active version: sf data query --query "SELECT Id, VersionNumber, Status FROM FlowVersionView WHERE FlowDefinitionViewId = 'DEFINITION_ID' AND Status = 'Active'" -o TARGET_ORG --jsonAlways define your action
inputs:/outputs:to match the active Flow version, not the latest retrieved metadata.
Step 2: Edit
# Edit the agent script
vim force-app/main/default/aiAuthoringBundles/MyAgent/MyAgent.agent
Step 3: Validate
# Validate authoring bundle syntax
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
Step 4: Publish
# Publish agent to org (4-step process: Validate → Publish → Retrieve → Deploy)
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# If publish fails AFTER validate/preview pass, retry without retrieve-back:
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --skip-retrieve --json
# Expected output:
# ✔ Validate Bundle ~1-2s
# ✔ Publish Agent ~8-10s
# ✔ Retrieve Metadata ~5-7s
# ✔ Deploy Metadata ~4-6s
⚠️ Do NOT use
sf project deploy start- it will fail with "Required fields are missing: [BundleType]"⚠️ Real-world failure split:
- If plain publish fails but
--skip-retrievesucceeds, the problem is usually the CLI retrieve/deploy-back phase, not Agent Script compilation.- If publish still fails even with
--skip-retrieve, suspectdefault_agent_userfirst.
Step 5: Activate
⚠️ Publishing does NOT activate. The new BotVersion is created as
Inactive. Tests, preview, and end users continue hitting the previously active version until you explicitly activate.
# Manual activation (choose interactively if you omit --version)
sf agent activate --api-name MyAgent -o TARGET_ORG
# CI / deterministic activation of a known BotVersion
sf agent activate --api-name MyAgent --version <n> -o TARGET_ORG --json
# Verify activation (optional)
sf data query --query "SELECT DeveloperName, VersionNumber, Status FROM BotVersion WHERE BotDefinition.DeveloperName = 'MyAgent' AND Status = 'Active' LIMIT 1" -o TARGET_ORG --json
ℹ️
sf agent activateandsf agent deactivatenow support--json. If you use--jsonwithout--version, the CLI activates the latest agent version. Prefer--versionfor CI/CD and reproducible rollouts.
Testing Commands
# Run agent tests (--api-name refers to an AiEvaluationDefinition, not the agent)
sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Validation Commands
# Validate authoring bundle syntax
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# Run tests against test definition
sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Common Validation / Publish Errors
| Error | Cause | Fix |
|---|---|---|
Internal Error, try again later during publish |
Often invalid default_agent_user for Service Agent |
Verify the user exists, is active, is NOT AutomatedProcess, and has Profile.Name = Einstein Agent User |
Plain publish fails, --skip-retrieve succeeds |
CLI retrieve/deploy-back phase failed after successful publish | Re-run sf agent publish authoring-bundle ... --skip-retrieve --json |
SyntaxError: You cannot mix spaces and tabs |
Mixed indentation | Use consistent spacing |
Transition to undefined topic "@topic.X" |
Typo in topic name | Check spelling |
Variables cannot be both mutable AND linked |
Conflicting modifiers | Choose one modifier |
Einstein Agent User Setup (Service Agents Only)
This section applies to
AgentforceServiceAgentonly.AgentforceEmployeeAgentdoes NOT need an Einstein Agent User — it runs as the logged-in user. See agent-user-setup.md for the full provisioning workflow, CLI Fast Track, and Deploy → Test → Publish pattern.
Query Existing Users
sf data query --query "SELECT Id, Username, IsActive FROM User WHERE Profile.Name = 'Einstein Agent User' AND IsActive = true" -o TARGET_ORG --json
Native Pre-Publish Check (Recommended)
sf data query --query "
SELECT Username, IsActive, UserType, Profile.Name
FROM User
WHERE Username = 'prontorefund_agent@00Dxxxx.ext'
LIMIT 1
" -o TARGET_ORG --json
Use this native CLI check before publish for Service Agents. A passing result must show:
- a matching user record
IsActive = trueUserType != AutomatedProcessProfile.Name = 'Einstein Agent User'
This covers the most common real-world publish failure: a default_agent_user value that passes sf agent validate but fails sf agent publish because the user is missing, inactive, AutomatedProcess, or not on the Einstein Agent User profile.
Native Pre-Publish Workflow
Use this exact sequence for production-safe Service Agent publishes:
# 1. Static validation
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# 2. Verify the exact default_agent_user from the .agent config
sf data query --query "
SELECT Username, IsActive, UserType, Profile.Name
FROM User
WHERE Username = 'myagent_agent@00Dxxxx.ext'
LIMIT 1
" -o TARGET_ORG --json
# 3. Smoke-test the authoring bundle (authoring bundles now require an explicit mode)
SESSION_ID=$(sf agent preview start --authoring-bundle MyAgent --simulate-actions -o TARGET_ORG --json | jq -r '.result.sessionId')
sf agent preview send --session-id "$SESSION_ID" --authoring-bundle MyAgent --utterance "hello" -o TARGET_ORG --json
sf agent preview end --session-id "$SESSION_ID" --authoring-bundle MyAgent -o TARGET_ORG --json
# 4. Publish
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# 5. If plain publish fails after validate + preview pass, retry:
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --skip-retrieve --json
Interpretation:
- Plain publish fails,
--skip-retrieveworks → retrieve/deploy-back phase issue in the CLI path - Both publish commands fail → inspect
default_agent_user, action I/O, and other server-side publish constraints
Create Einstein Agent User
Option A: Scratch Org (definition file):
sf org create user --definition-file config/einstein-agent-user.json -o TARGET_ORG
Option B: Production/Sandbox (direct record creation):
PROFILE_ID=$(sf data query \
--query "SELECT Id FROM Profile WHERE Name = 'Einstein Agent User'" \
-o TARGET_ORG --json | jq -r '.result.records[0].Id')
sf data create record --sobject User --values \
"Username='{agent_name}_agent@{orgId}.ext' LastName='{AgentName} Agent' Email='placeholder@example.com' Alias='agntuser' ProfileId='${PROFILE_ID}' TimeZoneSidKey='America/Los_Angeles' LocaleSidKey='en_US' EmailEncodingKey='UTF-8' LanguageLocaleKey='en_US'" \
-o TARGET_ORG --json
sf org create useronly works in scratch orgs. For production/sandbox, usesf data create record.
Username Format
{agent_name}_agent@<org-id>.ext
Example: automotive_agent@00dkd00000g7lv7.ext
Get Org ID
sf org display -o TARGET_ORG --json | jq -r '.result.id'
Verify Permission Set Assignments
Both the system PS and custom PS must be assigned to the Einstein Agent User:
# Check system PS
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '<agent-username>' AND PermissionSet.Name = 'AgentforceServiceAgentUser'" -o TARGET_ORG --json
# Check custom PS
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '<agent-username>' AND PermissionSet.Name = '{AgentName}_Access'" -o TARGET_ORG --json
# All assigned PSs
sf data query --query "SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE Assignee.Username = '<agent-username>'" -o TARGET_ORG --json
Recommended Workflow: Deploy → Test → Publish
After user setup and permissions are configured, follow this order to avoid version management overhead:
- Deploy agent bundle as unpublished metadata
- Test with
sf agent preview start— verify topics and actions - Publish only after tests pass —
sf agent publish authoring-bundle - Activate separately —
sf agent activate(publish does NOT auto-activate)
See agent-user-setup.md Step 6 for the full workflow with CLI commands.
CI/CD Integration
GitHub Actions Example — 4-Step Deployment Pipeline
name: Agent Deploy & Test
on: [push, pull_request]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Step 1: Deploy supporting metadata (Flows, Apex, Objects)
- name: Deploy Supporting Metadata
run: sf project deploy start --source-dir force-app -o TARGET_ORG --json
# Step 2: Validate agent bundle syntax
- name: Validate Agent Bundle
run: sf agent validate authoring-bundle --api-name My_Agent -o TARGET_ORG --json
# Step 3: Publish agent (4-step atomic: validate -> publish -> retrieve -> deploy)
- name: Publish Agent
run: sf agent publish authoring-bundle --api-name My_Agent -o TARGET_ORG --json
# Step 4: Activate the published version
- name: Activate Agent
run: sf agent activate --api-name My_Agent --version "$AGENT_VERSION" -o TARGET_ORG --json
# Optional: Run agent tests after activation
- name: Run Agent Tests
run: sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Set AGENT_VERSION in the workflow environment to the BotVersion number you intend to activate.
SF Agent CLI Error Codes (current high-signal set)
Use sf <command> --help for the full command-specific list. The most relevant current codes are:
| Command | Codes to expect | What they mean |
|---|---|---|
sf agent validate authoring-bundle |
0, 1, 2, 3 |
Succeeded, Failed (compilation errors), NotFound, ServerError |
sf agent publish authoring-bundle |
aligns with validate for compilation failures | publish now uses the same compilation-related codes as validate when Agent Script compilation fails |
sf agent preview start |
0, 1, 2, 3, 4 |
Succeeded, Failed, NotFound, ServerError, PreviewStartFailed |
sf agent preview send |
0, 2, 4, 5 |
Succeeded, NotFound, PreviewSendFailed, SessionAmbiguous |
sf agent preview end |
0, 2, 4, 5 |
Succeeded, NotFound, PreviewEndFailed, SessionAmbiguous |
CI/CD guidance:
- block immediately on
1+for validate / publish - if preview returns
SessionAmbiguous (5), runsf agent preview sessions --json, pick the right session, and retry with--session-id
Deployment Pipeline
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Sandbox │ ───▶ │ Staging │ ───▶ │ Production │
│ v1.3.0 │ │ Validate │ │ v1.3.0 │
└─────────────┘ └─────────────┘ └─────────────┘
6-Step Pipeline
- Retrieve from Sandbox - Pull latest agent bundle
- Validate Syntax - Check Agent Script for errors
- Run Tests - Execute automated agent tests
- Code Review - Automated best practices checks
- Deploy to Production - Push validated bundle
- Verify Deployment - Confirm agent is active
Agent Creation Commands
Create Agent from Spec File
# Generate an agent specification YAML first
sf agent generate agent-spec \
--type customer \
--role "Customer Service Representative" \
--company-name "Acme Corp" \
--company-description "E-commerce platform" \
--output-file agent-spec.yaml
# Create the agent from the spec
sf agent create \
--name "My Service Agent" \
--api-name MyServiceAgent \
--spec agent-spec.yaml \
-o TARGET_ORG --json
Managed Packaging Status
sf agent generate template is not an Agent Script packaging workflow.
The current CLI command targets Bot / BotVersion metadata, requires a .bot-meta.xml file plus --source-org, and doesn't package .agent authoring bundles.
For Agent Script agents today:
- use source-driven deployment (
sf agent publish authoring-bundle) for org rollout - treat managed-package templating as unsupported for
.agentbundles - see known-issues.md for the current packaging limitation
Programmatic Preview (Non-Interactive)
⛔ NEVER run bare
sf agent preview— it launches an interactive terminal requiring keyboard input. Claude Code CANNOT use it. ALWAYS use subcommands:start,send,endwith--json.
# 1. Start a published-agent preview session
# Published agents always use live actions.
SESSION_ID=$(sf agent preview start --api-name MyAgent -o TARGET_ORG --json | jq -r '.result.sessionId')
# 2. Send utterances programmatically
sf agent preview send --session-id $SESSION_ID --api-name MyAgent --utterance "I need a refund" -o TARGET_ORG --json
# 3. Send follow-up messages
sf agent preview send --session-id $SESSION_ID --api-name MyAgent --utterance "Order #12345" -o TARGET_ORG --json
# 4. End the session
sf agent preview end --session-id $SESSION_ID --api-name MyAgent -o TARGET_ORG --json
# List cached preview sessions (no target-org flag)
sf agent preview sessions --json
Preview Modes
| Target | Required flags | Behavior |
|---|---|---|
Published agent (--api-name) |
none | programmatic preview always uses live actions |
Authoring bundle (--authoring-bundle) |
exactly one of --simulate-actions or --use-live-actions |
choose simulated vs real-action execution explicitly |
Additional preview flags:
| Flag | Purpose |
|---|---|
--simulate-actions |
Use AI to simulate action execution. Required with --authoring-bundle when you want simulated mode. |
--use-live-actions |
Execute real Apex/Flows/Prompt Templates. Required with --authoring-bundle when you want live mode. |
--authoring-bundle |
Preview the local authoring bundle instead of a published Bot. |
--api-name |
Preview an activated published agent. |
# Authoring-bundle preview in simulated mode
SESSION_ID=$(sf agent preview start --authoring-bundle MyBundle --simulate-actions -o TARGET_ORG --json | jq -r '.result.sessionId')
sf agent preview send --session-id $SESSION_ID --authoring-bundle MyBundle --utterance "What can you help me with?" -o TARGET_ORG --json
sf agent preview end --session-id $SESSION_ID --authoring-bundle MyBundle -o TARGET_ORG --json
# Authoring-bundle preview in live mode
SESSION_ID=$(sf agent preview start --authoring-bundle MyBundle --use-live-actions -o TARGET_ORG --json | jq -r '.result.sessionId')
If preview send or preview end returns SessionAmbiguous (5), run sf agent preview sessions --json and retry with the explicit --session-id.
Activate / Deactivate Agent
After publishing, activate the agent to make it live. Deactivate before re-publishing updates.
# Activate agent manually (interactive version selection if omitted)
sf agent activate --api-name MyAgent -o TARGET_ORG
# Activate a specific BotVersion in CI / automation
sf agent activate --api-name MyAgent --version <n> -o TARGET_ORG --json
# Deactivate agent (takes it offline — required before re-publishing)
sf agent deactivate --api-name MyAgent -o TARGET_ORG --json
Deterministic activation in CI
--version <n>maps to thevNsuffix of the agent'sBotVersionmetadata.- If you omit
--version, the CLI prompts you to choose a version interactively. - If you use
--jsonwithout--version, the CLI activates the latest agent version. - For reproducible pipelines, pass the exact
--versionyou intend to activate.
Verify activation status:
sf data query --query "SELECT DeveloperName, VersionNumber, Status FROM BotVersion WHERE BotDefinition.DeveloperName = 'MyAgent' AND Status = 'Active' LIMIT 1" -o TARGET_ORG --json
Full update lifecycle: Deactivate → Re-publish → Re-activate
# Update an already-active agent:
sf agent deactivate --api-name MyAgent -o TARGET_ORG --json
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG --json
sf agent activate --api-name MyAgent --version <n> -o TARGET_ORG --json
Generate Authoring Bundle (--no-spec)
The --no-spec flag skips requiring an agent spec YAML file and uses default Agent Script boilerplate:
v2.126.4 change: When
--jsonis specified,--nameis now required. The CLI no longer prompts interactively for missing flags in JSON mode — it errors instead. Always include--namewhen scripting with--json.
# Scaffold a new authoring bundle without an agent spec
sf agent generate authoring-bundle --no-spec --name "My Agent" -o TARGET_ORG --json
# With a spec file (standard flow)
sf agent generate authoring-bundle --spec agent-spec.yaml --name "My Agent" -o TARGET_ORG --json
# Overwrite existing bundle without confirmation (v2.125.1+)
sf agent generate authoring-bundle --spec agent-spec.yaml --name "My Agent" --force-overwrite -o TARGET_ORG --json
Generate Agent Spec — Full Flag Reference
Optional path only. In this repository, direct
.agentauthoring is the default path; spec generation is a bootstrap aid, not the primary authoring workflow.
| Flag | Values / Type | Description |
|---|---|---|
--type |
customer | internal |
Required. Agent audience type |
--role |
string | Required. Agent's role description |
--company-name |
string | Company name for context |
--company-description |
string | Company description for context |
--company-website |
URL | Company website URL for grounding |
--tone |
formal | casual | neutral |
Conversational style |
--enrich-logs |
true | false |
Add agent conversation data to event logs |
--max-topics |
number | Maximum topics to generate (default: 5) |
--agent-user |
username | Einstein Agent User to assign |
--output-file |
path | Output path (default: specs/agentSpec.yaml) |
--full-interview |
(flag) | Prompt for both required AND optional flags |
--spec |
file path | Use existing spec for iterative refinement |
--prompt-template |
API name | Custom prompt template reference |
--grounding-context |
string | Context value for custom prompt template |
--force-overwrite |
(flag) | Overwrite existing spec without confirmation |
# Full example with optional flags
sf agent generate agent-spec \
--type customer \
--role "Customer Service Representative" \
--company-name "Acme Corp" \
--company-description "E-commerce platform" \
--company-website "https://acme.example.com" \
--tone formal \
--enrich-logs true \
--max-topics 8 \
--agent-user "agent_user@00dxx000001234.ext" \
--output-file specs/my-agent-spec.yaml
# Iterative refinement — feed existing spec back in
sf agent generate agent-spec \
--spec specs/my-agent-spec.yaml \
--max-topics 3 \
--tone casual \
--force-overwrite
Browser Quick-Open Commands
# Open specific agent in Agentforce Builder
sf org open agent --api-name MyAgent -o TARGET_ORG
# Open Agentforce Studio (list view of all authoring bundles)
sf org open authoring-bundle -o TARGET_ORG
# Get URL only (for CI/CD logs or scripts)
sf org open agent --api-name MyAgent -o TARGET_ORG --url-only
<a id="three-phase-lifecycle"></a>
Three-Phase Lifecycle
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ ✏️ Draft │ → │ 🔒 Commit │ → │ ✅ Activate │
│ EDITABLE │ │ READ-ONLY │ │ LIVE │
└─────────────┘ └─────────────┘ └─────────────┘
| Phase | Capabilities |
|---|---|
| Draft | Edit freely, preview, run batch tests |
| Commit | Script frozen, version assigned, bundle compiled |
| Activate | Assign to Connections, go live, monitor |
Key Insight: Commit doesn't deploy - it freezes. Activate makes it live.
API Versioning Behavior
Agent versions share the same agentId (the BotDefinition / Agent record) but have distinct version IDs.
| Concept | Description |
|---|---|
agentId / BotDefinition.Id |
Unique per agent — does NOT change between versions |
versionId / BotVersion.Id |
Unique per version — changes with each commit |
| Default API behavior | API calls target the active version unless a specific versionId is provided |
# The Agent Runtime API defaults to the active version:
curl -X POST ".../einstein/ai-agent/v1" \
-d '{"agentDefinitionId": "0XxXXXXXXXXXXX"}' # Uses active version
# To target a specific version (draft/committed), include versionId:
curl -X POST ".../einstein/ai-agent/v1" \
-d '{"agentDefinitionId": "0XxXXXXXXXXXXX", "agentVersionId": "4KdXXXXXXXXXXX"}'
Key implication: When testing draft versions via API, you must explicitly pass the version ID. Otherwise, the API will use the last activated version — which may not reflect your latest changes.
⛔ CLI Anti-Patterns
DO NOT SOQL query metadata types
These are metadata types, NOT sObjects. SOQL queries against them return INVALID_TYPE.
| Type | ❌ WRONG (SOQL) | ✅ CORRECT (Metadata API) |
|---|---|---|
| GenAiPlannerBundle | SELECT ... FROM GenAiPlannerBundle |
sf project retrieve start --metadata "GenAiPlannerBundle:Name" |
| AiAuthoringBundle | SELECT ... FROM AiAuthoringBundle |
sf project retrieve start --metadata "AiAuthoringBundle:Name" |
| GenAiFunction | SELECT ... FROM GenAiFunction |
sf project retrieve start --metadata "GenAiFunction:Name" |
For SOQL, query
BotDefinitionandBotVersioninstead — these ARE sObjects.
BotDefinition vs BotVersion field reference
| Field | BotDefinition | BotVersion |
|---|---|---|
| Id, DeveloperName | ✅ | ✅ |
| MasterLabel | ✅ | ❌ |
| Status | ❌ | ✅ |
| VersionNumber | ❌ | ✅ |
⚠️
Statuslives onBotVersion, NOTBotDefinition. QueryingBotDefinition.Statusreturns "No such column."
DO NOT run bare sf agent preview
| ❌ WRONG (interactive, hangs) | ✅ CORRECT (programmatic) |
|---|---|
sf agent preview |
sf agent preview start --authoring-bundle MyAgent --simulate-actions -o TARGET_ORG --json |
| (waits for keyboard input) | sf agent preview send --session-id $ID --authoring-bundle MyAgent --utterance "..." -o TARGET_ORG --json |
sf agent preview end --session-id $ID --authoring-bundle MyAgent -o TARGET_ORG --json |
DO NOT pass context variables via sf agent preview
⛔
sf agent previewdoes NOT support context or session variable injection. There are no--context,--session-var, or--variablesflags.
| Variable Source | Works in Preview? | Alternative |
|---|---|---|
@session.sessionID |
❌ | Agent Runtime API with session context |
@context.customerId |
❌ | Agent Runtime API with contextVariables |
@context.RoutableId |
❌ | Agent Runtime API with contextVariables |
| Mutable vars (defaults) | ✅ | Works normally via default values |
with param=... (slot-filling) |
✅ | Works normally via LLM extraction |
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->complex_data_type_name Mapping Table
"#1 source of compile errors" - Use this table when defining action inputs/outputs in Agentforce Assets.
| Data Type | complex_data_type_name Value |
Notes |
|---|---|---|
string |
(none needed) | Primitive type |
number |
(none needed) | Primitive type — variables only† |
boolean |
(none needed) | Primitive type |
object (SObject) |
lightning__recordInfoType |
Use for Account, Contact, etc. |
list[string] |
lightning__textType |
Collection of text values |
list[object] (JSON text) |
lightning__textType |
Serialized as JSON text |
list[object] (SObject collection) |
lightning__recordInfoType |
USE THIS for Flow SObject outputs |
| Apex Inner Class | @apexClassType/NamespacedClass__InnerClass |
Namespace required |
| Custom LWC Type | lightning__c__CustomTypeName |
Custom component types |
| Currency field | lightning__currencyType |
For monetary values |
datetime |
lightning__dateTimeStringType |
DateTime values (TDD v2.1.0) |
integer |
lightning__integerType |
Integer numbers (action I/O only) |
double / number |
lightning__doubleType |
Decimal/floating-point numbers (action I/O only) |
object (structured) |
lightning__objectType |
Complex data structures (action I/O only) |
list (generic) |
lightning__listType |
Arrays/lists (action I/O only) |
† WARNING: #1 Publish Error Source — Bare
numberworks invariables:declarations but FAILS at publish in actioninputs:/outputs:. For action I/O, you MUST use:
- Integer values →
lightning__integerType- Decimal values →
lightning__doubleType
Naming variance: Upstream documentation uses
lightning__dateTimeTypewhile our TDD-validated testing confirmslightning__dateTimeStringType. Both may be valid depending on API version — uselightning__dateTimeStringTypeas the tested default.
Agent Script → Lightning Type Mapping (TDD Validated v2.1.0)
Use this when troubleshooting type errors between Agent Script action I/O and Apex/Flow targets.
| Agent Script Type | Lightning Type | Apex Type | Notes |
|---|---|---|---|
string |
lightning__textType |
String |
No complex_data_type_name needed |
number |
lightning__numberType |
Decimal / Double |
No complex_data_type_name needed |
boolean |
lightning__booleanType |
Boolean |
No complex_data_type_name needed |
datetime |
lightning__dateTimeStringType |
DateTime |
Actions only — not valid for variables |
date |
lightning__dateType |
Date |
Valid for both variables and actions |
currency |
lightning__currencyType |
Decimal |
Annotated with currency type |
Flow Type -> Agent Script Mapping (Production-Validated)
When defining action I/O for
flow://targets, use this table to map Flow variable types to Agent Script declarations.
| Flow Type | Agent Script Type | complex_data_type_name |
Notes |
|---|---|---|---|
String |
string |
(none needed) | Or lightning__textType (optional) |
Date |
object |
lightning__dateType |
Must use object, not date |
DateTime |
object |
lightning__dateTimeStringType |
NOT lightning__dateTimeType |
Boolean |
boolean |
(none needed) | Primitive type |
SObject collection |
list[object] |
lightning__recordInfoType |
NOT lightning__objectType |
Common Mistake: Using
lightning__textTypefor SObject collection outputs. The publisher accepts it but the LLM receives serialized JSON text instead of structured records, breaking field access patterns.
Pro Tip: Don't manually edit complex_data_type_name - use the UI dropdown in Agentforce Assets > Action Definition, then export/import the action definition.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Phase 5.5: CustomerWebClient Surface Enablement
⚠️ Without
CustomerWebClientsurface, Agent Builder Preview shows "Something went wrong" and Agent Runtime API / CLI testing returns500 Internal Server Error.
The Problem: connection messaging: in the .agent file ONLY generates a Messaging plannerSurface during compilation. There is NO connection customerwebclient: DSL syntax — attempting it causes ERROR_HTTP_404 on publish. Agent Builder Preview + CLI testing require CustomerWebClient, which must be manually patched after every publish.
Post-Publish Patch Workflow (6 steps, required after EVERY publish)
# Step 1: Publish the agent (creates new version, e.g., v22)
sf agent publish authoring-bundle --api-name AgentName -o TARGET_ORG --json
# Step 2: Retrieve the compiled GenAiPlannerBundle
sf project retrieve start --metadata "GenAiPlannerBundle:AgentName_vNN" -o TARGET_ORG --json
# Step 3: Add CustomerWebClient plannerSurface to the XML (see template below)
# Step 4: Deactivate agent (deploy fails while active)
sf agent deactivate --api-name AgentName -o TARGET_ORG --json
# Step 5: Deploy patched bundle
sf project deploy start --metadata "GenAiPlannerBundle:AgentName_vNN" -o TARGET_ORG --json
# Step 6: Reactivate the same BotVersion created in Step 1
sf agent activate --api-name AgentName --version NN -o TARGET_ORG --json
Use the same
NNvalue from theGenAiPlannerBundle:AgentName_vNNversion you just patched so the reactivation is deterministic.
Step 3 — XML patch template
Add after existing Messaging plannerSurfaces block:
<!-- Add this SECOND plannerSurfaces block for CustomerWebClient -->
<plannerSurfaces>
<adaptiveResponseAllowed>false</adaptiveResponseAllowed>
<callRecordingAllowed>false</callRecordingAllowed>
<outboundRouteConfigs>
<escalationMessage>Your escalation message here.</escalationMessage>
<outboundRouteName>Your_OmniChannel_Flow_Name</outboundRouteName>
<outboundRouteType>OmniChannelFlow</outboundRouteType>
</outboundRouteConfigs>
<surface>SurfaceAction__CustomerWebClient</surface>
<surfaceType>CustomerWebClient</surfaceType>
</plannerSurfaces>
Note: The
outboundRouteConfigsshould mirror your Messaging surface config. If no escalation routing is configured, omit theoutboundRouteConfigsblock.
Note:
EinsteinAgentApiChannelsurfaceType is NOT available on all orgs (see Known Issue 17). UseCustomerWebClientinstead — it enables both Agent Builder Preview and Agent Runtime API access.
ECA for Client Credentials Flow
The Agent Runtime API requires OAuth with chatbot_api, sfap_api, and api scopes. See /sf-connected-apps for ECA creation. If you only need interactive testing via sf agent preview, skip ECA setup — preview uses standard org auth (sf org login web, v2.121.7+).
Validation
# Acquire token
curl -X POST "https://YOUR_DOMAIN.my.salesforce.com/services/oauth2/token" \
-d "grant_type=client_credentials&client_id=KEY&client_secret=SECRET"
# Create agent session
curl -X POST "https://YOUR_DOMAIN.my.salesforce.com/einstein/ai-agent/v1" \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{"agentDefinitionId":"0XxXXXXXXXXXXXXXXX"}'
Symptom: 500 error with
"errorCode": "UNKNOWN_EXCEPTION"→ MissingCustomerWebClientplannerSurface. Symptom: Agent Builder Preview → "Something went wrong. Refresh and try again." → Same root cause.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Debugging & Observability Guide
Find the Leak Before It Finds You
The Debugging Workflow
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ 📋 Interaction │ → │ 📊 Trace │ → │ ⚙️ Find the │
│ Details │ │ Waterfall │ │ Leak │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
The 4 Debugging Views
| Tab | Icon | Description |
|---|---|---|
| 📋 Interaction Details | List | The Summary View |
| 📊 Trace Waterfall | Chart | The Technical View |
| ↔️ Variable State Tracking | Arrows | Entry vs. Exit Values |
| <> Script View with Linting | Code | Red Squiggles |
View 1: Interaction Details (Summary)
Purpose: High-level chronological list with AI-generated summaries
Shows:
- ✅ Input received from user
- ✅ Reasoning decisions made
- ✅ Actions executed
- ✅ Output evaluation results
Best For: Quickly understanding WHAT happened
View 2: Trace Waterfall (Technical)
Purpose: Granular view showing every internal step
Shows:
- ✅ Exact prompt sent to the LLM
- ✅ Latency for each span (milliseconds)
- ✅ Raw JSON input/output for every tool call
- ✅ Variable state at each step
Best For: Understanding WHY something happened
View 3: Variable State Tracking
Purpose: Real-time table of variable Entry vs Exit values
Shows:
- ✅ Which variables changed during each span
- ✅ Critical security variables (verified, customer_id)
- ✅ Values LLM used vs values it should have used
Best For: Finding when LLM ignored variable state ("goal drift")
View 4: Script View with Linting
Purpose: Agent Script code with real-time syntax validation
Shows:
- ✅ Missing required top-level blocks
- ✅ Indentation issues
- ✅ Missing required fields
- ✅ Invalid resource references
Best For: Catching errors before deployment
View Selection Guide
| Question | Use This View |
|---|---|
| "What happened in this conversation?" | Interaction Details |
| "What exactly did the LLM see?" | Trace Waterfall |
| "Why did the variable have wrong value?" | Variable State |
| "Why won't my agent compile?" | Script View |
The 6 Span Types
| # | Span Type | Internal Name | Description |
|---|---|---|---|
| 1 | ➡️ Topic Enter | topic_enter |
Execution enters a new topic |
| 2 | ▶ before_reasoning | before_reasoning |
Deterministic pre-processing |
| 3 | 🧠 reasoning | reasoning |
LLM processes instructions |
| 4 | ⚡ Action Call | action_call |
Action invoked |
| 5 | → Transition | transition |
Topic navigation |
| 6 | ✓ after_reasoning | after_reasoning |
Deterministic post-processing |
Reading a Trace Waterfall
Example Timeline
SPAN DURATION TIMELINE
────────────────────────────────────────────────────────────────────
➡️ Topic Enter 15ms ████░░░░░░░░░░░░░░░░░░░░░░░░░░░░
▶ before_reasoning 850ms ████████████████████░░░░░░░░░░░░
🧠 reasoning 1250ms ██████████████████████████████░░
⚡ Action Call 450ms ██████████████░░░░░░░░░░░░░░░░░░
Latency Benchmarks
| Span Type | Expected Duration | If Slower... |
|---|---|---|
topic_enter |
10-20ms | Check topic complexity |
before_reasoning |
50-500ms | Data fetch issues |
reasoning |
1-3s | Normal LLM latency |
action_call |
100-500ms | External service slow |
after_reasoning |
10-50ms | Logging overhead |
Variable State Analysis
Entry vs Exit Pattern
| Step | Variable | Entry | Exit | Problem? |
|---|---|---|---|---|
| 1 | customer_verified |
False |
False |
- |
| 2 | customer_verified |
False |
True |
- |
| 3 | refund_processed |
False |
True |
⚠️ Processed while verified=False! |
KEY INSIGHT: If a critical variable like
is_verifiedwasFalsewhen an action executed, you've found your leak point.
Common Debug Patterns
Pattern 1: Wrong Policy Applied
Symptom: Customer received wrong regional policy
Trace Analysis:
- Check Variable State →
CustomerCountrywas empty at filter step - Check variable declaration →
mutable string = "" - Root Cause: Should be
linked stringwithsource: @session.Country
Fix:
# Wrong
CustomerCountry: mutable string = ""
# Correct
CustomerCountry: linked string
source: @session.Country
Pattern 2: Action Executed Without Authorization
Symptom: Refund processed without identity verification
Trace Analysis:
- Check reasoning span → LLM selected
process_refund - Check action definition → No
available whenguard - Root Cause: LLM could see and select unguarded action
Fix:
# Wrong - no guard
process_refund: @actions.process_refund
description: "Issue refund"
# Correct - guarded
process_refund: @actions.process_refund
description: "Issue refund"
available when @variables.customer_verified == True
Pattern 3: Post-Action Logic Didn't Run
Symptom: CRM case wasn't created after refund approval
Trace Analysis:
- Check instruction resolution order → Post-action check at bottom
- Check transition → Topic transitioned before check could run
- Root Cause: Post-action check must be at TOP
Fix:
# Wrong - check at bottom
instructions: ->
| Help with refund.
transition to @topic.next
if @variables.refund_done: # Never reaches here!
run @actions.log_refund
# Correct - check at TOP
instructions: ->
if @variables.refund_done:
run @actions.log_refund
transition to @topic.success
| Help with refund.
Pattern 4: Infinite Loop
Symptom: Agent keeps returning to same topic
Trace Analysis:
- Check transitions →
topic_enterrepeating for same topic - Check conditions → No exit condition defined
- Root Cause: Missing state change or exit condition
Fix:
# Wrong - no exit condition
instructions: ->
| Continue processing.
# Correct - track state, add exit
instructions: ->
if @variables.processing_complete == True:
transition to @topic.done
| Continue processing.
set @variables.step_count = @variables.step_count + 1
Pattern 5: LLM Ignores Variable State (Goal Drift)
Symptom: LLM makes decision contradicting variable value
Trace Analysis:
- Check Variable State → Variable had correct value
- Check resolved instructions → Condition should have pruned text
- Root Cause: Using pipe syntax (
|) instead of arrow (->)
Fix:
# Wrong - pipe doesn't support conditionals
instructions: |
if @variables.verified:
Help the user.
# This is literal text, not a condition!
# Correct - arrow enables conditionals
instructions: ->
if @variables.verified:
| Help the user.
else:
| Please verify first.
Diagnostic Checklist
Quick Triage
| Check | Command/Action |
|---|---|
| Syntax valid? | sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json |
| User exists? | sf data query -q "SELECT Username FROM User WHERE Profile.Name='Einstein Agent User'" |
| Topic exists? | Search for topic name in script |
| Variable initialized? | Check variables: block |
Deep Investigation
| Issue | What to Check |
|---|---|
| Wrong output | Variable State (Entry/Exit values) |
| Skipped logic | Instruction resolution order |
| Security bypass | available when guards |
| Data missing | Action target protocol, linked variable sources |
| Slow response | Trace Waterfall latencies |
The Big Picture
"Prompts are suggestions. Guards are guarantees."
The LLM might ignore your instructions. The only way to truly prevent unwanted behavior is through deterministic guards like available when.
When you remove an action from the LLM's toolkit, it literally cannot invoke it. That's not a suggestion - that's enforcement.
Key Takeaways
| # | Takeaway |
|---|---|
| 1 | Two Views for Two Purposes - Interaction Details for quick understanding, Trace Waterfall for forensics |
| 2 | Entry vs Exit Reveals Problems - Variable state changes show exactly when/where issues occurred |
| 3 | available when Blocks Actions - Makes unauthorized actions invisible, not just discouraged |
| 4 | Post-Action at TOP - Check for completed actions at the start of instructions |
| 5 | Linked vs Mutable - Wrong variable modifier causes empty values |
Programmatic Trace Access via CLI
sf agent preview start/send/endprovides full v1.1 trace data with 13 step types — far richer than the 5-type STDM data in Builder UI.
Workflow
# 1. Start preview session
SESSION_ID=$(sf agent preview start \
--api-name My_Agent \
--target-org myOrg --json 2>/dev/null | jq -r '.result.sessionId')
# 2. Send utterance(s)
PLAN_ID=$(sf agent preview send \
--session-id "$SESSION_ID" \
--api-name My_Agent \
--utterance "I need help with my order" \
--target-org myOrg --json 2>/dev/null | jq -r '.result.messages[-1].planId')
# 3. End session and get trace path
TRACES_PATH=$(sf agent preview end \
--session-id "$SESSION_ID" \
--api-name My_Agent \
--target-org myOrg --json 2>/dev/null | jq -r '.result.tracesPath')
# 4. Analyze trace
jq '.' "$TRACES_PATH/$PLAN_ID.json"
Key jq Recipes for Agent Script Debugging
TRACE="$TRACES_PATH/$PLAN_ID.json"
# What instructions did the LLM actually receive?
jq -r '.steps[] | select(.stepType == "LLMStep") | .data.prompt_content[0].content' "$TRACE"
# Which topic was selected and why?
jq '.steps[] | select(.stepType == "TransitionStep") | {from: .data.from, to: .data.to}' "$TRACE"
# What actions were available per iteration?
jq '.steps[] | select(.stepType == "EnabledToolsStep") | .data.enabled_tools' "$TRACE"
# Did any action fail?
jq '.steps[] | select(.stepType == "FunctionStep") | {fn: .function, error: .error}' "$TRACE"
# Variable state changes (verify instruction resolution)
jq '.steps[] | select(.stepType == "VariableUpdateStep") | {var: .data.variableName, old: .data.oldValue, new: .data.newValue}' "$TRACE"
Trace ↔ Agent Script Mapping
| Agent Script Concept | Trace Step Type | What to Check |
|---|---|---|
instructions: -> |
LLMStep.prompt_content[0] |
Verify resolved text appears |
when blocks |
LLMStep.prompt_content[3] |
Verify late-injected context |
actions: definitions |
EnabledToolsStep.enabled_tools |
Verify action visibility |
available when: |
EnabledToolsStep (per iteration) |
Verify conditional filtering |
transition to |
TransitionStep |
Verify from→to routing |
run @actions.X |
FunctionStep |
Verify inline action execution |
| Variable assignments | VariableUpdateStep |
Verify state mutations |
For full trace schema and analysis patterns, see sf-ai-agentforce-testing trace-analysis.md.
Planner Engine Note
Agent Script compiles against the Atlas planner engine. Legacy Java planner behavior is not relevant for Agent Script agents. If you encounter "it worked in dev but not in prod" issues, focus on variable state, action I/O, and permission differences rather than planner engine variations.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Feature Validity by Context (TDD Validated v2.2.0)
Key distinction: Many action metadata properties are valid on action definitions with targets (
flow://,apex://) but NOT on utility actions (@utils.transition). The v1.3.0 finding that tested only@utils.transitionwas too narrow — v2.2.0 corrects this.
| Feature | On @utils.transition |
On action definitions with target: |
Notes |
|---|---|---|---|
label: on topics |
❌ v1.3.0 | ✅ v2.2.0 | Valid on topic blocks |
label: on actions |
❌ v1.3.0 | ✅ v2.2.0 | Valid on Level 1 action definitions |
label: on I/O fields |
❌ v1.3.0 | ✅ v2.2.0 | Valid on inputs/outputs |
require_user_confirmation: |
❌ | ✅ v2.2.0 | Compiles; runtime no-op (Issue 6) |
include_in_progress_indicator: |
❌ | ✅ v2.2.0 | Shows spinner during action execution |
progress_indicator_message: |
❌ | ✅ v2.2.0 | Works on both flow:// and apex:// |
output_instructions: |
❌ | ❓ Untested | Not tested on target-backed actions |
always_expect_input: |
❌ | ❌ | NOT implemented anywhere |
What works on @utils.transition actions:
actions:
go_next: @utils.transition to @topic.next
description: "Navigate to next topic" # ✅ ONLY description works
What works on action definitions with target::
actions:
process_order:
label: "Process Order" # ✅ Display label
description: "Process the customer's order" # ✅ LLM description
require_user_confirmation: True # ✅ Compiles (runtime Issue 6)
include_in_progress_indicator: True # ✅ Shows spinner
progress_indicator_message: "Processing..." # ✅ Custom spinner message
inputs:
order_id: string
label: "Order ID" # ✅ I/O display label
description: "The order identifier"
outputs:
status: string
label: "Order Status" # ✅ I/O display label
description: "Current order status"
target: "apex://OrderProcessor"
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->FSM Architecture Guide
Design agent behavior as a finite state machine with deterministic nodes and explicit transitions.
Why FSM Architecture?
The Problem with Prompt-Only Agents
| Anti-Pattern | Description |
|---|---|
| ReAct Pattern | Agents get stuck in reasoning loops without guardrails |
| Doom-Prompting | Prompts grow exponentially to handle edge cases |
| Goal Drift | Agents forget original intent after several turns |
KEY INSIGHT: "LLMs are non-deterministic by design. Without structured control flow, enterprise agents become unpredictable, expensive, and impossible to debug."
The FSM Solution
| FSM Concept | Traffic Light Example | Agent Benefit |
|---|---|---|
| States | Red, Green, Yellow | Agent always knows exactly what it's doing |
| Transitions | Timer expires | No ambiguity about what happens next |
| Determinism | Red → Green (guaranteed) | Auditable, testable, trustworthy |
The Three FSM Pillars
| Pillar | Definition | Agent Benefit |
|---|---|---|
| States | Distinct "modes" the system can be in | Clear context at any moment |
| Transitions | Explicit rules for moving between states | Defined paths, no surprises |
| Determinism | Same input → same output | Auditable and testable |
The 5 Node Patterns
Pattern Overview
| Pattern | Color | Purpose |
|---|---|---|
| 🔵 ROUTING | Blue | Routes based on intent |
| 🔵 VERIFICATION | Light Blue | Security checks |
| 🟡 DATA-LOOKUP | Yellow | External data fetch |
| 🟢 PROCESSING | Green | Business logic |
| 🔴 HANDOFF | Red | Human escalation |
Pattern 1: ROUTING (Topic Selector)
Purpose: Routes conversations based on detected intent
start_agent topic_selector:
description: "Route to appropriate topic based on intent"
reasoning:
instructions: ->
| You are the support agent.
Classify the customer's intent and route:
- Refund requests go to identity verification
- General inquiries are handled directly
actions:
start_refund: @utils.transition to @topic.identity_verification
description: "Customer wants a refund"
handle_inquiry: @utils.transition to @topic.general_support
description: "General question or inquiry"
When to Use: Entry point for multi-purpose agents
Routing Heuristics
Terminology note: Public Agentforce docs increasingly say subagent. In Agent Script and this repo, the routing unit is still a topic.
- Use
description:as the primary routing signal. Uselabel:for display only. - Topic names should be short and literal; descriptions should capture the exact job to be done.
- If one utterance fits two topics, narrow, merge, or rename them.
- Keep escalation, handoff, and frustration separate from business-domain intents. Broad escalation descriptions absorb real work.
- Expect re-classification on every new turn. Protected actions and gates must still hold after rerouting.
Pattern 2: VERIFICATION (Identity Gate)
Purpose: Enforces security checks before proceeding
topic identity_verification:
description: "Verify customer identity before refund"
reasoning:
instructions: ->
if @variables.failed_attempts >= 3:
| Too many failed attempts. Escalating to human agent.
if @variables.email_verified == True:
| Identity verified. Proceed to risk assessment.
else:
| Ask customer to verify their email address.
actions:
verify_email: @actions.verify_email
description: "Verify customer email"
with email = @variables.customer_email
set @variables.email_verified = @outputs.verified
proceed: @utils.transition to @topic.risk_assessment
description: "Continue to risk assessment"
available when @variables.email_verified == True
escalate: @utils.escalate
description: "Transfer to human agent"
available when @variables.failed_attempts >= 3
When to Use: Before accessing sensitive data or actions
Pattern 3: DATA-LOOKUP (Risk Assessment)
Purpose: Fetches data from external sources
topic risk_assessment:
description: "Fetch customer data and assess churn risk"
reasoning:
instructions: ->
| Fetch customer profile using the action.
Once loaded, review:
- Churn Risk: {!@variables.churn_risk_score}%
- Lifetime Value: {!@variables.lifetime_value}
actions:
get_profile: @actions.get_customer_profile
description: "Load customer data from CRM"
with customer_id = @variables.customer_id
set @variables.churn_risk_score = @outputs.churn_risk
set @variables.lifetime_value = @outputs.ltv
process_refund: @utils.transition to @topic.refund_processor
description: "Continue to refund processing"
When to Use: When decisions require external data
Pattern 4: PROCESSING (Refund Processor)
Purpose: Applies business logic based on conditions
topic refund_processor:
description: "Process refund based on churn risk"
reasoning:
instructions: ->
if @variables.churn_risk_score >= 80:
| HIGH CHURN RISK - Approve full refund.
if @variables.churn_risk_score < 80:
| LOW CHURN RISK - Offer partial credit.
actions:
approve_full: @actions.process_refund
available when @variables.churn_risk_score >= 80
with amount = @variables.order_total
with type = "full"
offer_credit: @actions.issue_credit
available when @variables.churn_risk_score < 80
with amount = 10
When to Use: Applying business rules to data
Pattern 5: HANDOFF (Escalation)
Purpose: Transfers conversation to human agent
topic escalation:
description: "Escalate to human agent"
reasoning:
instructions: ->
| Customer has failed verification 3 times.
Escalating to a human agent for assistance.
actions:
handoff: @utils.escalate
description: "Transfer to human agent"
When to Use: Failed verification, complex issues, customer request
Escalation with Availability Check
Production-validated issue: When
@utils.escalateis invoked but no human agents are available, the conversation re-enters the topic and triggers the escalation logic again — creating an infinite loop. The built-in 3-4 loop guardrail eventually breaks the cycle, but the user experience is poor (repeated "Connecting you..." messages).
Fix: Use a latch variable to detect re-entry after a failed escalation, and route to a fallback topic.
variables:
escalation_attempted: mutable boolean = False
topic escalation:
description: "Escalate to human agent"
before_reasoning:
if @variables.escalation_attempted == True:
# Already attempted — agents unavailable, go to fallback
transition to @topic.leave_message
set @variables.escalation_attempted = True
reasoning:
instructions: ->
| I'm connecting you with a support specialist now.
actions:
handoff: @utils.escalate
description: "Transfer to human agent"
topic leave_message:
description: "Collect contact info when agents are unavailable"
reasoning:
instructions: |
Our team is currently unavailable. Please leave your name
and a brief description of your issue, and we'll follow up.
Key Points:
@utils.escalatedoes NOT return a success/failure status — you cannot check if escalation succeeded- Use
before_reasoning:(FREE, deterministic) to detect re-entry before the LLM runs - Always provide a fallback topic (leave message, callback request, self-service) for graceful degradation
- See known-issues.md Issue 31 for full details
Architecture Patterns
Pattern 1: Hub and Spoke
Central router to specialized topics.
┌─────────────┐
│ topic_sel │
│ (hub) │
└──────┬──────┘
┌─────────┼─────────┐
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│refunds │ │ orders │ │support │
│(spoke) │ │(spoke) │ │(spoke) │
└────────┘ └────────┘ └────────┘
When to Use: Multi-purpose agents with distinct request types
Pattern 2: Linear Flow
Sequential A → B → C pipeline.
┌───────┐ ┌────────┐ ┌─────────┐ ┌─────────┐
│ entry │ → │ verify │ → │ process │ → │ confirm │
└───────┘ └────────┘ └─────────┘ └─────────┘
When to Use: Mandatory steps (onboarding, checkout, compliance)
Pattern 3: Escalation Chain
Tiered support with complexity-based routing.
┌───────┐ ┌───────┐ ┌──────────┐ ┌─────────┐
│ L1 │ → │ L2 │ → │ L3 │ → │ human │
│(basic)│ │ (adv) │ │ (expert) │ │ agent │
└───┬───┘ └───┬───┘ └────┬─────┘ └─────────┘
▼ ▼ ▼
[resolved] [resolved] [resolved]
When to Use: Support workflows with complexity levels
Pattern 4: Verification Gate
Security gate before protected topics.
┌───────────┐
│ entry │
└─────┬─────┘
▼
┌───────────┐◄─────────────┐
│ VERIFY │ │
│ (GATE) │ │
└─────┬─────┘ │
┌─────────┴─────────┐ │
▼ ▼ │
[verified=True] [verified=False]──┘
│
┌─────┴─────────────┐
▼ ▼ ▼
┌─────────┐┌─────────┐┌──────────┐
│ account ││payments ││ settings │
│(protect)││(protect)││(protected)│
└─────────┘└─────────┘└──────────┘
When to Use: Sensitive data, payments, PII access
Auth Gate Leak Anti-Pattern
Production-validated issue: Escalation topics with broad descriptions absorb auth-gated intents, bypassing the verification gate entirely.
The Problem: When an Escalation topic's description includes broad terms like "billing", "payments", or "appointment changes", the topic classifier routes those intents directly to Escalation — skipping the Verification Gate.
Example: User says "Make a payment" -> Expected: Verification Gate -> Payments topic. Actual: Escalation topic (because its description mentions "billing inquiries").
Common leak intents (confirmed in production):
- "update credit card" -> Escalation (instead of Auth -> Payment Settings)
- "reschedule appointment" -> Escalation (instead of Auth -> Appointments)
- "pay my bill" -> Escalation (instead of Auth -> Payments)
- "when will my package arrive" -> Escalation (instead of Auth -> Shipping)
- "billing issue" -> Escalation (instead of Auth -> Payments)
Fix:
- Narrow the Escalation description — Remove business-domain terms. Keep it focused on meta-intents: "Customer explicitly requests a human agent" or "Customer is frustrated and wants to speak to someone"
- Guard protected topics with
available when— Addavailable when @variables.verified == Trueto all post-auth actions so even if routing leaks, the actions are invisible - Test for leaks — For every auth-gated intent, write a test case asserting the expected auth-first routing path
# ❌ Broad escalation description — absorbs payment/appointment intents
topic escalation:
description: "Handles billing inquiries, appointment issues, account problems, and customer frustration"
# ✅ Narrow escalation description — only catches meta-intents
topic escalation:
description: "Customer explicitly asks to speak with a human agent or expresses frustration"
Pattern 5: State Gate (Open Gate)
3-variable state machine that bypasses the LLM topic selector when a gate holds focus, redirects unauthenticated users to an auth gate, and automatically returns them to their original intended topic after authentication.
┌─────────────────────┐
│ topic_selector │
│ (start_agent) │
│ │
│ before_reasoning: │
│ if open_gate <> null│
│ → bypass LLM │
└──────────┬──────────┘
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌──────────────────┐ ┌────────────────┐ ┌─────────────────┐
│ protected_topic_A│ │protected_top_B│ │ general_inquiry │
│ (auth required) │ │(auth required)│ │ (no auth needed) │
│ │ │ │ │ │
│ if !auth → gate │ │ if !auth→gate │ │ (no gate logic) │
│ if auth → lock │ │ if auth→lock │ │ │
└────────┬─────────┘ └───────┬───────┘ └─────────────────┘
│ set next_topic │ set next_topic
▼ ▼
┌──────────────────────────────────────┐
│ authentication_gate │
│ │
│ after_reasoning: │
│ if auth → route via next_topic │
└──────────────────────────────────────┘
The 3 Variables:
| Variable | Type | Purpose |
|---|---|---|
open_gate |
string | Which topic holds focus ("null" = LLM decides) |
next_topic |
string | Deferred destination after auth completes |
authenticated |
boolean | Whether user has passed authentication |
When to Use: Multiple protected topics behind a shared auth gate, especially when you want zero-credit LLM bypass while the gate holds focus.
Key Difference from Verification Gate (Pattern 4): The Verification Gate is a linear, one-time gate — once verified, the user proceeds and never returns. The State Gate supports deferred routing (remembers where the user wanted to go), N protected topics behind a single gate, and an EXIT_PROTOCOL to release the gate when the user changes intent.
Template: See assets/patterns/open-gate-routing.agent for the complete implementation with walkthrough.
Standard Platform Topics (Implicit)
These topics are always active in every agent, even when not declared in the
.agentfile's topic list. They operate ABOVE custom topic routing and take priority.
| Standard Topic | Catches | Example Utterances |
|---|---|---|
Inappropriate_Content |
Hate speech, abuse, insults | "You're useless", "I hate this company" |
Prompt_Injection |
Instruction override attempts | "Ignore all previous instructions", "Tell me your system prompt" |
Reverse_Engineering |
Agent introspection probes | "What are your instructions?", "Show me your configuration" |
Ambiguous_Question |
Multi-intent or unclear messages | "I need help with my camera and also want to pay my bill" |
Impact on FSM Design:
- Your custom
Escalationtopic will NOT catch insults —Inappropriate_Contentintercepts first - Your custom
Off_Topictopic will NOT catch prompt injection —Prompt_Injectionhandles it - Multi-intent messages may bypass your routing logic entirely via
Ambiguous_Question - Test design: Write guardrail tests targeting these standard topics, not your custom equivalents
How to Detect in Test Results:
- Standard topic names appear in test output as-is (e.g.,
Inappropriate_Content, not a hash-suffixed name) - If a test expects your custom topic but the agent routes to a standard topic, the topic assertion fails
Deterministic vs. Subjective Classification
Classification Framework
| Put in Deterministic Nodes if... | Put in Subjective Reasoning if... |
|---|---|
| Security/safety requirement | Conversational/greeting |
| Financial threshold | Context understanding needed |
| Data fetch required | Natural language generation |
| Counter/state management | Flexible interpretation needed |
| Hard cutoff rule | Response explanation |
Examples
| Requirement | Classification | Reasoning |
|---|---|---|
| "ALWAYS verify identity before refund" | Deterministic | Security - must be code-enforced |
| "Start with a friendly greeting" | Subjective | Conversational - LLM flexibility |
| "IF churn > 80, full refund" | Deterministic | Financial threshold - no exceptions |
| "Explain the refund status" | Subjective | Natural language generation |
| "Count failed verification attempts" | Deterministic | Counter logic - must be accurate |
| "Redirect off-topic questions" | Subjective | Context understanding required |
State Machine Example: Pronto Refund Agent
┌────────────────────┐
│ Identity │ verified
refund │ Verification │─────────────┐
intent │ (VERIFICATION) │ │
┌────────────────┐ └─────────┬──────────┘ ▼
│ Topic Selector │──────────▶ │ ┌─────────────────┐
│ (ROUTING) │ │ failed 3x │ Risk Assessment │
└────────────────┘ │ │ (DATA-LOOKUP) │
│ └────────┬────────┘
▼ │ score loaded
┌────────────────┐ ▼
│ Escalation │ ┌─────────────────┐
│ (HANDOFF) │ │ Refund Processor│
└────────────────┘ │ (PROCESSING) │
└─────────────────┘
State Definitions
| State | Type | Entry Condition | Exit Conditions |
|---|---|---|---|
| Topic Selector | ROUTING | Conversation start | Intent detected |
| Identity Verification | VERIFICATION | Refund intent | Verified OR 3 failures |
| Risk Assessment | DATA-LOOKUP | Identity verified | Score loaded |
| Refund Processor | PROCESSING | Score loaded | Refund complete |
| Escalation | HANDOFF | 3 failures | Human takeover |
Best Practices
1. Single Responsibility per Topic
Each topic should handle ONE concern. If a topic does verification AND processing, split it.
2. Explicit Transitions
Always define how to enter AND exit each state. No dead ends.
3. Guard Sensitive Transitions
Use available when to make actions invisible when conditions aren't met.
actions:
process_payment: @actions.charge_card
available when @variables.customer_verified == True
# LLM literally cannot see this action if not verified
4. Design for the Happy Path First
Map the success flow, then add failure states.
5. Use Escalation as a Safety Net
When in doubt, escalate to human. It's better than a bad automated decision.
Topic Design Patterns
Migrated from the former
sf-ai-agentforce-legacy/references/topics-guide.mdon 2026-02-07.
Topic Fundamentals
Topics are conversation modes that group related actions and reasoning logic. Think of them as "skill areas" or "conversation contexts" for your agent.
| Benefit | Description |
|---|---|
| Separation of Concerns | Group related functionality (e.g., "Order Management", "Support") |
| Focused Instructions | Each topic has its own reasoning instructions |
| Action Scoping | Actions defined in a topic are available only in that topic |
| Persona Switching | Topics can override system instructions for different modes |
Topic Structure
Required Fields
Every topic MUST have:
description:- What the topic does (used by LLM for routing decisions)
label:is valid on topics (TDD v2.2.0). Uselabel:for display names anddescription:to convey the topic's purpose to the LLM.
topic order_lookup:
description: "Helps customers look up their order status and details"
reasoning:
instructions: ->
| Help the user find their order.
Optional Blocks
| Block | Purpose | Example |
|---|---|---|
system: |
Override global system instructions | Persona switching |
actions: |
Define topic-specific actions | Flow/Apex actions |
reasoning: |
Topic reasoning logic | Instructions + action invocations |
Topic Transition Mechanics
@utils.transition to @topic.[name]
Permanently move to another topic. The user CANNOT return to the previous topic without explicit routing.
start_agent topic_selector:
description: "Routes users to topics"
reasoning:
instructions: ->
| What would you like to do?
| 1. Check order status
| 2. Get support
actions:
go_orders: @utils.transition to @topic.order_lookup
go_support: @utils.transition to @topic.support
When to Use:
- Permanent mode switches (e.g., "I want to check my order" → order_lookup)
- One-way transitions where user won't return to previous topic
- Entry point routing (start_agent → specific topics)
Topic Delegation vs Transition
There are TWO ways to reference other topics:
1. @utils.transition to @topic.[name] — Permanent Transition
Behavior:
- Permanently moves to the target topic
- User CANNOT automatically return
- Current topic is abandoned
- Target topic becomes the active context
Use Cases:
- Main menu routing (start_agent → feature topics)
- Mode switches (FAQ → Support)
- One-way workflows
# Permanent transition
actions:
go_to_orders: @utils.transition to @topic.order_management
2. @topic.[name] — Topic Delegation (Sub-Agent Pattern)
Behavior:
- Temporarily delegates to target topic
- Target topic can "return" control to caller
- Original topic resumes after delegation completes
- Like calling a subroutine
Use Cases:
- Specialist consultation (Main Agent → Tax Expert → Main Agent)
- Reusable sub-workflows (Address Collection)
- Modular agent design
# Topic delegation (can return)
actions:
consult_specialist: @topic.tax_specialist
Key Difference:
| Pattern | Control Flow | Returns? |
|---|---|---|
@utils.transition to @topic.x |
Permanent move | No |
@topic.x |
Temporary delegation | Yes (if target topic transitions back) |
Routing Pattern Examples
Hub-and-Spoke (with Back Navigation)
start_agent topic_selector:
description: "Main menu / router"
reasoning:
instructions: ->
| What can I help you with?
actions:
go_orders: @utils.transition to @topic.order_management
go_support: @utils.transition to @topic.support
go_faq: @utils.transition to @topic.faq
topic order_management:
description: "Order lookup and tracking"
reasoning:
instructions: ->
| Help with orders.
actions:
back: @utils.transition to @topic.topic_selector
topic support:
description: "Customer support"
reasoning:
instructions: ->
| Provide support.
actions:
back: @utils.transition to @topic.topic_selector
Benefits: Clear entry point, easy to add new topics, users can always go back to menu.
Linear Workflow
start_agent onboarding:
description: "Collect user information"
reasoning:
instructions: ->
| Welcome! Let's get started.
actions:
next: @utils.transition to @topic.collect_address
topic collect_address:
description: "Get shipping address"
reasoning:
instructions: ->
| What's your address?
actions:
next: @utils.transition to @topic.confirm_details
topic confirm_details:
description: "Review and confirm"
reasoning:
instructions: ->
| Please confirm your information.
Benefits: Guided, step-by-step experience. Prevents users from skipping steps.
Contextual Routing (Data-Driven)
topic order_lookup:
description: "Look up order by number"
reasoning:
instructions: ->
| if @variables.order_found == False:
| | I couldn't find that order.
actions:
lookup: @actions.get_order
# Conditional routing based on outcome
go_support: @utils.transition to @topic.support
available when @variables.order_found == False
back: @utils.transition to @topic.topic_selector
available when @variables.order_found == True
Benefits: Dynamic routing based on data, handles error cases gracefully.
Multi-Topic Agent Design
When to Use Multiple Topics
| Scenario | Topics Needed |
|---|---|
| Multi-feature agent | 1 topic per feature + 1 router topic |
| Workflow with steps | 1 topic per step + 1 entry topic |
| Persona switching | 1 topic per persona + 1 selector |
| Specialist delegation | 1 main topic + N specialist topics |
Bidirectional Routing (Specialist Consultation)
topic main_agent:
description: "General assistant that can consult specialists"
reasoning:
instructions: ->
| I can help with most questions.
| For specialized topics, I'll consult our experts.
actions:
# Delegation - specialist can return control
consult_tax: @topic.tax_specialist
consult_legal: @topic.legal_specialist
topic tax_specialist:
description: "Expert on tax questions"
reasoning:
instructions: ->
| [Tax Specialist Mode]
| Provide detailed tax guidance.
actions:
# Return to main agent when done
return_to_main: @utils.transition to @topic.main_agent
topic legal_specialist:
description: "Expert on legal questions"
reasoning:
instructions: ->
| [Legal Specialist Mode]
| Provide legal information.
actions:
return_to_main: @utils.transition to @topic.main_agent
Benefits: Main agent stays in control, specialists provide focused expertise, clean separation of concerns, reusable specialist topics.
Topic Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Topic name | snake_case | order_management |
| Action name | snake_case | get_order_status |
Common Topic Design Mistakes
| Mistake | Fix |
|---|---|
Missing description |
Add description: to every topic (required for LLM routing) |
| Overlapping sibling topics | Increase semantic distance or merge/split by clearer jobs-to-be-done |
| Broad escalation or handoff descriptions | Restrict them to meta-intents only; remove business-domain wording |
| Trying to fix routing in instructions | Strengthen topic names and descriptions instead |
| Orphaned topics (unreachable) | Ensure all topics have incoming transitions |
| No way to go back | Add transition to topic_selector or escalation |
| Too many topics | Combine related functionality |
| Too few topics | Split complex topics into focused ones |
Topic Transitions Checklist
-
start_agenttransitions to at least one topic - All topics are reachable from
start_agent(directly or indirectly) - Each topic has at least one outbound transition (or escalation)
- Users can navigate back to main menu or exit
- Topic descriptions are clear and detailed for LLM routing
- High-traffic topics have nearest-neighbor collision tests
- Turn-2 pivot / re-classification paths are tested for important workflows
- Protected topics still enforce gates even after rerouting
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Data Grounding & Multi-Agent Guide
High-stakes enterprise agents cannot rely on training data. They must be grounded in real-time business data and coordinate with specialized agents for complex tasks.
Two Pillars
| Pillar | Icon | Description |
|---|---|---|
| 🔽 Retriever Actions | Filter | Dynamic filtering ensures agents only see relevant data |
| 🔀 Multi-Agent SOMA | Branch | Primary agents delegate to expert agents |
Context Placement Rules
- Instructions: behavior, tone, guardrails, tool-choice guidance.
- Knowledge / retrieval: facts, policy text, mutable rules, product specifics.
- Filters: what the agent can see or use; stronger than instructions for scope control.
- Variables: facts or state that must survive turn history or feed later actions.
Retrieval Storage Heuristic
- Do not put long policy text in instructions.
- Retrieve facts just in time.
- Store retrieval output in variables only when it must persist across turns or feed deterministic follow-up.
- Prefer Flow-wrapped filtering over prose like “only use region X policy.”
Retriever Actions
Connecting Agents to Data Cloud
Retriever Actions connect your agent to Data Cloud Search Indexes, enabling context-aware knowledge retrieval.
Capabilities:
- ✅ Search Index wraps unstructured data (PDFs, docs, web pages)
- ✅ Chunking parses text, tables, and images into searchable segments
- ✅ Returns relevant chunks based on semantic similarity
- ✅ Integrated with Data Cloud for current data
Basic Retriever Action
actions:
fetch_refund_policy:
description: "Retrieve refund policy from knowledge base"
target: "retriever://RefundSOP_Retriever"
inputs:
query: string
outputs:
chunks: list[object]
relevance_scores: list[number]
Retrieval Pipeline
┌────────────┐ ┌────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐
│ User Query │ → │ Dynamic Filter │ → │ Data Cloud Index│ → │ Relevant Chunks │ → │ LLM Response │
└────────────┘ └────────────────┘ └─────────────────┘ └─────────────────┘ └──────────────┘
Filtered Retrieval with Flows
Agent Script cannot filter retrieval results inline. When you need filtered knowledge retrieval, wrap the retriever in a Flow.
Problem: Direct retriever:// targets don't support inline filtering.
Solution: Use flow:// to wrap the retriever with filter logic.
# WRONG - No filtering capability
actions:
fetch_policy:
target: "retriever://RefundSOP_Index" # Can't filter!
# CORRECT - Flow handles filtering
actions:
fetch_regional_policy:
description: "Fetch policy filtered by customer region"
inputs:
query: string
customer_country: string
description: "Country code for regional filtering"
outputs:
chunks: list[object]
policy_region: string
target: "flow://GetRegionalRefundPolicy" # Flow filters internally
⚠️ Security Note: Filtering in a Flow prevents accidental cross-region data exposure. The Flow enforces the filter - the LLM cannot bypass it.
Safe Expressions
Agent Script uses a safe subset of Python for expressions:
Allowed Operations:
| Category | Operators |
|---|---|
| Comparison | ==, != (not-equal), >, <, >=, <= |
| Logical | and, or, not |
| String | contains, startswith, endswith |
⚠️ Guardrail note: These string operators may compile, but they are not the most reliable way to enforce control-flow-critical validation or intent routing. For anything that must deterministically gate behavior — such as URL validation, cancellation detection, or revision handling — prefer a Flow/Apex/classifier action that returns an explicit boolean or enum.
Security Constraints:
- ❌ No
importstatements - ❌ No file access
- ❌ No arbitrary code execution
# Valid safe expressions:
@variables.risk_score > 80
@variables.country == "Germany"
@variables.is_vip and @variables.order_total > 100
not @variables.verified
# INVALID (security risk):
import os # NOT ALLOWED
eval(...) # NOT ALLOWED
open(...) # NOT ALLOWED
The 6 Action Target Protocols
Every action uses a target: field to specify where to send the request.
| Protocol | Use When | Example |
|---|---|---|
flow:// |
Data operations, business logic | target: "flow://GetOrderStatus" |
apex:// |
Custom calculations, validation | target: "apex://RefundCalculator" |
generatePromptResponse:// |
Grounded LLM responses | target: "generatePromptResponse://Summary" |
retriever:// |
RAG knowledge search | target: "retriever://Policy_Index" |
externalService:// |
Third-party APIs | target: "externalService://AddressAPI" |
standardInvocableAction:// |
Built-in SF actions | target: "standardInvocableAction://email" |
Protocol 1: Salesforce Flow (flow://)
Use Case: Data operations, business logic, filtered retrieval
actions:
get_order_status:
description: "Retrieves order details by order number"
inputs:
order_number: string
description: "The order ID to look up"
outputs:
status: string
tracking_number: string
target: "flow://GetOrderStatus"
Protocol 2: Apex Class (apex://)
Use Case: Custom calculations, complex validation
actions:
calculate_refund:
description: "Calculate refund amount based on policy rules"
inputs:
order_id: string
refund_reason: string
outputs:
refund_amount: currency
requires_approval: boolean
target: "apex://RefundCalculatorService"
Protocol 3: Prompt Template (generatePromptResponse://)
Use Case: Grounded LLM responses, summarization
actions:
summarize_case:
description: "Generate a summary of the customer case"
inputs:
"Input:caseId": id
description: "The Case record ID"
outputs:
promptResponse: string
target: "generatePromptResponse://Generate_Case_Summary"
⚠️ Note: Input keys use quoted strings with colon notation (
"Input:caseId")
Protocol 4: Data Cloud Retriever (retriever://)
Use Case: Knowledge base search, FAQ lookup
actions:
search_knowledge:
description: "Search the knowledge base for relevant info"
inputs:
query: string
outputs:
chunks: list[object]
relevance_scores: list[number]
target: "retriever://RefundPolicy_Retriever"
Protocol 5: External Service (externalService://)
Use Case: Third-party APIs via Named Credentials
actions:
verify_address:
description: "Validate shipping address via external API"
inputs:
street: string
city: string
postal_code: string
outputs:
is_valid: boolean
normalized_address: object
target: "externalService://AddressValidation"
Protocol 6: Standard Invocable (standardInvocableAction://)
Use Case: Built-in Salesforce actions (email, tasks, Chatter)
actions:
send_email:
description: "Send confirmation email to customer"
inputs:
recipient_email: string
template_id: id
outputs:
success: boolean
target: "standardInvocableAction://emailSimple"
Protocol Selection Guide
| If you need... | Use this protocol |
|---|---|
| Complex data queries, record updates | flow:// |
| Custom calculations, validation | apex:// |
| LLM-generated summaries | generatePromptResponse:// |
| Knowledge search, RAG | retriever:// |
| External REST APIs | externalService:// |
| Standard SF actions | standardInvocableAction:// |
Conditional Knowledge Retrieval Pattern
Use available when to route to different knowledge bases based on user context:
topic knowledge_router:
description: "Route to appropriate knowledge base"
reasoning:
instructions: ->
| Let me find the right information for you.
actions:
search_premium_kb: @actions.search_premium_knowledge
description: "Search premium support articles"
available when @variables.customer_tier == "premium"
with query = ...
search_standard_kb: @actions.search_standard_knowledge
description: "Search standard support articles"
available when @variables.customer_tier != "premium"
with query = ...
Why this matters: Different customer tiers may need access to different knowledge bases with different SLA guidance, pricing, or support procedures. The
available whenguard ensures the LLM can only search the appropriate knowledge base.
Same Org Multi-Agent (SOMA)
When a primary agent encounters specialized needs, it can coordinate with expert agents.
Two Coordination Patterns
| Pattern | Description | Return Behavior |
|---|---|---|
| 🔀 Delegation | Farm out, then return | ✅ Control returns to original agent |
| ➡️ Handoff | Transfer permanently | ❌ No return - original agent exits |
Pattern 1: Delegation
Flow:
┌─────────┐ DELEGATE ┌────────────┐ RETURN ┌─────────┐
│ Primary │ ─────────────▶ │ Specialist │ ───────────▶ │ Primary │
└─────────┘ └────────────┘ └─────────┘
Use Cases:
- Tax questions → Compliance Agent
- Technical issues → Support Specialist
- Order changes → Fulfillment Agent
Implementation:
# Delegation uses topic reference (NOT @utils.transition)
# Parent orchestrates — child returns control
reasoning:
actions:
ask_compliance: @topic.compliance
description: "Consult compliance specialist on tax questions"
# ✅ Returns to this topic after specialist finishes
ask_refund_help: @topic.refund_specialist
description: "Consult refund specialist for calculations"
# ✅ Control returns to continue conversation
Pattern 2: Handoff
Flow:
┌─────────┐ HANDOFF ┌────────┐ NO RETURN
│ Primary │ ────────────▶ │ Target │ ────────────▶ ✗
└─────────┘ └────────┘
Use Cases:
- Escalation to human agent
- Domain boundary (Sales → Support)
- Fraud detection requiring specialized handling
Implementation:
# Permanent handoff - conversation leaves this agent
reasoning:
actions:
escalate_to_human: @utils.escalate
description: "Transfer to live support"
# Conversation ends for this agent
Delegation vs Handoff Decision
| Use This | When You Need |
|---|---|
@topic.X (in reasoning.actions) |
Temporary delegation — control returns |
@utils.transition to @topic.X |
Permanent handoff — no return |
@utils.escalate |
Permanent handoff to human |
@agent.X (Connections) |
Permanent handoff to another agent |
KEY INSIGHT: The difference is whether the original agent continues after the specialist finishes.
SOMA Limitations (Community-Confirmed)
| Limitation | Description | Workaround |
|---|---|---|
| Single action per supervision call | Delegated topic can only execute ONE action before returning | Break complex operations into separate delegation calls |
related_agent nodes may fail |
SOMA configuration with related agent references can cause "Node does not have corresponding topic" errors | Use @topic.X delegation within same agent instead |
| No cross-agent variable sharing | Delegated agents cannot read/write parent agent's variables | Pass data through action inputs/outputs |
Variable Configuration for Grounding
Linked Variables for Session Context
variables:
# WRONG - mutable allows modification
CustomerCountry: mutable string = ""
# CORRECT - linked preserves session data
CustomerCountry: linked string
source: @session.Country
Why This Matters:
mutable string = ""starts empty - filter won't worklinked stringpulls from session - filter gets real value
Debug Exercise: Wrong Policy Applied
Symptom: German customer received US refund policy
Root Cause Trace:
| Step | Wrong Implementation | Correct Implementation |
|---|---|---|
| 1. Session Start | CustomerCountry: "" |
CustomerCountry: "Germany" |
| 2. Filter | Region == "" |
Region == "Germany" |
| 3. Knowledge Fetch | US_Refund_Policy | EU_Refund_Policy_GDPR |
| 4. Refund | $10 credit | Full refund (€45.99) |
Fix: Change mutable string = "" to linked string with source: @session.Country
Best Practices
1. Always Filter Regional Data
Never return unfiltered results for region-specific policies.
2. Use Flows for Complex Filtering
Agent Script can't filter inline - wrap retrievers in Flows.
3. Validate Session Variables
Ensure linked variables have sources - empty values cause wrong retrievals.
4. Choose Delegation vs Handoff Carefully
@topic.X(delegation) — returns control to parent topic@utils.transition to @topic.X(handoff) — permanent, no return
5. Use available when for Sensitive Protocols
Guard external service calls with verification checks.
actions:
call_payment_api: @actions.charge_card
target: "externalService://PaymentGateway"
available when @variables.customer_verified == True
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Instruction Resolution Guide
One Pass. Top to Bottom. Before the LLM Sees Anything.
The Three Phases
Agent Script instructions resolve in a predictable order. Understanding this flow gives you precise control over what the LLM sees and when actions execute.
| Phase | Icon | Name | Description |
|---|---|---|---|
| 1 | ▶ | Pre-LLM Setup | Instructions resolve line-by-line, deterministically |
| 2 | ⚙ | LLM Reasoning | LLM sees only resolved text and available actions |
| 3 | ↻ | Post-Action Loop | After action completes, topic loops with updated variables |
Phase 1: Pre-LLM Resolution
Everything resolves top-to-bottom BEFORE the LLM processes them.
What Happens
| Step | Description |
|---|---|
| Conditions evaluate | if/else logic evaluates and prunes paths |
| Actions execute | run @actions.X executes immediately |
| Templates resolve | Template syntax resolves to actual values |
| Transitions short-circuit | transition to can exit the topic immediately |
⚠️
run @actions.Xresolution scope: Therundirective resolves only against topic-level action definitions that declare a realtarget:field (flow://,apex://,prompt://, etc.). It does NOT work for reasoning-level utilities like@utils.setVariables, and it is also the wrong tool for topic-level utilities / delegations such as@utils.transitionor@topic.X. If you need deterministic non-target behavior, use directset/transition to. If you need utility-style behavior chosen from context, expose it inreasoning.actions:and let the LLM invoke it.
Example
topic refund_request:
description: "Handle refund requests"
reasoning:
instructions: ->
# --- PRE-LLM: These resolve BEFORE the LLM sees anything ---
# Security gate - check attempt limit
if @variables.attempt_count >= 3:
transition to @topic.escalation
# Load data deterministically
run @actions.get_churn_score
with customer_id = @variables.customer_id
set @variables.churn_score = @outputs.score
# Increment counter
set @variables.attempt_count = @variables.attempt_count + 1
# --- LLM INSTRUCTIONS: Only this text reaches the LLM ---
| Customer churn score: {!@variables.churn_score}
if @variables.churn_score >= 80:
| Offer a full cash refund to retain this customer.
else:
| Offer a $10 credit as a goodwill gesture.
Execution Timeline
┌─────────────────────────────────────────────────────────────────┐
│ ▶ PRE-LLM [LINE-BY-LINE] │
├─────────────────────────────────────────────────────────────────┤
│ ● Message Received ~10ms │
│ ● Instructions Resolve ~50-500ms │
│ ● Templates Hydrate ~5ms │
└─────────────────────────────────────────────────────────────────┘
Phase 2: LLM Processing
The LLM receives clean, final instructions with all values populated.
What the LLM Sees
The LLM never sees your conditionals - only the resolved result.
Your code:
instructions: ->
| Customer churn score: {!@variables.churn_score}
if @variables.churn_score >= 80:
| Offer a full cash refund to retain this customer.
else:
| Offer a $10 credit as a goodwill gesture.
What the LLM actually sees (if churn_score = 85):
Customer churn score: 85
Offer a full cash refund to retain this customer.
Action Visibility
The available when clause is also evaluated deterministically:
actions:
process_refund: @actions.process_refund
description: "Issue the refund"
available when @variables.is_verified == True
If is_verified is False, the LLM never sees process_refund as an option.
Phase 3: Post-Action Loop
When the LLM invokes an action, the topic loops back. Instructions resolve AGAIN.
What Happens
| Step | Description |
|---|---|
| Outputs stored | LLM action completes, outputs stored in variables |
| Re-resolve | Topic instructions resolve again (same top-to-bottom pass) |
| New conditions trigger | Conditions can trigger based on new values |
| Follow-up executes | Deterministic follow-up actions run |
The Loop Pattern
TURN 1: Initial Request
├─ User asks for refund
├─ Instructions resolve (refund_status is empty)
├─ LLM sees "Help the customer with their refund request"
├─ LLM calls process_refund action
└─ Action sets refund_status = "Approved"
↓ LOOP
TURN 2: After Action (Same Topic)
├─ Topic loops back
├─ Instructions resolve AGAIN
├─ Condition triggers: refund_status == "Approved"
├─ Deterministic action runs: create_crm_case
└─ Transition to success_confirmation
Example: Deterministic Follow-Up
topic refund_request:
description: "Handle refund requests with deterministic follow-up"
reasoning:
instructions: ->
# --- POST-ACTION CHECK: Did we just process a refund? ---
# This block runs AGAIN after the LLM action completes!
if @variables.refund_status == "Approved":
# Deterministic follow-up - LLM cannot skip this!
run @actions.create_crm_case
with customer_id = @variables.customer_id
with refund_amount = @variables.refund_amount
transition to @topic.success_confirmation
# --- PRE-LLM: Normal instruction flow ---
| Customer churn score: {!@variables.churn_score}
| Help the customer with their refund request.
actions:
process_refund: @actions.process_refund
description: "Issue the refund"
set @variables.refund_status = @outputs.status
set @variables.refund_amount = @outputs.amount
💡 KEY INSIGHT: The post-action check pattern ensures business-critical follow-up actions ALWAYS execute. The LLM cannot "forget" or "decide not to" - it's code, not a suggestion.
The Instruction Pattern Structure
Recommended Order
reasoning:
instructions: ->
# 1. POST-ACTION CHECKS (at TOP - triggers on loop)
if @variables.action_completed == True:
run @actions.follow_up_action
transition to @topic.next_step
# 2. PRE-LLM DATA LOADING
run @actions.load_required_data
set @variables.data = @outputs.result
# 3. DYNAMIC INSTRUCTIONS FOR LLM
| Here is the context: {!@variables.data}
if @variables.condition:
| Do this thing.
else:
| Do that thing.
actions:
# LLM-selectable actions
my_action: @actions.do_something
set @variables.action_completed = True
Why This Order Matters
- Post-action at TOP: When the topic loops after action completion, the check triggers immediately
- Data loading next: LLM needs current data to make decisions
- Instructions last: LLM sees resolved values from data loading
Execution Timeline Summary
| Phase | What Happens | Duration |
|---|---|---|
| Pre-LLM | Message received, instructions resolve, templates hydrate | ~60-515ms |
| LLM | LLM processes resolved instructions, decides on response/action | ~1-3s |
| Post-Action | Action executes, topic loops with updated variables | ~150-550ms |
Common Patterns
Pattern 1: Security Gate with Early Exit
instructions: ->
if @variables.failed_attempts >= 3:
| Account locked due to too many attempts.
transition to @topic.lockout # Early exit - LLM never reasons
| Please verify your identity.
Pattern 2: Data-Dependent Instructions
instructions: ->
run @actions.get_account_tier
set @variables.tier = @outputs.tier
if @variables.tier == "Gold":
| You're a Gold member! Enjoy priority support.
if @variables.tier == "Silver":
| Welcome back, Silver member.
else:
| Thanks for contacting support.
Pattern 3: Action Chaining
instructions: ->
# Step 1 complete?
if @variables.step1_done == True and @variables.step2_done == False:
run @actions.step2
set @variables.step2_done = True
# Step 2 complete?
if @variables.step2_done == True:
transition to @topic.complete
| Let's start with step 1.
actions:
do_step1: @actions.step1
set @variables.step1_done = True
Syntax Patterns Reference
| Pattern | Purpose |
|---|---|
instructions: -> |
Arrow syntax enables inline expressions |
if @variables.x: |
Conditional - resolves BEFORE LLM |
run @actions.x |
Execute action during resolution |
set @var = @outputs.y |
Capture action output |
| Curly-bang: {!@variables.x} | Template injection into LLM text |
available when |
Control action visibility to LLM |
transition to @topic.x |
Deterministic topic change |
Anti-Patterns to Avoid
❌ Data Load After LLM Text
# WRONG - LLM sees empty values
instructions: ->
| Customer name: {!@variables.name} # name is empty!
run @actions.load_customer
set @variables.name = @outputs.name
✅ Correct Order
# RIGHT - Load first, then reference
instructions: ->
run @actions.load_customer
set @variables.name = @outputs.name
| Customer name: {!@variables.name} # name is populated
❌ Post-Action Check at Bottom
# WRONG - Never triggers because transition happens first
instructions: ->
| Help with refund.
transition to @topic.main # Exits before check!
if @variables.refund_done:
run @actions.log_refund
✅ Post-Action Check at Top
# RIGHT - Check first, then normal flow
instructions: ->
if @variables.refund_done:
run @actions.log_refund
transition to @topic.success
| Help with refund.
What the LLM Actually Receives (Compilation Output)
Validated via
sf agent previewv1.1 trace data. See sf-ai-agentforce-testing Phase F for programmatic trace capture.
When a topic activates, the Agent Script DSL compiles into a 4-message prompt structure sent to the LLM:
| # | Message Role | Content | Source |
|---|---|---|---|
| 1 | system |
Protocol + resolved instructions | DSL compilation |
| 2 | assistant |
Conversation history | Prior turns |
| 3 | user |
Current utterance | User input |
| 4 | system |
Late-injected context | when blocks + variables |
System Message 1 — Main Prompt Structure
The first system message contains these sections IN ORDER:
- TOOL USAGE PROTOCOL — How the LLM should invoke tools (JSON schema, parameter formatting)
- PROMPT INJECTION CRITERIA — Instructions to detect and refuse injection attempts
- SAFETY GUARDRAILS — Toxicity, PII, harmful content rules
- EQUALITY PRINCIPLES — Non-discrimination guidelines
- LANGUAGE GUIDELINES — Response language matching rules
- OFF-TOPIC RULES — Topic boundary enforcement
- RESPONSE GUIDELINES — Formatting, tone, length preferences
- PROHIBITED ACTIONS — Actions the agent must never take
- Resolved
system.instructions— Your DSLinstructions: ->block after one-pass resolution
The header varies by agent stage:
- Topic Selector →
"Topic Selector & Safety Router" - Topic Agents →
"Specialized Topic Agent"
System Message 4 — Late-Injected Context
Contains resolved when block instructions and customer context variables. This is where runtime context ($Context.RoutableId, custom variables) appears.
Tool Definitions (tools_sent[])
Actions compile into tools_sent[] as plain string names. Guardrails ALSO appear as tool names:
- Regular actions:
Get_Order_Status,Process_Refund - Guardrail tools:
Inappropriate_Content,Prompt_Injection,Reverse_Engineering
Per-iteration tool visibility changes — tools shift between reasoning iterations based on topic transitions. Extract with:
jq '.steps[] | select(.stepType == "EnabledToolsStep") | .data.enabled_tools' trace.json
Verifying Compilation Output
Use jq to extract the compiled prompt from trace files:
# Extract System Message 1 (your resolved instructions)
jq '.steps[] | select(.stepType == "LLMStep") | .data.prompt_content[0].content' trace.json
# Extract System Message 4 (late-injected context)
jq '.steps[] | select(.stepType == "LLMStep") | .data.prompt_content[3].content' trace.json
# Verify your instructions appear in the compiled output
jq -r '.steps[] | select(.stepType == "LLMStep") | .data.prompt_content[0].content' trace.json | grep -c "your instruction text"
Key Takeaways
| # | Takeaway |
|---|---|
| 1 | One Pass Resolution - Instructions resolve top-to-bottom BEFORE the LLM sees anything |
| 2 | Inline Pattern - Use reasoning.instructions: -> with inline conditionals |
| 3 | LLM Sees Clean Text - No if/else logic visible, no action calls visible |
| 4 | Post-Action Loop - Topic loops back after LLM action, instructions resolve AGAIN |
| 5 | Deterministic Follow-Up - Use post-action checks to guarantee critical actions |
| 6 | 4-Message Structure - System (protocol) → Assistant (history) → User (utterance) → System (context) |
| 7 | Guardrails as Tools - Safety guardrails compile into both system prompt text AND tool definitions |
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Known Issues Tracker
Unresolved platform bugs, limitations, and edge cases that affect Agent Script development. Unlike the "Common Issues & Fixes" table in SKILL.md (which covers resolved troubleshooting), this file tracks open platform issues where the root cause is in Salesforce, not in user code.
Issue Template
## Issue N: [Title]
- **Status**: OPEN | RESOLVED | WORKAROUND
- **Date Discovered**: YYYY-MM-DD
- **Affects**: [Component/workflow affected]
- **Symptom**: What the user sees
- **Root Cause**: Why it happens (if known)
- **Workaround**: How to get around it
- **Open Questions**: What we still don't know
- **References**: Links to related docs, issues, or discussions
Open Issues
Issue 1: Agent test files block force-app deployment
- Status: WORKAROUND
- Date Discovered: 2026-01-20
- Affects:
sf project deploy start --source-dir force-app - Symptom: Deployment hangs for 2+ minutes or times out when
AiEvaluationDefinitionmetadata files exist underforce-app/. The deploy may eventually succeed but with excessive wait times. - Root Cause:
AiEvaluationDefinitionmetadata type triggers server-side processing that blocks the deployment pipeline. The metadata type is not well-suited for source-dir deploys. - Workaround: Move test definitions to a separate directory outside the main deploy path, or use
--metadataflag to deploy specific types instead of--source-dir.# Instead of: sf project deploy start --source-dir force-app -o TARGET_ORG # Use targeted deployment: sf project deploy start --metadata AiAuthoringBundle:MyAgent -o TARGET_ORG - Open Questions: Will Salesforce optimize
AiEvaluationDefinitiondeploy performance in a future release?
Issue 2: sf agent publish fails with namespace prefix on apex:// targets
- Status: OPEN
- Date Discovered: 2026-02-01
- Affects: Namespaced orgs using
apex://action targets - Symptom:
sf agent publish authoring-bundlefails with "invocable action does not exist" error, despite the Apex class being deployed and confirmed via SOQL query. - Root Cause: Unknown. Unclear whether
apex://ClassNameorapex://ns__ClassNameis the correct format in namespaced orgs. The publish step may not resolve namespace prefixes the same way as standard metadata deployment. - Workaround: None confirmed. Potential approaches to try:
- Use
apex://ns__ClassNameformat - Use unmanaged classes (no namespace)
- Wrap Apex in a Flow and use
flow://target instead
- Use
- Open Questions:
- Does
apex://ns__ClassNamework? - Is this a bug or by-design limitation?
- Does the same issue affect
flow://targets with namespaced Flows?
- Does
Issue 3: Agent packaging workflow unclear
- Status: OPEN
- Date Discovered: 2026-02-05
- Affects: ISV partners, AppExchange distribution
- Symptom: No documented way to package Agent Script agents for distribution. The
AiAuthoringBundlemetadata type has no known packaging equivalent toBotTemplate. - Root Cause: Agent Script is newer than the packaging system. Salesforce has not published ISV packaging guidance for
.agentfiles. - Workaround: None. Current options:
- Distribute as source code (customer deploys manually)
- Use unlocked packages (may include
.agentfiles but subscriber customization is untested) - Convert to Agent Builder UI (GenAiPlannerBundle) for packaging — loses Agent Script benefits
- Open Questions:
- Will
AiAuthoringBundlebe supported in 2GP managed packages? - Can subscribers modify
.agentfiles post-install? - Is there a roadmap item for Agent Script packaging?
- Will
Issue 4: Legacy sf bot CLI commands incompatible with Agent Script
- Status: OPEN
- Date Discovered: 2026-01-25
- Affects: Users migrating from Einstein Bots to Agent Script
- Symptom: Old
sf botandsf bot versioncommands were removed in sf CLI v2 — these commands no longer exist, not just "don't recognize Agent Script". Running anysf botcommand returns "Command not found". - Root Cause: The
sf botcommand family was deprecated and removed in sf CLI v2. It targetedBotDefinition/BotVersionmetadata types. Agent Script usesAiAuthoringBundle, a completely separate metadata structure. - Workaround: Use
sf agentcommands exclusively for Agent Script:# ❌ Old commands (don't work with Agent Script): sf bot list sf bot version list # ✅ New commands (for Agent Script): sf project retrieve start --metadata Agent:MyAgent sf agent validate authoring-bundle --api-name MyAgent sf agent publish authoring-bundle --api-name MyAgent - Open Questions: Will Salesforce unify the
sf botandsf agentcommand families?
Issue 5: Agent tests cannot be deployed/retrieved for source control
- Status: OPEN
- Date Discovered: 2026-02-06
- Affects: CI/CD pipelines, test version control
- Symptom: Tests created in the Agent Testing Center UI cannot be retrieved via
sf project retrieve start. Old test XML format referencesbot/versionfields that don't exist in Agent Script. No metadata type or CLI command exists for new-style agent tests. - Root Cause: The Agent Testing Center was originally built for Einstein Bots. The test metadata schema hasn't been updated for Agent Script's
AiAuthoringBundlestructure. TheAiEvaluationDefinitiontype exists but doesn't correspond to the Testing Center's UI-created tests. - Workaround:
- Use YAML test spec files managed in source control (see
/sf-ai-agentforce-testingskill) - Treat UI-created tests as ephemeral / org-specific
- Use the Connect API directly to run tests programmatically
- Use YAML test spec files managed in source control (see
- Open Questions:
- Will a new metadata type be introduced for Agent Script tests?
- Can
AiEvaluationDefinitionbe used with Agent Script agents? - Is there a roadmap for test portability?
- References: See
references/custom-eval-investigation.mdinsf-ai-agentforce-testingfor related findings on custom evaluation data structure issues.
Issue 6: require_user_confirmation does not trigger confirmation dialog
- Status: OPEN
- Date Discovered: 2026-02-14
- Date Updated: 2026-02-17 (TDD v2.2.0 — confirmed compiles on target-backed actions)
- Affects: Actions with
require_user_confirmation: True - Symptom: Setting
require_user_confirmation: Trueon an action definition does not produce a user-facing confirmation dialog before execution. The action executes immediately without user confirmation. - Root Cause: The property is parsed and saved without error, but the runtime does not implement the confirmation UX for Agent Script actions. It may only work for GenAiPlannerBundle actions in the Agent Builder UI.
- TDD Update (v2.2.0): Property compiles and publishes successfully on action definitions with
target:(bothflow://andapex://). Val_Action_Meta_Props confirms compilation. The issue is purely runtime — the confirmation dialog never appears. Property is NOT valid on@utils.transitionactions (Val_Action_Properties, v1.3.0). - Workaround: Implement confirmation logic manually using a two-step pattern: (1) LLM asks user to confirm, (2) action has
available when @variables.user_confirmed == Trueguard. - Open Questions: Will this be implemented for AiAuthoringBundle in a future release?
Issue 7: OOTB Asset Library actions may ship without proper quote wrapping
- Status: WORKAROUND
- Date Discovered: 2026-02-14
- Affects: Out-of-the-box (OOTB) actions from the Agentforce Asset Library
- Symptom: Some pre-built actions from the Asset Library have input parameters that are not properly quote-wrapped, causing parse errors when referenced in Agent Script.
- Root Cause: Asset Library actions were designed for the Agent Builder UI path, which handles quoting differently than Agent Script's text-based syntax.
- Workaround: When importing Asset Library actions, manually verify all input parameter names in the action definition. If a parameter name contains special characters or colons (e.g.,
Input:query), wrap it in quotes:with "Input:query" = ... - Open Questions: Will Salesforce update Asset Library actions for Agent Script compatibility?
Issue 8: Lightning UI components do not render on new planner
- Status: OPEN
- Date Discovered: 2026-02-14
- Affects: Agents using Lightning Web Components for rich UI rendering
- Symptom: Custom Lightning UI components referenced in agent actions do not render in the chat interface when using the newer planner engine. Components that worked with the legacy planner appear as plain text or are silently dropped.
- Root Cause: The newer planner (Atlas/Daisy) does not support the same Lightning component rendering pipeline as the legacy Java planner.
- Workaround: None for rich UI. Fall back to text-based responses or use the legacy planner if Lightning component rendering is critical.
- Open Questions: Is Lightning UI rendering on the roadmap for the new planner?
Issue 9: Large action responses cause data loss from state
- Status: OPEN
- Date Discovered: 2026-02-14
- Affects: Actions returning large payloads (>50KB response data)
- Symptom: When an action returns a large response payload, subsequent variable access may return null or incomplete data. State appears to lose previously stored values.
- Root Cause: Action output data accumulates in conversation context without compaction. Very large responses may push earlier state data beyond the context window boundary.
- Workaround: Design Flow/Apex actions to return minimal, summarized data. Use
filter_from_agent: Trueon outputs the LLM doesn't need. AvoidSELECT *patterns in data retrieval. - Open Questions: Will automatic context compaction be added for action outputs?
Issue 10: Agent fails if user lacks permission for ANY action
- Status: OPEN
- Date Discovered: 2026-02-14
- Affects: Agents with actions targeting secured resources
- Symptom: If the running user (Einstein Agent User or session user) lacks permission to execute ANY action defined in the agent — even actions in other topics — the entire agent may fail with a permission error rather than gracefully skipping the unauthorized action.
- Root Cause: The planner appears to validate permissions for all registered actions at startup, not lazily per-topic.
- Workaround: For Service Agents: Ensure the Einstein Agent User has both the
AgentforceServiceAgentUsersystem PS AND a custom{AgentName}_AccessPS with<classAccesses>for ALL Apex classes across all topics. Do NOT rely on the auto-generatedNextGen_{AgentName}_Permissions— it is often incomplete (ORM1 testing: 3/4 classes, missingShipmentTracker). For Employee Agents: Ensure each employee user has the custom PS assigned. See agent-user-setup.md for the full provisioning workflow and permission set XML template. Alternatively, split agents by permission boundary. - Open Questions: Will the planner support lazy permission checking in a future release?
Issue 11: Welcome/error interpolation written as a quoted string renders literally
Status: WORKAROUND
Date Discovered: 2026-02-14
Affects:
system.messages.welcome/system.messages.errorwhen{!...}interpolation is authored inlineSymptom: A message such as
welcome: "Hi {!@variables.user_preferred_name}!"can display the{!...}token literally instead of rendering the variable value.Root Cause: System messages use a template-style rendering path for interpolation. Plain quoted string form is reliable for static text, but dynamic welcome/error messages should be authored in template/block form.
Workaround: Replace quoted interpolation with block-form template syntax.
❌ Wrong
system: messages: welcome: "Hi {!@variables.user_preferred_name}!" error: "Sorry, something went wrong."✅ Correct
system: messages: welcome: | Hi {!@variables.user_preferred_name}! How can I help? error: "Sorry, something went wrong."Open Questions: Should the validator auto-suggest template mode whenever
{!...}appears on a quoted welcome/error line?
Issue 12: System welcome/error messages are templates, not procedural instruction blocks
- Status: WORKAROUND
- Date Discovered: 2026-02-14
- Affects:
system.messages.welcome/system.messages.errorpersonalization - Symptom: Authors sometimes expect welcome/error messages to behave like
reasoning.instructions: ->, including conditional logic or step-by-step instruction resolution. - Root Cause:
system.messagessupports simple template rendering, not the procedural control flow available in topicinstructions: ->blocks. - Workaround: Keep welcome/error messages to static text or direct variable references. Move
if/else,run, or richer personalization logic into the first topic'sreasoning.instructions: ->block. - Open Questions: Will system messages eventually gain richer templating beyond direct variable injection?
Issue 13: Related agent nodes fail in SOMA configuration
- Status: OPEN
- Date Discovered: 2026-02-14
- Affects: Multi-agent configurations using
related_agentreferences - Symptom: SOMA (Same Org Multi-Agent) configurations that reference related agents via node declarations fail with "Node does not have corresponding topic" error at runtime.
- Root Cause: The planner resolves agent references at compile time but may not correctly map cross-agent topic references when agents are deployed independently.
- Workaround: Use
@topic.Xdelegation within the same agent instead of cross-agent references. For true multi-agent scenarios, use the@utils.escalateor connection-based handoff patterns. - Open Questions: Will SOMA node resolution be fixed in a future planner update?
Issue 14: Previously valid OpenAPI schemas now fail validation
- Status: OPEN
- Date Discovered: 2026-02-14
- Affects: External Service actions using OpenAPI 3.0 schemas
- Symptom: OpenAPI schemas that previously passed validation and worked with
externalService://targets now fail with schema validation errors after org upgrades. No changes were made to the schema files. - Root Cause: Salesforce tightened OpenAPI schema validation rules in recent releases. Schemas that were previously accepted with minor deviations (e.g., missing
info.version, non-standard extensions) are now rejected. - Workaround: Re-validate schemas against strict OpenAPI 3.0 spec. Common fixes: ensure
info.versionis present, remove non-standardx-extensions, verify all$refpaths resolve correctly. - Open Questions: Will Salesforce publish the exact validation rules that changed?
Issue 15: Action definitions without outputs: block cause "Internal Error" on publish
- Status: WORKAROUND
- Date Discovered: 2026-02-16
- Date Updated: 2026-02-17 (TDD v2.1.0 — clarified outputs specifically required)
- Affects:
sf agent publish authoring-bundlewith topic-level action definitions - Symptom:
sf agent publishreturns "Internal Error, try again later" when topic-level action definitions havetarget:but nooutputs:block. Also triggered when usinginputs:withoutoutputs:. LSP + CLI validation both PASS — error is server-side compilation only. - Root Cause: The server-side compiler needs output type contracts to resolve
flow://andapex://action targets. Without anoutputs:block, the compiler cannot generate return bindings. Theinputs:block alone is NOT sufficient —outputs:is specifically required. - Workaround: Always include an
outputs:block in action definitions. Theinputs:block can be omitted if the target has no required inputs (the LLM will still slot-fill viawith param=...), butoutputs:must always be present. - TDD Validation:
Val_No_Outputs(v2.1.0) confirms inputs-only action definition → "Internal Error".Val_Partial_Outputconfirms declaring a subset of outputs IS valid.Val_Apex_Bare_Outputconfirms bare@InvocableMethodwithout wrapper classes also triggers this error. - Cross-reference: See also Issue 27 — a related but distinct error occurs when action I/O is present but doesn't match ALL invocable target parameters.
- Open Questions: Will the compiler be updated to infer I/O schemas from the target's metadata?
Issue 17: EinsteinAgentApiChannel surfaceType not available on all orgs
- Status: OPEN
- Date Discovered: 2026-02-16
- Affects: Agent Runtime API channel enablement via
plannerSurfacesmetadata - Symptom: Adding
plannerSurfaceswithsurfaceType: EinsteinAgentApiChannelcauses deployment errors on some orgs. Valid surfaceType values on tested orgs:Messaging,CustomerWebClient,Telephony,NextGenChat. - Root Cause: The
EinsteinAgentApiChannelsurfaceType may require specific org features or licenses that are not universally available. - Workaround: Use
CustomerWebClientfor Agent Runtime API / CLI testing. This surfaceType is available on all tested orgs and enables API access. - Open Questions: Is
EinsteinAgentApiChannellimited to specific editions or feature flags?
Issue 18: connection messaging: only generates Messaging plannerSurface — CustomerWebClient dropped on every publish
- Status: OPEN
- Date Discovered: 2026-02-17
- Affects: Agent Builder Preview, Agent Runtime API testing, CLI testing (
sf agent test,sf agent preview) - Symptom: After
sf agent publish authoring-bundle, the compiled GenAiPlannerBundle only contains aMessagingplannerSurface.CustomerWebClientis never auto-generated. Agent Builder Preview shows "Something went wrong. Refresh and try again." because it requiresCustomerWebClient. - Root Cause: The
connection messaging:DSL block only generates aMessagingplannerSurface during compilation. There is noconnection customerwebclient:DSL syntax — attempting it causesERROR_HTTP_404on publish. The compiler has no mechanism to auto-generateCustomerWebClient. - Impact: Every publish overwrites the GenAiPlannerBundle, dropping any manually-added
CustomerWebClientsurface. This requires a post-publish patch after EVERY publish. - Workaround — 6-Step Post-Publish Patch Workflow:
sf agent publish authoring-bundle --api-name AgentName -o TARGET_ORG --json→ creates new version (e.g., v22)sf project retrieve start --metadata "GenAiPlannerBundle:AgentName_vNN" -o TARGET_ORG --json→ retrieve compiled bundle- Manually add second
<plannerSurfaces>block to the XML with<surfaceType>CustomerWebClient</surfaceType>(copy the existingMessagingblock, change surfaceType and surface fields) sf agent deactivate --api-name AgentName -o TARGET_ORG→ deactivate agent (deploy fails while active)sf project deploy start --metadata "GenAiPlannerBundle:AgentName_vNN" -o TARGET_ORG --json→ deploy patched bundlesf agent activate --api-name AgentName -o TARGET_ORG→ reactivate agent
- Patch XML Example:
<!-- Add this AFTER the existing Messaging plannerSurfaces block --> <plannerSurfaces> <adaptiveResponseAllowed>false</adaptiveResponseAllowed> <callRecordingAllowed>false</callRecordingAllowed> <outboundRouteConfigs> <escalationMessage>One moment while I connect you with a support specialist.</escalationMessage> <outboundRouteName>Route_from_Your_Agent</outboundRouteName> <outboundRouteType>OmniChannelFlow</outboundRouteType> </outboundRouteConfigs> <surface>SurfaceAction__CustomerWebClient</surface> <surfaceType>CustomerWebClient</surfaceType> </plannerSurfaces> - Note: The
outboundRouteConfigsshould mirror the Messaging surface config. If no routing is configured, omitoutboundRouteConfigs. - Note:
outboundRouteNamein compiled XML does NOT needflow://prefix — the publisher strips it during compilation. Both forms work in production XML. - Validated on: Production org, 2026-02-17
Issue 19: Comments inside if blocks treated as empty body
- Status: OPEN
- Date Discovered: 2026-03-04
- Affects:
if/elseblocks ininstructions: -> - Symptom: An
ifblock containing only comments (e.g.,# TODO) compiles but produces an empty body at runtime. The parser strips comments during tokenization, and the resultingINDENT → DEDENTwith no executable statements creates a no-op branch that silently swallows the conditional path. - Root Cause: Comments are not executable statements in Agent Script. The parser treats a comment-only block identically to an empty block.
- Workaround: Always include at least one executable statement (
| text,run,set, ortransition) in everyif/elseblock. Never use comment-only blocks as placeholders.# ❌ WRONG — empty body after comment stripping if @variables.premium == True: # TODO: add premium greeting # ✅ CORRECT — executable statement present if @variables.premium == True: | Welcome back, valued premium member! - Open Questions: Will the compiler emit a warning for empty
ifbodies?
Issue 20: GenAiPlannerBundle / AiAuthoringBundle / GenAiFunction NOT SOQL-queryable
- Status: WORKAROUND (by design — metadata types, not sObjects)
- Date Discovered: 2026-03-04
- Affects: Any workflow that attempts SOQL queries on agent metadata types
- Symptom:
SELECT ... FROM GenAiPlannerBundlereturnsINVALID_TYPE: GenAiPlannerBundle. Same forAiAuthoringBundleandGenAiFunction. These types do not appear inEntityDefinitionSOQL queries. - Root Cause: These are Metadata API types, not sObjects. They exist in the metadata layer and are only accessible via
sf project retrieve start --metadataor the Metadata API. This is by design, not a bug. - Workaround: Use
sf project retrieve start --metadata "TypeName:ApiName"instead of SOQL. For querying agent status/versions via SOQL, useBotDefinitionandBotVersionsObjects.# ❌ WRONG — these are NOT sObjects sf data query --query "SELECT Id FROM GenAiPlannerBundle" -o ORG --json sf data query --query "SELECT Id FROM AiAuthoringBundle" -o ORG --json # ✅ CORRECT — use Metadata API sf project retrieve start --metadata "GenAiPlannerBundle:MyAgent_v1" -o ORG --json sf project retrieve start --metadata "AiAuthoringBundle:MyAgent" -o ORG --json # ✅ CORRECT — query sObjects for agent info sf data query --query "SELECT Id, DeveloperName FROM BotDefinition WHERE DeveloperName = 'MyAgent'" -o ORG --json sf data query --query "SELECT Id, VersionNumber, Status FROM BotVersion WHERE BotDefinition.DeveloperName = 'MyAgent'" -o ORG --json - Open Questions: None — this is by design.
Issue 21: Old GenAiPlannerBundle versions block Apex class deletion
- Status: WORKAROUND
- Date Discovered: 2026-03-10
- Affects: Apex class lifecycle when iterating agent versions
- Symptom:
sf project delete source --metadata ApexClass:MyClassfails with "setup object in use" even though the Apex class is only referenced by inactive/old GenAiPlannerBundle versions. The current active bundle may reference a different (newer) Apex class, but old bundles still hold GenAiFunction references to the original. - Root Cause: Each
sf agent publish authoring-bundlecreates a new GenAiPlannerBundle version. Old versions remain in the org and retainGenAiPluginActionDefinitionrecords that reference the Apex class viaGenAiFunction. The platform blocks deletion of any metadata referenced by ANY GenAiFunction — active or not. - Workaround: Delete old bundles using the Orphan-Then-Delete pattern (Tooling API PATCH to null
PlannerIdon childGenAiPluginDefinitionrecords, then DELETE the parentGenAiPlannerBundle). After all referring bundles are removed, the Apex class can be deleted normally.- Note: Apex test classes (not referenced by GenAiFunction) can be deleted freely at any time.
- Open Questions: Will Salesforce add cascade cleanup for inactive bundle versions?
- References: See metadata-lifecycle.md for the full Orphan-Then-Delete pattern and API comparison table.
Issue 22: Flow version drift causes publish failure
- Status: WORKAROUND
- Date Discovered: 2026-03-10
- Affects: Action definitions targeting
flow://with I/O schemas - Symptom:
sf agent publish authoring-bundlefails with I/O mismatch errors when the action'sinputs:/outputs:block matches the latest Flow version but NOT the active Flow version. The publisher validates against the active version's I/O contract. - Root Cause:
sf project retrieve start --metadata Flow:FlowNameretrieves the latest Flow version, which may be Draft or Obsolete. If the latest version renamed, added, or removed inputs/outputs compared to the active version, the locally-defined action I/O will not match what the publisher expects. - Example: Flow
Locate_Itemshas v2 (active) with inputIncomingCaseIdand v5 (latest, Obsolete) with inputRecordId. Retrieving the Flow gives v5 metadata, so the developer definesinputs: record_id: string— but publish validates against v2'sIncomingCaseId. - Workaround: Before defining action I/O, verify the active Flow version's inputs:
Ifsf data query --query "SELECT ActiveVersionId, LatestVersionId FROM FlowDefinitionView WHERE ApiName = 'My_Flow' LIMIT 1" -o TARGET_ORG --jsonActiveVersionId != LatestVersionId, inspect the active version's I/O before writing your action definition. - Open Questions: Will
sf project retrieve startgain a--active-versionflag for Flows? - References: See metadata-lifecycle.md § "Flow Version Drift" and cli-guide.md § "Step 1: Retrieve" warning box.
Issue 23: HTTP 500 on publish when default_agent_user is set for Employee Agent
- Status: WORKAROUND
- Date Discovered: 2026-03-11
- Affects:
sf agent publish authoring-bundle - Symptom: Publish fails with generic HTTP 500 error (no detailed message). Occurs when
default_agent_useris included in the config block for anAgentforceEmployeeAgent, or whendefault_agent_userreferences a non-existent user for a Service Agent. - Root Cause: The Einstein Platform tries to resolve the
default_agent_userreference during publish. For Employee Agents, this field is invalid entirely. For Service Agents, if the user doesn't exist or lacks the Einstein Agent User profile, the API returns 500 instead of a descriptive error. - Workaround: For Employee Agents, remove
default_agent_userentirely and setagent_type: "AgentforceEmployeeAgent". For Service Agents, verify the user exists and is truly valid for publish: active, notAutomatedProcess, andProfile.Name = 'Einstein Agent User'. - Extra diagnostic: If
sf agent publish authoring-bundle --jsonstill fails after validate/preview pass, retry with--skip-retrieve. If--skip-retrievesucceeds, the failure was in the CLI retrieve/deploy-back phase rather than in the publish itself. - Open Questions: Will the API return a descriptive error instead of 500? Will the CLI expose retrieve-phase failures separately from publish failures?
Issue 24: Omitting agent_type silently defaults to Service Agent behavior
- Status: WORKAROUND
- Date Discovered: 2026-03-11
- Affects: Agent config block
- Symptom: Agent without explicit
agent_typebehaves as Service Agent. Ifdefault_agent_useris also missing, publish fails with HTTP 500. No warning or error is emitted about the missing field. - Root Cause: The compiler defaults to
EinsteinServiceAgentinternally whenagent_typeis not specified. - Workaround: Always set
agent_typeexplicitly to"AgentforceServiceAgent"or"AgentforceEmployeeAgent". - Open Questions: Will the compiler emit a warning when
agent_typeis omitted?
Issue 25: GenAiPluginDefinition Duplicate Name Collision
Symptom: Publish fails with GenAiPluginDefinition name conflict error.
Cause: When start_agent and a topic share the same API name, the generated GenAiPluginDefinition metadata collides — both produce identically-named plugin definitions.
Workaround: Ensure start_agent and all topic blocks use unique API names. A common pattern is to prefix the start agent name (e.g., Start_My_Agent vs My_Agent_Topic).
Issue 26: is_required: True is a no-op for the planner
- Status: OPEN
- Date Discovered: 2026-03-11
- Affects: Action input definitions with
is_required: True - Symptom: Actions are invoked by the planner with empty or missing values for inputs marked
is_required: True. The planner does not enforce the required constraint — it treats it as a hint, not a hard gate. Users expect the planner to refuse invocation until all required inputs are filled, but it proceeds regardless. - Root Cause: The
is_requiredproperty compiles and is stored in the GenAiFunction metadata, but the planner does not validate required inputs before action invocation. The property only influences LLM slot-filling behavior (the LLM tries to collect the value but is not blocked from proceeding without it). - Workaround: Use
available whenguards to enforce required inputs deterministically:# ❌ INSUFFICIENT — planner ignores is_required inputs: order_id: string is_required: True # ✅ CORRECT — deterministic enforcement reasoning: actions: lookup: @actions.get_order available when @variables.order_id is not None - Open Questions: Will the planner enforce
is_requiredin a future release? - Cross-reference: See syntax-reference.md § Action Metadata Properties, Common Pitfalls.
Issue 27: ConcurrentModificationException when action I/O doesn't match invocable target
- Status: WORKAROUND (fix expected in 260.4)
- Date Discovered: 2026-03-11
- Affects: Action definitions with
inputs:/outputs:blocks where the I/O schema does not declare ALL parameters on the invocable target - Symptom:
sf agent publish authoring-bundlefails withConcurrentModificationExceptionor "Internal Error" when the action definition's I/O schema is a subset of the target's invocable parameters. For example, if a Flow has 5 inputs but the action only declares 3, the server-side compiler throws an internal error. - Root Cause: The compiler iterates over target parameters and agent I/O simultaneously. When the agent-side schema omits parameters that exist on the target, the iterator state becomes inconsistent, causing a
ConcurrentModificationException. - Workaround: Declare ALL inputs and outputs from the invocable target in the action definition, even parameters the agent doesn't use. Unused inputs can be given a default or left for the LLM to fill. Unused outputs can be marked
filter_from_agent: True.# ❌ WRONG — subset of target params causes ConcurrentModificationException inputs: customer_id: string # (target also has order_type, priority — not declared) # ✅ CORRECT — declare all target params inputs: customer_id: string order_type: string description: "Type of order" priority: string description: "Priority level" - Open Questions: Fix expected in release 260.4. Will partial I/O schemas be supported?
- Cross-reference: Related to Issue 15 (missing outputs block). Issue 15 covers the case where
outputs:is absent entirely; this issue covers the case where I/O is present but incomplete.
<a id="issue-28"></a>
Issue 28: date primitive type in action I/O causes runtime error
- Status: WORKAROUND
- Date Discovered: 2026-03-11
- Affects: Action input/output definitions using
dateas the type - Symptom: Actions with
datetyped inputs or outputs compile and publish without error, but fail at runtime with'Date'type error when the action is invoked. The LLM-provided value cannot be coerced into the platform's expected Date format. - Root Cause: The
dateprimitive in Agent Script compiles to a type that the action invocation runtime does not handle correctly. The runtime expects a specific ISO-8601 format that the LLM's slot-filled value does not match. - Workaround: Use
objecttype withcomplex_data_type_namereferencing the Lightning date type:# ❌ WRONG — causes runtime error 'Date' inputs: appointment_date: date # ✅ CORRECT — use object + Lightning type mapping inputs: appointment_date: object complex_data_type_name: "lightning__dateType" - Open Questions: Will the
dateprimitive be fixed to work in action I/O? - Cross-reference: See syntax-reference.md § Variable Types, complex-data-types.md.
Issue 29: ANTLR parser error for large/complex .agent files
- Status: OPEN
- Date Discovered: 2026-03-11
- Affects: Large
.agentfiles (approximately 1,664+ lines observed) - Symptom: The Agent Script parser (ANTLR-based) fails with a parser error when processing very large or highly complex
.agentfiles. The error is non-specific and occurs during the parsing phase before any semantic validation. - Root Cause: The ANTLR parser has practical limits on grammar complexity and token count. Very large agents with many topics, deep nesting, or extensive instruction blocks can exceed these limits.
- Workaround: None confirmed. Potential mitigations:
- Reduce agent size by simplifying instructions (move verbose prompts into Prompt Templates)
- Reduce topic count by consolidating related topics
- Use topic delegation (
@topic.X) to split into multiple smaller agents
- Open Questions: What is the exact line/token limit? Will the parser be updated to handle larger files?
Issue 30: 500 "Failed to create planner session" (widespread, multi-version)
- Status: OPEN
- Date Discovered: 2026-03-11
- Affects: Agent runtime — all agent types and versions
- Symptom: Agent returns HTTP 500 with "Failed to create planner session" when a user initiates a conversation. Error is intermittent and affects multiple orgs across different Salesforce releases. Not correlated with agent complexity, user permissions, or time of day.
- Root Cause: Unknown. The error originates in the planner session initialization layer. Suspected to be a transient infrastructure issue on the Einstein Platform side.
- Workaround: None reliable. Retry after a few minutes. If persistent:
- Deactivate and reactivate the agent
- Re-publish the authoring bundle (creates a new BotVersion)
- Contact Salesforce support with the session ID and timestamp
- Open Questions: Is this a known infrastructure issue with an ETA for fix?
<a id="issue-31"></a>
Issue 31: Escalation loops when no human agents available
- Status: WORKAROUND
- Date Discovered: 2026-03-11
- Affects:
@utils.escalateaction in agents deployed without live human agents - Symptom: When
@utils.escalateis invoked but no human agents are available (e.g., outside business hours, no Omni-Channel agents online), the escalation fails silently and the conversation re-enters the same topic. This triggers the escalation logic again, creating an infinite loop. The built-in 3-4 loop guardrail eventually breaks the cycle, but the user receives confusing repeated messages. - Root Cause:
@utils.escalatedoes not return a success/failure status. There is no built-in mechanism to detect whether human agents are available before attempting escalation, and no way to handle a failed escalation gracefully. - Workaround: Check agent availability before escalating, and provide a fallback path:
variables: escalation_attempted: mutable boolean = False topic escalation: description: "Escalate to human agent" reasoning: instructions: -> if @variables.escalation_attempted == True: | I'm sorry, but our team is currently unavailable. | Please try again during business hours or leave a message. transition to @topic.leave_message | Let me connect you with a support specialist. actions: handoff: @utils.escalate description: "Transfer to human agent" before_reasoning: if @variables.escalation_attempted == True: # Already tried — don't loop transition to @topic.leave_message set @variables.escalation_attempted = True - Open Questions: Will
@utils.escalatereturn a status code in a future release? Will a built-in availability check action be added? - Cross-reference: See fsm-architecture.md § Pattern 5 (HANDOFF) — Escalation with Availability Check sub-pattern. See production-gotchas.md § Escalation Fallback Loop.
Issue 32: Citations not rendering in NGA agents vs legacy agents
- Status: OPEN
- Date Discovered: 2026-03-11
- Affects: Next-Generation Agent (NGA / Agent Script) agents using knowledge bases with citations enabled
- Symptom: Despite enabling all citation settings (
citations_enabled: True,citations_urlconfigured, knowledge base attached), citations do not render in agent responses for NGA agents. The same knowledge base with citations works correctly in legacy Einstein Bot agents. - Root Cause: The citation rendering pipeline is not fully implemented for the NGA/Agent Script agent runtime. Legacy agents use a different response rendering path that supports citation markup.
- Workaround: None for NGA agents. If citations are critical, use a legacy agent for knowledge-intensive topics, or include source URLs directly in the knowledge article content so they appear in the response text.
- Open Questions: Will citation rendering be added to the NGA runtime? Is there a timeline?
Issue 33: == [] and set ... = [] — empty list literal not supported in expressions
- Status: WORKAROUND
- Date Discovered: 2026-03-12
- Affects: Expressions using
[]literal for empty list comparison or assignment - Symptom: Two related parse errors:
if @variables.my_list == []:→ parse error ([not allowed in expression position)set @variables.my_list = []→ parse error ([not allowed in assignment position)
- Root Cause: The expression parser's sandboxed Python AST subset does not include list literal construction.
[]is valid inmutable list[T] = []declarations (handled by the declaration parser), but NOT in runtime expressions. - Workaround:
- Empty check:
if @variables.my_list is None or len(@variables.my_list) == 0: - Reset to empty: Use a dedicated empty list variable and copy:
variables: empty_temp: mutable list[string] = [] my_list: mutable list[string] = [] # To reset my_list at runtime: set @variables.my_list = @variables.empty_temp
- Empty check:
- Open Questions: Will
[]be added to the expression parser? - Cross-reference: See syntax-reference.md § Expression Limitations.
<a id="issue-34"></a>
Issue 34: is_displayable: True on prompt template outputs causes blank response
- Status: WORKAROUND
- Date Discovered: 2026-03-12
- Affects: Action outputs on prompt template actions (
prompt:///generatePromptResponse://targets) - Symptom: Setting
is_displayable: True(or toggling "Show in conversation" in the UI) on a prompt template action's output causes the agent to return a blank or empty response. The prompt template executes correctly (visible in trace), but the response text is not surfaced to the user. - Root Cause: When
is_displayable: True, the platform attempts to render the raw prompt template output directly instead of letting the reasoner synthesize it. The rendering pipeline does not handle prompt template output format correctly, resulting in blank display. - Workaround: Set
is_displayable: Falseon prompt template outputs and let the reasoner synthesize the output into its response naturally. If the output should influence the reply or routing, also setis_used_by_planner: Trueon that field.# ❌ WRONG — causes blank response outputs: response_text: string is_displayable: True # ✅ CORRECT — reasoner synthesizes output outputs: response_text: string is_displayable: False is_used_by_planner: True - Open Questions: Will the rendering pipeline be updated to handle prompt template output with
is_displayable: True? - Cross-reference: See production-gotchas.md §
is_displayable: Trueon Prompt Outputs.
Issue 35: Topic description: with line breaks breaks the script
- Status: WORKAROUND
- Date Discovered: 2026-03-12
- Affects:
topicandstart_agentblocks with multi-linedescription:values - Symptom: Including line breaks (literal newlines) inside a topic's
description: "..."string causes the script to fail during parsing. The error is non-specific and may manifest as a syntax error on the following line. - Root Cause: The topic
description:parser expects a single-line string value. Unlikeinstructions:which supports|and->multiline syntax,description:does not have a multiline variant. - Workaround: Keep topic descriptions on a single line. Remove all line breaks.
# ❌ WRONG — line break in description topic support: description: "Handles customer support requests including billing and technical issues" # ✅ CORRECT — single line topic support: description: "Handles customer support requests including billing and technical issues" - Open Questions: Will
description:gain multiline support (e.g.,description: |)?
Issue 36: Variable names conflict with system context variable mappings
- Status: WORKAROUND
- Date Discovered: 2026-03-12
- Affects: Variable declarations using names that match platform context variable field names
- Symptom: Declaring a variable with a name like
Localethat matches an existing system context variable field name produces the error: "The field is already mapped to a Context Variable." The agent fails to compile. - Root Cause: The platform reserves certain variable names for internal context variable mappings (e.g.,
MessagingSessionfields likeLocale,Channel,Status). These names collide with user-declared variables at the namespace level. - Workaround: Use unique, prefixed names that avoid common MessagingSession and system field names:
Known reserved names (partial list):# ❌ WRONG — collides with system context mapping variables: Locale: mutable string = "" # ✅ CORRECT — unique prefixed name variables: customer_locale: mutable string = ""Locale,Channel,Status,Origin - Open Questions: Will Salesforce publish a complete list of reserved context variable names?
Issue 37: Draft version works but Committed version fails
- Status: OPEN
- Date Discovered: 2026-03-12
- Affects: Agent behavior difference between Draft and Committed/Active versions
- Symptom: Actions, variable updates, and topic routing that work correctly in Draft mode (preview) fail silently or produce different behavior in the Committed/Active version. The agent may skip actions, fail to update variables, or route incorrectly.
- Root Cause: Multiple potential causes reported: graph serialization differences between Draft and Committed compilation, action registry timing (Draft resolves actions lazily, Committed resolves eagerly), and stale cache from previous versions.
- Workaround: No universal workaround. Mitigation strategies:
- Re-commit (deactivate → re-publish → re-activate) to force a clean compilation
- Verify all action targets exist and are active in the org
- Compare Draft and Committed trace outputs to identify specific divergence points
- Open Questions: Will the Draft and Committed compilation paths be unified?
Issue 38: Object variables not editable in preview
- Status: OPEN
- Date Discovered: 2026-03-12
- Affects:
sf agent previewand Agent Builder Preview - Symptom: Only scalar variable types (
string,number,boolean) can be overridden in the preview interface. Object and list variables cannot be edited or injected — the UI does not provide input fields for complex types. - Root Cause: The preview interface only renders scalar input controls. No JSON editor or structured input is provided for
objectorlist[T]types. - Workaround: For values needed during testing:
- Use scalar variables that can be set in preview, then assemble in logic
- Test object/list variable scenarios via the Agent Runtime API (Connect API) which accepts JSON payloads
- Pre-populate object variables in
before_reasoning:for testing
- Open Questions: Will the preview interface add JSON editing for object/list variables?
<a id="issue-39"></a>
Issue 39: @context.* linked sources not supported for NGA Service Agents
- Status: WORKAROUND
- Date Discovered: 2026-03-12
- Affects: Linked variables using
@context.*sources in NGA Service Agents (ExternalCopilot / EinsteinServiceAgent) - Symptom: Linked variables with
source: @context.currentRecordId,source: @context.customerId, or other@context.*references produce "Unsupported data type" errors at runtime in NGA Service Agents. The variables compile and publish without error but fail when the agent starts a conversation. - Root Cause:
@context.*references resolve page-level context from Lightning Experience (LEX). This context is only available to Employee Agents embedded on LEX record pages where arecordIdand user context are present. NGA Service Agents (chat, messaging) do not have LEX page context — they receive channel context via@MessagingSession.*instead. - Workaround: For Service Agents, use
@MessagingSession.*for channel context:# ❌ WRONG for Service Agents — @context not available variables: customer_id: linked string source: @context.customerId # ✅ CORRECT for Service Agents — use messaging channel context variables: end_user_id: linked string source: @MessagingSession.MessagingEndUserId session_key: linked string source: @MessagingSession.MessagingSessionKey # ✅ CORRECT for Employee Agents on LEX — @context IS available variables: record_id: linked string source: @context.currentRecordId - Open Questions: Will
@context.*be extended to Service Agent channels? - Cross-reference: See syntax-reference.md § Resource References, Common Linked Variable Sources.
<a id="issue-40"></a>
Issue 40: Draft prompt template causes misleading publish errors for generatePromptResponse:// actions
- Status: WORKAROUND
- Date Discovered: 2026-03-17
- Affects:
sf agent publish authoring-bundlewithgeneratePromptResponse://action targets - Symptom: Publish fails with
invalid input parameters found: 'Input:query'orinvalid output parameters found: 'promptResponse'— implying the I/O names are wrong. Removing I/O blocks producesMetadata API request failed: Metadata retrieval failed:orInternal Error, try again later.sf agent validate authoring-bundlepasses in all cases. - Root Cause: The target prompt template is in Draft status. The platform cannot resolve the
generatePromptResponse://target, but reports the failure as invalid I/O parameters or generic internal errors rather than indicating the template status. - Workaround: Activate the prompt template in Setup > Prompt Builder before publishing. The original Agent Script syntax (with
"Input:X"inputs andpromptResponseoutput) publishes successfully once the template is Active. Pre-publish check: retrieve the template XML and verify<status>Published</status>or<status>Active</status>. - Open Questions: Will Salesforce improve the error message to mention template status? Will
sf agent validateadd a target resolution check? - References: action-prompt-templates.md — "Draft Template Publish Errors" section
Resolved Issues
<a id="issue-16"></a>
Issue 16: connections: (plural) wrapper block not valid — use connection messaging: (singular)
- Status: RESOLVED
- Date Discovered: 2026-02-16
- Date Resolved: 2026-02-16
- Affects: Agent Script escalation routing configuration
- Symptom: CLI validation rejects
connections:(plural wrapper) block withSyntaxError: Invalid syntax after conditional statement. - Root Cause: The correct syntax is
connection messaging:(singular, standalone top-level block) — NOT theconnections:plural wrapper shown in some docs andfuture_recipes/. Theconnection <channel>:block is a Beta Feature available on production orgs. - Resolution: Use
connection messaging:as a standalone block (no wrapper). Both minimal form (adaptive_response_allowedonly) and full form (withoutbound_route_type,outbound_route_name,escalation_message) are validated. - CRITICAL:
outbound_route_namerequiresflow://prefix — bare API name causesERROR_HTTP_404on publish. Correct format:"flow://My_Flow_Name". - All-or-nothing rule: When
outbound_route_typeis present, all three route properties are required. - Note:
outboundRouteNamein compiled XML does NOT need theflow://prefix — the publisher strips it during compilation. Both forms work in production XML. - Validated on: Production org, 2026-02-16
<a id="issue-40-filter-planner-conflict"></a>
Issue 40: filter_from_agent + is_used_by_planner on same output — InvalidFormatError with cascade
- Status: WORKAROUND
- Severity: High (Blocking)
- Discovered: 2026-03-17
- Affects: All Agent Script action output field declarations
- Symptom: Output fields that declare both
filter_from_agentandis_used_by_plannerproduceInvalidFormatErrorwith the message: "Remove the 'is_used_by_planner' field and use only 'filter_from_agent'." More critically, this invalidates the entire action definition, causing cascadingACTION_NOT_IN_SCOPEerrors everywhere the action is referenced — inbefore_reasoning:run @actions.Xcalls andreasoning.actions:invocations. The cascade makes the root cause very hard to diagnose because the error appears on action references, not on the offending output field. - Root Cause:
filter_from_agentandis_used_by_plannerare mutually exclusive output visibility controls. When both are present, the Agent Script parser rejects the output field, which poisons the entire action definition and makes it invisible to all scopes. - Cascade Pattern: One invalid output field on a shared action (e.g.,
update_sessionreused across topics) can triggerACTION_NOT_IN_SCOPEerrors in every topic that references it — often 4-6+ errors from a single root cause. - Workaround: Use only
filter_from_agent: Trueon outputs that should be hidden from the customer. Removeis_used_by_plannerfrom those fields entirely. The planner can still reason about the output viaset @variables.X = @outputs.Ybindings in reasoning actions. - Example:
# ❌ WRONG — causes InvalidFormatError + cascade outputs: caseId: string filter_from_agent: True is_used_by_planner: False # ✅ CORRECT — filter_from_agent alone outputs: caseId: string filter_from_agent: True - Validator Rule:
ASV-RUN-020(Blocking) - Real-world impact: Observed in a production agent — 6 output fields across 5 topics caused 4 cascading
ACTION_NOT_IN_SCOPEerrors that blocked publish. - Validated on: Production sandbox, 2026-03-17
Issue 41: Lifecycle arithmetic on mutable number crashes when variable is None at runtime
- Status: WORKAROUND
- Severity: High (Silent crash)
- Discovered: 2026-03-17
- Affects:
before_reasoning/after_reasoningblocks with arithmetic on mutable number variables - Symptom: Agent crashes silently with "unexpected error" when a
before_reasoningblock doesset @variables.counter = @variables.counter + 1and the variable isNoneat runtime. The crash isNone + 1— a type error in the expression evaluator. No useful error message is surfaced to the user or logs. - Root Cause: Mutable number variables declared with
= 0defaults can arrive asNoneat runtime. Known triggers: (1) Eval API / Testing Center state injection that omits the variable, (2) platform variable initialization bugs where defaults are not applied before the firstbefore_reasoningexecution. - Cascade Pattern: Common in guardrail topics where a strike counter is incremented on every entry. All guardrail topics (e.g.,
inappropriate_content,prompt_injection,reverse_engineering) crash simultaneously since they share the same counter pattern. - Workaround: Add a null guard before any arithmetic in lifecycle hooks:
# ❌ CRASHES when guardrail_strikes is None before_reasoning: set @variables.guardrail_strikes = @variables.guardrail_strikes + 1 if @variables.guardrail_strikes >= 3: transition to @topic.escalation # ✅ SAFE — null guard prevents None + 1 before_reasoning: if @variables.guardrail_strikes is None: set @variables.guardrail_strikes = 0 set @variables.guardrail_strikes = @variables.guardrail_strikes + 1 if @variables.guardrail_strikes >= 3: transition to @topic.escalation - Validator Rule:
ASV-RUN-021(Warning) - Validated on: Production sandbox, 2026-03-17
Issue 42: Raw @system_variables.user_input substring matching is brittle for deterministic routing
- Status: WORKAROUND
- Date Discovered: 2026-03-20
- Affects: Deterministic branching that uses
contains,startswith, orendswithdirectly on@system_variables.user_input - Symptom: Rules such as
if @system_variables.user_input contains "never mind":appear simple, but cancellation/revision detection behaves inconsistently across real user phrasing. The branch may miss intent variants or fail to trigger when punctuation, casing, or phrasing changes. - Root Cause:
@system_variables.user_inputis raw last-utterance text, not a normalized intent signal. Direct substring checks are too weak for control-flow-critical intent detection. - Workaround: Normalize the utterance first via Flow, Apex, or a classifier action, then branch on an explicit boolean or enum.
# ❌ BRITTLE — raw text matching if @system_variables.user_input contains "never mind": transition to @topic.cancel_request # ✅ SAFER — normalize first run @actions.classify_user_intent with utterance = @system_variables.user_input set @variables.cancel_requested = @outputs.cancel_requested if @variables.cancel_requested == True: transition to @topic.cancel_request - Validator Rule:
ASV-RUN-023(Warning) - Open Questions:
- Will future runtime layers provide stronger deterministic utterance-matching semantics?
- Will direct raw-text guards become portable enough to recommend for intent routing?
Contributing
When you discover a new platform issue during an Agent Script session:
- Add it to the Open Issues section using the template above
- Assign the next sequential issue number
- Set status to
OPENorWORKAROUND - Include the date discovered
- Be specific about the symptom and any error messages
- Note what you've tried so far under "Workaround"
When an issue is resolved:
- Update the status to
RESOLVED - Add the resolution date and what fixed it (e.g., "Fixed in Spring '26 release")
- Move the issue to the Resolved Issues section
Last updated: 2026-03-20 (v2.9.0)
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Agent Metadata Lifecycle & Cleanup
Versioning, cleanup, and deletion patterns for Agent Script metadata objects.
GenAiPlannerBundle Versioning
Each sf agent publish authoring-bundle creates a new GenAiPlannerBundle version. Understanding the naming conventions is critical for cleanup.
Naming Conventions
| Convention | Example | When Used |
|---|---|---|
| Hash suffix | MyAgent_16jXXXXXXXXXXXX |
Default — auto-generated by publisher |
| Version suffix | MyAgent_vNN |
Optional — set via GenAiPlannerBundle metadata after publish |
The hash suffix is non-deterministic — each publish generates a different hash. Over time, an org accumulates many bundle versions (e.g., _v18, _v19, _v22, ..., _v31).
What Each Publish Creates
sf agent publish authoring-bundle
└── GenAiPlannerBundle (new version)
├── GenAiPluginDefinition (per topic)
├── GenAiPluginActionDefinition (per action)
└── plannerSurfaces (channel config)
Old bundle versions remain in the org. They are inactive but retain references to Apex/Flow targets via GenAiFunction definitions.
Retrieve a Specific BotVersion
When you need to inspect or patch a specific published version, retrieve the exact BotVersion explicitly:
sf project retrieve start \
--metadata Bot:MyAgent \
--metadata BotVersion:MyAgent.v3 \
--target-org TARGET_ORG
Current SF CLI releases correctly retrieve the requested BotVersion rather than always falling back to only the latest version.
Flow Version Drift
sf project retrieve start --metadata Flow:FlowName retrieves the latest version (may be Draft/Obsolete), while the publisher validates against the active version's I/O.
Impact: If the latest Flow version renamed an input (e.g., RecordId -> IncomingCaseId), your locally-defined action I/O will mismatch the active version at publish time.
Prevention: Always verify the active Flow version before defining action I/O:
sf data query --query "SELECT ActiveVersionId, LatestVersionId FROM FlowDefinitionView WHERE ApiName = 'My_Flow' LIMIT 1" -o TARGET_ORG --json
If ActiveVersionId != LatestVersionId, inspect the active version's inputs via Tooling API before writing your action definition.
Orphan-Then-Delete Pattern
When Salesforce returns "setup object in use" on metadata deletion, parent-child references create circular dependency locks. The Tooling API can break these references.
Technique
- PATCH child records to null out their parent reference (e.g.,
PlannerId: null) - DELETE the now-childless parent via Tooling API REST DELETE
- Repeat up the dependency tree
Implementation
# Step 1: Orphan child PluginDefinitions by nulling PlannerId
# CRITICAL: Must set unique LocalDeveloperName to avoid DUPLICATE_DEVELOPER_NAME error
curl -X PATCH "$INSTANCE_URL/services/data/vXX.0/tooling/sobjects/GenAiPluginDefinition/PLUGIN_ID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"PlannerId": null, "LocalDeveloperName": "original_name_del_001"}'
# Step 2: Delete the now-childless PlannerBundle
curl -X DELETE "$INSTANCE_URL/services/data/vXX.0/tooling/sobjects/GenAiPlannerBundle/BUNDLE_ID" \
-H "Authorization: Bearer $TOKEN"
LocalDeveloperName Uniqueness Constraint
When nulling PlannerId, the platform enforces LocalDeveloperName uniqueness across all orphaned records. Use a unique suffix:
{"PlannerId": null, "LocalDeveloperName": "<original_name>_del_<sequence>"}
API Comparison for Setup Object Deletion
| Method | Result |
|---|---|
sf project delete source |
"setup object in use" |
SOAP deleteMetadata |
"setup object in use" |
| Tooling API DELETE (without orphaning) | "setup object in use" |
| REST API DELETE on BotDefinition | "insufficient access rights" |
| Apex DML | "DML not allowed on [object]" |
| Composite API (ordered) | "setup object in use" on each subrequest |
| Tooling API PATCH + DELETE | Works for PlannerBundle hierarchy |
What Cannot Be Deleted
Even with the Orphan-Then-Delete pattern, certain metadata objects are permanently locked:
| Object | Reason |
|---|---|
ConversationDefinitionDialog |
"System Dialog" internal protection flag |
ConversationDefinitionSession |
deletable: false at object level |
ConversationDefinitionEventLog |
deletable: false at object level |
BotVersion |
Locked by undeletable children above |
BotDefinition |
Locked by BotVersions |
Practical implication: Once a BotDefinition is created, it cannot be fully deleted via API. The UI "Delete Agent" button removes the AiAuthoringBundle and GenAiPlannerBundle, but NOT the BotDefinition itself. Contact Salesforce Support for full cleanup.
Old Bundles Block Apex Deletion
Previous GenAiPlannerBundle versions retain GenAiFunction references to Apex class targets. This creates a dependency chain:
Old GenAiPlannerBundle (v5)
└── GenAiPluginDefinition
└── GenAiPluginActionDefinition
└── References: apex://MyVerificationClass
Impact: sf project delete source --metadata ApexClass:MyVerificationClass fails with "setup object in use" even though the old bundle is inactive.
Workaround: Delete old bundles using the Orphan-Then-Delete pattern first, then delete the Apex class. Alternatively, accept orphaned Apex classes until bundles are cleaned up.
Note: Apex test classes (not referenced by GenAiFunction) can be deleted freely.
Shared Dependencies Between Agent Versions
When iterating on agent versions (V1 -> V2), Apex classes may be shared:
- V1 agent (original) created
MyVerificationClass,MySetVariable, etc. - V2 agent (rewrite) references the same Apex classes
- Deleting V1's metadata does NOT free the Apex classes if V2 still references them
- Orphaned V1 PluginDefinitions (PlannerId=null) also retain references
Best practice: Track which Apex classes are shared across agent versions. Only delete Apex classes after confirming no active agent OR orphaned PluginDefinition references them.
Recommended Cleanup Workflow
When retiring old agent bundle versions:
- Inventory: List all GenAiPlannerBundle versions (
sf project retrieve start --metadata GenAiPlannerBundle) - Identify active: Query
BotVersionfor the currently active version number - Map dependencies: For each old bundle, note which Apex/Flow classes it references
- Orphan children: PATCH each
GenAiPluginDefinitionto nullPlannerId - Delete bundles: DELETE each old
GenAiPlannerBundlevia Tooling API - Clean Apex (optional): Delete unreferenced Apex classes after all referring bundles are gone
Cross-reference: See known-issues.md Issue 21 (old bundles block Apex deletion) and Issue 22 (Flow version drift).
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Migration Guide: Agentforce Builder UI → Agent Script DSL
This guide maps every concept from the Agentforce Builder UI (Setup > Agents) to its Agent Script DSL equivalent. Use it when converting existing agents from the visual builder to code.
Builder UI → Agent Script Mapping
| # | Builder UI Concept | Agent Script Equivalent | Notes |
|---|---|---|---|
| 1 | Topic name | topic my_topic_name: |
Must use snake_case, max 80 chars |
| 2 | Classification description | description: "..." on topic |
Helps LLM decide when to enter topic |
| 3 | Scope / "What this topic can do" | reasoning.instructions + available actions |
Combined: instructions tell LLM what to do, actions tell it what tools are available |
| 4 | Instructions (numbered text boxes) | reasoning: instructions: |
Use -> for logic/expressions, | for literal text |
| 5 | Flow actions | target: flow://FlowName |
Flow must be Autolaunched and Active |
| 6 | Apex actions | target: apex://ClassName |
Class must have @InvocableMethod |
| 7 | Prompt Template actions | target: prompt://TemplateName |
generatePromptResponse://TemplateName is also valid; template must exist in org |
| 8 | "Collect from user" input | Slot-fill ... operator |
with query = ... — LLM extracts from conversation |
| 9 | "Show/Hide in conversation" toggle | filter_from_agent: True |
On action output definitions |
| 10 | "Require Confirmation" toggle | require_user_confirmation: True |
On action definitions |
| 11 | Guard Conditions | available when clause |
available when @variables.verified == True |
What's New in Agent Script (No Builder UI Equivalent)
These capabilities exist ONLY in Agent Script — they cannot be configured through the Builder UI:
| # | Feature | Description | Example |
|---|---|---|---|
| 1 | before_reasoning: hook |
Deterministic pre-processing before LLM sees instructions | Set variables, load data, enforce gates |
| 2 | after_reasoning: hook |
Deterministic post-processing after LLM finishes | Logging, cleanup, audit flags |
| 3 | Linked variables | Read-only variables bound to session/context sources | source: @MessagingSession.Id |
| 4 | Per-topic system.instructions override |
Different system prompts for different topics | Customize LLM persona per topic |
| 5 | Topic delegation (supervision) | Call a topic as a function — it returns to caller | @topic.expert in reasoning.actions |
| 6 | Conditional transitions with if/else |
Deterministic routing based on variable state | if @variables.risk >= 80: transition to @topic.escalation |
| 7 | Template arithmetic | Expression evaluation in text templates | {!@variables.x + 1} |
| 8 | Post-action loop pattern | Topic re-resolves after action, enabling check-at-top pattern | Deterministic post-action routing |
| 9 | Latch variables | Force topic re-entry after user provides input | Workaround for topic selector limitations |
| 10 | Connection block | Multi-channel escalation routing (messaging, voice) | Service Agent channel-specific escalation |
Known Migration Gaps Requiring Manual Review
| Gap | Why it matters | What to do |
|---|---|---|
| Legacy renderer / component override behavior | Rich rendering configured in legacy builders may not map 1:1 into Agent Script metadata | Re-test migrated actions in preview and runtime; be prepared for text fallback where the legacy surface used custom renderers |
Prompt-template input names containing Input: |
Raw Agent Script requires quoted parameter names with : |
Quote every prompt-template input key explicitly, for example "Input:customerId" |
| Exact quoted field names | Some visual editors can rewrite specially quoted field names during round-trip save/reformat | Keep the raw .agent file in source control as the source of truth and diff after UI edits |
| Legacy schema annotations | Some builder-era annotations and rendering hints do not have a direct Agent Script property | Record the intent in docs/comments and validate the migrated action manually instead of assuming automatic parity |
| Separate topic/action YAML files | Builder-era or generated assets may suggest extra per-topic files | Consolidate topic logic and action definitions in the .agent file unless a separate packaging system explicitly requires otherwise |
Practical migration rule: if a migrated action compiles but behaves differently, verify three things separately: (1) raw .agent syntax, (2) builder round-trip formatting, and (3) runtime behavior in the actual target surface.
Side-by-Side: Simple Topic
Builder UI Configuration
Topic Name: Order Lookup
Classification: Handles customer order status inquiries
Instructions:
1. Ask the customer for their order number
2. Look up the order using the Get Order Details action
3. Share the order status with the customer
Actions:
- Get Order Details (Flow: Get_Order_Details)
Input: order_id (Collect from user)
Output: status, estimated_delivery
Agent Script Equivalent
topic order_lookup:
description: "Handles customer order status inquiries"
actions:
get_order_details:
description: "Retrieves order information by order ID"
inputs:
order_id: string
description: "Customer's order number"
outputs:
status: string
description: "Current order status"
estimated_delivery: string
description: "Estimated delivery date"
target: "flow://Get_Order_Details"
reasoning:
instructions: ->
# Post-action check (if order was already looked up)
if @variables.order_status != "":
| Your order status is: {!@variables.order_status}
| Estimated delivery: {!@variables.estimated_delivery}
| I can help you check your order status.
| Please provide your order number.
actions:
lookup: @actions.get_order_details
with order_id = ...
set @variables.order_status = @outputs.status
set @variables.estimated_delivery = @outputs.estimated_delivery
Key differences in the Agent Script version:
- Explicit action definition with typed inputs/outputs and target
- Post-action check pattern (at TOP of instructions) enables deterministic routing after the action completes
- Variable injection (
{!@variables.X}) for dynamic text - Slot-fill (
...) replaces "Collect from user"
Side-by-Side: Verification Gate
Builder UI Configuration
Topic Name: Identity Verification
Classification: Verifies customer identity before accessing account
Instructions:
1. Ask the customer for their email address
2. Use the Verify Identity action to check their email
3. If verified, route to the Account Management topic
4. After 3 failed attempts, escalate to a human agent
Actions:
- Verify Identity (Apex: VerifyIdentityAction)
Input: email (Collect from user)
Output: verified (boolean)
- Go to Account Management (Topic Transition)
- Escalate (Escalate to Agent)
Agent Script Equivalent
variables:
customer_verified: mutable boolean = False
failed_attempts: mutable number = 0
topic identity_verification:
description: "Verifies customer identity before accessing account"
actions:
verify_identity:
description: "Checks customer identity by email"
inputs:
email: string
description: "Customer email address"
outputs:
verified: boolean
description: "Whether identity was verified"
target: "apex://VerifyIdentityAction"
reasoning:
instructions: ->
# Gate: Too many failures → escalate
if @variables.failed_attempts >= 3:
| Too many failed attempts. Connecting you with a human agent.
transition to @topic.escalation
# Gate: Already verified → proceed
if @variables.customer_verified == True:
transition to @topic.account_management
| Please provide your email address to verify your identity.
actions:
verify: @actions.verify_identity
with email = ...
set @variables.customer_verified = @outputs.verified
if @outputs.verified == False:
set @variables.failed_attempts = @variables.failed_attempts + 1
go_account: @utils.transition to @topic.account_management
description: "Proceed to account management"
available when @variables.customer_verified == True
escalate_now: @utils.escalate
description: "Transfer to human agent"
Key differences in the Agent Script version:
- Deterministic gates at top of instructions (cannot be bypassed by LLM)
- Explicit failure counter with arithmetic
available whenguard ensures the "proceed" action is invisible until verified@utils.escalatereplaces the UI "Escalate to Agent" button
Migration Checklist
When converting a Builder UI agent to Agent Script:
- Export current config: Document all topics, instructions, and actions from the UI
- Map each topic: Use the mapping table above to translate concepts
- Identify implicit logic: Builder UI often has implicit routing — make it explicit with
if/else - Add deterministic gates: Convert any "instruction-based" security to
available whenguards - Define variables: Builder UI hides state management — declare all needed variables explicitly
- Set action targets: Ensure all Flows/Apex classes are deployed with correct API names
- Test incrementally: Validate each topic independently before combining
- Verify
default_agent_user: Must be a valid Einstein Agent User in the target org
Common Migration Pitfalls
| Pitfall | Description | Fix |
|---|---|---|
| Missing deterministic logic | Builder UI relies on LLM to follow instructions; Agent Script should enforce with code | Add if/else gates and available when guards |
| Implicit routing | Builder UI auto-routes between topics; Agent Script needs explicit transitions | Add @utils.transition actions for each topic change |
| Action naming conflicts | Builder UI action names may conflict with reserved words | Rename to avoid description, label, escalate |
| Missing variable declarations | Builder UI manages state implicitly | Declare all mutable/linked variables explicitly |
| Wrong instruction syntax | Builder UI text → | (pipe) syntax; conditional logic → -> (arrow) syntax |
Use arrow when you need if, run, set, or transition |
| Renderer assumptions survived migration only in prose | Legacy descriptions may still mention a specific renderer even when the metadata no longer guarantees it | Re-validate rendering behavior in the target surface; treat description text as guidance, not a rendering contract |
| Prompt template bindings copied literally without quotes | Input:... names parse differently in text DSL than in UI forms |
Quote prompt-template input keys explicitly in .agent files |
| Exact field names changed after save/re-open | Builder round-trip formatting can alter edge-case quoted keys | Diff the raw .agent after editing in UI if your action depends on an exact quoted field name |
Last updated: 2026-04-03
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Minimal Working Examples
Hello-World Agent Script
A complete, deployable agent with one topic, one action, and conditional logic:
config:
developer_name: "simple_agent"
description: "A minimal working agent example"
agent_type: "AgentforceServiceAgent"
default_agent_user: "agent_user@yourorg.com"
system:
messages:
welcome: "Hello! How can I help you today?"
error: "Sorry, something went wrong."
instructions: "You are a helpful customer service agent."
variables:
customer_verified: mutable boolean = False
topic main:
description: "Main conversation handler"
reasoning:
instructions: ->
if @variables.customer_verified == True:
| You are speaking with a verified customer.
| Help them with their request.
else:
| Please verify the customer's identity first.
actions:
verify: @actions.verify_customer
description: "Verify customer identity"
set @variables.customer_verified = @outputs.verified
start_agent entry:
description: "Entry point for all conversations"
reasoning:
instructions: |
Greet the customer and route to the main topic.
actions:
go_main: @utils.transition to @topic.main
description: "Navigate to main conversation"
Key Points
configblock:developer_namemust match the folder name (case-sensitive)default_agent_user: Must be a valid Einstein Agent User in the target org — query withsf data queryinstructions: ->: Procedural mode enablesif/elseandrundirectivesinstructions: |: Literal mode for static text passed to the LLMset @variables.X = @outputs.Y: Captures action output into mutable state@utils.transition: Permanent handoff (does not return to calling topic)
Personalized Welcome Message
Use quoted strings for static system messages, but switch welcome / error to template/block form when you need interpolation:
variables:
user_preferred_name: linked string
source: @MessagingSession.UserPreferredName__c
description: "Example linked variable source for first-turn personalization"
system:
messages:
welcome: |
Hi {!@variables.user_preferred_name}! How can I help you today?
error: "Sorry, something went wrong."
instructions: "You are a helpful customer service agent."
- Use
|for dynamic welcome/error messages that include{!...}references. - Do not write dynamic system messages like
welcome: "Hi {!@variables.user_preferred_name}!"— that quoted form can render literally. - Keep quoted strings for static welcome/error text.
- Keep conditional logic in
reasoning.instructions: ->;system.messagesshould stay as static text or direct variable templates.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Official Sources Registry
Canonical Salesforce documentation URLs for Agent Script. Use this registry to verify syntax, resolve errors, and stay current with platform changes.
Primary References (Agent Script Documentation)
URL Prefix Note: Agent Script docs migrated from
/docs/einstein/genai/guide/ascript-*(older beta path) to/docs/ai/agentforce/guide/ascript-*(current path). Also note that some older per-topic/per-lifecycle URLs have been folded into newer pages or renamed (for example,ascript-ref-before-after-reasoning.htmlandascript-blocks.html#topic-blocks).
Official Pattern Pages
| # | Page | URL | Use When |
|---|---|---|---|
| P1 | System Overrides | https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-patterns-system-overrides.html | Topic-level system.instructions overrides |
| P2 | Variables Pattern | https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-patterns-variables.html | State sharing, slot filling, variable usage |
| P3 | Transitions Pattern | https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-patterns-transitions.html | @utils.transition to, deterministic vs LLM-selected routing |
Recipe Repository
Diagnostic Decision Tree
When something fails, use this tree to determine which doc page to fetch:
Error or Ambiguity
│
├─ Compilation / SyntaxError
│ ├─ Block-level error → Fetch #3 (Blocks Reference)
│ ├─ Expression error → Fetch #10 (Expressions) + #12 (Operators)
│ └─ Action error → Fetch #5 (Actions Reference)
│
├─ Action not executing
│ ├─ Action defined but LLM doesn't pick it → Fetch #5 (Actions) + #7 (Tools)
│ └─ Action target not found → Fetch #5 (Actions) + #18 (Agent DX)
│
├─ Variable not updating
│ ├─ Linked var empty → Fetch #6 (Variables)
│ └─ Mutable not changing → Fetch #6 (Variables) + #9 (Instructions)
│
├─ Topic transition wrong
│ ├─ Wrong topic selected → Fetch #13 (Topic Blocks) + #8 (Utils)
│ └─ Transition vs delegation confusion → Fetch #7 (Tools) + #13 (Topic Blocks)
│
├─ Lifecycle hook issue
│ └─ before/after_reasoning error → Fetch #11 (Before/After)
│
└─ New / unfamiliar syntax
└─ Start with #1 (Overview), then narrow to specific reference
Fallback Search Patterns
When a specific URL 404s or doesn't have the answer:
# Primary search pattern
site:developer.salesforce.com agent script <topic>
# Recipe search
site:developer.salesforce.com sample-apps agent-script-recipes <topic>
# GitHub issues (known bugs, community solutions)
site:github.com trailheadapps agent-script-recipes <error message>
# Salesforce Stack Exchange
site:salesforce.stackexchange.com agent script <topic>
URL Health Check
When verifying URLs, use WebFetch to confirm each resolves. If a URL redirects or 404s:
- Try swapping the URL prefix (see note above)
- Use the fallback search pattern
- If consistently broken, update this file and note the date
Last updated: 2026-03-12
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Agent Script Patterns Quick Reference
Decision trees and cheat sheets for common Agent Script patterns
Tool Selection Preflight
What kind of problem is this?
│
├─► Single-turn generation only?
│ └─► PROMPT TEMPLATE / prompt action
│
├─► Fully static deterministic sequence?
│ └─► FLOW / APEX
│
├─► Dynamic user input + branching + must-pass gates?
│ └─► AGENT SCRIPT
│
└─► Mostly flexible conversation with a few hard controls?
└─► AGENT SCRIPT + deterministic envelope
Pattern Selection Decision Tree
Which Architecture Pattern?
What's your agent's purpose?
│
├─► Multi-purpose (sales, support, orders)?
│ └─► HUB AND SPOKE
│ Central router → Specialized topics
│
├─► Sequential workflow (onboarding, checkout)?
│ └─► LINEAR FLOW
│ A → B → C pipeline
│
├─► Tiered support with escalation?
│ └─► ESCALATION CHAIN
│ L1 → L2 → L3 → Human
│
├─► Sensitive operations (payments, PII)?
│ └─► VERIFICATION GATE
│ Security check → Protected topics
│
└─► Multiple protected topics behind shared auth gate?
└─► STATE GATE (OPEN GATE)
3-variable bypass with deferred routing
Routing Quick Rules
- Use
description:for routing andlabel:for display. - If one utterance fits two sibling topics, redesign.
- Keep escalation and handoff topics limited to meta-intents.
- Assume every new turn can trigger re-matching.
Quick Overlap Check
Ask:
- Would the same utterance reasonably match both topics?
- Are you relying on instructions, not the topic description, to separate them?
- Does one topic use broad umbrella terms like
help,support,account, orbillingthat absorb adjacent intents?
Node Type Decision Tree
What should this topic do?
│
├─► Route based on intent?
│ └─► 🔵 ROUTING (Topic Selector)
│
├─► Security/identity check?
│ └─► 🔵 VERIFICATION
│
├─► Fetch external data?
│ └─► 🟡 DATA-LOOKUP
│
├─► Apply business rules?
│ └─► 🟢 PROCESSING
│
└─► Transfer to human?
└─► 🔴 HANDOFF
Variable Type Decision Tree
What kind of data is this?
│
├─► State that changes during conversation?
│ │ (counters, flags, accumulated data)
│ └─► MUTABLE
│ `failed_attempts: mutable number = 0`
│
└─► Data from external source?
│ (session, context, CRM)
└─► LINKED
`customer_id: linked string`
` source: @session.customerId`
Action Target Protocol Decision Tree
Where should this action go?
│
├─► Data queries, record updates?
│ └─► flow://
│
├─► Custom calculations, validation?
│ └─► apex://
│
├─► LLM-generated summaries?
│ └─► generatePromptResponse://
│
├─► Knowledge search, RAG?
│ └─► retriever://
│
├─► External REST APIs?
│ └─► externalService://
│
└─► Built-in SF actions (email, tasks)?
└─► standardInvocableAction://
Deterministic vs Subjective Decision Tree
Should this be code-enforced or LLM-flexible?
│
├─► Security/safety requirement?
│ └─► DETERMINISTIC (code)
│
├─► Financial threshold?
│ └─► DETERMINISTIC (code)
│
├─► Counter/state management?
│ └─► DETERMINISTIC (code)
│
├─► Conversational/greeting?
│ └─► SUBJECTIVE (LLM)
│
├─► Context understanding needed?
│ └─► SUBJECTIVE (LLM)
│
└─► Natural language generation?
└─► SUBJECTIVE (LLM)
Control Placement Cheat Sheet
| Need | Best home |
|---|---|
| Tone, behavior, conversational guidance | Instructions |
| Facts, policy text, mutable rules | Retrieval / knowledge |
| Visibility, scope, access control | Filters, available when, guarded transitions |
| Mandatory order, must-run logic | Agent Script transitions, run, or Flow / Apex |
| Long-lived context across turns | Variables |
SOMA Pattern Decision Tree
Does the conversation return to original agent?
│
├─► Yes, specialist handles sub-task
│ └─► DELEGATION
│ `@topic.specialist` (in reasoning.actions)
│
└─► No, permanent transfer
├─► To another topic?
│ └─► HANDOFF `@utils.transition to @topic.X`
│
├─► To human?
│ └─► `@utils.escalate`
│
└─► To another agent?
└─► `@agent.X` (Connections)
Transition Type Cheat Sheet
| Syntax | Type | Control |
|---|---|---|
@utils.transition to @topic.X |
LLM-chosen | LLM decides when to use |
transition to @topic.X |
Deterministic | Always executes when reached |
@utils.escalate |
Permanent handoff | Human takeover |
Instruction Resolution Order
instructions: ->
# 1. POST-ACTION CHECKS (at TOP - triggers on loop)
if @variables.action_completed == True:
run @actions.follow_up_action
transition to @topic.next_step
# 2. PRE-LLM DATA LOADING
run @actions.load_required_data
set @variables.data = @outputs.result
# 3. DYNAMIC INSTRUCTIONS FOR LLM
| Here is the context: {!@variables.data}
if @variables.condition:
| Do this thing.
else:
| Do that thing.
Why this order?
- Post-action at TOP → triggers immediately on loop
- Data loading next → LLM needs current data
- Instructions last → LLM sees resolved values
Common Patterns Quick Reference
Security Gate (Early Exit)
instructions: ->
if @variables.failed_attempts >= 3:
| Account locked due to too many attempts.
transition to @topic.lockout # LLM never reasons
Guarded Actions
actions:
process_refund: @actions.process_refund
description: "Issue refund"
available when @variables.customer_verified == True
Post-Action Follow-Up
instructions: ->
if @variables.refund_status == "Approved":
run @actions.create_crm_case
with customer_id = @variables.customer_id
transition to @topic.success
Data-Dependent Instructions
instructions: ->
run @actions.get_account_tier
set @variables.tier = @outputs.tier
if @variables.tier == "Gold":
| VIP treatment - offer 20% discount.
else:
| Standard customer service.
Open Gate (State Gate)
3-variable state machine that bypasses the LLM topic selector when a gate holds focus and routes users through an auth gate before accessing protected topics.
# In topic_selector's before_reasoning — zero-credit bypass:
before_reasoning:
if @variables.open_gate == "protected_workflow":
transition to @topic.protected_workflow
if @variables.open_gate == "authentication_gate":
transition to @topic.authentication_gate
# In protected topic's before_reasoning — auth redirect:
before_reasoning:
if @variables.authenticated == False:
set @variables.next_topic = "protected_workflow"
set @variables.open_gate = "authentication_gate"
transition to @topic.authentication_gate
set @variables.open_gate = "protected_workflow"
# EXIT_PROTOCOL — release gate when user changes intent:
before_reasoning:
set @variables.open_gate = "null"
set @variables.next_topic = ""
transition to @topic.topic_selector
Template: assets/patterns/open-gate-routing.agent
Anti-Patterns to Avoid
❌ Data Load After LLM Text
# WRONG - LLM sees empty values
instructions: ->
| Customer name: {!@variables.name} # empty!
run @actions.load_customer
set @variables.name = @outputs.name
❌ Post-Action Check at Bottom
# WRONG - Never triggers
instructions: ->
| Help with refund.
transition to @topic.main # Exits first!
if @variables.refund_done: # Never reached
run @actions.log_refund
❌ Mixing Tabs and Spaces
# WRONG - Compilation error
config:
developer_name: "MyAgent" # 3 spaces
agent_label: "Label" # 8 spaces - FAILS!
❌ Lowercase Booleans
# WRONG - Agent Script uses Python-style
is_verified: mutable boolean = true # WRONG
is_verified: mutable boolean = True # CORRECT
Syntax Quick Reference
| Pattern | Purpose |
|---|---|
instructions: -> |
Arrow syntax, enables expressions |
instructions: | |
Pipe syntax, simple multi-line |
if @variables.x: |
Conditional (pre-LLM) |
run @actions.x |
Execute during resolution |
set @var = @outputs.y |
Capture action output |
| Curly-bang: {!@variables.x} | Template injection |
available when |
Control action visibility |
transition to @topic.x |
Deterministic topic change |
@utils.transition to |
LLM-chosen topic change |
@utils.escalate |
Human handoff |
The 6 Deterministic Building Blocks
| # | Block | Example |
|---|---|---|
| 1 | Conditionals | if @variables.failed_attempts >= 3: |
| 2 | Topic Filters | available when @variables.cart_items > 0 |
| 3 | Variable Checks | if @variables.churn_risk >= 80: |
| 4 | Inline Actions | run @actions.load_customer |
| 5 | Utility Actions | @utils.transition, @utils.escalate |
| 6 | Variable Injection | Curly-bang: {!@variables.customer_name} |
Implementation Best Practices
Migrated from the former
sf-ai-agentforce-legacy/references/patterns-and-practices.mdon 2026-02-07.
Pattern Details
Lifecycle Events Pattern
File: assets/patterns/lifecycle-events.agent
Execute code automatically before and after every reasoning step.
⚠️ Deployment Note: The
runkeyword works inreasoning.actions:post-action blocks andinstructions: ->blocks. It does NOT work reliably inbefore_reasoning:/after_reasoning:lifecycle blocks.
topic conversation:
before_reasoning:
set @variables.turn_count = @variables.turn_count + 1
run @actions.refresh_context # ⚠️ GenAiPlannerBundle only
with user_id=@variables.EndUserId
set @variables.context = @outputs.fresh_context
reasoning:
instructions: ->
| Turn {!@variables.turn_count}: {!@variables.context}
after_reasoning:
run @actions.log_analytics # ⚠️ GenAiPlannerBundle only
with turn=@variables.turn_count
| ✅ Good Use Case | ❌ Not Ideal For |
|---|---|
| Track conversation metrics | One-time setup (use conditional) |
| Refresh context every turn | Heavy processing (adds latency) |
| Log analytics after each response | Actions that might fail often |
Action Callbacks Pattern
File: assets/patterns/action-callbacks.agent
Chain deterministic follow-up actions using the run keyword.
⚠️ Deployment Note: The
runkeyword works inreasoning.actions:post-action blocks andinstructions: ->blocks. It does NOT work reliably inbefore_reasoning:/after_reasoning:lifecycle blocks.
process_order: @actions.create_order
with customer_id=@variables.customer_id
set @variables.order_id = @outputs.order_id
run @actions.send_confirmation # ⚠️ GenAiPlannerBundle only
with order_id=@variables.order_id
run @actions.log_activity # ⚠️ GenAiPlannerBundle only
with event="ORDER_CREATED"
| ✅ Good Use Case | ❌ Not Ideal For |
|---|---|
| Audit logging (must happen) | Optional follow-ups (let LLM decide) |
| Send notification after action | Complex branching logic |
| Chain dependent actions | More than 1 level of nesting |
Critical Rule: Only 1 level of run nesting allowed!
Combining Patterns
Patterns can be combined for complex scenarios:
┌─────────────────────────────────────────────────────────────┐
│ LIFECYCLE + CALLBACKS + ROUTING │
├─────────────────────────────────────────────────────────────┤
│ │
│ topic order_hub: │
│ before_reasoning: ◄── Lifecycle │
│ set @variables.turn_count = ... + 1 │
│ │
│ reasoning: │
│ actions: │
│ process: @actions.create │
│ run @actions.notify ◄── Callback │
│ run @actions.log │
│ │
│ consult: @utils.transition ◄── Routing │
│ to @topic.specialist │
│ │
│ after_reasoning: ◄── Lifecycle │
│ run @actions.update_metrics │
│ │
└─────────────────────────────────────────────────────────────┘
N-ary Boolean Expressions
AgentScript supports 3 or more conditions chained with and/or:
# Three+ conditions with AND
before_reasoning:
if @variables.is_authenticated and @variables.has_permission and @variables.is_active:
transition to @topic.authorized
# Three+ conditions with OR
before_reasoning:
if @variables.is_admin or @variables.is_moderator or @variables.is_owner:
transition to @topic.elevated_access
# In available when clauses
reasoning:
actions:
process_return: @actions.handle_return
description: "Process customer return request"
available when @variables.eligible == True and @variables.order_id != None and @variables.tier != "basic"
premium_action: @actions.premium_feature
description: "Premium tier feature"
available when @variables.tier == "premium" or @variables.tier == "enterprise" or @variables.is_trial_premium == True
Key Points:
- Chain as many conditions as needed with
andoror - Use
()grouping for complex expressions:(a and b) or (c and d) - Works in
ifstatements andavailable whenclauses
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Agent name | PascalCase with underscores | Customer_Service_Agent |
| Topic name | snake_case | order_management |
| Variable name | snake_case | user_email |
| Action name | snake_case | get_account_details |
| Transition action name | go_to_ prefix |
go_to_checkout, go_to_support |
💡 Official GA docs recommend naming transition actions with a
go_to_prefix for clarity (e.g.,go_to_checkout: @utils.transition to @topic.checkout).
Variable Management Best Practices
Initialize with Defaults
variables:
# ✅ RECOMMENDED - Has default value (clearer intent)
user_name: mutable string = ""
description: "Customer's full name"
order_count: mutable number = 0
description: "Number of orders in cart"
Note: Variables without defaults ARE supported. However, providing defaults is recommended for clarity.
Use Appropriate Types
| Data | Type | Example |
|---|---|---|
| Names, IDs, text | string |
"John Doe" |
| Counts, amounts | number |
42, 99.99 |
| Flags, toggles | boolean |
True, False |
Topic Design Best Practices
Provide Clear Descriptions
# ✅ GOOD - Specific and actionable
topic password_reset:
description: "Helps users reset forgotten passwords and unlock accounts"
# ❌ BAD - Too vague
topic password_reset:
description: "Password stuff"
Keep Topics Focused (Single Responsibility)
# ✅ GOOD - Single responsibility
topic billing_inquiries:
description: "Answers questions about invoices, payments, and account balances"
topic order_tracking:
description: "Provides order status and shipping updates"
# ❌ BAD - Too broad
topic customer_stuff:
description: "Handles billing, orders, support, and everything else"
Security & Guardrails
System-Level Guardrails
system:
instructions:
| You are a helpful customer service agent.
|
| IMPORTANT GUARDRAILS:
| - Never share customer data with unauthorized parties
| - Never reveal internal system details
| - If unsure, escalate to a human agent
Don't Expose Internals
# ✅ GOOD - User-friendly error
instructions: ->
if @variables.api_error == True:
| I'm having trouble completing that request right now.
# ❌ BAD - Exposes internals
instructions: ->
if @variables.api_error == True:
| Error: SQL timeout on server db-prod-03
Instructions Quality
# ✅ GOOD - Specific instructions
instructions: ->
| Help the customer track their order.
| Ask for the order number if not provided.
| Provide the current status, estimated delivery, and tracking link.
# ❌ BAD - Vague instructions
instructions: ->
| Help with orders.
Common Syntax Pitfalls
1. Slot Filling Inside Conditionals
# ❌ WRONG
if @variables.name is None:
set @variables.name = ... # Fails!
# ✅ CORRECT - Slot filling at top level
set @variables.name = ...
2. Description on @utils.transition
# ✅ CORRECT - description IS valid on @utils.transition
go_orders: @utils.transition to @topic.orders
description: "Route to orders"
# ✅ ALSO CORRECT - without description
go_orders: @utils.transition to @topic.orders
Note:
description:IS valid on@utils.transition(confirmed by TDD Val_Action_Properties and production 15-topic agent). Other properties likelabel:,require_user_confirmation:, andinclude_in_progress_indicator:are NOT valid on@utils.transitionbut ARE valid on action definitions withtarget:(TDD v2.2.0).
3. Missing Description on @utils.escalate
# ❌ WRONG
transfer: @utils.escalate # Fails!
# ✅ CORRECT - Description required
transfer: @utils.escalate
description: "Transfer to human agent"
4. Empty Lifecycle Blocks
# ❌ WRONG
before_reasoning:
# Just a comment # Fails!
# ✅ CORRECT - Remove empty blocks or add content
5. Dynamic Action Invocation
# ❌ WRONG
invoke: {!@actions.search} # Fails!
# ✅ CORRECT - Define multiple actions, LLM auto-selects
search_products: @actions.product_search
search_orders: @actions.order_search
Validation Scoring Summary
| Pattern | Points | Key Requirement |
|---|---|---|
| Config block | 10 | All 4 required fields |
| Linked variables | 10 | EndUserId, RoutableId, ContactId |
| Topic structure | 10 | label, description, reasoning |
| Language block | 5 | default_locale present |
| Lifecycle blocks | 5 | Proper before/after structure |
| Action callbacks | 5 | No nested run |
| Error handling | 5 | Validation patterns |
| Template expressions | 5 | {!@variables.x} syntax |
Slot Filling Reliability Patterns
Problem: LLM Fails to Extract Values Correctly
| Symptom | What Happened | Example |
|---|---|---|
Empty JSON {} sent to action |
LLM couldn't find value in conversation | User said "look up my account" without ID |
| Wrong field names | LLM abbreviated or guessed | _id instead of account_id |
| Wrong value extracted | LLM picked similar value from context | Picked Contact ID instead of Account ID |
| Retry/crash cycles | No recovery path after failure | Agent keeps trying same extraction |
Root Cause: The ... syntax is probabilistic — the LLM infers what value to use. For critical inputs (IDs, amounts, required fields), this unreliability causes downstream failures.
5-Pattern Solution for Critical Inputs
Pattern 1: First-Interaction Collection — Tell the LLM its PRIMARY GOAL:
reasoning:
instructions: ->
| YOUR PRIMARY GOAL: Collect the account ID from the user.
| Do NOT proceed with any other actions until account_id is captured.
|
if @variables.account_id == "":
| ⚠️ Account ID not yet collected. ASK the user for it.
Pattern 2: Variable Setter Action — Dedicated action to capture and validate:
actions:
capture_account_id:
description: "Captures and validates the Salesforce Account ID from user"
inputs:
account_id: string
description: "The 18-character Salesforce Account ID (starts with 001)"
is_required: True
outputs:
validated_id: string
description: "The validated account ID (empty if invalid)"
is_valid: boolean
description: "Whether the ID is valid"
target: "flow://Validate_Account_Id"
Pattern 3: Single-Use Guard — Make setter unavailable after capture:
reasoning:
actions:
validate_id: @actions.capture_account_id
with account_id=...
set @variables.account_id = @outputs.validated_id
set @variables.account_id_validated = @outputs.is_valid
available when @variables.account_id == ""
Pattern 4: Null Guard Downstream Actions — Block until validated:
reasoning:
actions:
do_research: @actions.research_account
with account_id=@variables.account_id
available when @variables.account_id_validated == True
Pattern 5: Explicit Action References — Guide the LLM:
instructions: ->
| To capture the account ID, use {!@actions.capture_account_id}.
| This ensures the ID is validated before proceeding.
When NOT to Use Slot Filling
Use Slot Filling (...) |
Use Variable/Fixed Value |
|---|---|
| Optional, non-critical inputs | Critical IDs (account, order, case) |
| User preference inputs | Values that must be validated |
| One-time collection | Values used across multiple actions |
| Simple text descriptions | Values with specific formats (dates, IDs) |
Decision Rule: If invalid input would cause downstream failure, use deterministic collection.
⚠️ Chained action restriction: Slot filling (
...) works for top-level action inputs but NOT for chained action inputs (viarun). Chained actions run deterministically and cannot use LLM slot-filling.
Pre-Deploy Checklist
Before deploying an agent, verify:
- All topics have clear descriptions
- All variables have descriptions and defaults
- All actions have input/output descriptions
- System guardrails are defined
- Error handling is in place for critical operations
- Navigation back to main menu from all topics
- Template expressions use correct syntax
{!@variables.name} - Consistent indentation (tabs recommended)
<a id="discovery-questions-pre-authoring"></a>
Discovery Questions (Pre-Authoring)
Ask these questions before writing any Agent Script to clarify requirements and avoid rework. Sourced from AGENT_SCRIPT.md.
Agent Identity
- What is the agent's primary purpose?
- Who are the end users (customers, employees, partners)?
- What tone and persona should the agent adopt?
- What languages must be supported?
Topics
- What are the main conversation topics?
- Which topics require security gates (authentication, authorization)?
- What is the expected flow between topics (linear, hub-and-spoke, conditional)?
- Are there topics that should delegate to sub-agents?
State Management
- What data must persist across the conversation (mutable variables)?
- What external data is needed at start (linked variables from session/context)?
- Are there counters, flags, or accumulators that track progress?
- What default values make sense for each variable?
Actions
- Which actions require Flow targets vs. Apex targets?
- What are the required inputs and outputs for each action?
- Which actions need
available whenguards? - Are there actions that must chain deterministically (post-action follow-ups)?
Reasoning
- Which decisions must be deterministic (code-enforced) vs. LLM-flexible?
- Where should data be loaded (pre-LLM) vs. displayed (LLM instructions)?
- Are there escalation thresholds or retry limits?
- What guardrails must the system instructions enforce?
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Preview Smoke Test Loop (Phase 3.5)
Rapid feedback on
.agentfiles before publish — no CWC patch, no activate, no cross-skill delegation.
1. Overview
Purpose: After Phase 3 validation passes, run 3-5 smoke test utterances against the agent using the programmatic sf agent preview start/send/end --authoring-bundle flow to catch topic routing, action invocation, and grounding issues before the formal publish/activate/test cycle.
Why this matters: The --authoring-bundle flag compiles the .agent file server-side without publishing — no CustomerWebClient patch, no activation step. This enables ~15s iteration cycles (vs ~90s for publish+activate), letting Claude Code fix issues in a tight inner loop.
API used: /einstein/ai-agent/v1.1/preview/ endpoint (separate from the Runtime API used in Phase A testing). Traces are saved locally by the sf CLI.
Trace location: ~/.sf/sfdx/agents/{agent}/sessions/{sid}/traces/{planId}.json
2. Prerequisites
| Requirement | Why | How to Verify |
|---|---|---|
| Agent published at least once | Authoring bundle must exist in org for --authoring-bundle to work |
sf agent validate authoring-bundle --api-name AgentName -o ORG --json |
sf CLI v2.121.7+ |
Required for --authoring-bundle and programmatic preview subcommands |
sf version --json |
| Explicit preview mode chosen | Programmatic authoring-bundle preview now requires a mode flag | Pass exactly one of --simulate-actions or --use-live-actions to sf agent preview start --authoring-bundle ... |
Valid default_agent_user in .agent file |
Preview runs as this user | Query the exact username from the .agent config and confirm: IsActive = true, UserType != AutomatedProcess, and Profile.Name = 'Einstein Agent User' |
| Target org authenticated | Preview needs valid session | sf org display -o ORG_ALIAS --json |
⚠️ First-time agents: If the agent has NEVER been published,
sf agent preview start --authoring-bundlereturns a 500 error. Run Phase 5 (publish + activate) first, then come back to Phase 3.5 for subsequent iterations.
3. Step-by-Step Workflow
Step 1: Start preview session using authoring bundle
SESSION_ID=$(sf agent preview start \
--authoring-bundle AgentName \
--simulate-actions \
--target-org ORG_ALIAS --json 2>/dev/null \
| jq -r '.result.sessionId')
echo "Session: $SESSION_ID"
Step 2: Send smoke test utterance
RESPONSE=$(sf agent preview send \
--session-id "$SESSION_ID" \
--authoring-bundle AgentName \
--utterance "I need help with my order" \
--target-org ORG_ALIAS --json 2>/dev/null)
PLAN_ID=$(echo "$RESPONSE" | jq -r '.result.messages[-1].planId')
AGENT_RESPONSE=$(echo "$RESPONSE" | jq -r '.result.messages[-1].message')
echo "Plan ID: $PLAN_ID"
echo "Response: $AGENT_RESPONSE"
Step 3: Repeat for each utterance
Send each derived utterance (see "Utterance Derivation" below), capturing each PLAN_ID for trace analysis.
# Store plan IDs for later trace analysis
PLAN_IDS=()
for UTTERANCE in "Where is my order?" "I want to return this" "Tell me a joke" "My order #123 is late"; do
RESP=$(sf agent preview send \
--session-id "$SESSION_ID" \
--authoring-bundle AgentName \
--utterance "$UTTERANCE" \
--target-org ORG_ALIAS --json 2>/dev/null)
PID=$(echo "$RESP" | jq -r '.result.messages[-1].planId')
PLAN_IDS+=("$PID")
echo "[$PID] $UTTERANCE → $(echo "$RESP" | jq -r '.result.messages[-1].message' | head -c 80)"
done
Step 4: End session and get trace path
TRACES_PATH=$(sf agent preview end \
--session-id "$SESSION_ID" \
--authoring-bundle AgentName \
--target-org ORG_ALIAS --json 2>/dev/null \
| jq -r '.result.tracesPath')
echo "Traces at: $TRACES_PATH"
Step 5: Read trace for each plan ID
# Read a specific trace
TRACE="$TRACES_PATH/$PLAN_ID.json"
4. Trace Analysis — 6 Checks with jq
Each check includes: what to look for, the jq command, how to interpret results, and what to fix.
Check 1: Topic Routing
What: Did the utterance route to the expected topic?
jq '[.steps[] | select(.stepType == "TransitionStep") | .data.to]' "$TRACE"
Expected: Array contains the target topic name (e.g., ["order_mgmt"]).
If wrong or missing:
- Empty array → agent stayed in Topic Selector (descriptions too vague)
- Wrong topic name → keyword overlap between topics
Fix: Expand topic X: description: with keywords from the test utterance. See Fix Strategies §5.
Check 2: Action Invocation
What: Did the expected action get invoked?
jq '[.steps[] | select(.stepType == "FunctionStep") | .data.function]' "$TRACE"
Expected: Array contains the target action name (e.g., ["Get_Order_Status"]).
If missing (empty array):
available when:guards too restrictive for the test context- Action
description:doesn't clearly match what the user asked for - Action not listed in
reasoning.actions:for this topic
Fix: Relax available when: guards, improve action description. See Fix Strategies §5.
Check 3: Wrong Action Selected
What: An action was invoked, but it's the wrong one.
# Same jq as Check 2 — compare output against expected action name
jq '[.steps[] | select(.stepType == "FunctionStep") | .data.function]' "$TRACE"
If wrong action: Two actions have overlapping descriptions, and the planner picked the wrong one.
Fix: Differentiate action descriptions with exclusion language. Add available when: guards to the wrong action. See Fix Strategies §5.
Check 4: Grounding Assessment
What: Is the agent's response grounded in actual data (not hallucinated)?
jq '[.steps[] | select(.stepType == "ReasoningStep") | .data.groundingAssessment]' "$TRACE"
Expected: "GROUNDED" for all reasoning steps.
If "UNGROUNDED": The agent fabricated data instead of using action outputs or variable values.
Fix: Add explicit data references in instructions: -> block. Reference specific {!@variables.X} or {!@outputs.Y} values. See Fix Strategies §5.
Check 5: Safety Score
What: Does the agent response meet safety thresholds?
jq '.steps[] | select(.stepType == "PlannerResponseStep") | .data.safetyScore' "$TRACE"
Expected: .overall >= 0.9
If low:
- Agent revealing internal system details
- Agent responding to harmful prompts without guardrails
- Missing safety instructions in
system:block
Fix: Add explicit safety guidelines to system: instructions:. See Fix Strategies §5.
Check 6: Tool Visibility
What: Are the expected actions visible to the planner?
jq '[.steps[] | select(.stepType == "EnabledToolsStep") | .data.enabled_tools]' "$TRACE"
Expected: Array includes the action names defined in the topic's reasoning.actions:.
If missing:
available when:conditions not met for the test context- Action defined in wrong topic
- Action
target:protocol invalid (flow not deployed, apex class not found)
Fix: Check available when: conditions match the test state. Verify target: exists in org.
5. Fix Strategies Reference
| Failure | Target Block | Edit Strategy | Example |
|---|---|---|---|
| TOPIC_NOT_MATCHED | topic X: description: |
Add keywords from test utterance | "Handle orders" → "Handle order queries, order status, package tracking, shipping updates" |
| ACTION_NOT_INVOKED | reasoning.actions: X description: |
Make description more trigger-specific | "Get order" → "Look up order status when user asks about their order, package, or delivery" |
| ACTION_NOT_INVOKED | available when: |
Relax guard condition | Remove overly restrictive @variables.X == True if variable isn't set yet |
| WRONG_ACTION_SELECTED | Both competing description: fields |
Differentiate with exclusion language | Add "NOT for returns" to order action, "ONLY for returns" to refund action |
| UNGROUNDED_RESPONSE | reasoning: instructions: -> |
Add explicit data references | "Help the customer" → "Help the customer using {!@variables.order_data} from Get_Order action" |
| LOW_SAFETY_SCORE | system: instructions: |
Add safety guidelines | Add CRITICAL: Never reveal internal system details or customer PII |
| TOOL_NOT_VISIBLE | available when: |
Ensure guard matches test state | Set test variables before action, or remove guards for initial smoke test |
Fix Application Pattern
After identifying a failure:
- Edit the
.agentfile — Apply the specific edit from the table above - LSP auto-validates — The edit triggers LSP validation automatically (Phase 3 re-runs)
- Re-run preview — Start a new preview session with
--authoring-bundleand re-send the failing utterance - Re-check trace — Verify the fix resolved the issue
- Max 3 iterations — If still failing after 3 fix cycles, proceed to Phase 5 (publish) with warnings
6. Full Loop Walkthrough Example
A fictional OrderSupport agent with 2 topics: order_mgmt and returns.
Initial .agent file (relevant excerpt)
topic order_mgmt:
description: "Handle orders"
reasoning:
actions:
get_order: @actions.Get_Order_Status
description: "Get order"
available when @variables.order_id != ""
topic returns:
description: "Handle returns"
reasoning:
actions:
process_return: @actions.Process_Return
description: "Process return"
Iteration 1: Derive utterances and run preview
Derived utterances (one per topic + one guardrail + one multi-turn):
"Where is my order?"→ should route toorder_mgmt"I want to return this"→ should route toreturns"Tell me a joke"→ should trigger guardrail (off-topic)"My order #123 is late"→ should route toorder_mgmtand invokeGet_Order_Status
Run preview:
SESSION_ID=$(sf agent preview start --authoring-bundle OrderSupport --simulate-actions --target-org dev --json 2>/dev/null | jq -r '.result.sessionId')
RESP1=$(sf agent preview send --session-id "$SESSION_ID" --authoring-bundle OrderSupport --utterance "Where is my order?" --target-org dev --json 2>/dev/null)
PID1=$(echo "$RESP1" | jq -r '.result.messages[-1].planId')
# ... send remaining utterances, capture plan IDs ...
TRACES_PATH=$(sf agent preview end --session-id "$SESSION_ID" --authoring-bundle OrderSupport --target-org dev --json 2>/dev/null | jq -r '.result.tracesPath')
Analyze trace for utterance 1:
jq '[.steps[] | select(.stepType == "TransitionStep") | .data.to]' "$TRACES_PATH/$PID1.json"
# Output: [] ← EMPTY! Topic not matched!
Diagnosis: "Where is my order?" didn't route to order_mgmt because the description "Handle orders" is too vague — the planner couldn't confidently match it.
Iteration 2: Fix topic description
Edit .agent file:
# BEFORE
topic order_mgmt:
description: "Handle orders"
# AFTER
topic order_mgmt:
description: "Handle order queries, order status, package tracking, shipping updates, delivery questions"
Re-run preview:
SESSION_ID=$(sf agent preview start --authoring-bundle OrderSupport --simulate-actions --target-org dev --json 2>/dev/null | jq -r '.result.sessionId')
RESP1=$(sf agent preview send --session-id "$SESSION_ID" --authoring-bundle OrderSupport --utterance "Where is my order?" --target-org dev --json 2>/dev/null)
PID1=$(echo "$RESP1" | jq -r '.result.messages[-1].planId')
TRACES_PATH=$(sf agent preview end --session-id "$SESSION_ID" --authoring-bundle OrderSupport --target-org dev --json 2>/dev/null | jq -r '.result.tracesPath')
jq '[.steps[] | select(.stepType == "TransitionStep") | .data.to]' "$TRACES_PATH/$PID1.json"
# Output: ["order_mgmt"] ← PASS!
jq '[.steps[] | select(.stepType == "FunctionStep") | .data.function]' "$TRACES_PATH/$PID1.json"
# Output: [] ← Get_Order_Status not invoked!
Diagnosis: Topic routing fixed, but Get_Order_Status action not invoked because:
available when @variables.order_id != ""— butorder_idis empty (user didn't provide it yet)- Description
"Get order"is too vague for the planner to match
Iteration 3: Fix action description and guard
Edit .agent file:
# BEFORE
get_order: @actions.Get_Order_Status
description: "Get order"
available when @variables.order_id != ""
# AFTER
get_order: @actions.Get_Order_Status
description: "Look up order status when user asks about their order, package, delivery, or tracking"
with order_id=...
Re-run preview → all 4 utterances pass → proceed to Phase 5 (publish).
7. Error Handling
| Error | Cause | Resolution |
|---|---|---|
500 from preview start |
Agent never published (authoring bundle doesn't exist in org) | Run Phase 5 first (publish + activate), then return to Phase 3.5 |
preview start fails immediately for authoring bundle |
Missing execution-mode flag | Re-run with exactly one of --simulate-actions or --use-live-actions |
| Empty traces directory | sf agent preview end may not write traces in all CLI versions |
Check --json output of preview end for inline trace data; upgrade CLI if needed |
sessionId is null |
Auth expired or org session invalid | Re-authenticate: sf org login web --alias ORG_ALIAS |
SessionAmbiguous (5) |
Multiple cached sessions exist for the same agent | Run sf agent preview sessions --json, pick the right session ID, and retry with --session-id |
| No TransitionStep in trace | Agent used Topic Selector but didn't route to any topic | Topic descriptions are too vague — add more keywords |
| No FunctionStep in trace | Planner didn't select any action | Check available when: guards and action descriptions |
preview send timeout |
Preview compilation taking too long | .agent file may be too complex; simplify or wait longer |
| Session already ended | Sending to an expired/ended session | Start a new session with preview start |
Context Variable Limitations in Preview
⛔
sf agent previewdoes NOT support context/session variable injection. There are no--context,--session-var, or--variablesflags on any preview subcommand.
| Variable Source | Works in Preview? | Alternative |
|---|---|---|
@session.sessionID |
❌ | Agent Runtime API with session context |
@context.customerId |
❌ | Agent Runtime API with contextVariables |
@context.RoutableId |
❌ | Agent Runtime API with contextVariables |
| Mutable vars (defaults) | ✅ | Works normally via default values |
with param=... (slot-filling) |
✅ | Works normally via LLM extraction |
Impact: If your agent relies on
@contextor@sessionvariables for routing or guards, those paths CANNOT be tested viasf agent preview. Use the Agent Runtime API (/einstein/ai-agent/v1) withcontextVariablesin the request body instead.
8. Phase 3.5 vs Phase 4 Comparison
| Aspect | Phase 3.5 (Inner Loop) | Phase 4 (Formal Testing) |
|---|---|---|
| When | Pre-publish (--authoring-bundle) |
Post-publish + activate |
| Scope | 3-5 smoke utterances | 20-100+ test cases |
| Depth | Topic routing + action invocation | Multi-turn, re-matching, context preservation |
| Speed | ~15s per iteration (no publish needed) | ~90s+ per iteration (publish + CWC + activate) |
| Fix loop | Self-contained in sf-ai-agentscript | Cross-skill delegation to sf-ai-agentforce-testing |
| Skill | sf-ai-agentscript (internal) | sf-ai-agentforce-testing (Phase A/B/C) |
| Auth | sf CLI org auth (Named User JWT) | ECA + Client Credentials (for API testing) |
| Traces | Local ~/.sf/sfdx/agents/ JSON files |
Agent Runtime API response + STDM |
| Tools needed | Bash, Read, Edit, jq |
Python scripts, credential_manager, multi_turn_test_runner |
Utterance Derivation Guide
Claude Code derives smoke utterances from the .agent file itself:
- One per non-start topic — Based on
description:keywords. Pick the most natural user phrasing. - One that should trigger each key action — Match the action's
description:to a realistic user request. - One off-topic utterance — Tests guardrails (e.g., "Tell me a joke", "What's the weather?").
- One multi-turn pair — If agent has topic transitions, send two related utterances to test handoff (e.g., "Check my order" → "Actually I want to return it").
Example derivation for an agent with topics order_mgmt (description: "order status, tracking") and returns (description: "refunds, exchanges"):
1. "Where is my order?" → order_mgmt (from description keywords)
2. "I want to return this" → returns (from description keywords)
3. "Can you look up order 123" → order_mgmt + Get_Order_Status action
4. "Tell me a joke" → guardrail (off-topic)
5. "My order is late" → "Actually just process a return" → topic transition
Quick Reference: The Full Loop
Phase 3 passes (LSP + CLI validation clean)
│
▼
Derive 3-5 utterances from .agent file
│
▼
┌─► sf agent preview start --authoring-bundle AgentName --simulate-actions
│ │
│ ▼
│ sf agent preview send (for each utterance)
│ │
│ ▼
│ sf agent preview end → get traces path
│ │
│ ▼
│ Read traces with jq → run 6 checks
│ │
│ ├── All pass → Proceed to Phase 5 (publish) ✅
│ │
│ └── Failures found → Edit .agent file → LSP re-validates
│ │
│ └── iteration < 3? ──────────────────────┐
│ │ │
│ ▼ │
└───────────────── Yes ─┘ │
│
No (3 iterations exhausted) ◄──────────┘
│
▼
Phase 5 with warnings ⚠️
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->PRODUCTION GOTCHAS: Billing, Determinism & Performance
Credit Consumption Table
Key insight: Framework operations are FREE. Only actions that invoke external services consume credits.
| Operation | Credits | Notes |
|---|---|---|
@utils.transition |
FREE | Framework navigation |
@utils.setVariables |
FREE | Framework state management |
@utils.escalate |
FREE | Framework escalation |
if/else control flow |
FREE | Deterministic resolution |
before_reasoning |
FREE | Deterministic pre-processing (see note below) |
after_reasoning |
FREE | Deterministic post-processing (see note below) |
reasoning (LLM turn) |
FREE | LLM reasoning itself is not billed |
| Prompt Templates | 2-16 | Per invocation (varies by complexity) |
| Flow actions | 20 | Per action execution |
| Apex actions | 20 | Per action execution |
| Any other action | 20 | Per action execution |
✅ Lifecycle Hooks: The
before_reasoning:andafter_reasoning:lifecycle hooks are validated. Content goes directly under the block (noinstructions:wrapper). See "Lifecycle Hooks" section below for correct syntax.
Cost Optimization Pattern: Fetch data once in before_reasoning:, cache in variables, reuse across topics.
Lifecycle Hooks: before_reasoning: and after_reasoning:
topic main:
description: "Topic with lifecycle hooks"
# BEFORE: Runs deterministically BEFORE LLM sees instructions
before_reasoning:
# Content goes DIRECTLY here (NO instructions: wrapper!)
set @variables.pre_processed = True
set @variables.customer_tier = "gold"
# LLM reasoning phase
reasoning:
instructions: ->
| Customer tier: {!@variables.customer_tier}
| How can I help you today?
# AFTER: Runs deterministically AFTER LLM finishes reasoning
after_reasoning:
# Content goes DIRECTLY here (NO instructions: wrapper!)
set @variables.interaction_logged = True
if @variables.needs_audit == True:
set @variables.audit_flag = True
Key Points:
- Content goes directly under
before_reasoning:/after_reasoning:(NOinstructions:wrapper) - Reliable primitives:
set,if/else,transition to.runhas inconsistent runtime behavior across bundle types — use it inreasoning.actions:orinstructions: ->instead before_reasoning:is FREE (no credit cost) - use for data prepafter_reasoning:is FREE (no credit cost) - use for logging, cleanuptransition toworks inafter_reasoning:— but if a topic transitions mid-reasoning, the original topic'safter_reasoning:does NOT run
❌ WRONG Syntax (causes compile error):
before_reasoning:
instructions: -> # ❌ NO! Don't wrap with instructions:
set @variables.x = True
✅ CORRECT Syntax:
before_reasoning:
set @variables.x = True # ✅ Direct content under the block
Supervision vs Handoff (Clarified Terminology)
| Term | Syntax | Behavior | Use When |
|---|---|---|---|
| Handoff | @utils.transition to @topic.X |
Control transfers completely, child generates final response | Checkout, escalation, terminal states |
| Supervision | @topic.X (as action reference) |
Parent orchestrates, child returns, parent synthesizes | Expert consultation, sub-tasks |
# HANDOFF - child topic takes over completely:
checkout: @utils.transition to @topic.order_checkout
description: "Proceed to checkout"
# → @topic.order_checkout generates the user-facing response
# SUPERVISION - parent remains in control:
get_advice: @topic.product_expert
description: "Consult product expert"
# → @topic.product_expert returns, parent topic synthesizes final response
KNOWN BUG: Adding ANY new action in Canvas view may inadvertently change Supervision references to Handoff transitions.
Action Output Flags for Zero-Hallucination Routing
Key Pattern for Determinism: Control what the LLM can see and say.
When defining actions in Agentforce Assets, use these output flags carefully:
| Flag | Effect | Use When |
|---|---|---|
filter_from_agent: True |
Hide from direct customer display (GA standard) | Output should stay hidden and does not need is_used_by_planner on the same field |
is_displayable: False |
Hide from direct customer display (compile-valid alias) | Preferred hide-from-user flag when the planner still needs the same prompt output field |
is_used_by_planner: True |
Planner can reason about the value | Decision-making, routing, response synthesis |
⚠️ Do not combine
filter_from_agentandis_used_by_planneron the same output field. That combination is a known blocking parser/runtime conflict.
Zero-Hallucination Intent Classification Pattern:
# In Agentforce Assets - Action Definition outputs:
outputs:
intent_classification: string
is_displayable: False # Hide from direct display
is_used_by_planner: True # Planner can use for routing decisions
# In Agent Script - planner routes but the raw label is never shown directly:
topic intent_router:
reasoning:
instructions: ->
run @actions.classify_intent
set @variables.intent = @outputs.intent_classification
if @variables.intent == "refund":
transition to @topic.refunds
if @variables.intent == "order_status":
transition to @topic.orders
is_displayable: True on Prompt Template Outputs
Production impact: Agent returns blank/empty responses when prompt template action outputs have
is_displayable: Trueset.
The Problem: Setting is_displayable: True (or toggling "Show in conversation" in the UI) on a prompt template action's output causes the platform to attempt direct rendering of the raw output. The rendering pipeline does not handle prompt template output format correctly, resulting in a blank response to the user — even though the trace shows the prompt template executed successfully.
# ❌ WRONG — causes blank response for prompt template actions
outputs:
response_text: string
is_displayable: True # Platform tries to render raw output → blank
# ✅ CORRECT — let the reasoner synthesize the output
outputs:
response_text: string
is_displayable: False # Hide raw output from direct display
is_used_by_planner: True # LLM reads and synthesizes into response
Key Points:
- This only affects prompt template actions (
prompt:///generatePromptResponse://targets) is_displayable: Trueworks correctly on non-prompt actions (Flow, Apex) where the output is a simple string- The safest prompt-template default is
is_displayable: False+is_used_by_planner: True filter_from_agent: Trueis the GA-standard hide-from-user flag, but on prompt outputs it is a worse fit when the planner also needs the value becausefilter_from_agentandis_used_by_plannercannot be combined on the same field in this runtime- The reasoner naturally incorporates planner-visible outputs into its response — explicit display is unnecessary
If the prompt action ran but the response is still missing, check these next:
is_displayableis notTrueis_used_by_plannerisTrueon the output that should influence the reply- You did not combine
filter_from_agentwithis_used_by_planneron the same field - The action output is not a structured wrapper that still needs field extraction before deterministic use
Cross-reference: See known-issues.md Issue 34.
Raw user_input String Matching Is a Weak Deterministic Pattern
Production impact: Substring checks on the last utterance look simple, but they are brittle for deterministic routing, cancellation handling, and revision detection.
The Problem: Branches such as if @system_variables.user_input contains "never mind": treat raw user text as if it were a normalized intent signal. That works inconsistently for real conversations because phrasing varies, punctuation varies, and the deterministic layer is not a robust intent classifier.
# ❌ BRITTLE — raw utterance parsing as deterministic control flow
if @system_variables.user_input contains "never mind":
transition to @topic.cancel_request
# ✅ SAFER — normalize the utterance first, then branch on explicit state
run @actions.classify_user_intent
with utterance = @system_variables.user_input
set @variables.cancel_requested = @outputs.cancel_requested
if @variables.cancel_requested == True:
transition to @topic.cancel_request
Use raw string checks only for light heuristics. If a branch must deterministically gate behavior, normalize it into:
- a boolean (
cancel_requested,is_valid_url) - an enum/string (
intent = "cancel") - or a pre-validated scalar returned by Flow/Apex
Output Access Follows the Output Schema
Production impact: Deterministic comparisons fail when a target returns a wrapper object and the script treats
@outputs.Xlike a plain scalar.
The Problem: Some actions return structured outputs. In those cases, @outputs.output is an object envelope, not the final string/boolean you want to compare. The right accessor depends on the declared schema.
# ❌ WRONG — assumes object output is already a boolean
set @variables.is_after_hours = @outputs.output
# ✅ CORRECT — access a concrete field only if the schema exposes it
set @variables.is_after_hours = @outputs.output.value
Guidance:
- If the action output is declared as
string,number, orboolean, direct assignment is fine. - If the output is declared as
objector another structured type, inspect the contract before you branch on it. .valueis a common wrapper field, but it is not universal — only use it when that field actually exists in the output schema.- For deterministic branches, the safest design is to flatten the target output in Flow/Apex so Agent Script receives an explicit scalar such as
is_after_hours: boolean.
Action I/O Metadata Properties
Complete reference for all metadata properties available on action definitions, inputs, and outputs.
Action-Level Properties:
| Property | Type | Effect |
|---|---|---|
label |
String | Display name in UI |
description |
String | LLM reads this for decision-making |
require_user_confirmation |
Boolean | Request user confirmation before execution (compiles; runtime no-op per Issue 6) |
include_in_progress_indicator |
Boolean | Show spinner during execution |
progress_indicator_message |
String | Custom spinner text |
Input Properties:
| Property | Type | Effect |
|---|---|---|
description |
String | Explains parameter to LLM |
label |
String | Display name in UI |
is_required |
Boolean | Marks input as mandatory for LLM |
is_user_input |
Boolean | LLM extracts value from conversation |
complex_data_type_name |
String | Lightning type mapping |
Output Properties:
| Property | Type | Effect |
|---|---|---|
description |
String | Explains output to LLM |
label |
String | Display name in UI |
filter_from_agent |
Boolean | True = hide from user display (GA standard) |
is_displayable |
Boolean | False = hide from user (compile-valid alias). Prefer this on prompt outputs when the planner still needs the value |
is_used_by_planner |
Boolean | True = LLM can reason about value |
developer_name |
String | Overrides the parameter's developer name |
complex_data_type_name |
String | Lightning type mapping |
Cross-reference:
filter_from_agent: Trueis the GA standard name.is_displayable: Falseis a compile-valid alias.
⚠️ For prompt-template outputs specifically, prefer
is_displayable: Falsewhen the planner still needs the output.filter_from_agentis not a safe drop-in replacement there if you also needis_used_by_planner, because those two flags conflict on the same field.
User Input Pattern (is_user_input: True):
inputs:
customer_name: string
description: "Customer's full name"
is_user_input: True # LLM pulls from what user already said
is_required: True # Must have a value before action executes
Action Chaining with run Keyword
Known quirk: Parent action may complain about inputs needed by chained action - this is expected.
process_order: @actions.create_order
with customer_id = @variables.customer_id
run @actions.send_confirmation # Chains after create_order completes
set @variables.order_id = @outputs.id
KNOWN BUG: Chained actions with Prompt Templates don't properly map inputs using Input:Query format.
📖 For prompt template action definitions, input binding syntax, and grounded data patterns, see references/action-prompt-templates.md.
Latch Variable Pattern for Topic Re-entry
Problem: Topic selector doesn't properly re-evaluate after user provides missing input.
Solution: Use a "latch" variable to force re-entry:
variables:
verification_in_progress: mutable boolean = False
start_agent topic_selector:
reasoning:
instructions: ->
if @variables.verification_in_progress == True:
transition to @topic.verification
| How can I help you today?
actions:
start_verify: @topic.verification
description: "Start identity verification"
set @variables.verification_in_progress = True
topic verification:
reasoning:
instructions: ->
| Please provide your email to verify your identity.
actions:
verify: @actions.verify_identity
with email = ...
set @variables.verified = @outputs.success
set @variables.verification_in_progress = False
Loop Protection Guardrail
Agent Scripts have a built-in guardrail that limits iterations to approximately 3-4 loops before breaking out and returning to the Topic Selector.
Best Practice: Map out your execution paths and test for unintended circular references between topics.
Token & Size Limits
| Limit Type | Value | Notes |
|---|---|---|
| Max response size | 1,048,576 bytes (1MB) | Per agent response |
| Plan trace limit (Frontend) | 1M characters | For debugging UI |
| Transformed plan trace (Backend) | 32k tokens | Internal processing |
| Active/Committed Agents per org | 100 max | Org limit |
Progress Indicators
actions:
fetch_data: @actions.get_customer_data
description: "Fetch customer information"
include_in_progress_indicator: True
progress_indicator_message: "Fetching your account details..."
VS Code Pull/Push NOT Supported
# ❌ ERROR when using source tracking:
Failed to retrieve components using source tracking:
[SfError [UnsupportedBundleTypeError]: Unsupported Bundle Type: AiAuthoringBundle
# ✅ WORKAROUND - Use CLI directly:
sf project retrieve start -m AiAuthoringBundle:MyAgent
sf agent publish authoring-bundle --api-name MyAgent -o TARGET_ORG
Reserved @InvocableVariable Keywords
Validated March 2026: Certain common words cannot be used as
@InvocableVariablenames in Apex classes called by Agent Script. Using them causes "SyntaxError: Unexpected '{keyword}'" during agent script compilation.
Reserved names (cannot use as @InvocableVariable):
| Reserved Name | Workaround | Example |
|---|---|---|
model |
vehicle_model, data_model, model_name |
@InvocableVariable public String vehicle_model; |
description |
issue_description, desc_text, description_field |
@InvocableVariable public String issue_description; |
label |
label_text, display_label, label_field |
@InvocableVariable public String label_text; |
How it manifests:
- Apex compiles and deploys successfully (these are valid Apex identifiers)
- Error only appears when the Agent Script compiler processes the action's I/O schema
- Error message:
SyntaxError: Unexpected 'model'(ordescription,label) - Fix: Rename the
@InvocableVariablein Apex, redeploy, then republish the agent
Cross-reference: These same words are also reserved as Agent Script variable/field names. See SKILL.md reserved field names section.
Boolean-to-String Coercion Hazard
Production impact: Non-deterministic "Something went wrong" (SWW) errors scattered across turns. Extremely difficult to diagnose because failures are intermittent.
The Problem: When a Flow or Apex action outputs a Boolean value and you capture it into a mutable string variable, then compare with == "true", the coercion is non-deterministic. Some turns coerce True -> "true" correctly; others produce "True", "1", or empty string — causing silent routing failures.
# ❌ HAZARDOUS — Boolean output into string variable
variables:
verified: mutable string = "false"
actions:
verify: @actions.verify_user
target: "flow://Verify_User"
outputs:
verified_result: boolean # Flow outputs Boolean
# In reasoning:
set @variables.verified = @outputs.verified_result # Boolean -> string coercion
if @variables.verified == "true": # Non-deterministic match!
transition to @topic.protected_area
Fix Option A (preferred): Use mutable boolean and compare with == True:
variables:
verified: mutable boolean = False
# In reasoning:
set @variables.verified = @outputs.verified_result # Boolean -> boolean, no coercion
if @variables.verified == True: # Deterministic!
transition to @topic.protected_area
Fix Option B: Have the Flow/Apex output an explicit String ("true"/"false") instead of Boolean:
# Flow/Apex outputs String "true" or "false" explicitly
outputs:
verified_result: string # Already a string, no coercion
# In reasoning:
set @variables.verified = @outputs.verified_result # String -> string
if @variables.verified == "true": # Deterministic!
Production validation: Switching from Boolean->String coercion to explicit String output dropped SWW errors from scattered (multiple per session) to 1/61 turns (on an unrelated external callout).
Escalation Fallback Loop
Production impact: Agent enters infinite escalation loop when no human agents are available — user sees repeated "Connecting you..." messages until the 3-4 loop guardrail kicks in.
The Problem: @utils.escalate does not return a success/failure status. When no human agents are available (outside business hours, no Omni-Channel agents online), the escalation silently fails and the conversation re-enters the escalation topic, triggering the same logic again.
Fix: Use a latch variable in before_reasoning: to detect re-entry and route to a fallback:
variables:
escalation_attempted: mutable boolean = False
topic escalation:
description: "Escalate to human agent"
before_reasoning:
if @variables.escalation_attempted == True:
transition to @topic.leave_message
set @variables.escalation_attempted = True
reasoning:
instructions: ->
| Let me connect you with a support specialist.
actions:
handoff: @utils.escalate
description: "Transfer to human agent"
Key Points:
- The
before_reasoning:check is FREE (no credit cost) and runs deterministically before the LLM - Always provide a graceful fallback topic (leave message, callback, self-service links)
- This pattern also prevents credit waste — each failed escalation loop costs LLM reasoning credits
Cross-reference: See known-issues.md Issue 31. See fsm-architecture.md § Pattern 5 — Escalation with Availability Check.
Language Block Quirks
- Hebrew and Indonesian appear twice in the language dropdown
- Selecting from the second set causes save errors
- Use
adaptive_response_allowed: Truefor automatic language adaptation
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Scoring System (100 Points)
Categories
| Category | Points | Key Criteria |
|---|---|---|
| Structure & Syntax | 20 | Required blocks present, indentation consistency, valid identifiers, valid top-level wrappers |
| Deterministic Logic | 25 | Security via available when, post-action checks, proper conditionals |
| Instruction Resolution | 20 | Correct use of -> vs ` |
| FSM Architecture | 15 | Clear topic separation, explicit transitions, state management |
| Action Configuration | 10 | Correct protocols, input/output mapping, error handling |
| Deployment Readiness | 10 | Valid default_agent_user, no compilation errors, metadata complete |
Scoring Rubric Details
Structure & Syntax (20 points)
| Points | Criteria |
|---|---|
| 20 | All required blocks present, consistent indentation, valid identifiers |
| 15 | Minor issues (e.g., inconsistent spacing within tolerance) |
| 10 | Missing optional blocks that would improve clarity |
| 5 | Significant structural issues (for example mixed indentation, invalid top-level wrappers, or repeated structural problems) |
| 0 | Missing required blocks or compilation failures |
Top-level block order differences should be treated as style feedback unless they correspond to an actual validation or compiler issue.
Deterministic Logic (25 points)
| Points | Criteria |
|---|---|
| 25 | All security actions guarded with available when, post-action patterns used |
| 20 | Most guards present, minor gaps in deterministic enforcement |
| 15 | Some security logic relies on prompts instead of guards |
| 10 | Critical actions lack available when guards |
| 0 | Security logic entirely prompt-based (LLM can bypass) |
Instruction Resolution (20 points)
| Points | Criteria |
|---|---|
| 20 | Arrow syntax for complex logic, proper template injection, correct action execution |
| 15 | Mostly correct, minor syntax issues |
| 10 | Uses pipe syntax where arrow needed, template injection errors |
| 5 | Incorrect phase ordering (data loads after LLM sees instructions) |
| 0 | Fundamental misunderstanding of resolution order |
FSM Architecture (15 points)
| Points | Criteria |
|---|---|
| 15 | Clear topic boundaries, explicit transitions, appropriate escalation paths |
| 12 | Good structure with minor redundancy |
| 9 | Topics too broad or transitions unclear |
| 5 | Monolithic topic handling multiple concerns |
| 0 | No topic separation, all logic in start_agent |
Action Configuration (10 points)
| Points | Criteria |
|---|---|
| 10 | Correct protocols, proper I/O mapping, descriptions present |
| 8 | Minor issues (missing descriptions) |
| 5 | Wrong protocol for use case |
| 2 | Input/output mapping errors |
| 0 | Actions don't compile |
Deployment Readiness (10 points)
| Points | Criteria |
|---|---|
| 10 | Valid user, clean validation, metadata complete |
| 8 | Minor warnings |
| 5 | Validation errors that need fixing |
| 2 | Missing metadata files |
| 0 | Cannot deploy |
Score Thresholds
| Score | Rating | Action |
|---|---|---|
| 90-100 | ⭐⭐⭐⭐⭐ Excellent | Deploy with confidence |
| 80-89 | ⭐⭐⭐⭐ Very Good | Minor improvements recommended |
| 70-79 | ⭐⭐⭐ Good | Review flagged issues before deploy |
| 60-69 | ⭐⭐ Needs Work | Address issues before deploy |
| <60 | ⭐ Critical | BLOCK - Fix critical issues |
Score Report Format
📊 AGENT SCRIPT SCORE REPORT
════════════════════════════════════════
Score: 85/100 ⭐⭐⭐⭐ Very Good
├─ Structure & Syntax: 18/20 (90%)
├─ Deterministic Logic: 22/25 (88%)
├─ Instruction Resolution: 16/20 (80%)
├─ FSM Architecture: 12/15 (80%)
├─ Action Configuration: 9/10 (90%)
└─ Deployment Readiness: 8/10 (80%)
Issues:
⚠️ [Deterministic] Missing `available when` on process_refund action
⚠️ [Resolution] Post-action check should be at TOP of instructions
✓ All Structure & Syntax checks passed
✓ All Action Configuration checks passed
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Sources & Acknowledgments
| Source | Contribution |
|---|---|
| trailheadapps/agent-script-recipes | High-value secondary source for examples and emerging patterns. Mar 2026 audit against upstream commit 9c90176 confirmed: developer_name is now canonical, description: is the public config field used across the recipe corpus, @actions. prefix guidance is explicit, and run @actions.X vs reasoning-level utility resolution is documented. Caveats: repo still contains stale/inconsistent examples (connections: plural wrapper, mixed lifecycle-hook guidance, strong Employee-Agent bias, weak Service-Agent coverage). Treat as a corroborating source, not sole truth. See upstream-recipes-audit.md. |
| Official GA Documentation | GA alignment audit (v2.4.0): filter_from_agent as GA standard output property, @system_variables.user_input, prompt:// shorthand, developer_name output property, go_to_ naming convention, is None vs == "" distinction, topic-level system: overrides, variable label property, timestamp/currency type restrictions |
| Salesforce Official Documentation | Core syntax, API references, deployment guides |
| TDD Validation (this skill) | 13 validation agents confirming current-release syntax compatibility |
| Tribal knowledge interviews | Canvas View bugs, VS Code limitations, credit consumption patterns |
| agentforce.guide | Unofficial but useful examples (note: some patterns don't compile in current release) |
| @kunello (PR #20) | Prompt template "Input:fieldName" binding syntax, context-aware description overrides, {!@actions.X} instruction reference patterns, callback behavior notes, error pattern catalog |
| aquivalabs/my-org-butler | Official sources registry pattern, known-issues tracking structure, verification protocol, Builder UI → Agent Script migration guide, self-improvement protocol |
⚠️ Note on Feature Validation: Some patterns from external sources (e.g.,
always_expect_input:) do NOT compile in Winter '26. Action metadata properties (label:,require_user_confirmation:, etc.) are valid on action definitions with targets but NOT on@utils.transition. Thebefore_reasoning:/after_reasoning:lifecycle hooks ARE valid but require direct content (noinstructions:wrapper). This skill documents only patterns that pass TDD validation.
Source-of-truth order for this skill: official Salesforce docs → local validate/preview/publish evidence → upstream/community examples. When these disagree, prefer observed org behavior over recipe prose.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Agent Script Syntax Reference
Complete syntax guide for the Agent Script DSL. Your entire agent in one
.agentfile.
Design Principles
| Principle | Description |
|---|---|
| Declarative Over Imperative | Describe WHAT the agent should do, not HOW step-by-step |
| Human-Readable by Design | Syntax resembles structured English - non-engineers can read it |
| Single File Portability | Entire agent definition in one .agent file - copy/paste ready |
| Version Control Friendly | Plain text works with Git - diff, review, rollback |
Block Structure
Recommended Top-Level Block Convention
Use the following order as this skill's preferred convention:
config → variables → system → connection → knowledge → language → start_agent → topic
| Block | Required | Purpose |
|---|---|---|
config: |
✅ Yes | Agent metadata and identification |
variables: |
Optional | State management (mutable/linked) |
system: |
✅ Yes | Global messages and instructions |
connection: |
Optional | Escalation routing (connection messaging: — singular, NOT connections:) |
knowledge: |
Optional | Knowledge base configuration |
language: |
Optional | Supported languages |
start_agent: |
✅ Yes | Entry point (exactly one) |
topic: |
✅ Yes | Conversation topics (one or more) |
✅ Evidence note: Official Salesforce docs and examples present top-level blocks in varying sequences, and local validation evidence indicates both config-first and system-first orderings compile. Use one convention consistently, but do not treat top-level block order alone as a correctness rule.
Block Internal Ordering
Within start_agent and topic blocks, sub-blocks follow this order:
description → system → actions → reasoning → after_reasoning
Within a reasoning block:
instructions → actions
Block Definitions
1. system: Block (Required)
system:
messages:
welcome: "Hello! How can I help?"
error: "Sorry, something went wrong."
instructions: "You are a helpful assistant."
| Field | Purpose |
|---|---|
messages.welcome |
Initial greeting message |
messages.error |
Fallback error message |
instructions |
Global system prompt for the agent |
Message syntax note: Quoted strings are fine for static
welcome/errormessages. If a welcome or error message includes variable interpolation such as{!@variables.user_preferred_name}, author that message in template/block form with|so the value is rendered in the system message. For first-turn personalization, prefer linked or session-backed variables.
❌ Wrong — quoted interpolation can render literally
system:
messages:
welcome: "Hi {!@variables.user_preferred_name}!"
error: "Sorry, something went wrong."
instructions: "You are a helpful assistant."
✅ Correct — use block form for dynamic system messages
system:
messages:
welcome: |
Hi {!@variables.user_preferred_name}! How can I help today?
error: "Sorry, something went wrong."
instructions: "You are a helpful assistant."
2. config: Block (Required)
config:
developer_name: "refund_agent"
description: "Handles refund requests"
agent_type: "AgentforceServiceAgent"
default_agent_user: "admin@yourorg.com"
| Field | Required | Purpose |
|---|---|---|
developer_name |
✅ Yes | Internal identifier (must match folder name, case-sensitive) |
description |
✅ Yes | Agent's goals and purpose |
agent_type |
✅ Yes | AgentforceServiceAgent or AgentforceEmployeeAgent |
default_agent_user |
⚠️ REQUIRED | Must be valid Einstein Agent User |
agent_label |
Optional | Display name for the agent in UI (defaults to developer_name if omitted) |
agent_description |
Optional / compatibility | Alternative config key accepted by local tooling; public docs/examples in this skill prefer description |
company |
Optional | Company context for the agent |
role |
Optional | Role/persona description for the agent |
agent_version |
Optional / system-managed | Agent version metadata |
enable_enhanced_event_logs |
Optional | Enables enhanced conversation logging (True / False) |
user_locale |
Optional | User locale setting |
⚠️ Critical:
default_agent_usermust exist in the org with the "Einstein Agent User" profile. Query:SELECT Username FROM User WHERE Profile.Name = 'Einstein Agent User' AND IsActive = true
⚠️ Official-docs caution:
company,role,agent_version,enable_enhanced_event_logs, anduser_localeare documented by Salesforce. This skill now records them for completeness, but local field behavior has not been revalidated to the same depth as the core fields above.
3. variables: Block (Optional)
variables:
# Mutable: State we track and modify
failed_attempts: mutable number = 0
customer_verified: mutable boolean = False
label: "Customer Verified"
order_ids: mutable list[string] = []
order_notes: mutable string = ""
description: |
Notes collected during the order process.
May contain multiple lines of customer input.
# Linked: Read-only from external sources
session_id: linked string
source: @session.sessionID
description: "Current session identifier"
customer_id: linked string
source: @context.customerId
description: "Customer ID from context"
💡 Variables support a
label:property for UI display names and multilinedescription: |using pipe syntax.
💡 Variables also support a
visibility:property with values"Internal"(default — hidden from end user, used by planner only) or"External"(visible to end user in the chat interface). Example:visibility: "External"
Variable Types
| Type | Description | Example |
|---|---|---|
string |
Text values | name: mutable string = "" |
number |
Numeric values | count: mutable number = 0 |
boolean |
True/false flags | verified: mutable boolean = False |
object |
Structured data | data: mutable object = {} |
date |
Calendar dates | created: mutable date |
id |
Unique identifiers | record_id: mutable id |
list[T] |
Arrays of type T | items: mutable list[string] = [] |
Action-Only Types (valid for action I/O, NOT for mutable/linked variables):
| Type | Description |
|---|---|
datetime |
Date and time (action I/O only) |
time |
Time of day (action I/O only) |
integer |
Whole numbers (action I/O only) |
long |
Large whole numbers (action I/O only) |
timestamp |
Date and time (action I/O only) |
currency |
Money values (action I/O only) |
⚠️ Undocumented variable types:
timestampandcurrencycompile as variable types but are absent from official GA documentation. Preferdatefor date/time variables andnumberfor currency values. These types are reliable for action I/O.
⚠️
datetype fails in action I/O: Usingdateas an action input or output type compiles but causes a runtime error ('Date'). Useobjectwithcomplex_data_type_name: "lightning__dateType"instead. Thedatetype works correctly for mutable/linked variables — the issue is only in action I/O. See known-issues.md Issue 28.
Variable Modifiers
| Modifier | Behavior | Use Case |
|---|---|---|
mutable |
Read/write - can be changed during conversation | Counters, flags, accumulated state |
linked |
Read-only - populated from external source | Session IDs, user profiles, context data |
⚠️ Booleans are capitalized: Use
True/False, nottrue/false
4. language: Block (Optional)
language:
default: "en_US"
supported: ["en_US", "es_ES", "fr_FR"]
5. knowledge: Block (Optional)
knowledge:
knowledge_base: "My_Knowledge_Base"
citations_enabled: False
| Field | Required | Purpose |
|---|---|---|
knowledge_base |
✅ Yes (if block present) | Name of the knowledge base to attach to the agent |
citations_enabled |
Optional | True/False — controls whether knowledge citations are included in responses (default: True if omitted). Set to False if citations are not needed or if using NGA agents where citations do not render (Issue 32). |
💡 Knowledge bases are configured in the Salesforce org and referenced by name. The knowledge block enables RAG (Retrieval Augmented Generation) capabilities for the agent.
⚠️ Required even without Data Library: If your agent references knowledge in any topic but you don't have a Data Library configured, you still need a
knowledge:block withcitations_enabled: Falseto prevent compilation errors.
6. connection: Block (Optional)
# Minimal form (no routing):
connection messaging:
adaptive_response_allowed: True
# Full form with escalation routing:
connection messaging:
outbound_route_type: "OmniChannelFlow"
outbound_route_name: "flow://Route_from_Agent"
escalation_message: "Connecting you with a specialist."
adaptive_response_allowed: False
⚠️ Use
connection messaging:(singular, NOTconnections:). The pluralconnections:wrapper is invalid — see known-issues.md Issue 16.
Supported Channels
| Channel | Purpose |
|---|---|
messaging |
Chat/messaging channels (Enhanced Chat, Web Chat, In-App) |
voice |
Voice/phone channels (Service Cloud Voice) |
web |
Web-based channels |
7. topic: Block (Required - one or more)
topic main:
description: "Main conversation handler"
reasoning:
instructions: |
Help the user with their request.
actions:
do_something: @actions.my_action
description: "Action description"
| Field | Purpose |
|---|---|
description |
Helps LLM understand topic purpose |
reasoning.instructions |
Instructions for this topic |
reasoning.actions |
Available actions in this topic |
Topic-Level System Overrides
Topics can override the agent-level system: instructions with their own system: block:
topic specialized_support:
description: "Handles technical support"
system:
instructions: "You are a technical support specialist. Be precise and methodical."
reasoning:
instructions: |
Help with technical issues.
The topic-level
system:replaces (not appends to) the agent-level system instructions for that topic's reasoning context.
8. start_agent: Block (Required - exactly one)
start_agent entry:
description: "Entry point for conversations"
reasoning:
instructions: |
Greet the user and route appropriately.
actions:
go_main: @utils.transition to @topic.main
description: "Navigate to main topic"
💡 The name can be anything - "main", "entry", "topic_selector" - just be consistent.
Instruction Syntax
Pipe vs Arrow Syntax
| Syntax | Use When | Example |
|---|---|---|
instructions: | |
Simple multi-line text (no expressions) | instructions: | Help the user. |
instructions: -> |
Complex logic with conditionals/actions | instructions: -> if @variables.x: |
Arrow Syntax (->) Patterns
reasoning:
instructions: ->
# Conditional (resolves BEFORE LLM)
if @variables.customer_verified == True:
| Welcome back, verified customer!
else:
| Please verify your identity first.
# Inline action execution
run @actions.load_customer
with customer_id = @variables.customer_id
set @variables.customer_data = @outputs.data
# Variable injection in text
| Customer name: {!@variables.customer_name}
# Deterministic transition
if @variables.failed_attempts >= 3:
transition to @topic.escalation
Instruction Syntax Elements
| Element | Syntax | Purpose |
|---|---|---|
| Literal text | | text |
Text that becomes part of LLM prompt |
| Conditional | if @variables.x: |
Resolves before LLM sees instructions |
| Else clause | else: |
Alternative path |
| Inline action | run @actions.x |
Execute action during resolution |
| Set variable | set @var = @outputs.y |
Capture action output |
| Template injection | Curly-bang syntax: {!@variables.x} | Insert variable value into text |
| Deterministic transition | transition to @topic.x |
Change topic without LLM |
⚠️
else ifis NOT supported: Agent Script does not have anelse ifkeyword. Nestedifinsideelse:is also invalid. Use compound conditions (if A and B:) or flatten to sequentialifstatements.
Multiline String Continuation
Long literal text can span multiple lines using indented continuation:
instructions: |
| This is a long instruction that
continues on the next line without a pipe.
The continued line is indented further than the | line and does NOT start with a new |.
Deterministic Resolution vs LLM-Driven Tool Use
instructions: -> mixes two very different execution modes. Treat them separately when authoring.
| Pattern | Who executes it | When it runs | Supports ... |
Best use |
|---|---|---|---|---|
run @actions.X inside instructions: -> |
Deterministic resolver | Before the LLM sees the final prompt | No | Preload data, normalize state, perform fixed control flow |
reasoning.actions tool invocation |
LLM / planner | After instructions resolve | Yes | Slot filling, user-driven tool calls, flexible next-step selection |
@utils.setVariables from reasoning.actions |
LLM / planner | After instructions resolve | Yes | Capture user-provided values into variables for later deterministic use |
Rule of thumb: if a line begins with run inside instructions: ->, every with value must already exist as a literal, a variable, or a prior action output. Do not expect the resolver to slot-fill ... in that phase.
❌ Wrong — deterministic run cannot slot-fill
reasoning:
instructions: ->
run @actions.send_verification_code
with email = ...
✅ Correct — let the LLM capture first, then use the saved variable
variables:
member_email: mutable string = ""
topic collect_email:
reasoning:
instructions: ->
if @variables.member_email == "":
| Ask the user for their email address, then call {!@actions.save_email}.
else:
transition to @topic.send_code
actions:
save_email: @utils.setVariables
description: "Save the user's email address"
with member_email = ...
topic send_code:
reasoning:
instructions: ->
run @actions.send_verification_code
with email = @variables.member_email
Action Configuration
Action Declaration
actions:
action_name: @actions.my_action
description: "What this action does"
with input_param = @variables.some_value
set @variables.result = @outputs.output_field
available when @variables.is_authorized == True
Action source Attribute
Actions imported from the Agentforce Asset Library require a source: attribute that matches the asset library's API name:
actions:
search_knowledge:
description: "Search the knowledge base"
source: "My_Knowledge_Asset" # Must match asset library API name exactly
inputs:
query: string
outputs:
answer: string
target: "retriever://My_Knowledge_Base"
⚠️ If
source:does not match the asset library API name exactly (case-sensitive), the action will fail at publish time with a reference resolution error.
Action Metadata Properties
Action definitions with target: support the following metadata properties. These are NOT valid on @utils.transition utility actions.
Action-Level:
| Property | Type | Context | Notes |
|---|---|---|---|
label |
String | Action def, topic, I/O | Display name in UI |
description |
String | Action def, I/O | LLM decision-making context |
require_user_confirmation |
Boolean | Action def | Compiles; runtime no-op (Issue 6) |
include_in_progress_indicator |
Boolean | Action def | Shows spinner during execution |
progress_indicator_message |
String | Action def | Custom spinner text |
Input-Level:
| Property | Type | Notes |
|---|---|---|
is_required |
Boolean | Marks input as mandatory — ⚠️ NOT enforced by planner (Issue 26) |
is_user_input |
Boolean | LLM extracts from conversation |
label |
String | Display name |
description |
String | LLM context |
complex_data_type_name |
String | Lightning type mapping |
lightning:isPII |
Boolean | Marks field as PII for platform data handling and masking |
Output-Level:
| Property | Type | Notes |
|---|---|---|
filter_from_agent |
Boolean | True = hide from user display (GA standard name) |
is_displayable |
Boolean | False = hide from user (compile-valid alias for filter_from_agent). ⚠️ Setting True on prompt template outputs causes blank response (Issue 34) |
is_used_by_planner |
Boolean | True = LLM can reason about value |
developer_name |
String | Overrides the parameter's developer name |
label |
String | Display name |
description |
String | LLM context |
complex_data_type_name |
String | Lightning type mapping |
lightning:isPII |
Boolean | Marks field as PII for platform data handling and masking |
Two-Level Action System
Agent Script uses a two-level system for actions. Understanding this distinction is critical:
Level 1: ACTION DEFINITION (in topic's `actions:` block)
→ Has `target:`, `inputs:`, `outputs:`, `description:`
→ Specifies WHAT to call (e.g., "flow://GetOrderStatus")
Level 2: ACTION INVOCATION (in `reasoning.actions:` block)
→ References Level 1 via `@actions.name`
→ Specifies HOW to call it (`with`, `set` clauses)
→ Does NOT use `inputs:`/`outputs:` (use `with`/`set` instead)
Complete Example:
topic order_lookup:
description: "Look up order details"
# Level 1: DEFINE the action (with target + I/O schemas)
actions:
get_order:
description: "Retrieves order information by ID"
inputs:
order_id: string
description: "Customer's order number"
outputs:
status: string
description: "Current order status"
target: "flow://Get_Order_Details"
reasoning:
instructions: |
Help the customer check their order status.
# Level 2: INVOKE the action (with/set, NOT inputs/outputs)
actions:
lookup: @actions.get_order
with order_id = ...
set @variables.order_status = @outputs.status
⚠️ I/O schemas are REQUIRED for publish: Action definitions with only
description:andtarget:(noinputs:/outputs:) will PASS LSP and CLI validation but FAIL server-side compilation with "Internal Error." Always include complete I/O schemas in Level 1 definitions.
Lifecycle Hooks: before_reasoning: and after_reasoning:
Lifecycle hooks enable deterministic pre/post-processing around LLM reasoning. They are FREE (no credit cost).
topic main:
description: "Topic with lifecycle hooks"
# BEFORE: Runs deterministically BEFORE LLM sees instructions
before_reasoning:
# Content goes DIRECTLY here (NO instructions: wrapper!)
set @variables.turn_count = @variables.turn_count + 1
if @variables.needs_redirect == True:
transition to @topic.redirect
# LLM reasoning phase
reasoning:
instructions: ->
| Turn {!@variables.turn_count}: How can I help?
# AFTER: Runs deterministically AFTER LLM finishes reasoning
after_reasoning:
# Content goes DIRECTLY here (NO instructions: wrapper!)
set @variables.interaction_logged = True
Key Rules:
- Content goes directly under the block (NO
instructions:wrapper) - Reliable primitives:
set,if/else,transition to runbehavior: lifecycle-hook syntax is valid, butrun @actions.Xinsidebefore_reasoning:/after_reasoning:is not portable enough to treat as universally reliable. It has worked in some target-backed cases, but behavior is inconsistent across bundle types and org states. Safest guidance: keep lifecycle hooks focused onset,if/else, andtransition to, and userunprimarily inreasoning.actions:post-action chains orinstructions: ->blocks.transition toworks inafter_reasoning:blocks- If a topic transitions mid-execution, the original topic's
after_reasoning:does NOT run - Both hooks are FREE (no credit cost) — use for data prep, logging, cleanup
💡 Official GA docs show
after_reasoning:->(arrow syntax). Our TDD validated the direct-content form. Both forms may work — we recommend the tested direct-content form.
Action Target Protocols
Core Targets (Validated)
| Protocol | Use When | Status |
|---|---|---|
flow:// |
Data operations, business logic | ✅ Validated |
apex:// |
Custom calculations, validation | ✅ Validated |
prompt:// / generatePromptResponse:// |
Grounded LLM responses | ✅ Validated |
api:// |
REST API callouts | ✅ Validated |
retriever:// |
RAG knowledge search | ✅ Validated |
externalService:// |
Third-party APIs via Named Credential | ✅ Validated |
standardInvocableAction:// |
Built-in SF actions | ✅ Validated |
Additional Targets (From agent-script-recipes)
| Protocol | Use When | Status |
|---|---|---|
datacloudDataGraphAction:// |
Data Cloud graph queries | ⚠️ Untested |
datacloudSegmentAction:// |
Data Cloud segment operations | ⚠️ Untested |
triggerByKnowledgeSource:// |
Knowledge-triggered actions | ⚠️ Untested |
contextGrounding:// |
Context grounding operations | ⚠️ Untested |
predictiveAI:// |
Einstein predictions | ⚠️ Untested |
runAction:// |
Sub-action execution | ⚠️ Untested |
external:// |
External services | ⚠️ Untested |
copilotAction:// |
Copilot actions | ⚠️ Untested |
@topic.X |
Topic delegation (supervision) | ✅ Validated |
Note: Untested targets are documented in the official AGENT_SCRIPT.md rules. They may require specific licenses, org configurations, or future API versions.
💡
prompt://is the official shorthand forgeneratePromptResponse://. Both forms resolve to the same target. Example:target: "prompt://Email_Draft_Template"
Utility Actions
| Action | Purpose | Example |
|---|---|---|
@utils.transition to @topic.x |
LLM-chosen topic navigation | go_main: @utils.transition to @topic.main |
@utils.escalate |
Hand off to human agent | escalate: @utils.escalate |
@utils.setVariables |
Set multiple variables | set_vars: @utils.setVariables |
Resource References
| Syntax | Purpose | Example |
|---|---|---|
@variables.x |
Reference a variable | @variables.customer_id |
@actions.x |
Reference an action | @actions.process_refund |
@topic.x |
Reference a topic | @topic.escalation |
@outputs.x |
Reference action output | @outputs.status |
@session.x |
Reference session data | @session.sessionID |
@context.x |
Reference context data (Employee Agents on LEX only — NOT available for Service Agents; see Issue 39) | @context.userProfile |
@inputs.x |
Reference procedure input | @inputs.account_number ⚠️ Procedure context only — see Common Pitfalls |
@system_variables.user_input |
Most recent user utterance | @system_variables.user_input |
@knowledge.citations_url |
Knowledge citation URL config | @knowledge.citations_url |
@knowledge.rag_feature_config_id |
RAG feature configuration ID | @knowledge.rag_feature_config_id |
@knowledge.citations_enabled |
Whether citations are active | @knowledge.citations_enabled |
💡
@system_variablesis a separate namespace from@variables. Theuser_inputsystem variable contains the customer's most recent utterance.
⚠️ Treat
@system_variables.user_inputas raw text, not a durable deterministic intent signal. Direct guards likeif @system_variables.user_input contains "never mind":are brittle for control-flow-critical routing. Prefer a Flow, Apex, or classifier action that normalizes the utterance into a boolean or enum variable first.
Common Linked Variable Sources
Linked variables commonly reference these external source patterns:
| Source Pattern | Description | Example |
|---|---|---|
@session.sessionID |
Current session identifier | Standard session context |
@context.customerId |
Customer ID from context | Employee Agents on LEX pages only — NOT available for Service Agents (Issue 39) |
@MessagingSession.{field} |
Messaging session fields (Service Agents) | @MessagingSession.MessagingEndUserId |
@MessagingEndUser.{field} |
Messaging end user fields (Service Agents) | @MessagingEndUser.Name, @MessagingEndUser.ContactId |
⚠️ Agent Type Determines Source Availability:
@context.*sources resolve LEX page-level context — they only work for Employee Agents embedded on Lightning record pages. Service Agents (NGA / ExternalCopilot) must use@MessagingSession.*or@MessagingEndUser.*for channel context. Using@context.*in a Service Agent compiles but produces "Unsupported data type" at runtime. See known-issues.md Issue 39.
# Common Messaging channel linked variables
variables:
session_key: linked string
source: @MessagingSession.MessagingSessionKey
description: "Unique messaging session key"
end_user_name: linked string
source: @MessagingEndUser.Name
description: "End user display name from messaging channel"
contact_id: linked string
source: @MessagingEndUser.ContactId
description: "Contact record ID linked to messaging end user"
💡
@MessagingSessionand@MessagingEndUsersources are available when the agent is deployed on a Messaging channel (Enhanced Chat, In-App, Web Chat). They are NOT available in Agent Builder Preview orsf agent preview.
Output Access Depends on the Declared Schema
Do not assume @outputs.X is always a plain scalar. The correct access pattern depends on the action's declared output shape.
# Scalar output → direct assignment is fine
set @variables.order_status = @outputs.status
# Structured output → keep it as an object, or access a concrete field
set @variables.raw_result = @outputs.output
set @variables.result_text = @outputs.output.value # if the output schema exposes 'value'
Guidance:
- If the output is declared as
string,number, orboolean, direct assignment is fine. - If the output is declared as
objector another structured type, inspect the schema before branching on it. - Some actions wrap their primary scalar under a field such as
.value; others expose named properties directly. - When a deterministic branch depends on the result, the safest design is to flatten the target output in Flow/Apex so Agent Script receives an explicit scalar like
is_after_hours: booleaninstead of a wrapper object.
Whitespace Rules
Indentation
| ✅ CORRECT | ❌ INCORRECT |
|---|---|
| 2-space consistent | Mixed tabs and spaces |
| 3-space consistent | Inconsistent spacing |
| Tabs consistent | Tab in one block, spaces in another |
CRITICAL: Never mix tabs and spaces in the same file. This causes compilation errors.
Boolean Values
| ✅ CORRECT | ❌ INCORRECT |
|---|---|
True |
true |
False |
false |
Complete Example
system:
messages:
welcome: "Welcome to Pronto Support!"
error: "Sorry, something went wrong. Let me connect you with a human."
instructions: "You are a helpful customer service agent for Pronto Delivery."
config:
developer_name: "pronto_refund_agent"
description: "Handles customer refund requests with churn risk assessment"
agent_type: "AgentforceServiceAgent"
default_agent_user: "agent_user@myorg.com"
variables:
# Mutable state
customer_verified: mutable boolean = False
failed_attempts: mutable number = 0
churn_risk_score: mutable number = 0
refund_status: mutable string = ""
# Linked from session
customer_id: linked string
source: @session.customerId
description: "Customer ID from messaging session"
topic identity_verification:
description: "Verify customer identity before refund processing"
reasoning:
instructions: ->
if @variables.failed_attempts >= 3:
| Too many failed attempts. Escalating to human agent.
transition to @topic.escalation
if @variables.customer_verified == True:
| Identity verified. Proceeding to refund assessment.
transition to @topic.refund_processor
| Please verify your identity by providing your email address.
actions:
verify: @actions.verify_customer
description: "Verify customer by email"
set @variables.customer_verified = @outputs.verified
topic refund_processor:
description: "Process refund based on churn risk assessment"
reasoning:
instructions: ->
# Post-action check (triggers on loop after refund)
if @variables.refund_status == "Approved":
run @actions.create_crm_case
with customer_id = @variables.customer_id
transition to @topic.success
# Pre-LLM: Load churn data
run @actions.get_churn_score
with customer_id = @variables.customer_id
set @variables.churn_risk_score = @outputs.score
# Dynamic instructions based on score
| Customer churn risk: {!@variables.churn_risk_score}%
if @variables.churn_risk_score >= 80:
| HIGH RISK - Offer full cash refund to retain customer.
else:
| LOW RISK - Offer $10 store credit as goodwill.
actions:
process_refund: @actions.process_refund
description: "Issue the refund"
available when @variables.customer_verified == True
set @variables.refund_status = @outputs.status
topic escalation:
description: "Escalate to human agent"
reasoning:
instructions: |
Apologize for the inconvenience and transfer to a human agent.
actions:
handoff: @utils.escalate
description: "Transfer to live support"
topic success:
description: "Successful refund confirmation"
reasoning:
instructions: |
Thank the customer and confirm their refund has been processed.
start_agent topic_selector:
description: "Entry point - route to identity verification"
reasoning:
instructions: |
Greet the customer and begin identity verification.
actions:
start: @utils.transition to @topic.identity_verification
description: "Begin refund process"
Expression Operators
Comparison Operators
| Operator | Description | Example |
|---|---|---|
== |
Equal to | if @variables.status == "active": |
!= |
Not equal to | if @variables.status != "closed": |
< |
Less than | if @variables.count < 10: |
<= |
Less than or equal | if @variables.count <= 5: |
> |
Greater than | if @variables.risk > 80: |
>= |
Greater than or equal | if @variables.attempts >= 3: |
is |
Identity check | if @variables.data is None: |
is not |
Negated identity check | if @variables.data is not None: |
Note: Use
!=for not-equal comparisons. The<>operator does NOT compile.
Logical Operators
| Operator | Description | Example |
|---|---|---|
and |
Logical AND | if @variables.verified == True and @variables.active == True: |
or |
Logical OR | if @variables.status == "open" or @variables.status == "pending": |
not |
Logical NOT | if not @variables.blocked: |
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
+ |
Addition | set @variables.count = @variables.count + 1 |
- |
Subtraction | set @variables.remaining = @variables.total - @variables.used |
⚠️ NOT supported:
*(multiplication),/(division),%(modulo). For complex arithmetic, use a Flow or Apex action.
Access Operators
| Operator | Description | Example |
|---|---|---|
. |
Property access | @outputs.result.status |
[] |
Index access | @variables.items[0] |
Conditional Expression (Ternary-like)
| Status: {!@variables.status if @variables.status else "pending"}
Expression Limitations (Sandboxed Python AST Subset)
Agent Script expressions use a sandboxed subset of Python. Not all Python operations are available.
Supported:
| Category | Operations |
|---|---|
| Arithmetic | +, - |
| Comparison | ==, !=, <, <=, >, >=, is, is not |
| Logical | and, or, not |
| Ternary | x if condition else y |
| Built-in functions | len(), max(), min() |
| Attribute access | @outputs.result.field |
| Index access | @variables.items[0] |
| String methods | contains, startswith, endswith |
⚠️ Portability warning:
contains/startswith/endswithmay compile, but they are not the safest choice for control-flow-critical validation or intent routing. Use them only as light heuristics. For URL validation, cancellation detection, or anything that must deterministically gate behavior, prefer a Flow/Apex/classifier action that returns a normalized boolean or enum.
NOT Supported:
| Operation | Workaround |
|---|---|
Multiplication (*) |
Use Flow/Apex action |
Division (/) |
Use Flow/Apex action |
Modulo (%) |
Use Flow/Apex action |
String concatenation (+ on strings) |
Use {!var1}{!var2} template injection |
List slicing (items[1:3]) |
Use Flow to extract sublist |
List comprehensions ([x for x in ...]) |
Use Flow/Apex for list transformation |
| Lambda expressions | Use Flow/Apex action |
for/while loops |
Use topic loop pattern (re-entry) |
import statements |
Not available (security sandbox) |
Empty list literal in expressions (== [], = []) |
Use len(@variables.list) == 0 for empty check; use temp empty var for reset (Issue 33) |
Apex Complex Type Notation
When action inputs or outputs reference Apex inner classes, use the @apexClassType notation:
@apexClassType/c__OuterClass$InnerClass
| Component | Description | Example |
|---|---|---|
@apexClassType/ |
Required prefix | — |
c__ |
Default namespace (or your package namespace) | c__, myns__ |
OuterClass |
The containing Apex class | OrderService |
$ |
Inner class separator | — |
InnerClass |
The inner class name | LineItem |
Example:
actions:
process_order:
inputs:
line_items: list[object]
complex_data_type_name: "@apexClassType/c__OrderService$LineItem"
target: "apex://OrderService"
Note: This notation is used in the
complex_data_type_namefield of action input/output definitions in Agentforce Assets, not in the.agentfile directly.
Current Limitations and Practical Workarounds
| Limitation | What happens | Practical workaround |
|---|---|---|
set @variables.list = [] in runtime logic |
Parse error ([ not allowed in expression position) |
Define a dedicated empty list variable and assign from it |
Nested object mutation such as set @variables.profile.name = ... |
Mutation is not portable / may fail silently or parse incorrectly | Flatten state into scalar variables or shape structured data upstream in Flow/Apex |
Direct variable capture with set @variables.x = ... |
No user input is captured | Expose @utils.setVariables (or another LLM-invoked action) and let the planner fill ... |
| Exact quoted field names in special cases | Raw .agent may be valid, but some visual editors can rewrite the field name during round-trip save/reformat |
Treat the raw .agent file in source control as the source of truth and diff after builder edits |
Common Pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Mixed tabs/spaces | SyntaxError: cannot mix |
Use consistent indentation |
| Invalid boolean | Type mismatch | Use True/False (capitalized) |
| Spaces in variable names | Parse error | Use snake_case |
| Mutable + linked | Conflicting modifiers | Choose one modifier |
Missing source: for linked |
Variable empty | Add source: @session.X |
Missing default_agent_user |
Internal error on deploy | Add valid Einstein Agent User |
@inputs in set directive |
Unknown deploy error | Use @utils.setVariables to capture inputs separately, then reference via @variables |
set @variables.X = ... |
Variable never fills from user input | Capture the value through an LLM-invoked action such as @utils.setVariables, then read @variables.X later |
| Bare action name (no prefix) | Action not found / ignored | Always use @actions.action_name in run, templates, and instruction text |
run @actions.X with param = ... |
Deterministic inline run never slot-fills the parameter |
Capture the value first with an LLM-invoked action, then run deterministically using the saved variable |
run @actions.X for utility / delegation / unresolved action |
ACTION_NOT_IN_SCOPE, action not found, or available-actions list excludes the name |
run @actions.X resolves only to topic-level actions: that declare target:. Use direct set / transition to for deterministic utility behavior, or let reasoning.actions: invoke the utility. |
set @variables.object.field = ... or set @variables.object["field"] = ... |
Nested object updates fail or behave inconsistently | Use flattened scalar variables, or update the structure in Flow/Apex and return a fresh object |
| Null check vs empty string | Wrong comparison for null | Use is None for null checks, == "" for empty strings — they are different |
is_required not enforced |
Planner invokes action without required inputs | Use available when @variables.X is not None guard instead. is_required is a hint, not a gate. See Issue 26 |
Raw @system_variables.user_input contains/startswith/endswith routing |
Cancellation/revision intent checks behave inconsistently | Use a Flow/Apex/classifier action to normalize the utterance into a boolean or enum, then branch on @variables.X. See Issue 42 |
contains / startswith / endswith as critical validation gates |
URL or string guards compile but behave unevenly across authoring/runtime contexts | Prefer an upstream validation action that returns an explicit scalar like is_valid_url: boolean. |
date type in action I/O |
Runtime error 'Date' |
Use object + complex_data_type_name: "lightning__dateType" in action I/O. date works fine for variables. See Issue 28 |
== [] or set = [] in expressions |
Parse error ([ not allowed) |
Use len(@variables.list) == 0 for empty check; use temp empty var for reset. See Issue 33 |
is_displayable: True on prompt outputs |
Agent returns blank/empty response | Set is_displayable: False and let the reasoner synthesize the output. If the output should influence the response or routing, also set is_used_by_planner: True. See Issue 34 |
| Structured output assigned directly to scalar variable | Comparisons fail or wrapper/object text leaks into state | Inspect the output schema and access a concrete property such as .value only when that field actually exists, or flatten the output in Flow/Apex first. |
Line breaks in topic description: |
Script breaks with syntax error | Keep description: on a single line — no line breaks. See Issue 35 |
| Variable name matches system context | "Field is already mapped to a Context Variable" | Avoid names like Locale, Channel, Status, Origin — use prefixed names like customer_locale. See Issue 36 |
filter_from_agent + is_used_by_planner on output |
InvalidFormatError + cascading ACTION_NOT_IN_SCOPE |
These are mutually exclusive. Use only filter_from_agent: True; remove is_used_by_planner. See Issue 40. |
| Lifecycle arithmetic on mutable number without null guard | Silent crash: None + 1 → "unexpected error" |
Add if @variables.X is None: set @variables.X = 0 before arithmetic in before_reasoning / after_reasoning. See Issue 41 |
@inputs in set — Deploy-Breaking Anti-Pattern
# ❌ WRONG — @inputs in set causes unknown error at deploy time
verify: @actions.verify_customer
with account_number=...
set @variables.account_number = @inputs.account_number
# ✅ CORRECT — use @utils.setVariables to capture input separately
collect_input: @utils.setVariables
with account_number=...
verify: @actions.verify_customer
with account_number=@variables.account_number
set @variables.customer_name = @outputs.customer_name
Direct Variable Capture — Use @utils.setVariables, not set ... = ...
# ❌ WRONG — direct slot-fill in deterministic instructions does not work
reasoning:
instructions: ->
set @variables.member_email = ...
run @actions.send_verification_code
with email = @variables.member_email
# ✅ CORRECT — let the LLM capture the value through a tool
reasoning:
instructions: ->
if @variables.member_email == "":
| Ask the user for their email address, then call {!@actions.save_email}.
actions:
save_email: @utils.setVariables
description: "Save the user's email address"
with member_email = ...
Once the variable is set, later deterministic logic can safely reference @variables.member_email.
Bare Action Names — Always Use @actions. Prefix
# ❌ WRONG — bare names in run, templates, and instructions
run set_user_name
| Use add_to_cart to add items.
# ✅ CORRECT — always prefix with @actions.
run @actions.set_user_name
| Use {!@actions.add_to_cart} to add items.
is None vs == "" — Different Checks
# ❌ WRONG — checks for empty string, not null
if @variables.data == "":
| Data is missing.
# ✅ CORRECT — checks for null/undefined
if @variables.data is None:
| Data has not been set.
# ✅ CORRECT — checks for empty string
if @variables.data == "":
| Data is set but empty.
Use
is Nonewhen a variable may not have been set at all. Use== ""when checking for an explicitly empty string value.
run @actions.X Only Works for Topic-Level Target-Backed Actions
run @actions.X resolves only against topic-level actions: definitions that declare a real target:. It does not work for reasoning-level utilities, and it is also the wrong tool for topic-level utilities / delegations that do not have target:.
# ❌ WRONG — set_user_name is a reasoning-level utility, not a target-backed action
run @actions.set_user_name # ACTION_NOT_IN_SCOPE / action not found
reasoning:
actions:
set_user_name: @utils.setVariables
with user_name=...
# ❌ WRONG — go_help is topic-level, but it is still a utility transition (no target:)
actions:
go_help: @utils.transition to @topic.help
reasoning:
instructions: ->
run @actions.go_help # not a valid deterministic run target
# ✅ CORRECT — use direct deterministic primitives for non-target utility behavior
reasoning:
instructions: ->
set @variables.user_name = "Pat"
transition to @topic.help
# ✅ CORRECT — use run only for a topic-level target-backed action definition
actions:
load_customer:
target: "flow://Load_Customer"
inputs:
customer_id: string
outputs:
customer_name: string
reasoning:
instructions: ->
run @actions.load_customer
with customer_id = @variables.customer_id
set @variables.customer_name = @outputs.customer_name
Rule of thumb: if you want deterministic execution, run is correct only when the referenced action is a topic-level definition with target:. Otherwise use direct set / transition to, or let reasoning.actions: expose the utility for LLM-driven invocation.
Upcoming: Naming Changes (Forward-Looking)
Roadmap signal: Salesforce is moving toward renaming core Agent Script concepts. Both old and new names will be supported during a transition period, with the old names deprecated later.
| Current Name | New Name | Notes |
|---|---|---|
topic |
subagent |
Reflects the delegation/supervision model |
action |
tool |
Aligns with industry-standard LLM terminology |
No action required now — current topic: and actions: syntax continues to work. This is informational for forward planning.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Testing & Validation Guide
The 100-Turn Gauntlet: Automated Batch Testing with LLM-as-Judge Scoring
Enterprise Testing Infrastructure
Testing Center Overview
A centralized hub for batch-testing utterances without deactivating your agent.
Capabilities:
- ✅ Run tests against draft or committed versions
- ✅ No need to deactivate the live agent
- ✅ Execute up to 100 test cases simultaneously
- ✅ Compare results across different script versions
- ✅ Export test results for stakeholder review
💡 Think of it as "staging" for your agent - test safely while production runs.
The 5 Quality Metrics
| Metric | Description | Scale |
|---|---|---|
| Completeness | Did the response include ALL necessary information? | 0-5 |
| Coherence | Did the agent sound natural vs raw JSON output? | 0-5 |
| Topic Assertion | Did the agent route to the correct topic? | Pass/Fail |
| Action Assertion | Did the agent invoke the expected actions? | Pass/Fail |
| Combined Score | Determines production readiness | Composite |
⚠️ 100% assertions with 0% coherence = correct but robotic. Both matter.
Coherence: The Difference
| Coherence: 0/5 ❌ | Coherence: 5/5 ✅ |
|---|---|
| USER: "I want a refund for order #123" | USER: "I want a refund for order #123" |
AGENT: {"status": "success", "case_id": "5008000123", "refund_auth": true} |
AGENT: Great news! Your refund has been approved. For your records, your case number is 5008000123. The refund should appear on your card within 3-5 business days. |
| Raw JSON dump - not conversational | Complete information in natural language |
LLM-as-Judge
A "Judge LLM" evaluates the "Agent LLM" using criteria that match your use case.
Benefits:
- ✅ Scalable: Evaluate thousands of responses automatically
- ✅ Customizable: Criteria match your specific use case
- ✅ Consistent: Removes human reviewer variability
- ✅ Explainable: Each score includes reasoning
- ✅ Iterative: Refine criteria based on edge cases
💡 The Judge LLM compares responses against your "Golden Response" definition.
Batch Testing Workflow
Step 1: Prepare Test Cases
Create a set of test utterances covering:
- Happy path scenarios
- Edge cases
- Error conditions
- Multi-turn conversations
Step 2: Define Assertions
For each test case, specify:
- Expected Topic: Which topic should be activated
- Expected Actions: Which actions should be invoked
- Golden Response: Ideal response pattern
Step 3: Run Batch
# Run agent tests (--api-name refers to an AiEvaluationDefinition, not the agent)
sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Step 4: Analyze Results
| Metric | Score | Status |
|---|---|---|
| TOPIC ASSERTION | 100% | ✅ PASS |
| ACTION ASSERTION | 100% | ✅ PASS |
| COMPLETENESS | 100% | ✅ PASS |
| COHERENCE | 0% | ❌ FAIL |
The Coherence Collapse Problem
Symptom
Batch test shows:
- Topic assertions: 100% ✅
- Action assertions: 100% ✅
- Completeness: 100% ✅
- Coherence: 0% ❌
Root Cause
Agent returns raw action output instead of natural language response.
# Problem: No instruction to format response
actions:
get_order: @actions.get_order_details
set @variables.order_data = @outputs.data
# LLM just dumps the data
Fix
Add explicit formatting instructions:
instructions: ->
run @actions.get_order_details
set @variables.order_data = @outputs.data
| Here are your order details:
| - Order Number: {!@variables.order_data.number}
| - Status: {!@variables.order_data.status}
| - Estimated Delivery: {!@variables.order_data.eta}
|
| Is there anything else I can help with?
Metadata Lifecycle
See cli-guide.md for the Draft -> Commit -> Activate lifecycle.
Test Case Design
Coverage Categories
| Category | Examples |
|---|---|
| Happy Path | Standard refund request, order lookup |
| Edge Cases | Empty cart, expired offers, boundary values |
| Error Handling | Invalid input, service failures |
| Security | Unauthorized access attempts |
| Multi-Turn | Conversation continuity, context preservation |
Test Case Template
test_case:
name: "High-risk customer full refund"
utterance: "I want a refund for order #12345"
context:
customer_id: "CUST_001"
churn_risk: 85
expected:
topic: "refund_processor"
actions: ["get_churn_score", "process_refund"]
response_contains: ["approved", "full refund"]
assertions:
topic_match: true
action_sequence: true
coherence_min: 4
Context Variable Injection in Tests
Context variables control agent behavior at the session level. Injecting them correctly in tests is critical for testing auth-gated flows, routing logic, and action execution.
YAML Test Spec Format
Context variables in sf agent test YAML specs use bare names (not $Context. prefixed):
testCases:
- name: "Test post-auth routing"
utterance: "I need to check my account"
contextVariables:
- name: RoutableId # Bare name, NOT $Context.RoutableId
value: "0MwXXXXXXXXXXXX" # Real MessagingSession ID
- name: CaseId
value: "500XXXXXXXXXXXXX"
- name: Verified_Check # Bypass auth flow in tests
value: "true"
expectedTopic: Account_Management
Key Patterns
| Pattern | Value | Effect |
|---|---|---|
RoutableId |
Real MessagingSession ID | Actions receive real recordId instead of topic internal name |
CaseId |
Real Case ID | Flows that reference $Context.CaseId work correctly |
Verified_Check=true |
String "true" | Unlocks auth-gated topics (bypasses verification flow in tests) |
conversationHistory for Multi-Turn Tests
For multi-turn test scenarios, the conversationHistory block provides prior conversation context. The topic field in conversation history resolves local developer names (no hash suffix needed):
testCases:
- name: "Follow-up after product help"
utterance: "Actually, I want to leave feedback"
conversationHistory:
- role: user
content: "My doorbell camera isn't working"
- role: assistant
content: "I can help with that. Let me look up your devices."
topic: Product_Help # Local name, NOT Product_Help_16jXXX
expectedTopic: Feedback
Prefix Resolution
Both bare names and $Context. prefixed names work at runtime — the platform resolves both. Recommend $Context. prefix for clarity in documentation, but use bare names in YAML specs (the YAML parser expects bare names).
Cross-reference: For Evaluation API testing patterns with state injection, see the
sf-ai-agentforce-testingskill.
Validation Commands
Pre-Deployment Validation
# Validate authoring bundle syntax
sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
# Run agent tests
sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Common Validation Errors
| Error | Cause | Fix |
|---|---|---|
Invalid default_agent_user |
User doesn't exist | Create Einstein Agent User |
Topic not found |
Typo in transition | Check topic name spelling |
Mixed indentation |
Tabs + spaces | Use consistent formatting |
Action not callable |
Wrong protocol | Check target protocol |
Continuous Testing
CI/CD Integration
# Example GitHub Actions workflow
name: Agent Testing
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Validate Agent
run: sf agent validate authoring-bundle --api-name MyAgent -o TARGET_ORG --json
- name: Run Tests
run: sf agent test run --api-name MyTestDef --wait 10 -o TARGET_ORG --json
Test Automation Best Practices
- Run validation on every commit
- Run full test suite before merge
- Monitor coherence scores over time
- Alert on assertion failures
- Track coverage by topic and action
Key Takeaways
| # | Concept |
|---|---|
| 1 | Testing Center - Run up to 100 tests simultaneously |
| 2 | 5 Quality Metrics - Completeness, Coherence, Topic/Action Assertions, Combined |
| 3 | LLM-as-Judge - Automated scoring against golden responses |
| 4 | Coherence Matters - 100% assertions with 0% coherence = technically correct but unusable |
| 5 | Three-Phase Lifecycle - Draft (edit) → Commit (freeze) → Activate (live) |
| 6 | CI/CD Integration - Automate validation and testing in deployment pipeline |
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Upstream Recipes Audit
Audit target:
trailheadapps/agent-script-recipesAudited against upstream commit:
9c9017691db4a90bc73189371d7d540e1d9f077c(Mar 2026)
This document explains how this skill uses TrailheadApps as an input source without treating it as the sole source of truth.
Audit Summary
Verdict: useful and worth tracking, but not authoritative by itself.
Use TrailheadApps for:
- example structures
- emerging syntax patterns
- recipe-style action and topic composition
- corroborating evidence when it matches official docs and downstream org behavior
Do not use TrailheadApps alone as the final truth for:
- Service Agent user requirements
- publish-time permission behavior
connection messaging:/connections:syntax- lifecycle hook runtime guarantees
- config field canonical naming
What Upstream Confirms
| Upstream finding | Evidence | Our verdict | Action in this skill |
|---|---|---|---|
developer_name is canonical |
Commit 9aa5ee2 changed .airules/AGENT_SCRIPT.md from agent_name to developer_name |
Confirmed | Keep developer_name as canonical |
Always use @actions. prefixes |
Commit b790a6f added explicit guidance for run, templates, and instruction text |
Confirmed | Keep validator/doc guidance |
run @actions.X does not work for reasoning-level utilities |
Commit 25e6865 documents run resolving only against topic-level actions: with target: |
Confirmed | Keep instruction-resolution.md and validator guidance |
| Employee Agents are now the dominant recipe model | Commit 60ca531 switched recipes to AgentforceEmployeeAgent |
Confirmed | Treat upstream as Employee-Agent-heavy |
Where Upstream Is Stale or Inconsistent
| Upstream pattern | Evidence | Our verdict | Guidance |
|---|---|---|---|
connections: plural wrapper |
.airules/AGENT_SCRIPT.md still shows connections: top-level ordering; future_recipes/escalationPatterns still uses it |
Stale / contradicts downstream validation | Prefer connection messaging: only |
Config description: shown as primary field |
.airules/AGENT_SCRIPT.md config block and current recipes still use description: |
Aligned with official/public usage | Prefer description: in public docs/examples; keep agent_description: compatibility in local tooling |
before_reasoning removed from rules but still appears in recipes |
Main rules removed it, but future_recipes/customerServiceAgent still uses it |
Internally inconsistent | Keep lifecycle-hook docs, but be cautious about runtime guarantees |
| Service Agent coverage is weak | Current repo is almost entirely Employee-Agent examples and has effectively no real Service-Agent .agent corpus |
Incomplete source for Service-Agent authoring | Prefer this skill's service-user and publish docs |
Specific Upstream References Worth Knowing
1. developer_name migration
- Commit:
9aa5ee2 - Meaning: upstream moved away from
agent_namein.airules/AGENT_SCRIPT.md - Impact: aligns with this skill's canonical field choice
2. Bare action name fix
- Commit:
b790a6f - Meaning: upstream now explicitly warns against bare action names and recommends
@actions.references everywhere - Impact: supports this skill's validator rule
3. run @actions.X scope clarification
- Commit:
25e6865 - Meaning:
runresolves against topic-level target-backed actions, not reasoning-level utilities like@utils.setVariables - Impact: supports this skill's instruction-resolution guidance
4. Employee-Agent bias
- Commit:
60ca531 - Meaning: recipes moved broadly toward Employee Agent examples
- Impact: upstream is now less representative of Service Agent deployment realities
Maintenance Policy for This Skill
When upstream and local evidence disagree, use this priority order:
- official Salesforce docs
- local
sf agent validate/preview/publishbehavior in real orgs - this skill's TDD and field validation corpus
- upstream/community examples
Recommended Ongoing Audit Checklist
When reviewing new TrailheadApps commits, specifically check for:
- config field changes (
developer_name,description,agent_type, and any compatibility behavior aroundagent_description) - lifecycle hook additions/removals
- connection block syntax
- target protocol examples (
flow://,apex://,prompt://) - Service vs Employee agent assumptions
- examples that contradict known publish/runtime behavior
Current Decision Log
- Adopted from upstream:
developer_name, public configdescription:,@actions.prefix guidance,runvs utility clarification - Not adopted from upstream: plural
connections:wrapper, implicit Employee-Agent bias as general guidance - Handled cautiously: lifecycle hooks and
runinside lifecycle hooks
Open this reference as its own page
Agent Script Validator Rule Catalog
Source of truth for the automatic
.agentwrite/edit validator athooks/scripts/agentscript-syntax-validator.py.Validator output prefixes findings with stable rule IDs like
[ASV-STR-015]so teams can search this catalog, commit messages, and incident notes consistently.
Severity Model
| Severity | Meaning | Typical action |
|---|---|---|
| Blocking | High-confidence compiler, publish, or severe runtime-break pattern | Fix before preview/publish |
| Warning | Portability, runtime, org-drift, or best-practice risk | Review before publish |
| Info / N/A | Checklist-only status when a rule is not applicable | No action |
Rule Prefixes
| Prefix | Area |
|---|---|
ASV-STR-* |
Core structure / parse safety |
ASV-CFG-* |
Config / identity semantics |
ASV-CON-* |
Connection routing rules |
ASV-ORG-* |
Org-aware existence / permission checks |
ASV-RUN-* |
Runtime / planner / publish gotchas |
ASV-QLT-* |
Quality / maintainability heuristics |
Structure Rules
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-STR-001 |
Blocking | Indentation consistency | Errors when tabs and spaces are mixed in leading indentation. |
ASV-STR-002 |
Blocking | Boolean capitalization | Errors on lowercase true / false in assignment-style lines; requires True / False. |
ASV-STR-003 |
Blocking | Required top-level blocks | Requires config, system, and exactly one start_agent. |
ASV-STR-004 |
Blocking | Exactly one start_agent |
Errors on zero or multiple start_agent blocks. |
ASV-STR-005 |
Blocking | Topic / start collision | Errors if a start_agent name collides with a topic API name. |
ASV-STR-006 |
Blocking | Naming rules | Enforces Salesforce-style API names: starts with letter, alnum/underscore only, no trailing/consecutive underscores, max 80 chars. |
ASV-STR-007 |
Blocking | Invalid connections: wrapper |
Errors on top-level connections:; use connection messaging: etc. |
ASV-STR-008 |
Blocking | mutable + linked conflict |
Errors if a variable line combines both modifiers. |
ASV-STR-009 |
Warning | Context-colliding variable names | Warns on names like Locale, Channel, Status, Origin. |
ASV-STR-010 |
Blocking | Undefined variable references | Errors on @variables.X references in executable lines when X is undeclared. |
ASV-STR-011 |
Blocking | Undefined topic references | Errors on @topic.X when topic X: / start_agent X: is missing. |
ASV-STR-012 |
Warning | Topic/start description formatting | Warns when topic / start_agent description: appears multiline or block-scalar based. |
ASV-STR-013 |
Warning | Lifecycle instructions: wrapper |
Warns when before_reasoning: / after_reasoning: nests instructions: instead of direct content. |
ASV-STR-014 |
Blocking | Empty conditional bodies | Errors on if / else blocks that contain no executable body. |
ASV-STR-015 |
Blocking | else if unsupported |
Errors on literal else if. |
ASV-STR-016 |
Blocking | Nested if unsupported |
Errors when an if/else is nested inside another conditional block. |
ASV-STR-017 |
Blocking | Top-level actions: unsupported |
Errors on root-level actions: blocks. |
ASV-STR-018 |
Blocking | Linked variable defaults | Errors when a linked variable declares = .... |
ASV-STR-019 |
Blocking | Linked variable container types | Errors on linked object and linked list[...]. |
ASV-STR-020 |
Blocking | Ellipsis misuse | Errors when ... is used outside slot-fill style with param=... bindings. |
ASV-STR-021 |
Blocking | Reserved variable / I/O field names | Errors when variables or action I/O fields use reserved names such as description, label, is_required, is_displayable, is_used_by_planner, model. |
Config / Identity Rules
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-CFG-001 |
Blocking | Config completeness | Requires an identifier (developer_name or legacy agent_name) and description (description or compatibility agent_description). |
ASV-CFG-002 |
Blocking / Warning | Agent type semantics | Errors when Service Agents omit default_agent_user, Employee Agents include it, or agent_type is invalid. Warns when agent_type is omitted but default_agent_user implies Service Agent fallback. |
ASV-CFG-003 |
Warning | Duplicate config description fields | Warns when both description: and agent_description: are defined in the same config block. |
ASV-CFG-004 |
Warning | default_agent_user inline comments |
Warns when default_agent_user: contains trailing inline comments / extra text. |
ASV-CFG-005 |
Warning | Optional config field shape | Warns on malformed optional config fields such as non-boolean enable_enhanced_event_logs or empty company / role / agent_version / user_locale. |
ASV-CFG-006 |
Blocking | Topic system override syntax | Errors on topic-level shorthand system: "..."; enforces nested system: + instructions: shape. |
Connection Rules
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-CON-001 |
Blocking | Route property completeness | If any route property is used on connection messaging: / voice: / web:, all required route fields must be present: outbound_route_type, outbound_route_name, escalation_message. |
ASV-CON-002 |
Blocking | Route target prefix | Errors when outbound_route_name does not start with flow://. |
ASV-CON-003 |
Warning | Route type portability | Warns when outbound_route_type is not the TDD-validated OmniChannelFlow. |
Org-Aware Rules
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-ORG-001 |
Blocking / Warning | Service Agent user existence | Queries the resolved target org and verifies default_agent_user exists, is active, is not AutomatedProcess, and has profile Einstein Agent User. Warns if the org query cannot run. |
ASV-ORG-002 |
Warning | Required Service Agent assignments | Warns when the Service Agent user is missing a verified AgentforceServiceAgentUser assignment or expected {AgentName}_Access assignment for target-backed actions. |
ASV-ORG-003 |
Warning | Apex permission coverage | Warns when the custom {AgentName}_Access permission set lacks SetupEntityAccess / <classAccesses> for apex targets or cannot be verified. |
ASV-ORG-004 |
Blocking / Warning | Flow target readiness | Errors when flow:// action targets are missing or inactive in the resolved org. Warns if the org query cannot run. |
ASV-ORG-005 |
Warning | Other target protocol review | Warns when target protocols cannot be permission-checked automatically. |
ASV-ORG-006 |
Blocking / Warning | Apex target existence | Errors when apex:// targets do not exist in the resolved org. Warns if the org query cannot run. |
ASV-ORG-007 |
Blocking / Warning | Connection route Flow readiness | Errors when connection outbound_route_name: flow://... targets are missing or inactive in the resolved org. Warns if the org query cannot run. |
Runtime / Publish Gotchas
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-RUN-001 |
Blocking | Empty list literal gotchas | Errors on == [], != [], and set ... = []. |
ASV-RUN-002 |
Warning | @inputs in set |
Warns on set @variables.x = @inputs.y. |
ASV-RUN-003 |
Blocking | Bare run action names |
Errors on run foo; requires run @actions.foo. |
ASV-RUN-004 |
Blocking | Invalid metadata on @utils.transition |
Errors when transition utilities use target-action-only metadata such as label, require_user_confirmation, etc. |
ASV-RUN-005 |
Warning | Prompt output displayability | Warns on prompt/generatePromptResponse outputs with is_displayable: True. |
ASV-RUN-006 |
Warning | date in action I/O |
Warns when action inputs/outputs use primitive date; recommends Lightning date object mapping. |
ASV-RUN-007 |
Warning | is_required: True planner gap |
Warns when required inputs exist without an available when guard. |
ASV-RUN-008 |
Warning | Agent-type-specific messaging patterns | Warns on Messaging config for Employee Agents and related mismatches. |
ASV-RUN-009 |
Blocking | Pipe content in lifecycle hooks | Errors when before_reasoning: / after_reasoning: contains ` |
ASV-RUN-010 |
Warning | Lifecycle run portability |
Warns on run @actions.X inside lifecycle hooks. |
ASV-RUN-011 |
Blocking | Missing target action outputs: |
Errors when a target-backed action definition omits outputs:. |
ASV-RUN-012 |
Warning | Multiple available when portability |
Warns when an action declares more than one available when clause. |
ASV-RUN-013 |
Warning | require_user_confirmation runtime gap |
Warns on require_user_confirmation: True because runtime dialogs are unreliable. |
ASV-RUN-014 |
Blocking | run resolves outside target-backed definition scope |
Errors when run @actions.X points at a reasoning-only utility, a topic-level utility/delegation without target:, or an unresolved action name instead of a topic-level target-backed action definition. |
ASV-RUN-015 |
Warning | Welcome/error interpolation in quoted string form | Warns when a system welcome/error line appears to combine inline {!...} interpolation with plain string form instead of template/block form. |
ASV-RUN-016 |
Warning | Welcome/error folded-scalar guidance | Warns when system welcome/error messages use folded scalars (>); prefer literal block style (` |
ASV-RUN-017 |
Warning | Service Agent @context.* sources |
Warns on linked @context.* sources in Service Agent files because support is surface-dependent. |
ASV-RUN-018 |
Warning | Escalation fallback heuristic | Warns when @utils.escalate is present without an obvious fallback / latch pattern. |
ASV-RUN-019 |
Warning | Large-file parser risk | Warns when line/topic/action counts cross heuristic complexity thresholds. |
ASV-RUN-020 |
Blocking | Output filter_from_agent + is_used_by_planner conflict |
Errors when an action output field declares both filter_from_agent and is_used_by_planner. These are mutually exclusive visibility controls; the combination causes InvalidFormatError and cascading ACTION_NOT_IN_SCOPE failures that make the entire action invisible to before_reasoning and reasoning blocks. |
ASV-RUN-021 |
Warning | Lifecycle arithmetic without null guard | Warns when before_reasoning or after_reasoning does arithmetic on a mutable number variable (e.g., set @variables.X = @variables.X + 1) without a preceding if @variables.X is None: guard. Mutable number variables can arrive as None at runtime via Eval API state injection or platform initialization bugs, causing silent None + 1 crashes. |
ASV-RUN-022 |
Warning | Platform guardrail topic conflict | Warns when custom topics duplicate the platform's 3 built-in guardrail tools (Inappropriate Content Guardrail, Prompt Injection Guardrail, Reverse Engineering Guardrail). The platform auto-injects these tools into every topic's EnabledToolsStep. Custom topics with names containing inappropriate, prompt_injection, or reverse_engineering create 3+3 tool duplication in the LLM tool set, confusing the planner and causing "unexpected error" crashes. Recommended: remove custom guardrail topics and let the platform handle content moderation. |
ASV-RUN-023 |
Warning | Raw user_input string matching |
Warns when deterministic guards use contains / startswith / endswith directly on @system_variables.user_input. Raw last-utterance text is not a stable intent signal; normalize it into a boolean or enum first. |
ASV-RUN-024 |
Warning | String-method guard portability | Warns when deterministic guards rely on contains / startswith / endswith for control-flow-critical validation. These operators may compile, but they are not portable enough to be the sole routing or validation gate. |
ASV-RUN-025 |
Warning | Hidden prompt outputs without planner visibility | Warns when a prompt target output is hidden from direct display (is_displayable: False or filter_from_agent: True) but is not planner-visible. This often leads to "action ran but response is missing" behavior. |
ASV-RUN-026 |
Warning | Structured output assigned directly to scalar variable | Warns when an action output declared as object/list[...] is assigned directly to a scalar @variables.X. The output likely needs property access (for example .value if present in the schema) or flattening upstream in Flow/Apex. |
Quality / Maintainability Heuristics
| Rule ID | Severity | Check | Encoded behavior |
|---|---|---|---|
ASV-QLT-001 |
Warning | Transition naming convention | Warns when utility transitions do not use the recommended go_to_ prefix. |
ASV-QLT-002 |
Warning | Duplicate action descriptions | Warns when sibling actions reuse near-identical descriptions, reducing planner clarity. |
ASV-QLT-003 |
Warning | Duplicate topic descriptions | Warns when topic/start descriptions are near-identical, reducing topic-selection clarity. |
ASV-QLT-004 |
Warning | Sensitive action guard suggestion | Warns when obviously sensitive target-backed actions lack available when guards. |
ASV-QLT-005 |
Warning | Post-action check ordering | Warns when status-completion checks appear after LLM prompt lines instead of before them. |
Checklist Sections Emitted by the Validator
The hook groups findings into these report sections:
- Structure
- Agent identity
- Connections
- Targets & permissions
- Runtime gotchas
- Quality
This grouping is intentionally broader than the rule prefixes so operators can scan reports quickly without memorizing every ID.
Authoring Guidance
- Treat blocking IDs as pre-publish must-fix items.
- Add rule IDs to commit messages when fixing platform regressions, for example:
fix(agent): resolve ASV-RUN-011 missing outputs on flow action. - When the validator emits a warning that is intentionally accepted, record the reason in code comments or PR notes using the rule ID.
- Keep this catalog in sync with
hooks/scripts/agentscript-syntax-validator.pywhenever a rule is added, removed, or re-severitized.
Open this reference as its own page
Validator Test Matrix
Snapshot generated against the current repository assets using
hooks/scripts/agentscript-syntax-validator.pyafter the rule-catalog expansion.Goal: distinguish clean examples, warning-only templates, and intentionally partial snippets that are expected to fail a full-agent validator.
Command Used
python3 - <<'PY'
from importlib.util import spec_from_file_location, module_from_spec
from pathlib import Path
spec=spec_from_file_location('v','skills/sf-ai-agentscript/hooks/scripts/agentscript-syntax-validator.py')
mod=module_from_spec(spec)
spec.loader.exec_module(mod)
for path in sorted(Path('skills/sf-ai-agentscript/assets').rglob('*.agent')):
res=mod.AgentScriptValidator(path.read_text(), str(path)).validate()
print(path, len(res['errors']), len(res['warnings']))
PY
Summary
| Outcome | Count | Notes |
|---|---|---|
Clean (0 blocking / 0 warnings) |
1 | Fully self-contained example |
Warning-only (0 blocking / 1+ warnings) |
16 | Usually complete templates with demo placeholders, portability notes, or style suggestions |
Blocking (1+ blocking) |
13 | Mostly partial snippets by design; a small number are org-dependent or pattern examples that still need hardening |
Clean
| File | Notes |
|---|---|
assets/agents/hello-world-employee.agent |
Clean pass in current repo/context. |
Warning-Only Examples / Templates
| File | Dominant rules | Interpretation |
|---|---|---|
assets/agents/hello-world.agent |
ASV-CFG-007 |
Complete example; uses demo default_agent_user. |
assets/agents/multi-topic.agent |
ASV-CFG-007 |
Complete template; placeholders intentionally unresolved. |
assets/agents/production-faq.agent |
ASV-CFG-007 |
Valid example; remaining warning is the demo default_agent_user. |
assets/agents/simple-qa.agent |
ASV-CFG-007 |
Complete template with unresolved placeholders. |
assets/components/escalation-setup.agent |
ASV-CFG-007, ASV-RUN-018 |
Complete escalation template; placeholders remain unresolved, plus the connection-backed escalation fallback heuristic. |
assets/deterministic-routing.agent |
ASV-CFG-007 |
Complete example; nested-if issue fixed during validator audit and inline demo-user comment removed. |
assets/flow-action-lookup.agent |
ASV-CFG-007 |
Complete example with only the demo default_agent_user reminder remaining. |
assets/hub-and-spoke.agent |
ASV-CFG-007 |
Complete example with only the demo default_agent_user reminder remaining. |
assets/minimal-starter.agent |
ASV-CFG-007 |
Minimal starter is structurally valid; remaining warning is the demo default_agent_user. |
assets/patterns/critical-input-collection.agent |
ASV-RUN-012, ASV-RUN-007, ASV-CFG-007 |
Complete pattern demonstrating planner-hint caveats; warnings are instructional. |
assets/patterns/multi-step-workflow.agent |
ASV-RUN-007, ASV-RUN-012, ASV-QLT-005 |
Complete pattern; warnings are mostly planner-hint guidance plus one post-action ordering suggestion. |
assets/patterns/procedural-instructions.agent |
ASV-RUN-007, ASV-CFG-007 |
Complete pattern with advisory warnings only. |
assets/patterns/prompt-template-action.agent |
ASV-RUN-007, ASV-CFG-007 |
Complete pattern now uses the safer prompt-output flags; remaining warnings are planner-hint guidance plus demo placeholders. |
assets/patterns/system-instruction-overrides.agent |
ASV-RUN-010, ASV-CFG-007 |
Complete pattern; lifecycle run warnings are expected portability cautions. |
assets/prompt-rag-search.agent |
ASV-CFG-007 |
Complete example with only the demo default_agent_user reminder remaining. |
assets/verification-gate.agent |
ASV-CFG-007 |
Complete pattern; undefined refund_amount bug was fixed during validator audit and inline demo-user comment removed. |
Blocking Files
A. Intentionally Partial Snippets
These are not complete agents and are expected to fail a full-agent validator because they are meant to be embedded into a larger file.
| File | Dominant blockers |
|---|---|
assets/components/apex-action.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/components/error-handling.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/components/flow-action.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/components/n-ary-conditions.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/components/topic-with-actions.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/action-callbacks.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/advanced-input-bindings.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/delegation-routing.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/lifecycle-events.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/llm-controlled-actions.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-004 |
assets/patterns/open-gate-routing.agent |
ASV-STR-003, ASV-CFG-001 |
assets/patterns/bidirectional-routing.agent |
ASV-STR-003, ASV-CFG-001, ASV-STR-011 |
B. Context / Org-Dependent Blocking Cases
| File | Dominant blockers | Interpretation |
|---|---|---|
assets/escalation-pattern.agent |
ASV-ORG-007 |
Structurally valid, but the referenced outbound route Flows do not exist in the currently resolved org, so the org-aware validator correctly blocks publish readiness. |
Notes from This Audit
- The profile-aware harness now tracks both expected blocking IDs and expected warning IDs. That means remaining warning-heavy teaching templates are documented rather than treated as unexplained noise.
- The validator expansion surfaced real sample issues that were worth fixing:
assets/deterministic-routing.agentwas flattened to remove unsupported nestedifblocks.assets/verification-gate.agentnow declaresrefund_amountbefore it is referenced.assets/components/escalation-setup.agentno longer uses invalidset @variables.x = ...syntax.
- The new
ASV-CFG-007rule reduces noise on template/demo values by reporting them as unresolved placeholders/demo credentials instead of hard org failures. - The remaining blocking cohort is largely expected because many
assets/components/*andassets/patterns/*files are partial building blocks, not standalone publishable agents.
Recommended Next Step
If you want the entire assets/ tree to pass as a test suite, split it into two lanes:
- standalone agents/templates — must validate with
0 blocking - partial snippets — validate with a snippet-aware harness or a looser parser profile
That separation would let CI enforce publishability for complete examples without falsely failing the reference snippets.
Open this reference as its own page
<!-- Parent: sf-ai-agentscript/SKILL.md -->Version History
| Version | Date | Changes |
|---|---|---|
| 2.10.0 | 2026-03-28 | SF CLI 2.128.5 command refresh: Updated Agent Script CLI guidance to reflect that sf agent activate / sf agent deactivate now support --json, documented the new --version flag for deterministic activation in CI/CD, and removed the invalid Agent Script packaging example that used sf agent generate template with .agent files. Added managed-packaging caveats pointing back to the current Agent Script limitation, refreshed activation examples across SKILL.md, cli-guide.md, agent-user-setup.md, and customer-web-client.md, and added explicit BotVersion retrieve examples for version-targeted workflows. |
| 2.9.0 | 2026-03-20 | Distilled deterministic-string and prompt-output guidance: Added public, source-agnostic guidance that raw @system_variables.user_input substring checks are brittle for deterministic routing and that contains / startswith / endswith should not be the sole gate for control-flow-critical validation. Documented the safer prompt-template output pattern (is_displayable: False + is_used_by_planner: True) and clarified that missing prompt responses often require checking planner visibility separately from displayability. Added output-schema guidance explaining that structured outputs may require field access such as .value, but only when the declared schema actually exposes that field. Expanded the validator with new warning rules for raw user_input string matching, general string-method guard portability, prompt outputs hidden without planner visibility, and structured outputs assigned directly to scalar variables. Updated prompt-template teaching assets to use the safer output flags. |
| 2.8.1 | 2026-03-19 | Deterministic run scope clarification: Tightened skill guidance so run @actions.X is documented as deterministic only when X resolves to a topic-level action definition with target:. Expanded ASV-RUN-014 in agentscript-syntax-validator.py to block three real-world failure modes with one rule: (1) run against reasoning-only utilities like @utils.setVariables, (2) run against topic-level utilities/delegations without target: such as @utils.transition / @topic.X, and (3) run against unresolved action names. Error messaging now points authors toward direct set / transition to or LLM-invoked reasoning.actions: utilities, matching observed ACTION_NOT_IN_SCOPE builder failures. Updated SKILL.md, README.md, instruction-resolution.md, actions-reference.md, syntax-reference.md, and teaching asset patterns/llm-controlled-actions.agent so the deterministic-vs-LLM-directed distinction is explicit. |
| 2.8.0 | 2026-03-13 | Validator rule-catalog expansion: Expanded agentscript-syntax-validator.py with stable ASV-* rule IDs across structure, config, connection, org-aware, runtime, and quality checks. Added new blockers for else if, nested if, empty conditional bodies, top-level actions:, linked-variable defaults/types, lifecycle ` |
| 2.7.0 | 2026-03-13 | Field-validated insights (wave 2): 7 new known issues (33-39): empty list literal [] not supported in expressions, is_displayable: True causes blank response on prompt outputs, topic description: line breaks break script, variable names conflict with system context mappings, Draft-vs-Committed behavior divergence, object variables not editable in preview, @context.* not supported for NGA Service Agents (P0 accuracy fix). New patterns: knowledge: citations_enabled property documented, lightning:isPII flag added to action I/O properties, empty list comparison/reset workarounds. Added is_displayable: True blank response gotcha to production-gotchas.md. Updated @context documentation with Employee-Agent-only caveat across syntax-reference.md and SKILL.md. |
| 2.6.0 | 2026-03-12 | Field-validated insights integration: 7 new known issues (26-32): is_required planner no-op, ConcurrentModificationException on partial I/O, date type runtime error, ANTLR parser limit for large agents, "Failed to create planner session" 500, escalation loops without availability check, citations not rendering in NGA agents. 8 new syntax patterns documented: agent_label config property, visibility variable property, @knowledge.* resource references (citations_url, rag_feature_config_id, citations_enabled), @MessagingSession.* and @MessagingEndUser.* linked variable sources, action source attribute for asset library, limited run @actions.X success observed in some before_reasoning: target-backed cases (not reliable enough for broad recommendation), upcoming "topic→subagent" / "action→tool" naming changes. 2 P0 accuracy gaps fixed: is_required is not enforced by planner (use available when guards), date type fails at runtime in action I/O (use object + lightning__dateType). Added escalation availability check pattern to fsm-architecture.md and production-gotchas.md. Updated Issue 15 cross-reference to Issue 27. |
| 2.5.0 | 2026-03-11 | Production learnings integration: Fixed list[object] SObject collection mapping (lightning__recordInfoType not lightning__textType) in complex-data-types.md. Added Flow Type -> Agent Script mapping table. Added Boolean-to-String coercion hazard to production-gotchas.md. Added Flow version mismatch warning to cli-guide.md. New metadata-lifecycle.md — GenAiPlannerBundle versioning, Orphan-Then-Delete cleanup pattern, Flow version drift, shared Apex dependencies. Added Standard Platform Topics (Inappropriate_Content, Prompt_Injection, Reverse_Engineering, Ambiguous_Question) to fsm-architecture.md. Added Auth Gate Leak anti-pattern with fix strategies. Added Context Variable Injection patterns to testing-guide.md (YAML format, conversationHistory, Verified_Check bypass). Moved Issue 16 to Resolved, sanitized Issue 18, added Issues 21-22 (old bundles block Apex deletion, Flow version drift). Collapsed stale planner engine comparison in debugging-guide.md. Removed duplicate Three-Phase Lifecycle from testing-guide.md. Updated document map with metadata-lifecycle.md. |
| 2.4.0 | 2026-03-07 | Agent user setup & permission model: New agent-user-setup.md reference — 6-step Service Agent provisioning workflow, Employee Agent path, auto-generated PS warning (ORM1 testing: NextGen_*_Permissions incomplete), custom PS XML template, end-to-end verification checklist, troubleshooting table. Updated SKILL.md (service vs employee distinction across 6 locations), cli-guide.md (PS verification queries), README.md (requirements table), known-issues.md (Issue 10 enhanced with agent-type context). |
| 2.3.0 | 2026-02-20 | CLI audit & line budget refactoring: Fixed --message → --utterance in preview send examples (P0 bug — flag doesn't exist). Added sf agent activate / sf agent deactivate lifecycle commands. Added --no-spec flag for generate authoring-bundle. Added 12 new generate agent-spec flags (--tone, --enrich-logs, --full-interview, --spec for iterative refinement, --prompt-template, --grounding-context, --force-overwrite, --company-website, --max-topics, --agent-user, --output-file, --company-description). Added preview mode documentation (simulated vs live, --use-live-actions, --apex-debug, --output-dir, --authoring-bundle). Moved Minimal Working Example to references/minimal-examples.md. Compressed Deployment Checklist to pointer. Updated deployment lifecycle: Validate → Deploy → Publish → Activate → (Deactivate → Re-publish → Re-activate). Verified against SF CLI v2.123.1. |
| 2.2.0 | 2026-02-17 | TDD Validation v2.2.0 — Action metadata properties validated: 2 new agents (Val_Action_Meta_Props, Val_IO_Meta_Props). Corrected "Features NOT Valid" table → "Feature Validity by Context" — properties ARE valid on action definitions with targets, only invalid on @utils.transition. Validated 9 properties: label (action/topic/I/O), require_user_confirmation, include_in_progress_indicator, progress_indicator_message, is_required, is_user_input, is_displayable, is_used_by_planner. Root cause: v1.3.0 only tested on @utils.transition, never on target-backed actions. Added "Action I/O Metadata Properties" section with complete property tables. Clarified reserved field names (reserved as variable names, valid as I/O metadata properties). Updated actions-reference.md (label property, Input Properties table, Output Properties expansion). Updated known-issues.md Issue 6 (compiles on target-backed actions). Updated VALIDATION.md Tier 4 + findings. Updated syntax-reference.md with Action Metadata Properties subsection. 24 validation agents total. |
| 2.0.0 | 2026-02-16 | Production learnings audit: Fixed <> operator references in 3 files. Fixed config block field names. Removed false label: claims. Added 3 new known issues (I/O schemas, connections block, EinsteinAgentApiChannel). Added Two-Level Action System section. |
| 1.9.0 | 2026-02-14 | TDD v1.9.0 (16/16 PASS): 3 new agents. TDD disproved else: + nested if. <> not valid. Multiple available when IS valid. |
| 1.8.0 | 2026-02-12 | Gap analysis audit: Added official-sources.md, known-issues.md, migration-guide.md. Verification Protocol + Self-Improvement. |
| 1.7.0 | 2026-02-09 | CRITICAL FIX: apex:// works directly, GenAiFunction NOT needed for Agent Script. Rewrote action sections. |
| 1.6.0 | 2026-02-07 | Content migration from former sf-ai-agentforce-legacy. Created actions-reference.md (602 lines). |
| 1.5.0 | 2026-02-06 | Action patterns & prompt template docs (from @kunello PR #20). |
| 1.3.0 | 2026-01-20 | Lifecycle hooks validated. Features NOT Valid section (corrected in v2.2.0). |
| 1.2.0 | 2026-01-20 | Gap analysis vs agent-script-recipes. Expanded Action Target Protocols. |
| 1.1.0 | 2026-01-20 | "Ultimate Guide" tribal knowledge integration. |
| 1.0.x | 2026-01 | Initial release through progressive testing validation. |
More in this playbook
Sf ai agentforce
Agentforce Builder metadata path for Builder-managed topics/actions, Prompt Builder templates, GenAiFunction/GenAiPlugin, Models API, and custom Lightning types. TRIGGER when: user maintains or configures Builder metadata agents, creates topics/actions, works with Prompt Builder templates, or touches .genAiFunction, .genAiPlugin, or .genAiPromptTemplate metadata XML files. DO NOT TRIGGER when: Agent Script DSL .agent files (use sf-ai-agentscript), agent testing (use sf-ai-agentforce-testing), or persona design (use sf-ai-agentforce-persona).
Agentic workflowsMITSf ai agentforce grid
Use this skill whenever users want to build, inspect, debug, automate, or publish workflows in Agentforce Grid (AI Workbench) using Salesforce plus the Grid MCP or direct Grid REST calls. Trigger it for Grid workbook creation, worksheet setup, Object/Reference/AI/Agent/AgentTest/Evaluation/PromptTemplate/InvocableAction column design, prompt drafting inside Grid, worksheet execution troubleshooting, Grid YAML `apply_grid` specs, and Windows-specific Grid setup issues. Also use it when users mention AI Workbench, Grid Studio, workbook IDs, worksheet IDs, Grid Connect, or ask for recipes like "top opportunities with AI email drafts", "agent test suite in Grid", or "build this worksheet from YAML". Do not use it for generic Salesforce work unrelated to Agentforce Grid.
Agentic workflowsMITSf ai agentforce observability
Agentforce session tracing extraction and analysis. TRIGGER when: user extracts STDM data from Data Cloud, analyzes agent session traces, debugs agent conversations via telemetry, or works with .parquet files from Agentforce. DO NOT TRIGGER when: testing agents (use sf-ai-agentforce-testing), Apex debug logs (use sf-debug), or building agents (use sf-ai-agentforce).
