Agentforce self-service, with a path to a human
Architecture, code, configuration and metadata for the Site Helper agent on the public chat, its escalation to a human through Omni-Channel, the internal Case Triage Assistant, and the Slack alerts built around them.
Site_Helper, with BYOC_Messaging_Queue as the human fallback. This version is rebuilt from the metadata retrieved from the org. I read that configuration but did not run a live chat myself.Where things stand
Configured Public chat (live chat not run by Claude)
- Agent
Site_Helper, version 4 active, a router and four subagents, written in Agent Script - Messaging channel
Site_Helper_Web_Chathands sessions to the agent - Embedded chat deployment on the live site
ESW_Site_Helper_We_17955492998421 - Escalation action sends the chat to queue
BYOC_Messaging_Queue
Built and tested Internal and Slack
- Agent
Case_Triage_Assistantwith two Apex actions, 2 tests pass - Knowledge enabled, 14 public articles, guest read access
- Slack alert trigger, proven end to end, and a scheduled daily digest. See Slackforce
- 10 sample Cases
Open Worth knowing
- Site Helper answers from facts typed into its script, not from the 14 Knowledge articles
- The queue has one member, the admin user
- Slack alerts are live. Rotate the webhook if its URL was ever shared
- The
Site HelperExperience site is still UnderConstruction, separate from the live chat site
What Agentforce is for
Agentforce handles conversations. Someone types a request in their own words, and an agent decides what to do: answer, collect details, run an action on Salesforce data, or hand the person to a human. Use it when the input is free text and the right response depends on what was said.
Meant for
- Open questions from website visitors about the company and products
- Guided capture, such as a demo or callback request
- Answering routine questions before they reach staff, which is the deflection
- Staff lookups and small updates in plain language
- Handing a person to a human with the conversation attached
Not meant for
- Sending notifications nobody asked for. Use Slackforce.
- Fixed rules that never vary. Use a Flow or a trigger.
- Statements where a wrong answer costs money, such as prices or guarantees. The Site Helper script forbids them.
- Letting anonymous visitors change records
Use cases
| Use case | Who | How it works | Status |
|---|---|---|---|
| Answer product and company questions | Website visitor | General Info subagent answers only from approved facts and offers a follow-up for anything else | Built Site Helper |
| Request a demo or callback | Website visitor | Follow-Up Capture asks name, then email, and keeps them in agent variables | Built Not saved to a Lead yet |
| Talk to a person | Website visitor | Router sends requests for a person, or frustration, to Escalation. Omni-Channel transfers the chat to a queue | Built Configured. A live human handoff was not run by Claude |
| Decline unrelated requests | Website visitor | Off Topic subagent declines and redirects | Built Site Helper |
| List open cases by priority | Support staff | Case Triage Assistant calls the List Open Cases Apex action | Built Tested |
| Change a case priority | Support staff | Set Case Priority action, with a confirmation step | Built Confirmation prompt seen, update not run |
| Answer from Knowledge articles | Website visitor | Connect a data library to General Info and add an answer action | Next 14 articles exist, not connected |
| Save visitor details as a Lead | Visitor, sales | Add a Lead-creating action to Follow-Up Capture | Next |
| Route by hours, language or VIP | Website visitor | Omni-Flow router in front of the agent | Next |
| Case status for a verified customer | Customer | Needs identity verification before any lookup | Next |
| State prices, guarantees or take payments | Website visitor | Not allowed by the agent instructions | Out of scope |
| Let the public edit Cases | Anyone | Case Triage is internal only | Out of scope |
Architecture
A visitor opens the chat on the site. The Embedded Messaging deployment starts a messaging session on the channel, and the channel's session handler passes that session to the Site_Helper agent. The agent's router picks one of four subagents. Only the Escalation subagent leaves the agent: it calls @utils.escalate, and Omni-Channel routes the session to the fallback queue where a human accepts it in the Service Console.
sessionHandlerQueue).MsgRouting. The switch is on the channel: set the routing type to Omni-Flow and select a flow with a Route Work action that targets the agent first and a queue second. Nothing in the agent script changes.One conversation, step by step
What Agentforce agents add
A chatbot follows a fixed script. An Agentforce agent reasons about each message, chooses from the topics and actions you gave it, runs them against live Salesforce data, and hands off to a person when it should. This project uses most of these pieces. The table says which.
| Capability | What it gives you | In this project |
|---|---|---|
| Reasoning planner | Understands free-text requests and picks a topic and action, so visitors do not need menus or exact phrases. | Used. The router in Site Helper, the planner in Case Triage. |
| Topics with instructions | Business rules in plain language, such as never state prices, or escalate on frustration. | Used in both agents. |
| Agent Script | A text format that mixes fixed rules (transitions, variables) with model reasoning, and lives in source control. | Used for Site Helper. |
| Actions on your data | Apex, Flow, prompt templates and standard actions let the agent read and change Salesforce records. | Apex used for Cases. Flow and prompts not used. |
| Grounding | Answers drawn from Knowledge or a data library, so replies cite your content. | Not yet. Knowledge articles exist but are not connected. |
| Einstein Trust Layer | Masks sensitive data and applies safety checks on traffic to the language model. | Applies to any agent. Nothing to configure here. |
| Run-as user and permissions | The agent acts as its own user, so access is limited to what that user can see and do. | Used. Bot users, a permission set and user-mode queries. |
| Omni-Channel handoff | Escalation passes the live conversation, with its transcript, to the right queue or person. | Used by the Escalation subagent. |
| Many channels | The same agent can serve web chat, messaging apps, voice, email and Slack. | Web chat used. Slack is alerts only. |
| Agent testing | Test cases check the chosen topic, the actions called and the outcome before you release. | Used for Case Triage. |
The Site Helper agent
Active, version 4Site Helper is a service agent written in Agent Script, Salesforce's text format for agents. The script defines the system prompt, the variables linked to the messaging session, a start router and four subagents. It answers about a finance automation product called Tallyforge, using only facts typed into the General Info subagent.
- API name
- Site_Helper (bot), Site_Helper_v4 (planner bundle)
- Type
- EinsteinServiceAgent,
agentDSLEnabledtrue - Runs as
- bot user
site_helper@…ext - Model
- sfdc_ai__DefaultGPT41, router uses DefaultEinsteinHyperClassifier
- Session variables
- EndUserId, RoutableId, ContactId, EndUserLanguage (linked), visitor_name, visitor_email (mutable)
- Escalation
@utils.escalate, instructed to call it as the very first response with no questions- Knowledge grounding
- none,
rag_feature_config_idis empty
| Subagent | Job | Leaves the agent? |
|---|---|---|
| agent_router | Start point. Classifies intent. Escalation rule has highest priority. | No |
| general_info | Answers from the listed Tallyforge facts. Never states prices or turnaround times. Offers follow-up for anything it cannot answer. | No |
| follow_up_capture | Asks for name, then email, saves them with @utils.setVariables, thanks the visitor. | No |
| off_topic | Declines unrelated questions without answering them, redirects. | No |
| escalation | Calls @utils.escalate immediately. If the transfer fails, points to the support email. | Yes, to Omni-Channel |
docs/site_helper_agent_script.agent.txt (decoded from the retrieved .agent file)
system:
instructions: "You are Site Helper, a friendly assistant on our public website. You help visitors learn about our company, products, and services, and collect their contact information when they would like a team member to follow up. You are warm, concise, and professional. Never answer questions unrelated to the company, its products, or its services."
messages:
welcome: |
Hi there! Welcome. I'm Site Helper — I can answer questions about our company, products, and services. How can I help you today?
error: "Sorry, something went wrong. Please try again."
config:
developer_name: "Site_Helper"
agent_label: "Site Helper"
description: "Friendly public website assistant that answers visitor questions about the company, products, and services, and collects contact info for team follow-ups."
access:
default_agent_user: "AGENT_BOT_USER_PLACEHOLDER"
model_config:
model: "model://sfdc_ai__DefaultGPT41"
language:
default_locale: "en_US"
additional_locales: ""
all_additional_locales: False
variables:
EndUserId: linked string
source: @MessagingSession.MessagingEndUserId
description: "This variable may also be referred to as MessagingEndUser Id"
RoutableId: linked string
source: @MessagingSession.Id
description: "This variable may also be referred to as MessagingSession Id"
ContactId: linked string
source: @MessagingEndUser.ContactId
description: "This variable may also be referred to as MessagingEndUser ContactId"
EndUserLanguage: linked string
source: @MessagingSession.EndUserLanguage
description: "This variable may also be referred to as MessagingSession EndUserLanguage"
VerifiedCustomerId: mutable string
description: "This variable may also be referred to as VerifiedCustomerId"
visitor_name: mutable string = ""
description: "The website visitor's name, collected when they request a follow-up"
visitor_email: mutable string = ""
description: "The website visitor's email address, collected when they request a follow-up"
knowledge:
rag_feature_config_id: ""
citations_url: ""
citations_enabled: False
start_agent agent_router:
label: "Agent Router"
description: "Welcome the visitor and route their request to the appropriate subagent"
model_config:
model: "model://sfdc_ai__DefaultEinsteinHyperClassifier"
reasoning:
instructions: ->
| Select the best tool to call based on the visitor's intent.
HIGHEST PRIORITY — route to escalation immediately if the visitor:
- asks for a human, a person, a live agent, a representative, a sales rep, or someone to talk to
- expresses frustration, anger, or repeated dissatisfaction
- uses phrases like "talk to someone", "real person", "speak with someone", or similar
This rule overrides all other routes, including follow_up_capture and general_info.
Route to follow_up_capture ONLY when the visitor wants a demo or a callback by email
AND has not asked for a live person.
Route to general_info for questions about the company, products, or services.
Route to off_topic for anything unrelated to the company, products, or services.
actions:
go_to_general_info: @utils.transition to @subagent.general_info
go_to_follow_up_capture: @utils.transition to @subagent.follow_up_capture
go_to_escalation: @utils.transition to @subagent.escalation
go_to_off_topic: @utils.transition to @subagent.off_topic
subagent escalation:
label: "Escalation"
description: "Transfers the visitor to a human agent via Omni-Channel when they ask for a person, express frustration, or the agent cannot help"
reasoning:
instructions: ->
| Immediately call {!@actions.escalate_to_human} to transfer this visitor to a human agent.
Do NOT ask for the visitor's name, email, or any other information before calling the action.
Do NOT ask questions or add conversational steps — call the action as your very first response.
If the transfer fails, apologise briefly and direct the visitor to support@tallyforge.example,
Monday to Friday during business hours.
actions:
escalate_to_human: @utils.escalate
description: "Transfer the conversation to a human agent via Omni-Channel."
subagent follow_up_capture:
label: "Follow-Up Capture"
description: "Collects the visitor's name and email address so a team member can follow up with them"
reasoning:
instructions: ->
| Your goal is to collect the visitor's name and email address for a follow-up from our team.
Ask for their first and last name first, then their email address. Keep the tone warm and brief.
Once you have both, use {!@actions.set_visitor_info} to save their details.
Then confirm: tell them a team member will be in touch soon, and thank them.
If the visitor declines to provide their details, acknowledge that politely and let them know
they are welcome to reach out again whenever they are ready.
actions:
set_visitor_info: @utils.setVariables
description: "Save the visitor's name and email once both have been provided."
with visitor_name=...
with visitor_email=...
subagent general_info:
label: "General Info"
description: "Answers visitor questions about Tallyforge's products and services using only approved facts"
reasoning:
instructions: ->
| You represent Tallyforge, a finance automation platform for small and mid-sized businesses.
Answer ONLY from the facts listed below. If a visitor asks something not covered here,
say you are not sure and offer to have a team member follow up using {!@actions.go_to_follow_up}.
Never state prices, guarantees, or turnaround times.
Keep answers short and friendly. At natural points — especially when a visitor asks about
integrations, wants to get started, or has a question you cannot answer — offer to collect
their details for a demo or follow-up using {!@actions.go_to_follow_up}.
Facts you can share:
- AP Automation: capture vendor bills by email or upload, route them for approval, and pay
vendors by ACH, check, or virtual card.
- AR Automation: send professional invoices, accept card and bank payments, and send automatic
payment reminders.
- Spend Management: issue employee cards with budgets and limits, collect receipts, and sync
expenses.
- Integrations: connects with popular accounting systems and CRMs. Ask the visitor which system
they use and offer a follow-up via {!@actions.go_to_follow_up}.
- Security: role-based approvals, audit trails, and encryption in transit and at rest.
- Getting started: visitors can request a demo through this chat; a team member follows up by
email. Use {!@actions.go_to_follow_up} to collect their details.
- Support: contact support@tallyforge.example, Monday to Friday during business hours.
actions:
go_to_follow_up: @utils.transition to @subagent.follow_up_capture
description: "Route the visitor to follow-up capture when they want a demo, ask about integrations, or ask something not covered by the available facts."
subagent off_topic:
label: "Off Topic"
description: "Politely declines visitor requests unrelated to the company, products, or services and redirects them"
reasoning:
instructions: ->
| The visitor has asked about something outside what you can help with.
Politely let them know you can only assist with questions about the company, products, and services, or help them request a follow-up with our team.
Be warm and brief — do not lecture or repeat yourself. Offer to help with something relevant instead.
Never answer the off-topic question, even partially.Channel, queue and deployment configuration
These four files are what connect the website chat to the agent and to the humans. They were retrieved from the org and are now in the project.
- sessionHandlerType
- AgentforceServiceAgent
- sessionHandlerAsa
- Site_Helper, the agent that receives every new session
- sessionHandlerQueue
- BYOC_Messaging_Queue, the human fallback
- Queue handles
- MessagingSession records, one member, routing config BYOC_Messaging_Routing
- Routing model
- LEAST_ACTIVE, capacity inherited, priority 1
- Deployment site
- ESW_Site_Helper_We_17955492998421, guest users
falsein the deployment config
force-app/main/default/messagingChannels/Site_Helper_Web_Chat.messagingChannel-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<MessagingChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<automatedResponses>
<autoResponseContentType>TextResponse</autoResponseContentType>
<language>en_US</language>
<response>You've opted out of receiving messages from us, so we won't contact you again.</response>
<type>OptOutConfirmation</type>
</automatedResponses>
<automatedResponses>
<autoResponseContentType>TextResponse</autoResponseContentType>
<language>en_US</language>
<response>Text STOP to opt out of further messages.</response>
<type>HelpResponse</type>
</automatedResponses>
<masterLabel>Site Helper Web Chat</masterLabel>
<messagingChannelType>EmbeddedMessaging</messagingChannelType>
<messagingKeywords>
<keyword>cancel</keyword>
<keyword>end</keyword>
<keyword>quit</keyword>
<keyword>stop</keyword>
<keyword>stopall</keyword>
<keyword>unsubscribe</keyword>
<keywordType>OptOut</keywordType>
<language>en_US</language>
</messagingKeywords>
<messagingKeywords>
<keyword>help</keyword>
<keywordType>Help</keywordType>
<language>en_US</language>
</messagingKeywords>
<sessionHandlerAsa>Site_Helper</sessionHandlerAsa>
<sessionHandlerQueue>BYOC_Messaging_Queue</sessionHandlerQueue>
<sessionHandlerType>AgentforceServiceAgent</sessionHandlerType>
</MessagingChannel>force-app/main/default/queues/BYOC_Messaging_Queue.queue-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<Queue xmlns="http://soap.sforce.com/2006/04/metadata">
<doesIncludeBosses>true</doesIncludeBosses>
<doesSendEmailToMembers>false</doesSendEmailToMembers>
<name>BYOC Messaging Queue</name>
<queueMembers>
<users>
<user>ORG_USER_USERNAME_PLACEHOLDER</user>
</users>
</queueMembers>
<queueRoutingConfig>BYOC_Messaging_Routing</queueRoutingConfig>
<queueSobject>
<sobjectType>MessagingSession</sobjectType>
</queueSobject>
</Queue>force-app/main/default/queueRoutingConfigs/BYOC_Messaging_Routing.queueRoutingConfig-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<QueueRoutingConfig xmlns="http://soap.sforce.com/2006/04/metadata">
<capacityType>INHERITED</capacityType>
<capacityWeight>1.0</capacityWeight>
<isAttributeBased>false</isAttributeBased>
<label>BYOC Messaging Routing</label>
<routingModel>LEAST_ACTIVE</routingModel>
<routingPriority>1</routingPriority>
</QueueRoutingConfig>force-app/main/default/EmbeddedServiceConfig/Site_Helper_Web_Chat.EmbeddedServiceConfig-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<EmbeddedServiceConfig xmlns="http://soap.sforce.com/2006/04/metadata">
<areGuestUsersAllowed>false</areGuestUsersAllowed>
<branding>EmbeddedServiceConfig_BrandingSet_1a20f143ec3</branding>
<deploymentFeature>EmbeddedMessaging</deploymentFeature>
<deploymentType>Web</deploymentType>
<embeddedServiceMessagingChannel>
<fabDisplayModeForMobileWeb>IconAndLabel</fabDisplayModeForMobileWeb>
<fabDisplayModeForWeb>IconAndLabel</fabDisplayModeForWeb>
<isChatInvitationCustomizable>false</isChatInvitationCustomizable>
<isEnabled>true</isEnabled>
<isInvitationEnabled>false</isInvitationEnabled>
<isSendInvtAllowedAfterAccept>false</isSendInvtAllowedAfterAccept>
<isSendInvtAllowedAfterReject>false</isSendInvtAllowedAfterReject>
<messagingChannel>Site_Helper_Web_Chat</messagingChannel>
<shouldShowAgentforceTagline>true</shouldShowAgentforceTagline>
<shouldShowDeliveryReceipts>false</shouldShowDeliveryReceipts>
<shouldShowEmojiSelection>false</shouldShowEmojiSelection>
<shouldShowReadReceipts>false</shouldShowReadReceipts>
<shouldShowTypingIndicators>false</shouldShowTypingIndicators>
<shouldStartNewLineOnEnter>false</shouldStartNewLineOnEnter>
</embeddedServiceMessagingChannel>
<isEnabled>true</isEnabled>
<isTermsAndConditionsEnabled>false</isTermsAndConditionsEnabled>
<isTermsAndConditionsRequired>false</isTermsAndConditionsRequired>
<masterLabel>Site_Helper_Web_Chat</masterLabel>
<shouldHideAuthDialog>false</shouldHideAuthDialog>
<site>ESW_Site_Helper_We_17955492998421</site>
</EmbeddedServiceConfig>Case Triage Assistant, the internal agent
Built and testedA second, separate agent for support staff. It lists open Cases and changes a Case's priority. It reads and writes Case data, so it should not face the public. It shows how to give an agent Apex actions.
Apex classes
Two
@InvocableMethodclasses. Reads useWITH USER_MODE. The write action validates the priority and the case number.Agent action definitions
Each class is wrapped by a
GenAiFunction. The folder must containinput/schema.jsonandoutput/schema.json. Without them the action cannot be used and the agent falls into Off Topic.Topic
The
GenAiPlugintopic lists the two actions and holds the instructions. The write action asks for confirmation.Bot user access
A permission set gives the bot user the two classes and Case read/edit. The Einstein Agent license rejects View All permissions.
force-app/main/default/classes/CaseTriageListInvocable.cls
/**
* Agentforce action: list open (non-closed) Cases, optionally filtered by priority.
* Runs in user mode so the agent only sees what the running user can see.
*/
public with sharing class CaseTriageListInvocable {
private static final Integer MAX_ROWS = 10;
public class Request {
@InvocableVariable(label='Priority' description='Optional: High, Medium or Low. Leave blank for all open cases.')
public String priority;
}
public class Result {
@InvocableVariable(label='Summary' description='Human-readable list of the matching open cases')
public String summary;
@InvocableVariable(label='Case Count')
public Integer caseCount;
}
@InvocableMethod(
label='List Open Cases'
description='Returns up to 10 open cases (newest first), optionally filtered by priority.'
category='Case Triage'
)
public static List<Result> listOpenCases(List<Request> requests) {
List<Result> results = new List<Result>();
for (Request req : requests) {
String prio = String.isBlank(req.priority) ? null : req.priority.trim();
List<Case> cases;
if (prio == null) {
cases = [
SELECT CaseNumber, Subject, Status, Priority, Account.Name
FROM Case
WHERE IsClosed = FALSE
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :MAX_ROWS
];
} else {
cases = [
SELECT CaseNumber, Subject, Status, Priority, Account.Name
FROM Case
WHERE IsClosed = FALSE AND Priority = :prio
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :MAX_ROWS
];
}
List<String> lines = new List<String>();
for (Case c : cases) {
lines.add(
c.CaseNumber + ' | ' + c.Priority + ' | ' + c.Status + ' | ' +
(c.Account.Name == null ? 'No account' : c.Account.Name) + ' | ' + c.Subject
);
}
Result r = new Result();
r.caseCount = cases.size();
r.summary = cases.isEmpty() ? 'No open cases found.' : String.join(lines, '\n');
results.add(r);
}
return results;
}
}force-app/main/default/classes/CaseTriageEscalateInvocable.cls
/**
* Agentforce action: change the Priority of a Case identified by its case number.
*/
public with sharing class CaseTriageEscalateInvocable {
public class Request {
@InvocableVariable(label='Case Number' description='The case number, e.g. 00001002' required=true)
public String caseNumber;
@InvocableVariable(label='New Priority' description='High, Medium or Low' required=true)
public String newPriority;
}
public class Result {
@InvocableVariable(label='Message' description='Outcome of the update')
public String message;
}
@InvocableMethod(
label='Set Case Priority'
description='Sets the priority of a case (High, Medium or Low) using its case number.'
category='Case Triage'
)
public static List<Result> setPriority(List<Request> requests) {
List<Result> results = new List<Result>();
for (Request req : requests) {
Result r = new Result();
try {
if (req.newPriority == null || !new Set<String>{ 'High', 'Medium', 'Low' }.contains(req.newPriority)) {
r.message = 'Priority must be High, Medium or Low.';
} else {
List<Case> found = [
SELECT Id, Priority FROM Case WHERE CaseNumber = :req.caseNumber WITH USER_MODE LIMIT 1
];
if (found.isEmpty()) {
r.message = 'Case ' + req.caseNumber + ' was not found.';
} else {
String old = found[0].Priority;
found[0].Priority = req.newPriority;
update as user found;
r.message = 'Case ' + req.caseNumber + ' priority changed from ' + old + ' to ' + req.newPriority + '.';
}
}
} catch (Exception e) {
r.message = 'Could not update case: ' + e.getMessage();
}
results.add(r);
}
return results;
}
}force-app/main/default/genAiFunctions/ListOpenCasesAction/ListOpenCasesAction.genAiFunction-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<description>Lists up to 10 open cases, newest first, optionally filtered by priority (High, Medium, Low).</description>
<invocationTarget>CaseTriageListInvocable</invocationTarget>
<invocationTargetType>apex</invocationTargetType>
<isConfirmationRequired>false</isConfirmationRequired>
<masterLabel>List Open Cases</masterLabel>
</GenAiFunction>force-app/main/default/genAiFunctions/ListOpenCasesAction/input/schema.json
{
"required": [],
"unevaluatedProperties": false,
"properties": {
"priority": {
"title": "priority",
"description": "Optional: High, Medium or Low. Leave blank for all open cases.",
"lightning:type": "lightning__textType",
"lightning:isPII": false,
"copilotAction:isUserInput": true
}
},
"lightning:type": "lightning__objectType"
}force-app/main/default/genAiFunctions/ListOpenCasesAction/output/schema.json
{
"unevaluatedProperties": false,
"properties": {
"summary": {
"title": "summary",
"description": "Human-readable list of the matching open cases",
"lightning:type": "lightning__textType",
"lightning:isPII": false,
"copilotAction:isDisplayable": true,
"copilotAction:isUsedByPlanner": true
}
},
"lightning:type": "lightning__objectType"
}force-app/main/default/genAiPlugins/p_16jgL000002k4kD_Case_Triage.genAiPlugin-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<GenAiPlugin xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<canEscalate>false</canEscalate>
<description>Handles ANY request about support cases: show, list or view open cases, find high, medium or low priority cases, and change or escalate the priority of a case by case number. Use this topic whenever the user mentions cases, tickets or priorities.</description>
<developerName>p_16jgL000002k4kD_Case_Triage</developerName>
<genAiFunctions>
<functionName>ListOpenCasesAction</functionName>
</genAiFunctions>
<genAiFunctions>
<functionName>SetCasePriorityAction</functionName>
</genAiFunctions>
<genAiPluginInstructions>
<description>To show cases, call List Open Cases. Pass a priority only if the user asked for one (High, Medium or Low); otherwise leave it blank. Present the result as a short list.</description>
<developerName>instruction_0</developerName>
<language xsi:nil="true"/>
<masterLabel>instruction_0</masterLabel>
<sortOrder>0</sortOrder>
</genAiPluginInstructions>
<genAiPluginInstructions>
<description>To change a case priority, you need both the case number and the new priority (High, Medium or Low). Ask for whichever is missing, then call Set Case Priority and report its message exactly.</description>
<developerName>instruction_1</developerName>
<language xsi:nil="true"/>
<masterLabel>instruction_1</masterLabel>
<sortOrder>1</sortOrder>
</genAiPluginInstructions>
<genAiPluginInstructions>
<description>Never invent cases or case numbers. If an action returns no results or an error, say so plainly.</description>
<developerName>instruction_2</developerName>
<language xsi:nil="true"/>
<masterLabel>instruction_2</masterLabel>
<sortOrder>2</sortOrder>
</genAiPluginInstructions>
<language>en_US</language>
<localDeveloperName>p_16jgL000002k4kD_Case_Triage</localDeveloperName>
<masterLabel>Case Triage</masterLabel>
<pluginType>Topic</pluginType>
<scope>Your job is to only assist with listing open Salesforce cases, filtering them by priority, and updating the priority of a case based on its case number. You aren't able to create new cases or provide case details beyond the scope of priority and status.</scope>
</GenAiPlugin>force-app/main/default/permissionsets/CaseTriage_Agent_Access.permissionset-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Case Triage Agent Access</label>
<description>Lets the Case Triage Assistant agent user run its Apex actions and read/edit Cases.</description>
<hasActivationRequired>false</hasActivationRequired>
<classAccesses>
<apexClass>CaseTriageListInvocable</apexClass>
<enabled>true</enabled>
</classAccesses>
<classAccesses>
<apexClass>CaseTriageEscalateInvocable</apexClass>
<enabled>true</enabled>
</classAccesses>
<objectPermissions>
<allowCreate>false</allowCreate>
<allowDelete>false</allowDelete>
<allowEdit>true</allowEdit>
<allowRead>true</allowRead>
<modifyAllRecords>false</modifyAllRecords>
<object>Case</object>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
<objectPermissions>
<allowCreate>false</allowCreate>
<allowDelete>false</allowDelete>
<allowEdit>false</allowEdit>
<allowRead>true</allowRead>
<modifyAllRecords>false</modifyAllRecords>
<object>Account</object>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
<fieldPermissions>
<editable>true</editable>
<field>Case.Priority</field>
<readable>true</readable>
</fieldPermissions>
</PermissionSet>force-app/main/default/classes/CaseTriageAgentActionsTest.cls
@IsTest
private class CaseTriageAgentActionsTest {
@TestSetup
static void setup() {
insert new List<Case>{
new Case(Subject = 'A', Status = 'New', Priority = 'Low'),
new Case(Subject = 'B', Status = 'New', Priority = 'High')
};
}
@IsTest
static void listsAllAndFiltered() {
CaseTriageListInvocable.Request all = new CaseTriageListInvocable.Request();
CaseTriageListInvocable.Request high = new CaseTriageListInvocable.Request();
high.priority = 'High';
List<CaseTriageListInvocable.Result> res = CaseTriageListInvocable.listOpenCases(
new List<CaseTriageListInvocable.Request>{ all, high }
);
Assert.areEqual(2, res[0].caseCount);
Assert.areEqual(1, res[1].caseCount);
}
@IsTest
static void setsPriorityAndHandlesBadInput() {
Case c = [SELECT CaseNumber FROM Case WHERE Subject = 'A'];
CaseTriageEscalateInvocable.Request ok = new CaseTriageEscalateInvocable.Request();
ok.caseNumber = c.CaseNumber;
ok.newPriority = 'High';
CaseTriageEscalateInvocable.Request badPrio = new CaseTriageEscalateInvocable.Request();
badPrio.caseNumber = c.CaseNumber;
badPrio.newPriority = 'Urgent';
CaseTriageEscalateInvocable.Request missing = new CaseTriageEscalateInvocable.Request();
missing.caseNumber = '99999999';
missing.newPriority = 'High';
List<CaseTriageEscalateInvocable.Result> res = CaseTriageEscalateInvocable.setPriority(
new List<CaseTriageEscalateInvocable.Request>{ ok, badPrio, missing }
);
Assert.isTrue(res[0].message.contains('changed from Low to High'));
Assert.isTrue(res[1].message.contains('must be'));
Assert.isTrue(res[2].message.contains('not found'));
Assert.areEqual('High', [SELECT Priority FROM Case WHERE Id = :c.Id].Priority);
}
}specs/caseTriageAgent.yaml
agentType: internal
role: A support-team assistant that helps agents triage open Salesforce Cases, showing what is open and re-prioritizing cases when asked.
companyName: srinip company
companyDescription: A company that supports its customers through Salesforce Service Cloud cases.
maxNumOfTopics: 1
topics:
- name: Case Triage
description: Lists open support cases (optionally filtered by High, Medium or Low priority) and changes the priority of a case identified by its case number.specs/caseTriageTests.yaml
name: Case Triage Assistant Tests
description: Smoke tests for the Case Triage Assistant agent
subjectType: AGENT
subjectName: Case_Triage_Assistant
testCases:
- utterance: Show me all open cases
expectedTopic: p_16jgL000002k4kD_Case_Triage
expectedActions:
- ListOpenCasesAction
expectedOutcome: The agent lists open cases including case numbers such as 00001002 and their priorities.
- utterance: Show me the open support cases that have High priority
expectedTopic: p_16jgL000002k4kD_Case_Triage
expectedActions:
- ListOpenCasesAction
expectedOutcome: The agent lists only open cases with High priority, or says none were found.
- utterance: Change the priority of case 99999999 to High
expectedTopic: p_16jgL000002k4kD_Case_Triage
expectedActions:
- SetCasePriorityAction
expectedOutcome: The agent reports that case 99999999 was not found.Knowledge and guest access
Fourteen articles are published to the Public Knowledge Base, and the Site Helper site's guest user can read them. The Site Helper agent does not use them yet. To use them, connect a Knowledge data library to the agent and add an answer action to General Info.
force-app/main/default/settings/Knowledge.settings-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<KnowledgeSettings xmlns="http://soap.sforce.com/2006/04/metadata">
<enableKnowledge>true</enableKnowledge>
<enableLightningKnowledge>true</enableLightningKnowledge>
<enableCreateEditOnArticlesTab>true</enableCreateEditOnArticlesTab>
<defaultLanguage>en_US</defaultLanguage>
<languages>
<language>
<active>true</active>
<name>en_US</name>
</language>
</languages>
</KnowledgeSettings>force-app/main/default/objects/Knowledge__kav/fields/Article_Body__c.field-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Article_Body__c</fullName>
<label>Article Body</label>
<type>Html</type>
<length>32768</length>
<visibleLines>25</visibleLines>
<required>false</required>
</CustomField>force-app/main/default/permissionsets/Knowledge_Guest_Read.permissionset-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Knowledge Guest Read</label>
<description>Lets the Site Helper guest user read published public knowledge articles.</description>
<hasActivationRequired>false</hasActivationRequired>
<objectPermissions>
<allowCreate>false</allowCreate>
<allowDelete>false</allowDelete>
<allowEdit>false</allowEdit>
<allowRead>true</allowRead>
<modifyAllRecords>false</modifyAllRecords>
<object>Knowledge__kav</object>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
<fieldPermissions>
<editable>false</editable>
<field>Knowledge__kav.Article_Body__c</field>
<readable>true</readable>
</fieldPermissions>
</PermissionSet>scripts/apex/createKnowledge.apex
List<Map<String,String>> arts = new List<Map<String,String>>{
new Map<String,String>{'t'=>'How to Perform Routine Generator Maintenance','u'=>'generator-routine-maintenance','s'=>'A simple schedule for keeping your generator reliable.',
'b'=>'<h2>Maintenance schedule</h2><ul><li><b>Weekly:</b> check oil, coolant and fuel levels; run the unit for 10 minutes.</li><li><b>Every 100 hours:</b> change the oil and inspect air filters.</li><li><b>Annually:</b> replace spark plugs or fuel filters and test the battery.</li></ul><p>Always switch the generator off and let it cool before servicing.</p>'},
new Map<String,String>{'t'=>'Electrical Wiring Installation Guidelines for the GC5060','u'=>'gc5060-wiring-installation','s'=>'Key safety and wiring steps before installing the GC5060.',
'b'=>'<h2>Before you start</h2><ol><li>Isolate power and lock out the supply.</li><li>Use cable rated for the unit load and run it in conduit.</li><li>Connect protective earth first, then neutral, then phases.</li><li>Have a licensed electrician inspect the installation before commissioning.</li></ol>'},
new Map<String,String>{'t'=>'Troubleshooting Mechanical Rotor Vibration','u'=>'rotor-vibration-troubleshooting','s'=>'Common causes of excessive rotor vibration and how to fix them.',
'b'=>'<h2>Common causes</h2><ul><li>Worn or damaged bearings</li><li>Imbalanced rotor or loose mounting bolts</li><li>Shaft misalignment</li></ul><p>Stop the machine, inspect mountings, and contact support if vibration persists after re-tightening.</p>'},
new Map<String,String>{'t'=>'How to Contact Support and What to Include in a Case','u'=>'contacting-support','s'=>'Get faster answers by including the right details.',
'b'=>'<p>When you open a case, include the product model, serial number, a clear description, and any error codes or photos. Cases are prioritised as High, Medium or Low based on business impact.</p>'},
new Map<String,String>{'t'=>'Warranty and Service Coverage FAQ','u'=>'warranty-faq','s'=>'Answers to common warranty questions.',
'b'=>'<h2>FAQ</h2><p><b>How long is the warranty?</b> Standard equipment carries a 12-month warranty from delivery.</p><p><b>What voids it?</b> Unauthorised modification or skipped scheduled maintenance.</p>'}
};
List<Knowledge__kav> recs = new List<Knowledge__kav>();
for (Map<String,String> a : arts) {
recs.add(new Knowledge__kav(Title=a.get('t'), UrlName=a.get('u'), Summary=a.get('s'), Article_Body__c=a.get('b'), Language='en_US', IsVisibleInPkb=true, IsVisibleInCsp=true));
}
insert recs;
for (Knowledge__kav k : [SELECT KnowledgeArticleId FROM Knowledge__kav WHERE Id IN :recs]) {
KbManagement.PublishingService.publishArticle(k.KnowledgeArticleId, true);
}
System.debug('Published ' + recs.size());Slack alerts
Live, tested end to endA trigger posts to Slack when a High priority Case is created, and a scheduled job posts a daily digest. Both go through one class that reads the webhook URL from the custom label Slack_Webhook_Url. While the label says REPLACE_ME, nothing is sent.
force-app/main/default/classes/SlackCaseNotifier.cls
/**
* Posts Case summaries to Slack through an incoming webhook.
* The webhook URL lives in the protected custom label Slack_Webhook_Url.
* While the label still says REPLACE_ME, nothing is sent.
*/
public with sharing class SlackCaseNotifier {
@TestVisible
private static String webhookOverride;
private static String webhookUrl() {
String url = webhookOverride != null ? webhookOverride : Label.Slack_Webhook_Url;
return (String.isBlank(url) || url == 'REPLACE_ME') ? null : url;
}
public static String buildDigest() {
List<AggregateResult> rows = [
SELECT Priority p, COUNT(Id) n FROM Case WHERE IsClosed = FALSE GROUP BY Priority
];
Map<String, Integer> counts = new Map<String, Integer>{ 'High' => 0, 'Medium' => 0, 'Low' => 0 };
for (AggregateResult r : rows) {
counts.put((String) r.get('p'), (Integer) r.get('n'));
}
return ':clipboard: *Daily case digest*\n' +
':red_circle: High: ' + counts.get('High') + '\n' +
':large_orange_circle: Medium: ' + counts.get('Medium') + '\n' +
':large_green_circle: Low: ' + counts.get('Low');
}
public static String buildAlert(List<Case> cases) {
List<String> lines = new List<String>();
for (Case c : cases) {
lines.add('• ' + c.CaseNumber + ' - ' + c.Subject);
}
return ':rotating_light: *New High priority case(s)*\n' + String.join(lines, '\n');
}
public static void send(String text) {
String url = webhookUrl();
if (url == null) {
return;
}
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, String>{ 'text' => text }));
new Http().send(req);
}
@future(callout=true)
public static void sendAsync(String text) {
send(text);
}
public static void alertHighPriority(List<Case> cases) {
List<Case> high = new List<Case>();
for (Case c : cases) {
if (c.Priority == 'High') {
high.add(c);
}
}
if (!high.isEmpty() && webhookUrl() != null && !System.isFuture() && !System.isBatch()) {
sendAsync(buildAlert(high));
}
}
}force-app/main/default/classes/SlackCaseDigestJob.cls
/**
* Schedulable job that posts the daily case digest to Slack.
* Schedule: System.schedule('Slack case digest', '0 0 8 * * ?', new SlackCaseDigestJob());
*/
public with sharing class SlackCaseDigestJob implements Schedulable, Database.AllowsCallouts {
public void execute(SchedulableContext sc) {
SlackCaseNotifier.sendAsync(SlackCaseNotifier.buildDigest());
}
}force-app/main/default/triggers/CaseSlackAlertTrigger.trigger
trigger CaseSlackAlertTrigger on Case (after insert) {
SlackCaseNotifier.alertHighPriority(Trigger.new);
}force-app/main/default/labels/CustomLabels.labels-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
<labels>
<fullName>Slack_Webhook_Url</fullName>
<language>en_US</language>
<protected>true</protected>
<shortDescription>Slack incoming webhook URL</shortDescription>
<value>REPLACE_ME</value>
</labels>
</CustomLabels>force-app/main/default/remoteSiteSettings/Slack_Hooks.remoteSite-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">
<disableProtocolSecurity>false</disableProtocolSecurity>
<isActive>true</isActive>
<url>https://hooks.slack.com</url>
</RemoteSiteSetting>force-app/main/default/classes/SlackCaseNotifierTest.cls
@IsTest
private class SlackCaseNotifierTest {
private class Mock implements HttpCalloutMock {
public Integer calls = 0;
public HttpResponse respond(HttpRequest req) {
calls++;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
}
}
@IsTest
static void digestCountsOpenCasesByPriority() {
insert new List<Case>{
new Case(Subject = 'a', Status = 'New', Priority = 'High'),
new Case(Subject = 'b', Status = 'New', Priority = 'Low')
};
String d = SlackCaseNotifier.buildDigest();
Assert.isTrue(d.contains('High: 1'));
Assert.isTrue(d.contains('Low: 1'));
}
@IsTest
static void doesNothingWithoutWebhook() {
Mock m = new Mock();
Test.setMock(HttpCalloutMock.class, m);
Test.startTest();
insert new Case(Subject = 'c', Status = 'New', Priority = 'High');
Test.stopTest();
Assert.areEqual(0, m.calls);
}
@IsTest
static void highPriorityInsertPostsOnce() {
SlackCaseNotifier.webhookOverride = 'https://hooks.slack.com/services/T/B/X';
Mock m = new Mock();
Test.setMock(HttpCalloutMock.class, m);
Test.startTest();
insert new List<Case>{
new Case(Subject = 'd', Status = 'New', Priority = 'High'),
new Case(Subject = 'e', Status = 'New', Priority = 'Low')
};
Test.stopTest();
Assert.areEqual(1, m.calls);
}
@IsTest
static void digestJobPosts() {
SlackCaseNotifier.webhookOverride = 'https://hooks.slack.com/services/T/B/X';
Mock m = new Mock();
Test.setMock(HttpCalloutMock.class, m);
Test.startTest();
new SlackCaseDigestJob().execute(null);
Test.stopTest();
Assert.areEqual(1, m.calls);
}
}Commands used
# deploy Apex actions with their tests (specified tests, only these classes)
sf project deploy start -o afdcnew -m ApexClass:CaseTriageListInvocable -m ApexClass:CaseTriageEscalateInvocable \
-m ApexClass:CaseTriageAgentActionsTest -l RunSpecifiedTests -t CaseTriageAgentActionsTest
# create an agent from a spec, then activate it
sf agent create -o afdcnew --name "Case Triage Assistant" --api-name Case_Triage_Assistant --spec specs/caseTriageAgent.yaml
sf agent activate -o afdcnew --api-name Case_Triage_Assistant
sf agent deactivate -o afdcnew --api-name Case_Triage_Assistant # before deploying topic changes
# agent actions and topic
sf project deploy start -o afdcnew -m GenAiFunction:ListOpenCasesAction -m GenAiFunction:SetCasePriorityAction \
-m GenAiPlugin:p_16jgL000002k4kD_Case_Triage
# test the live agent with real utterances
sf agent test create -o afdcnew --spec specs/caseTriageTests.yaml --api-name Case_Triage_Assistant_Tests --force-overwrite
sf agent test run -o afdcnew -n Case_Triage_Assistant_Tests -w 10 --result-format human
# bot user permissions
sf org assign permset -o afdcnew -n CaseTriage_Agent_Access -b <bot user name>
# retrieve the Site Helper agent, channel, queue and deployment
sf project retrieve start -o afdcnew -m Bot:Site_Helper -m GenAiPlannerBundle:Site_Helper_v4 \
-m MessagingChannel:Site_Helper_Web_Chat -m EmbeddedServiceConfig:Site_Helper_Web_Chat \
-m Queue:BYOC_Messaging_Queue -m QueueRoutingConfig:BYOC_Messaging_Routing
# seed data and schedule the digest
sf apex run -o afdcnew -f scripts/apex/createKnowledge.apex
sf apex run -o afdcnew -f scripts/apex/ingestCases.apex
# Execute Anonymous, after the webhook label is set:
System.schedule('Slack case digest', '0 0 8 * * ?', new SlackCaseDigestJob());
sf org open agent --api-name Site_Helper -o afdcnew
Problems hit and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Agent answered Off_Topic | Actions had no input/output schema | Add schema.json under the function folder |
| Function deploy failed with an unexpected error | A function without a schema cannot be updated in place | Create it under a new name, repoint the topic, delete the old one |
| Permission set would not assign to the bot user | Einstein Agent license rejects View All Account and Case | Set viewAllRecords false |
| Knowledge articles had no body | Default article type has title and summary only | Add a rich text field and a permission set |
| Apex: bind variable on the left of a comparison | SOQL requires the field on the left | Branch into two queries |
Apex: String[][] does not compile | No multi-dimensional arrays | Use List<List<String>> with explicit inner lists |
| Test report shows topic "p" | Topic name in the test spec differs from the runtime topic name | The action ran, so routing was right. Align the expected topic name. |
| Earlier page said chat reached nobody | Read the channel's routing type, which is empty for direct agent handling | Read sessionHandlerType and sessionHandlerAsa instead |
Suggested next steps
- Add more people to
BYOC_Messaging_Queueand test an escalation end to end with someone online in Omni-Channel. - Ground Site Helper on the 14 Knowledge articles instead of typed-in facts.
- Make Follow-Up Capture create a Lead so contact details survive the session.
- Move the Slack webhook from a label to a Named Credential, and rotate it if its URL was ever shared.
- Decide whether you need an Omni-Flow router. Add one only when routing needs a decision.
Where things live in the project
| Path | Contents |
|---|---|
| force-app/main/default/bots/Site_Helper, genAiPlannerBundles/Site_Helper_v4 | Public agent and its Agent Script (retrieved) |
| force-app/main/default/messagingChannels, queues, queueRoutingConfigs, EmbeddedServiceConfig | Channel, queue, routing and chat deployment (retrieved) |
| force-app/main/default/bots/Case_Triage_Assistant, genAiPlannerBundles/Case_Triage_Assistant, genAiPlugins, genAiFunctions | Internal agent, topic, actions |
| force-app/main/default/classes, triggers, labels, remoteSiteSettings | Apex actions, Slack alerts, tests |
| force-app/main/default/permissionsets, settings, objects/Knowledge__kav | Access, Knowledge setting, article body field |
| specs/, scripts/apex/, docs/ | Agent and test specs, seed scripts, this page, Slack notes |