Sub topic 8
Handling environment-specific settings
This chapter assumes you can retrieve and deploy metadata with Salesforce CLI and read package.xml and sfdx-project.json. It also assumes you know what a Named Credential and a custom metadata type are. By the end you should be able to find the values in an agent's metadata that differ between orgs and decide how to handle each one.
Why a copied agent can break
A deployment copies metadata files. It does not copy the org around them. Some values inside those files are correct only in the org where you retrieved them:
- The username of the agent user. Sandbox usernames usually end in
.sandboxname, so the production username is different. - Record IDs. A Flow or Apex class may hard-code the ID of a queue, record type, or Knowledge article. IDs differ in every org.
- Endpoint URLs and credentials used by actions that call external systems.
- Values such as email addresses, queue names, or channel names written into topic instructions.
- Feature switches and thresholds, such as a maximum refund amount, that should be lower in a sandbox than in production.
The deployment can still succeed with these values wrong. The agent then activates but fails when an action runs. That is why this chapter comes before the deploy step.
Sorting settings into three groups
Handle each environment-specific value in one of three ways:
- Remove it from the metadata. Move the value into something that is not deployed with the agent, or that is configured per org. Named Credentials, custom metadata records, and custom settings are the usual homes.
- Replace it at deploy time. Keep a placeholder in source and let Salesforce CLI swap in the right value for each target.
- Set it by hand after deploying. Use this only for values that cannot be deployed, such as secrets.
Finding the values that differ
Search your retrieved source for the values that tend to change. Start with these:
grep -rniE "\.(dev|uat|qa|full|sandbox)[a-z0-9]*</|https?://|00[0-9A-Za-z]{13,16}" force-app/main/default \
--include=*.xml --include=*.cls --include=*.flow-meta.xmlThe pattern is deliberately loose. It flags sandbox-style usernames, URLs, and strings shaped like 15 or 18 character Salesforce IDs. Expect false positives. Read each hit and decide which group it belongs to.
Also check by hand:
- The
Botfile, which names the agent user. - Each
GenAiFunctionand the Apex or Flow it targets. - Flows that use Get Records with a hard-coded ID or a name that only exists in one org.
- Topic instructions in
GenAiPluginthat mention an email address, queue, or URL.
The agent user
A service agent runs as a dedicated agent user. The agent's Bot metadata stores that user's username. In the target org that username must exist, or the deployment or activation fails.
Check what is in the source file:
grep -n "botUser" force-app/main/default/bots/My_Service_Agent/My_Service_Agent.bot-meta.xmlThen find the agent user in each org. Agent users are created from the Einstein Agent User profile:
sf data query \
--query "SELECT Username, IsActive FROM User WHERE Profile.Name = 'Einstein Agent User'" \
--target-org target-orgIf the query returns nothing, create the user in the target org before you deploy. Setting up the user and its permissions is covered in the previous chapter. The point here is that the username you find in each org is a deployment input, not a constant.
Replacing values at deploy time
Salesforce CLI can substitute strings in source files as it deploys. You configure this with a replacements array in sfdx-project.json. The replacement is applied to the files sent to the org. Your local source files are not changed.
{
"packageDirectories": [
{ "path": "force-app", "default": true }
],
"namespace": "",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "63.0",
"replacements": [
{
"filename": "force-app/main/default/bots/My_Service_Agent/My_Service_Agent.bot-meta.xml",
"stringToReplace": "[email protected]",
"replaceWithEnv": "AGENT_USER_NAME"
}
]
}Each entry names a file (or a glob), the text to find, and where the new value comes from. The main options are:
| Option | Purpose |
|---|---|
| `filename` or `glob` | Which file or files to change. |
| `stringToReplace` or `regexToReplace` | The text to find. |
| `replaceWithEnv` | Read the new value from an environment variable. |
| `replaceWithFile` | Read the new value from a file. |
| `allowUnsetEnvVariable` | Skip the replacement instead of failing when the variable is unset. |
| `replaceWhenEnv` | Apply the entry only when another environment variable has a given value. |
Set the variable in the shell, then deploy:
export AGENT_USER_NAME="[email protected]"
sf project deploy start \
--manifest manifest/package.xml \
--target-org target-org \
--dry-runBecause the CLI fails when AGENT_USER_NAME is unset, a forgotten variable stops the deployment before anything reaches the org. Leave allowUnsetEnvVariable off for values the agent cannot run without.
Keeping one config for several targets
With replaceWhenEnv, a single sfdx-project.json can handle several targets. Each entry applies only when a selector variable has a particular value.
{
"replacements": [
{
"filename": "force-app/main/default/bots/My_Service_Agent/My_Service_Agent.bot-meta.xml",
"stringToReplace": "[email protected]",
"replaceWithEnv": "UAT_AGENT_USER",
"replaceWhenEnv": [{ "env": "DEPLOY_ENV", "value": "uat" }]
},
{
"filename": "force-app/main/default/bots/My_Service_Agent/My_Service_Agent.bot-meta.xml",
"stringToReplace": "[email protected]",
"replaceWithEnv": "PROD_AGENT_USER",
"replaceWhenEnv": [{ "env": "DEPLOY_ENV", "value": "prod" }]
}
]
}export DEPLOY_ENV=uat
export UAT_AGENT_USER="[email protected]"
sf project deploy start --manifest manifest/package.xml --target-org uat-orgMoving values out of metadata
Replacement is a patch. When the value is read at run time by an Apex class or Flow, a cleaner option is to avoid putting it in the metadata at all.
Named Credentials for external calls
If an agent action calls an external API through Apex or an External Service, reference a Named Credential by its API name. Use the same API name in every org and point it at a different endpoint in each. The agent's Apex then contains callout:Order_API/orders, which works everywhere.
Named Credential definitions can be deployed, but secrets cannot. Passwords, tokens, and client secrets must be entered in each org after the deployment. Add that step to your checklist.
Custom metadata for business settings
Store thresholds, routing names, and feature switches in a custom metadata type. The records deploy with the rest of your source, but the values in each org can differ if you deploy a different record set or edit them after deployment. A Flow behind an action can read them with Get Records, and an Apex class can query them without using a query limit.
public with sharing class RefundPolicy {
public static Decimal maxAutoRefund() {
Refund_Setting__mdt setting = Refund_Setting__mdt.getInstance('Default');
return setting == null ? 0 : setting.Max_Auto_Refund__c;
}
}Looking up IDs by name
Replace a hard-coded record ID with a lookup on a stable field. This is a query on the queue's developer name instead of its ID:
public with sharing class QueueLookup {
public static Id supportQueueId() {
return [
SELECT Id FROM Group
WHERE Type = 'Queue' AND DeveloperName = 'Tier_1_Support'
LIMIT 1
].Id;
}
}The queue itself must exist in the target org with that developer name. Queues, record types, and similar setup records are often deployable, so include them in the manifest.
Instructions that mention org details
Topic instructions and action descriptions are plain text that the language model reads. If an instruction says "escalate to [email protected]", the production agent will say the same thing. Two options:
- Write instructions without org-specific details, and let the action supply the destination at run time.
- Keep the detail, and add that file to the
replacementslist.
The first option is easier to maintain, because one instruction text is reviewed and tested for every environment.
A checklist for each target
Build a short table per target org and fill it in before the real deployment.
| Setting | Source value | Target value | Handled by |
|---|---|---|---|
| Agent user | `[email protected]` | `[email protected]` | `replacements` |
| Order API endpoint | sandbox URL | production URL | Named Credential |
| Order API secret | sandbox token | production token | Manual after deploy |
| Max auto refund | 10 | 100 | Custom metadata record |
| Support queue | `Tier_1_Support` | `Tier_1_Support` | Deployed with the manifest |
Common mistakes
- Deploying the sandbox username to production. The agent user does not exist, and the deployment or activation fails.
- Leaving the replacement unset in a pipeline. A missing environment variable can silently skip a replacement if
allowUnsetEnvVariableis true. - Hard-coded IDs in Flows. The Flow deploys successfully and then finds no record at run time.
- Assuming secrets travel with Named Credentials. The definition deploys. The secret does not.
- Editing the target org directly. The next deployment overwrites the change. Fix the value in source, config, or a replacement entry.
Exercise
An agent's Flow action looks up a queue by its 15-character ID, which was copied from the sandbox. The agent deploys and activates in production without errors, but the action never routes cases. Why did the deployment succeed, and what would you change?
Show answer
The deployment checks that the metadata is valid, not that an ID refers to a real record. The queue ID exists only in the sandbox, so in production the lookup finds nothing at run time. Change the Flow or an Apex helper to find the queue by its DeveloperName, for example Tier_1_Support, and deploy the queue itself with the manifest so the name exists in the target org.
Exercise
Your sfdx-project.json replaces the agent username using replaceWithEnv: "AGENT_USER_NAME". In the CI job the variable is not set and allowUnsetEnvVariable is not enabled. What happens, and why is that preferable to enabling allowUnsetEnvVariable for this entry?
Show answer
The CLI stops with an error before sending the deployment. That is preferable because the agent cannot run without a valid agent user. With allowUnsetEnvVariable enabled, the replacement would be skipped and the sandbox username would be deployed, which causes a failure later and is harder to trace.