--- name: agentforce-generate description: "Build, modify, optimize, debug, and deploy agents with Agentforce Agent Script. TRIGGER when: user creates, modifies, optimizes, or asks about .agent files or aiAuthoringBundle metadata; changes agent behavior, responses, or conversation logic; designs agent actions, tools, subagents, or flow control; writes or reviews an Agent Spec; wants to optimize, improve, or refactor an agent; previews, debugs, deploys, publishes, or tests agents; uses Agent Script CLI commands (sf agent generate/preview/publish/test); registers/creates/lists/updates/deletes MCP servers, whitelists/approves MCP tools, fetches MCP assets, or configures MCP authentication (sf agent mcp). DO NOT TRIGGER when: Apex development, Flow building, Prompt Template authoring, Experience Cloud configuration, or general Salesforce CLI tasks unrelated to Agent Script." metadata: version: "0.11" minApiVersion: "66.0" relatedSkills: - "agentforce-observe" - "agentforce-test" - "automation-flow-generate" - "integration-connectivity-generate" - "platform-apex-generate" - "platform-metadata-deploy" cliTools: - tool: ["curl"] semver: ">=7.0.0" - tool: ["jq"] semver: ">=1.6.0" - tool: ["npm"] semver: ">=9.0.0" - tool: ["python3"] semver: ">=3.10.0" - tool: ["sf"] semver: ">=2.139.6" --- # 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: a `.agent` file (agent behavior) plus `bundle-meta.xml` (bundle metadata). Actions can be implemented with invocable Apex, autolaunched Flows, Prompt Templates, and other supported types. This skill covers the full Agent Script lifecycle: designing agents, writing Agent Script code, validating and debugging, deploying and publishing, and testing. ## How to Use This Skill This file maps user intent to task domains and relevant reference files in `references/`. Treat this file as the execution router for end-to-end agent development, and use references for deep detail. Identify user intent from task descriptions. 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. ## Rules That Always Apply 1. **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. 2. **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 `. 3. **Diagnose before you fix.** When validating/debugging agent behavior, ALWAYS `--use-live-actions` to preview authoring bundles. Send utterances then read resulting session traces to ground your understanding of the agent's behavior. Trace files reveal subagent selection, action I/O, and LLM reasoning. DO NOT modify `.agent` files or action implementations without this grounding. See [Validation & Debugging](references/agent-validation-and-debugging.md) for trace file locations and diagnostic patterns. 4. **Spec approval is a hard gate.** Never proceed past Agent Spec creation without explicit user approval. 5. **Don't stall.** After a step completes successfully, announce the next step and start it. Do not wait for the user to say "what's next" or "ok, continue." The only checkpoints that require explicit user approval are: (a) Agent Spec approval, (b) the pre-Publish CHECKPOINT, (c) any A/B branch the skill explicitly surfaces (e.g., Data Cloud not provisioned during ADL setup). Long-running async work like ADL indexing should run in the background while the skill continues with work that doesn't depend on the result. 6. **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. 7. **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](references/zen-of-agentscript.md) and [Posture & Determinism](references/posture-and-determinism.md). 8. **Use supported control flow.** Use the canonical conditional forms and never generate a nested `if`, which Agentforce lint rejects. See [Conditional Control Flow Syntax](references/agent-script-core-language.md#conditional-control-flow-syntax), then run full bundle validation. 9. **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. 10. **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](references/instruction-resolution.md). 11. **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. ## Task Domains Every task domain below has **Required Steps**. Follow verbatim, in order. The default path is: design -> draft implementation loop -> validation/preview loop -> explicit user-approved release. ### Create an Agent User wants to build new agent from scratch. ALWAYS use Agent Script. Work with User to understand the agent's purpose, subagents, and actions using plain language without Salesforce-specific terminology. #### Required Steps Before running an `sf` command, read only the applicable command section in [CLI for Agents](references/salesforce-cli-for-agents.md). Do not preload the CLI reference during design-only work. 1. **Design** — Read [Design & Agent Spec](references/agent-design-and-spec-creation.md) to draft an Agent Spec. Default all new actions to `NEEDS STUB` placeholders during planning. Ask the user which implementation path they want before implementation work: - Path A: Keep placeholders only (no implementation now) - Path B: Scan for existing actions to reuse - Path C: Generate new actions Only run scans (reading `sfdx-project.json`, searching `@InvocableMethod`, `AutoLaunchedFlow`, prompt templates, external service registrations, standard invocable actions, and custom objects) if the user explicitly chooses Path B or C. **If the agent's purpose involves answering from documents** (e.g., "answer customer questions from our product manual", "respond based on a policy guide", "FAQ from a PDF"), ask the user: *"Will this agent answer questions from a document corpus (PDF/DOCX/TXT)? If so, what file path?"* Capture the path in the Spec under a **"Knowledge Grounding"** section. Asking now — during requirements capture — is critical: ADL indexing takes minutes, so we want the file path captured pre-Spec-approval and provisioning kicked off as early as possible. **If the agent will handle voice/telephony** (e.g., "phone agent", "voice bot", "IVR replacement", "call center agent"), confirm it's a voice agent and capture a **"Voice Configuration"** section in the Spec. **Do not ask the user for a voice_id** — there is no reliable way to enumerate voice IDs and tuning values from the CLI. Always start with the platform default voice (`UgBBYS2sOqTuMpoF3BR0` — "Mark", en_US; `outbound_speed: 1`, `outbound_stability: 0.65`, `outbound_similarity: 0.75`) and tell the user they can customize the voice later in the Agent Builder UI (open the agent → **Connections → Voice**, click **Continue** to pick a different voice and tune speed/stability). See [Voice Modality Reference](references/voice-modality-reference.md) for the `modality voice:` block syntax and voice-specific authoring guidance. **Voice service agents are almost always knowledge-backed** (callers ask FAQ/policy/troubleshooting questions). When you detect a voice agent, proactively ask the Knowledge Grounding question above — do not wait for the user to mention documents. This pairing (voice + knowledge grounding) is the Project Codey "Steel Thread 2" shape, and grounding on an ADL/Salesforce Knowledge corpus is what keeps a voice agent from hallucinating spoken answers. If the user has a document corpus, capture the file path and provision the ADL as usual; the `assets/agents/voice-knowledge-grounded.agent` template shows the combined wiring. **Always save Agent Spec as file.** 2. **STOP for user approval of Agent Spec.** Present to user (including the Knowledge Grounding section if present). Ask for approval or feedback. **Do not proceed** without approval. Once approved, proceed without stopping unless a step fails. 3. **Validate environment prerequisites** — Read [Design & Agent Spec](references/agent-design-and-spec-creation.md), Section 3 (Environment Prerequisites). Based on agent type from design, validate org environment: - **Employee agent**: Confirm the file normally omits `access.default_agent_user`, `connection messaging:`, and MessagingSession linked variables. Remove them if present. **Exception:** If the agent has a `knowledge:` block (uses `AnswerQuestionsWithKnowledge`), `access.default_agent_user` IS required even for employee agents — the platform treats knowledge-grounded agents as requiring an Einstein Agent User context at runtime. Query for the agent user and include it. See [Examples](references/examples.md) for a complete employee agent example. - **Service agent**: Query org for Einstein Agent User. If one exists, confirm username with user. If none, guide user through creation. See [CLI for Agents](references/salesforce-cli-for-agents.md), Section 12 for creation steps and [Agent User Setup](references/agent-user-setup.md) for required permissions. **3b. Kick off ADL provisioning (only if the Spec has a Knowledge Grounding section).** Read [Data Library Reference](references/data-library-reference.md). Run the Step 0 preflight: `SELECT COUNT() FROM DataKnowledgeSpace` (DC provisioned check), then `sf agent adl list` (ADL service health check). If DC is not provisioned, present the A/B choice from that reference. If DC is provisioned but the ADL service returns `400 INTERNAL_ERROR`, surface the "DC up, ADL broken" path and skip grounding for this run. If both checks pass, run `sf agent adl create` (reference Step 1) to capture `libraryId`. Compute `rag_feature_config_id = "ARFPC_"` from the `libraryId` alone — that's enough to author the bundle. Then start the upload + indexing flow (reference Steps 2–6) **in the background** while authoring continues. Per Rule 5, do not block on async indexing; `retrieverId` is only needed for runtime queries (gated in Step 8). Also kick off the Data Cloud permset assignment for the agent user — see [Agent User Setup](references/agent-user-setup.md), Step 3b for the discovery-then-assign procedure, which now ends with Step 3b.5 pinned post-assignment verification (against the resolved running-user and Einstein Agent User IDs) so callers can treat "Step 3b passed" as an authoritative Data Cloud grounding gate without re-running inline SOQL. **Do not proceed to code generation until environment is validated** (ADL provisioning may continue running in background). 4. **Generate authoring bundle** — `sf agent generate authoring-bundle --json --no-spec --name "