Agent Script Skill
What This Skill Is For
This skill is for developing Agentforce agents, primarily with Agent Script, Salesforce's scripting language for AI agents.
Org-backed workflows require an Agentforce license, API v66.0 or later, and an
Einstein Agent User. Static authoring and review can proceed without org access.
CRITICAL: Agent Script is NOT AppleScript, JavaScript, Python, or any other
language. Do NOT confuse Agent Script syntax or semantics with any other
language you have been trained on.
Agent Script agents are defined by AiAuthoringBundle metadata: an
<ApiName>.agent file (agent behavior) plus a sibling
<ApiName>.bundle-meta.xml file (bundle metadata). The directory and both
filenames must use the same case-sensitive API name; a literal
bundle-meta.xml filename is not deployable. Actions can be implemented with
invocable Apex, autolaunched Flows, Prompt Templates, and other supported types.
This skill covers the full Agent Script lifecycle: designing agents,
writing Agent Script code, validating and debugging, deploying and
publishing, and testing.
How to Use This Skill
This file maps user intent to task domains and relevant reference files in references/. Treat this file as the execution router for end-to-end agent development, and use references for deep detail.
Identify user intent from task descriptions. Read only the reference explicitly
required by the active step or needed for the current decision. Every
Reference Files section is a lookup index, not a preload list; do not load
files for later or inapplicable steps.
For a comprehensive health check, common-pitfall audit, or audit-fix-evaluate
loop over an existing agent, use the Audit and Repair an Existing Agent
task domain below as part of the same authoring lifecycle.
Rules That Always Apply
Always --json. ALWAYS include --json on EVERY sf CLI command. Do NOT pipe CLI output through jq or 2>/dev/null. Read the full JSON response directly — LLMs parse JSON natively.
Verify target org. Before any org interaction, run sf config get target-org --json to confirm a target org is set. If none configured, ask the user to set one with sf config set target-org <alias>.
Diagnose in proportion to the change. For syntax or local static defects,
run the supported local parser/compiler first, then add target-org validation
when available.
For behavioral defects, preserve a baseline and use preview plus traces.
For a Surface repair, freeze the exact accepted edit list, then inspect the
final diff and revert every other hunk, including block-scalar or metadata
normalization. In a smallest-change repair, keep optional cosmetic findings
advisory unless the user explicitly includes cleanup in scope; valid syntax
with no diagnostic or use-case consequence is not an extra repair.
Simulation can establish routing and action selection; use
--use-live-actions only with explicit approval, a verified non-production
environment, and safe test data. Do not claim an external effect from
simulation or response text. See
Validation & Debugging.
Use a proportionate spec gate. Obtain explicit Agent Spec approval for
greenfield agents and Structural or Rewrite changes. A user-authorized,
well-specified local repair does not require recreating or reapproving the
entire spec; record the affected use case and preserve the existing design.
When the user supplies a sufficiently detailed design and explicitly says it
is already approved, treat that as the approved spec: do not recreate it or
stop for another approval unless requirements are missing or materially change.
Don't stall. After a step completes successfully, announce the
next step and start it. Do not wait for the user to say "what's next"
or "ok, continue." Checkpoints that require explicit user approval include:
(a) Agent Spec approval when required by Rule 4, (b) the pre-Publish
CHECKPOINT, (c) destructive or consequential external operations, and (d)
any A/B branch the skill explicitly surfaces (e.g., Data Cloud not
provisioned during ADL setup). Long-running async work like ADL
indexing should run in the background while the skill continues with
work that doesn't depend on the result.
Draft-first lifecycle. During normal authoring, stay in draft iteration:
edit .agent + action implementations, validate, deploy, and preview as many
times as needed. Do NOT publish/activate by default. Publish + activate are
explicit release actions that require the user to confirm they are ready to
commit the current draft to metadata and expose it to end users.
Start with one execution block and no mutable state. A focused agent puts
reasoning and actions directly in start_agent. Add a subagent only for a
real objective, instruction, action, authority, or escalation boundary. Add
persistent state only for a named deterministic consumer and give it a
complete lifecycle. Ordinary continuity stays in surviving history. Apply
the concrete checks in The Zen of AgentScript
and Posture & Determinism.
Use supported control flow. Use the canonical conditional forms and
never generate a nested if, which Agentforce lint rejects. See
Conditional Control Flow Syntax,
then run full bundle validation.
Action implementation is a user decision. During planning/spec work,
default new actions to NEEDS STUB placeholders. Always ask the user whether
they want to scan org/project for existing implementations and/or generate
new Apex/Flow/Prompt implementations before taking either path.
Give each reachable branch one next outcome. Choose exactly one primary
outcome: answer, ask, invoke an action, transition, refuse, or escalate.
The compiler selects a subagent system.instructions override instead of
the global value, and the current runtime assembles effective system and
resolved reasoning text for the model. Keep authoring constructs out of
model-facing text. See
Instruction Resolution.
Use portable structural indentation. Generate new .agent files with
4 spaces per level. Preserve a consistently indented legacy file during a
surgical edit, or normalize the whole file as a separate validated change.
Do not let prompt formatting impersonate control flow. Indentation,
numbered steps, and words such as Show, Ask, Call, Set, or STOP
inside | text are model instructions, not executable scope. Gate actions
independently. Use one | per contiguous prompt block; repeated adjacent
markers do not create stages or priority. Do not use
@utils.setVariables to force a turn boundary or another reasoning
iteration. Apply the checklist in
Common Control-Flow Pitfalls.
Choose who owns each decision. Use runtime predicates when an exact
machine-known fact has a consequence that must remain stable. Use model
instructions when semantic intent, ambiguity, recovery, or
situation-aware judgment makes flexibility more valuable. A model cannot
read stored variable values unless prompt text injects them with
{!@variables.X}; interpolation reveals a value but does not make the
model's comparison deterministic. Apply the tradeoff test in
Posture & Determinism.
Compile AgentScript locally first, cheaply, and visibly. For every
authoring, repair, or audit task with an existing .agent file, attempt the
bundled local index/compiler before org-side validation or a completion
report. Run
node <skill-directory>/scripts/index-agent.mjs <agent-file>. If the SDK
cannot load, follow
AgentScript Compiler Setup, retry,
and use its bounded npm/source fallback. Fix every severity-1 diagnostic
and rerun until clean. Report the provider and exact version or commit.
Org access does not replace this cheap local pass. If both local setup paths
fail, continue with target-org validation or a bounded static review and
state compiler not used with the cause; do not stall the task or imply
that a suggested future command was validation. Offline or
non-interactive mode does not waive this step: it prohibits network and
org operations, not the bundled local compiler.
Keep the authoring-bundle shape deployable. Under
aiAuthoringBundles/<ApiName>/, require exactly the matching pair
<ApiName>.agent and <ApiName>.bundle-meta.xml. Do not shorten the
metadata filename to bundle-meta.xml. Preserve scaffolded or retrieved
metadata rather than rewriting its schema. A new CLI-scaffolded bundle
normally uses <bundleType>AGENT</bundleType>; an existing descriptor can
instead use the established fullName/type/status shape, with optional
label and description. Do not create a partial hybrid or invent fields.
Local compilation of the .agent file does not verify the metadata
filename or XML, so check both before reporting validation success.
Task Domains
Choose the domain that matches the user's current objective. Read its named
references before acting; the links are load instructions, not an optional
bibliography. Follow only the applicable workflow and preserve any satisfied
prerequisites. The normal lifecycle is design -> draft -> validate/preview ->
explicitly approved release.
Create an Agent
Use for a new agent or authoring bundle.
- Read Design & Agent Spec,
then use an already-approved, sufficiently detailed supplied design as the
build contract without regenerating or reapproving it. Otherwise capture the
requirements in a saved Agent Spec and obtain explicit approval. Keep new
action implementations as
NEEDS STUB until the user chooses whether to
reuse implementations, generate them, or leave placeholders.
- Read the applicable sections of CLI for Agents
and validate the target-org prerequisites before org work. For document
grounding, read Data Library. For a
voice agent, read Voice Modality
and Voice Latency.
- Generate the authoring bundle with Salesforce CLI. Edit the scaffolded
<ApiName>.agent and preserve the matching <ApiName>.bundle-meta.xml.
Read Core Language,
Instruction Resolution, and the
applicable templates before writing.
- Run the local compiler required by Rule 14. When an authenticated target org
is available, also validate the authoring bundle in the org. Fix blocking
diagnostics before implementing or deploying action dependencies.
- Generate action implementations only when the user selected that path.
Validate and deploy one dependency at a time.
- Preview the draft and inspect traces using
Validation & Debugging.
Cover realistic happy, adjacent, recovery, and cancellation paths.
- Stay in the draft loop. Publish and activate only after the release gates in
Deploy, Publish, and Activate pass and the user explicitly approves.
Comprehend an Existing Agent
Use when the user wants to understand an existing bundle.
- Locate the package and matching authoring-bundle files.
- Read Core Language, then map the
subagent graph, deterministic blocks, model instructions, actions, variables,
and action implementations.
- Read Design & Agent Spec and
reverse-engineer a saved Agent Spec. Use
Subagent Map Diagrams for the
graph. Annotate source only when the user requests it.
- Flag supported anti-patterns, distinguishing observed behavior from static
inference. Load Known Issues only for an
otherwise unexplained workaround.
Audit and Repair an Existing Agent
Use for “fix my AgentScript,” health checks, common-pitfall reviews, and
baseline-versus-candidate repair loops.
- Read Audit and Repair, then follow its
linked scope/path-review and repair/report workflow in order.
- Use the Diagnostic Catalog
and its focused diagnostic references only for categories present in the
artifact. Use Common Control-Flow Pitfalls
and its focused references for suspected prompt/control-flow defects.
- Freeze accepted Surface edits before changing the artifact. For Structural
or Rewrite work, obtain the approval required by Rule 4.
- Compile locally, compare the unchanged baseline and candidate against the
same use cases, and follow
Audit Evaluation Loop.
- Report Surface, Structural, and Rewrite assessments separately. Stay
draft-only unless the user separately requests a release operation.
Audit Reference Files
- Audit Scope and Path Review
- Audit Repair and Report
- Audit Candidate Verification
- Instruction and Routing Diagnostics
- Action and State Diagnostics
- Architecture and Evaluation Diagnostics
- Action and Sequencing Pitfalls
- Lifecycle and Side-Effect Pitfalls
- AgentScript Compiler Setup
Modify an Existing Agent
Use for an approved change to an existing response, route, action, subagent,
state flow, grounding source, or modality.
- Comprehend the affected paths first. For a material design change, update the
Agent Spec and obtain approval; for a narrow specified repair, record the
affected use case without forcing a full spec rewrite.
- Read Core Language and only the
feature references needed for the change. Preserve unrelated metadata,
contracts, formatting, and behavior.
- Edit the existing bundle in place. Generate action implementations only when
explicitly requested.
- Compile locally and, when available, validate against the target org. Preview
every changed and adjacent path and inspect traces. Iterate in draft.
- Use the release workflow only if the user separately requests release.
Diagnose Compilation Errors
- Capture the exact reported errors and run the Rule 14 local compiler.
- When an authenticated target org is available, run org validation; use live
preview only when compilation succeeds but runtime preparation still fails.
- Classify and repair each concrete error using
Validation & Debugging and
Core Language.
- Rerun the surfaces that exposed the error. Report exact executed checks,
remaining limitations, and no unexecuted command as validation evidence.
Diagnose Behavioral or Production Issues
For a local behavioral problem, preserve a baseline, preview with realistic
utterances, and inspect traces using
Validation & Debugging. Confirm
which subagent, action calls, action results, state changes, and final response
actually occurred before editing.
For a production session or trace ID, use agentforce-observe for retrieval
and reconstruction. Return here only when evidence identifies an AgentScript
change. Never invent unavailable action inputs, outputs, or model reasoning.
Deploy, Publish, and Activate
- Read CLI for Agents,
Metadata & Lifecycle, and
Deploy.
- Compile locally and validate against the target org. Deploy the bundle and
dependencies, then run live preview with realistic coverage and inspect
traces. Do not proceed through a blocking result.
- Present the exact target org and version state. Obtain explicit user approval
before publishing or activating.
- Publish, activate, and verify the user-facing agent only after approval.
Delete or Rename an Agent
Read the delete/rename sections of CLI for Agents
and Metadata & Lifecycle. Enumerate
references and dependencies, show the exact affected bundle, and obtain explicit
confirmation before deletion. For rename, create and validate the replacement
before deleting the original; verify orphaned metadata afterward.
Test an Agent
Use agentforce-test for test-spec design, security coverage, metadata
creation, execution, and result analysis. First map the Agent Spec and all
reachable routes/actions into coverage targets. Confirm before adding security
tests or running tests that can invoke live actions.
Optimize an Agent
- Read Core Language and scan every
reachable path using Common Control-Flow Pitfalls.
- Load only applicable optimization references: data flow, deterministic
logic, reference syntax, human handoff, and voice readiness.
- Report evidence-backed improvements and obtain approval before editing.
- Apply only approved changes, compile locally, validate against the org when
available, and report the resulting evidence.
Manage MCP Servers
Read MCP Server Management before any
MCP operation. Verify the target org, use --json, keep secrets off command
lines, review tools before allowlisting, and require confirmation for destructive
or consequential changes.
The Agent Spec
Agent Spec is the central artifact this skill produces and consumes. A structured design document representing agent purpose, user outcomes, subagent graph, actions and implementations, variables, subagent posture, deterministic controls (when needed), and behavioral intent.
Agent Specs evolve with the agent. Sparse during agent creation (purpose, use cases, planned placeholders). Fleshed out during agent build (flowchart, action implementations mapped, posture choices documented, deterministic controls added only where justified). Reverse-engineered when comprehending existing agents. Critical for advanced troubleshooting, providing reference to compare expected vs. actual behavior. During testing, test coverage maps against it.
Produce or update an Agent Spec for greenfield work, material design changes,
or analysis whose result changes the documented contract. For a narrow,
already-specified repair, record the affected use case and evidence without
forcing a full spec rewrite.
Read Design & Agent Spec for Agent Spec structure and production methodology.
Assets
The assets/ directory contains templates and examples. Read when you need a starting point or a concrete reference for artifacts and source files.
assets/agent-spec-template.md — Agent Spec template with all sections and placeholder content. Copy to <AgentName>-AgentSpec.md in project directory, then fill in during design. Save Agent Spec as file — significant design artifact that benefits from proper rendering, especially Mermaid Subagent Map diagram.
assets/agents/local-info-agent-annotated.agent — Complete annotated example based on Local Info Agent, showing all major Agent Script constructs in context with inline comments explaining why each construct is used. Read when you need concrete reference for how concepts compose into working agent, or as fallback when focused examples in reference files aren't sufficient.
assets/agents/template-single-subagent.agent — Compatibility-named focused starter with one start_agent execution block and no router or subagent blocks.
assets/agents/template-multi-subagent.agent — Minimal agent with multiple subagents and transitions. Copy and modify for complex agents.
assets/agents/router-first.agent — Transition-only router example with
HyperClassifier and concise router instructions.
assets/agents/verification-gate.agent — Identity/authorization gate
with protected action availability.
assets/agents/simple-qa.agent, production-faq.agent, and
order-service.agent — Complete examples at increasing behavioral and
action complexity.
assets/patterns/README.md — Route to focused complete patterns for
callbacks, input binding, lifecycle, delegation, and multi-step workflows.
Use a pattern only when its stated use-case preconditions apply.
assets/invocable-apex-template.cls — Reference for invocable Apex
classes. Copy and modify when complex Apex action implementations are desired.
Important Constraints
Use supported tooling for the evidence needed. Use Salesforce CLI and the
target org for org-backed validation and release operations. Use the published
AgentScript SDK for local parse/compile checks, and invoke related skills only
within their documented boundaries.
Only certain implementation types are valid for actions. For example, only invocable Apex (not arbitrary Apex classes) can back an action. Similar constraints may apply to Flows and Prompt Templates. When wiring actions to implementations, consult Design & Agent Spec reference file for valid types and stubbing methodology.
sf agent generate test-spec is not for agentic use. It is interactive, REPL-style command designed for humans. When creating test specs, start from boilerplate template in assets instead.
Common Issues Quick Reference
Internal Error, try again later during publish:
Server-side compile failure. The 500 doesn't tell you which check failed — walk all four causes in order before asking the user what's wrong. Do NOT stop at cause 1.
- Agent type mismatch on
access.default_agent_user. Employee agents normally omit access.default_agent_user; service agents MUST have it (and the user must hold an Einstein Agent license). See Design & Agent Spec, Section 3. Re-run the query — do not invent the username.
- Action definition missing
outputs: block. If any action has target: and inputs: but no outputs:, the server-side compiler can't generate return bindings. CLI validate and LSP both PASS — only publish fails. See Known Issues, Issue 15.
- Other structural drift in the
.agent file. Diff against a known-good bundle in the same org:
sf project retrieve start --metadata "AiAuthoringBundle:<known-working-agent>" --output-dir /tmp/diff-bundle --json
Compare keyword-by-keyword. Look for missing required-but-undocumented fields, block-ordering drift, or DSL keywords your bundle uses that aren't in the working one.
- Genuine transient backend error. If 1–3 are clean and the response
requestId differs across retries, wait 60 s and retry once.
Unable to access Salesforce Agent APIs... during preview:
default_agent_user lacks permissions. See Agent User Setup & Permissions. Do NOT publish as fix — --use-live-actions does not require published agent.
Permission error referencing different username than configured:
Same fix as above — error references org's default running user, but root cause is Einstein Agent User permissions.
Agent fails with permission error even though current subagent's actions work:
Planner validates ALL actions across ALL subagents at startup. One missing permission fails entire agent.
Apex action returns empty results in live preview but works in simulated:
WITH USER_MODE + missing object permissions = silent failure (0 rows, no error). See Agent User Setup & Permissions, Section 6.2.
Agent published, ADL indexed (retrieverId populated), but every grounded question returns empty knowledgeSummary / "I don't have that information":
The Einstein Agent User lacks Data Cloud access. Two things to check, in order:
- Permset/PSL not assigned. Run the verification queries from Agent User Setup, Step 3b.3. If no Data Cloud permset/PSL appears, run the discovery-then-assign procedure (priority:
GenieDataPlatformStarterPsl PSL → GenieUserEnhancedSecurity PS → DataCloudUser PS → DataCloudArchitect PS).
- Data Space scope not granted on the permset. Currently no API. Setup → Permission Sets → click the assigned permset → "Data Cloud Data Space Management" under Apps → Edit → add the ADL's data space (usually
default) → Save. See Agent User Setup, Step 3b.4.
Quick Links (Deep Detail Lives in References)
- Syntax and execution model: Core Language
- Agent design/spec process: Design & Agent Spec
- Posture dial (agentic vs deterministic): Posture & Determinism
- Concrete authoring invariants: The Zen of AgentScript
- Pattern selection by scenario: Patterns by Requirement
- Architecture mechanics, HyperClassifier routing, and migration: Architecture Patterns
- Validation, preview, and traces: Validation & Debugging
- Deploy/publish/activate lifecycle: Deploy Reference
- Metadata lifecycle and publish troubleshooting: Metadata & Lifecycle
- ADL provisioning and wiring: Data Library Reference
- Agent access and permissions: Agent Access Guide, Agent User Setup
- Voice modality and telephony agents: Voice Modality Reference
- Safety review framework: Safety Review
- Rubric and review scoring: Scoring Rubric
- Optimization patterns: Pattern 1 — Data Flow, Pattern 2 — Deterministic Logic, Pattern 3 — Reference Syntax, Pattern 4 — Escalation
- MCP server registration and tool whitelisting: MCP Server Management
1---
2name: agentforce-generate
3description: "Build, modify, audit, repair, optimize, debug, and deploy agents with Agentforce Agent Script. TRIGGER when: user creates, reviews, or changes .agent files or aiAuthoringBundle metadata; asks to fix AgentScript, audit an existing agent, run an AgentScript health check, common-pitfall review, or baseline-versus-candidate repair loop; changes a response, action, subagent, route, state flow, or Agent Spec; previews, debugs, deploys, publishes, or tests agents; uses sf agent generate/preview/publish/test; or manages Agentforce MCP servers, tools, assets, or authentication. DO NOT TRIGGER when: Apex, Flow, Prompt Template, Experience Cloud, or general Salesforce CLI work is unrelated to Agent Script; or the primary input is a production session or trace ID rather than an agent artifact."
4metadata:
5 version: "0.11"
6 domains: ["Agentforce"]
7 minApiVersion: "66.0"
8 relatedSkills:
9 - "agentforce-observe"
10 - "agentforce-test"
11 - "automation-flow-generate"
12 - "integration-connectivity-generate"
13 - "platform-apex-generate"
14 - "platform-metadata-deploy"
15 cliTools:
16 - tool: ["corepack"]
17 semver: ">=0.25.0"
18 - tool: ["curl"]
19 semver: ">=7.0.0"
20 - tool: ["git"]
21 semver: ">=2.0.0"
22 - tool: ["jq"]
23 semver: ">=1.6.0"
24 - tool: ["node"]
25 semver: ">=20.0.0"
26 - tool: ["npm"]
27 semver: ">=9.0.0"
28 - tool: ["pnpm"]
29 semver: ">=8.0.0"
30 - tool: ["python3"]
31 semver: ">=3.10.0"
32 - tool: ["sf"]
33 semver: ">=2.139.6"
34---
35
36# Agent Script Skill
37
38## What This Skill Is For
39
40This skill is for developing Agentforce agents, primarily with Agent Script, Salesforce's scripting language for AI agents.
41
42Org-backed workflows require an Agentforce license, API v66.0 or later, and an
43Einstein Agent User. Static authoring and review can proceed without org access.
44
45**CRITICAL:** Agent Script is NOT AppleScript, JavaScript, Python, or any other
46language. Do NOT confuse Agent Script syntax or semantics with any other
47language you have been trained on.
48
49Agent Script agents are defined by `AiAuthoringBundle` metadata: an
50`<ApiName>.agent` file (agent behavior) plus a sibling
51`<ApiName>.bundle-meta.xml` file (bundle metadata). The directory and both
52filenames must use the same case-sensitive API name; a literal
53`bundle-meta.xml` filename is not deployable. Actions can be implemented with
54invocable Apex, autolaunched Flows, Prompt Templates, and other supported types.
55
56This skill covers the full Agent Script lifecycle: designing agents,
57writing Agent Script code, validating and debugging, deploying and
58publishing, and testing.
59
60## How to Use This Skill
61
62This file maps user intent to task domains and relevant reference files in `references/`. Treat this file as the execution router for end-to-end agent development, and use references for deep detail.
63
64Identify user intent from task descriptions. Read only the reference explicitly
65required by the active step or needed for the current decision. Every
66**Reference Files** section is a lookup index, not a preload list; do not load
67files for later or inapplicable steps.
68
69For a comprehensive health check, common-pitfall audit, or audit-fix-evaluate
70loop over an existing agent, use the **Audit and Repair an Existing Agent**
71task domain below as part of the same authoring lifecycle.
72
73## Rules That Always Apply
74
751. **Always `--json`.** ALWAYS include `--json` on EVERY `sf` CLI command. Do NOT pipe CLI output through `jq` or `2>/dev/null`. Read the full JSON response directly — LLMs parse JSON natively.
76
772. **Verify target org.** Before any org interaction, run `sf config get target-org --json` to confirm a target org is set. If none configured, ask the user to set one with `sf config set target-org <alias>`.
78
793. **Diagnose in proportion to the change.** For syntax or local static defects,
80 run the supported local parser/compiler first, then add target-org validation
81 when available.
82 For behavioral defects, preserve a baseline and use preview plus traces.
83 For a Surface repair, freeze the exact accepted edit list, then inspect the
84 final diff and revert every other hunk, including block-scalar or metadata
85 normalization. In a smallest-change repair, keep optional cosmetic findings
86 advisory unless the user explicitly includes cleanup in scope; valid syntax
87 with no diagnostic or use-case consequence is not an extra repair.
88 Simulation can establish routing and action selection; use
89 `--use-live-actions` only with explicit approval, a verified non-production
90 environment, and safe test data. Do not claim an external effect from
91 simulation or response text. See
92 [Validation & Debugging](references/agent-validation-and-debugging.md).
93
944. **Use a proportionate spec gate.** Obtain explicit Agent Spec approval for
95 greenfield agents and Structural or Rewrite changes. A user-authorized,
96 well-specified local repair does not require recreating or reapproving the
97 entire spec; record the affected use case and preserve the existing design.
98 When the user supplies a sufficiently detailed design and explicitly says it
99 is already approved, treat that as the approved spec: do not recreate it or
100 stop for another approval unless requirements are missing or materially change.
101
1025. **Don't stall.** After a step completes successfully, announce the
103 next step and start it. Do not wait for the user to say "what's next"
104 or "ok, continue." Checkpoints that require explicit user approval include:
105 (a) Agent Spec approval when required by Rule 4, (b) the pre-Publish
106 CHECKPOINT, (c) destructive or consequential external operations, and (d)
107 any A/B branch the skill explicitly surfaces (e.g., Data Cloud not
108 provisioned during ADL setup). Long-running async work like ADL
109 indexing should run in the background while the skill continues with
110 work that doesn't depend on the result.
111
1126. **Draft-first lifecycle.** During normal authoring, stay in draft iteration:
113 edit `.agent` + action implementations, validate, deploy, and preview as many
114 times as needed. Do NOT publish/activate by default. Publish + activate are
115 explicit release actions that require the user to confirm they are ready to
116 commit the current draft to metadata and expose it to end users.
117
1187. **Start with one execution block and no mutable state.** A focused agent puts
119 reasoning and actions directly in `start_agent`. Add a subagent only for a
120 real objective, instruction, action, authority, or escalation boundary. Add
121 persistent state only for a named deterministic consumer and give it a
122 complete lifecycle. Ordinary continuity stays in surviving history. Apply
123 the concrete checks in [The Zen of AgentScript](references/zen-of-agentscript.md)
124 and [Posture & Determinism](references/posture-and-determinism.md).
125
1268. **Use supported control flow.** Use the canonical conditional forms and
127 never generate a nested `if`, which Agentforce lint rejects. See
128 [Conditional Control Flow Syntax](references/agent-script-core-language.md#conditional-control-flow-syntax),
129 then run full bundle validation.
130
1319. **Action implementation is a user decision.** During planning/spec work,
132 default new actions to `NEEDS STUB` placeholders. Always ask the user whether
133 they want to scan org/project for existing implementations and/or generate
134 new Apex/Flow/Prompt implementations before taking either path.
135
13610. **Give each reachable branch one next outcome.** Choose exactly one primary
137 outcome: answer, ask, invoke an action, transition, refuse, or escalate.
138 The compiler selects a subagent `system.instructions` override instead of
139 the global value, and the current runtime assembles effective system and
140 resolved reasoning text for the model. Keep authoring constructs out of
141 model-facing text. See
142 [Instruction Resolution](references/instruction-resolution.md).
143
14411. **Use portable structural indentation.** Generate new `.agent` files with
145 4 spaces per level. Preserve a consistently indented legacy file during a
146 surgical edit, or normalize the whole file as a separate validated change.
147
14812. **Do not let prompt formatting impersonate control flow.** Indentation,
149 numbered steps, and words such as `Show`, `Ask`, `Call`, `Set`, or `STOP`
150 inside `|` text are model instructions, not executable scope. Gate actions
151 independently. Use one `|` per contiguous prompt block; repeated adjacent
152 markers do not create stages or priority. Do not use
153 `@utils.setVariables` to force a turn boundary or another reasoning
154 iteration. Apply the checklist in
155 [Common Control-Flow Pitfalls](references/common-control-flow-pitfalls.md).
156
15713. **Choose who owns each decision.** Use runtime predicates when an exact
158 machine-known fact has a consequence that must remain stable. Use model
159 instructions when semantic intent, ambiguity, recovery, or
160 situation-aware judgment makes flexibility more valuable. A model cannot
161 read stored variable values unless prompt text injects them with
162 `{!@variables.X}`; interpolation reveals a value but does not make the
163 model's comparison deterministic. Apply the tradeoff test in
164 [Posture & Determinism](references/posture-and-determinism.md).
165
16614. **Compile AgentScript locally first, cheaply, and visibly.** For every
167 authoring, repair, or audit task with an existing `.agent` file, attempt the
168 bundled local index/compiler before org-side validation or a completion
169 report. Run
170 `node <skill-directory>/scripts/index-agent.mjs <agent-file>`. If the SDK
171 cannot load, follow
172 [AgentScript Compiler Setup](references/agentscript-toolchain.md), retry,
173 and use its bounded npm/source fallback. Fix every severity-1 diagnostic
174 and rerun until clean. Report the provider and exact version or commit.
175 Org access does not replace this cheap local pass. If both local setup paths
176 fail, continue with target-org validation or a bounded static review and
177 state **compiler not used** with the cause; do not stall the task or imply
178 that a suggested future command was validation. **Offline** or
179 **non-interactive** mode does not waive this step: it prohibits network and
180 org operations, not the bundled local compiler.
181
18215. **Keep the authoring-bundle shape deployable.** Under
183 `aiAuthoringBundles/<ApiName>/`, require exactly the matching pair
184 `<ApiName>.agent` and `<ApiName>.bundle-meta.xml`. Do not shorten the
185 metadata filename to `bundle-meta.xml`. Preserve scaffolded or retrieved
186 metadata rather than rewriting its schema. A new CLI-scaffolded bundle
187 normally uses `<bundleType>AGENT</bundleType>`; an existing descriptor can
188 instead use the established `fullName`/`type`/`status` shape, with optional
189 `label` and `description`. Do not create a partial hybrid or invent fields.
190 Local compilation of the `.agent` file does not verify the metadata
191 filename or XML, so check both before reporting validation success.
192
193## Task Domains
194
195Choose the domain that matches the user's current objective. Read its named
196references before acting; the links are load instructions, not an optional
197bibliography. Follow only the applicable workflow and preserve any satisfied
198prerequisites. The normal lifecycle is design -> draft -> validate/preview ->
199explicitly approved release.
200
201### Create an Agent
202
203Use for a new agent or authoring bundle.
204
2051. Read [Design & Agent Spec](references/agent-design-and-spec-creation.md),
206 then use an already-approved, sufficiently detailed supplied design as the
207 build contract without regenerating or reapproving it. Otherwise capture the
208 requirements in a saved Agent Spec and obtain explicit approval. Keep new
209 action implementations as `NEEDS STUB` until the user chooses whether to
210 reuse implementations, generate them, or leave placeholders.
2112. Read the applicable sections of [CLI for Agents](references/salesforce-cli-for-agents.md)
212 and validate the target-org prerequisites before org work. For document
213 grounding, read [Data Library](references/data-library-reference.md). For a
214 voice agent, read [Voice Modality](references/voice-modality-reference.md)
215 and [Voice Latency](references/voice-latency-heuristics.md).
2163. Generate the authoring bundle with Salesforce CLI. Edit the scaffolded
217 `<ApiName>.agent` and preserve the matching `<ApiName>.bundle-meta.xml`.
218 Read [Core Language](references/agent-script-core-language.md),
219 [Instruction Resolution](references/instruction-resolution.md), and the
220 applicable templates before writing.
2214. Run the local compiler required by Rule 14. When an authenticated target org
222 is available, also validate the authoring bundle in the org. Fix blocking
223 diagnostics before implementing or deploying action dependencies.
2245. Generate action implementations only when the user selected that path.
225 Validate and deploy one dependency at a time.
2266. Preview the draft and inspect traces using
227 [Validation & Debugging](references/agent-validation-and-debugging.md).
228 Cover realistic happy, adjacent, recovery, and cancellation paths.
2297. Stay in the draft loop. Publish and activate only after the release gates in
230 **Deploy, Publish, and Activate** pass and the user explicitly approves.
231
232### Comprehend an Existing Agent
233
234Use when the user wants to understand an existing bundle.
235
2361. Locate the package and matching authoring-bundle files.
2372. Read [Core Language](references/agent-script-core-language.md), then map the
238 subagent graph, deterministic blocks, model instructions, actions, variables,
239 and action implementations.
2403. Read [Design & Agent Spec](references/agent-design-and-spec-creation.md) and
241 reverse-engineer a saved Agent Spec. Use
242 [Subagent Map Diagrams](references/agent-subagent-map-diagrams.md) for the
243 graph. Annotate source only when the user requests it.
2444. Flag supported anti-patterns, distinguishing observed behavior from static
245 inference. Load [Known Issues](references/known-issues.md) only for an
246 otherwise unexplained workaround.
247
248### Audit and Repair an Existing Agent
249
250Use for “fix my AgentScript,” health checks, common-pitfall reviews, and
251baseline-versus-candidate repair loops.
252
2531. Read [Audit and Repair](references/agent-audit-and-repair.md), then follow its
254 linked scope/path-review and repair/report workflow in order.
2552. Use the [Diagnostic Catalog](references/agent-audit-diagnostic-catalog.md)
256 and its focused diagnostic references only for categories present in the
257 artifact. Use [Common Control-Flow Pitfalls](references/common-control-flow-pitfalls.md)
258 and its focused references for suspected prompt/control-flow defects.
2593. Freeze accepted Surface edits before changing the artifact. For Structural
260 or Rewrite work, obtain the approval required by Rule 4.
2614. Compile locally, compare the unchanged baseline and candidate against the
262 same use cases, and follow
263 [Audit Evaluation Loop](references/agent-audit-evaluation-loop.md).
2645. Report Surface, Structural, and Rewrite assessments separately. Stay
265 draft-only unless the user separately requests a release operation.
266
267#### Audit Reference Files
268
269- [Audit Scope and Path Review](references/agent-audit-scope-path-review.md)
270- [Audit Repair and Report](references/agent-audit-repair-report.md)
271- [Audit Candidate Verification](references/agent-audit-candidate-verification.md)
272- [Instruction and Routing Diagnostics](references/agent-audit-diagnostics-instructions-routing.md)
273- [Action and State Diagnostics](references/agent-audit-diagnostics-actions-state.md)
274- [Architecture and Evaluation Diagnostics](references/agent-audit-diagnostics-architecture-evaluation.md)
275- [Action and Sequencing Pitfalls](references/control-flow-actions-sequencing.md)
276- [Lifecycle and Side-Effect Pitfalls](references/control-flow-lifecycle-side-effects.md)
277- [AgentScript Compiler Setup](references/agentscript-toolchain.md)
278
279### Modify an Existing Agent
280
281Use for an approved change to an existing response, route, action, subagent,
282state flow, grounding source, or modality.
283
2841. Comprehend the affected paths first. For a material design change, update the
285 Agent Spec and obtain approval; for a narrow specified repair, record the
286 affected use case without forcing a full spec rewrite.
2872. Read [Core Language](references/agent-script-core-language.md) and only the
288 feature references needed for the change. Preserve unrelated metadata,
289 contracts, formatting, and behavior.
2903. Edit the existing bundle in place. Generate action implementations only when
291 explicitly requested.
2924. Compile locally and, when available, validate against the target org. Preview
293 every changed and adjacent path and inspect traces. Iterate in draft.
2945. Use the release workflow only if the user separately requests release.
295
296### Diagnose Compilation Errors
297
2981. Capture the exact reported errors and run the Rule 14 local compiler.
2992. When an authenticated target org is available, run org validation; use live
300 preview only when compilation succeeds but runtime preparation still fails.
3013. Classify and repair each concrete error using
302 [Validation & Debugging](references/agent-validation-and-debugging.md) and
303 [Core Language](references/agent-script-core-language.md).
3044. Rerun the surfaces that exposed the error. Report exact executed checks,
305 remaining limitations, and no unexecuted command as validation evidence.
306
307### Diagnose Behavioral or Production Issues
308
309For a local behavioral problem, preserve a baseline, preview with realistic
310utterances, and inspect traces using
311[Validation & Debugging](references/agent-validation-and-debugging.md). Confirm
312which subagent, action calls, action results, state changes, and final response
313actually occurred before editing.
314
315For a production session or trace ID, use **agentforce-observe** for retrieval
316and reconstruction. Return here only when evidence identifies an AgentScript
317change. Never invent unavailable action inputs, outputs, or model reasoning.
318
319### Deploy, Publish, and Activate
320
3211. Read [CLI for Agents](references/salesforce-cli-for-agents.md),
322 [Metadata & Lifecycle](references/agent-metadata-and-lifecycle.md), and
323 [Deploy](references/deploy-reference.md).
3242. Compile locally and validate against the target org. Deploy the bundle and
325 dependencies, then run live preview with realistic coverage and inspect
326 traces. Do not proceed through a blocking result.
3273. Present the exact target org and version state. Obtain explicit user approval
328 before publishing or activating.
3294. Publish, activate, and verify the user-facing agent only after approval.
330
331### Delete or Rename an Agent
332
333Read the delete/rename sections of [CLI for Agents](references/salesforce-cli-for-agents.md)
334and [Metadata & Lifecycle](references/agent-metadata-and-lifecycle.md). Enumerate
335references and dependencies, show the exact affected bundle, and obtain explicit
336confirmation before deletion. For rename, create and validate the replacement
337before deleting the original; verify orphaned metadata afterward.
338
339### Test an Agent
340
341Use **agentforce-test** for test-spec design, security coverage, metadata
342creation, execution, and result analysis. First map the Agent Spec and all
343reachable routes/actions into coverage targets. Confirm before adding security
344tests or running tests that can invoke live actions.
345
346### Optimize an Agent
347
3481. Read [Core Language](references/agent-script-core-language.md) and scan every
349 reachable path using [Common Control-Flow Pitfalls](references/common-control-flow-pitfalls.md).
3502. Load only applicable optimization references: data flow, deterministic
351 logic, reference syntax, human handoff, and voice readiness.
3523. Report evidence-backed improvements and obtain approval before editing.
3534. Apply only approved changes, compile locally, validate against the org when
354 available, and report the resulting evidence.
355
356### Manage MCP Servers
357
358Read [MCP Server Management](references/mcp-management-reference.md) before any
359MCP operation. Verify the target org, use `--json`, keep secrets off command
360lines, review tools before allowlisting, and require confirmation for destructive
361or consequential changes.
362
363## The Agent Spec
364
365**Agent Spec** is the central artifact this skill produces and consumes. A structured design document representing agent purpose, user outcomes, subagent graph, actions and implementations, variables, subagent posture, deterministic controls (when needed), and behavioral intent.
366
367Agent Specs evolve with the agent. Sparse during agent creation (purpose, use cases, planned placeholders). Fleshed out during agent build (flowchart, action implementations mapped, posture choices documented, deterministic controls added only where justified). Reverse-engineered when comprehending existing agents. Critical for advanced troubleshooting, providing reference to compare expected vs. actual behavior. During testing, test coverage maps against it.
368
369Produce or update an Agent Spec for greenfield work, material design changes,
370or analysis whose result changes the documented contract. For a narrow,
371already-specified repair, record the affected use case and evidence without
372forcing a full spec rewrite.
373
374Read [Design & Agent Spec](references/agent-design-and-spec-creation.md) for Agent Spec structure and production methodology.
375
376## Assets
377
378The `assets/` directory contains templates and examples. Read when you need a starting point or a concrete reference for artifacts and source files.
379
380- **`assets/agent-spec-template.md`** — Agent Spec template with all sections and placeholder content. Copy to `<AgentName>-AgentSpec.md` in project directory, then fill in during design. Save Agent Spec as file — significant design artifact that benefits from proper rendering, especially Mermaid Subagent Map diagram.
381
382- **`assets/agents/local-info-agent-annotated.agent`** — Complete annotated example based on Local Info Agent, showing all major Agent Script constructs in context with inline comments explaining why each construct is used. Read when you need concrete reference for how concepts compose into working agent, or as fallback when focused examples in reference files aren't sufficient.
383
384- **`assets/agents/template-single-subagent.agent`** — Compatibility-named focused starter with one `start_agent` execution block and no router or subagent blocks.
385
386- **`assets/agents/template-multi-subagent.agent`** — Minimal agent with multiple subagents and transitions. Copy and modify for complex agents.
387
388- **`assets/agents/router-first.agent`** — Transition-only router example with
389 HyperClassifier and concise router instructions.
390
391- **`assets/agents/verification-gate.agent`** — Identity/authorization gate
392 with protected action availability.
393
394- **`assets/agents/simple-qa.agent`**, **`production-faq.agent`**, and
395 **`order-service.agent`** — Complete examples at increasing behavioral and
396 action complexity.
397
398- **`assets/patterns/README.md`** — Route to focused complete patterns for
399 callbacks, input binding, lifecycle, delegation, and multi-step workflows.
400 Use a pattern only when its stated use-case preconditions apply.
401
402- **`assets/invocable-apex-template.cls`** — Reference for invocable Apex
403 classes. Copy and modify when complex Apex action implementations are desired.
404
405## Important Constraints
406
407- **Use supported tooling for the evidence needed.** Use Salesforce CLI and the
408 target org for org-backed validation and release operations. Use the published
409 AgentScript SDK for local parse/compile checks, and invoke related skills only
410 within their documented boundaries.
411
412- **Only certain implementation types are valid for actions.** For example, only invocable Apex (not arbitrary Apex classes) can back an action. Similar constraints may apply to Flows and Prompt Templates. When wiring actions to implementations, consult Design & Agent Spec reference file for valid types and stubbing methodology.
413
414- **`sf agent generate test-spec` is not for agentic use.** It is interactive, REPL-style command designed for humans. When creating test specs, start from boilerplate template in assets instead.
415
416## Common Issues Quick Reference
417
418**`Internal Error, try again later` during publish:**
419Server-side compile failure. The 500 doesn't tell you which check failed — walk all four causes in order before asking the user what's wrong. Do NOT stop at cause 1.
420
4211. **Agent type mismatch on `access.default_agent_user`.** Employee agents normally omit `access.default_agent_user`; service agents MUST have it (and the user must hold an Einstein Agent license). See [Design & Agent Spec](references/agent-design-and-spec-creation.md), Section 3. Re-run the query — do not invent the username.
4222. **Action definition missing `outputs:` block.** If any action has `target:` and `inputs:` but no `outputs:`, the server-side compiler can't generate return bindings. CLI `validate` and LSP both PASS — only publish fails. See [Known Issues](references/known-issues.md), Issue 15.
4233. **Other structural drift in the `.agent` file.** Diff against a known-good bundle in the same org:
424 `sf project retrieve start --metadata "AiAuthoringBundle:<known-working-agent>" --output-dir /tmp/diff-bundle --json`
425 Compare keyword-by-keyword. Look for missing required-but-undocumented fields, block-ordering drift, or DSL keywords your bundle uses that aren't in the working one.
4264. **Genuine transient backend error.** If 1–3 are clean and the response `requestId` differs across retries, wait 60 s and retry once.
427
428**`Unable to access Salesforce Agent APIs...` during preview:**
429`default_agent_user` lacks permissions. See [Agent User Setup & Permissions](references/agent-user-setup.md). Do NOT publish as fix — `--use-live-actions` does not require published agent.
430
431**Permission error referencing different username than configured:**
432Same fix as above — error references org's default running user, but root cause is Einstein Agent User permissions.
433
434**Agent fails with permission error even though current subagent's actions work:**
435Planner validates ALL actions across ALL subagents at startup. One missing permission fails entire agent.
436
437**Apex action returns empty results in live preview but works in simulated:**
438`WITH USER_MODE` + missing object permissions = silent failure (0 rows, no error). See [Agent User Setup & Permissions](references/agent-user-setup.md), Section 6.2.
439
440**Agent published, ADL indexed (`retrieverId` populated), but every grounded question returns empty `knowledgeSummary` / "I don't have that information":**
441The Einstein Agent User lacks Data Cloud access. Two things to check, in order:
4421. **Permset/PSL not assigned.** Run the verification queries from [Agent User Setup, Step 3b.3](references/agent-user-setup.md). If no Data Cloud permset/PSL appears, run the discovery-then-assign procedure (priority: `GenieDataPlatformStarterPsl` PSL → `GenieUserEnhancedSecurity` PS → `DataCloudUser` PS → `DataCloudArchitect` PS).
4432. **Data Space scope not granted on the permset.** Currently no API. Setup → Permission Sets → click the assigned permset → "Data Cloud Data Space Management" under Apps → Edit → add the ADL's data space (usually `default`) → Save. See [Agent User Setup, Step 3b.4](references/agent-user-setup.md).
444
445## Quick Links (Deep Detail Lives in References)
446
447- Syntax and execution model: [Core Language](references/agent-script-core-language.md)
448- Agent design/spec process: [Design & Agent Spec](references/agent-design-and-spec-creation.md)
449- Posture dial (agentic vs deterministic): [Posture & Determinism](references/posture-and-determinism.md)
450- Concrete authoring invariants: [The Zen of AgentScript](references/zen-of-agentscript.md)
451- Pattern selection by scenario: [Patterns by Requirement](references/patterns-by-requirement.md)
452- Architecture mechanics, HyperClassifier routing, and migration: [Architecture Patterns](references/architecture-patterns.md)
453- Validation, preview, and traces: [Validation & Debugging](references/agent-validation-and-debugging.md)
454- Deploy/publish/activate lifecycle: [Deploy Reference](references/deploy-reference.md)
455- Metadata lifecycle and publish troubleshooting: [Metadata & Lifecycle](references/agent-metadata-and-lifecycle.md)
456- ADL provisioning and wiring: [Data Library Reference](references/data-library-reference.md)
457- Agent access and permissions: [Agent Access Guide](references/agent-access-guide.md), [Agent User Setup](references/agent-user-setup.md)
458- Voice modality and telephony agents: [Voice Modality Reference](references/voice-modality-reference.md)
459- Safety review framework: [Safety Review](references/safety-review-reference.md)
460- Rubric and review scoring: [Scoring Rubric](references/scoring-rubric.md)
461- Optimization patterns: [Pattern 1 — Data Flow](references/optimization-pattern-1-data-flow.md), [Pattern 2 — Deterministic Logic](references/optimization-pattern-2-deterministic-logic.md), [Pattern 3 — Reference Syntax](references/optimization-pattern-3-reference-syntax.md), [Pattern 4 — Escalation](references/optimization-pattern-4-escalation.md)
462- MCP server registration and tool whitelisting: [MCP Server Management](references/mcp-management-reference.md)