Skip to content

fix: W-24023175 don't fall back to internal Agent API hosts for customer orgs - #399

Closed
nhalko-sf wants to merge 3 commits into
mainfrom
nh/W-24023175-endpoint-fallback
Closed

nhalko-sf wants to merge 3 commits into
mainfrom
nh/W-24023175-endpoint-fallback

Conversation

@nhalko-sf

@nhalko-sf nhalko-sf commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes sf agent publish authoring-bundle failing with a bare TypeError: fetch failed (UND_ERR_CONNECT_TIMEOUT) on customer orgs.

requestWithEndpointFallback retried every 404 from api.salesforce.com on test., dev. and stage.api.salesforce.com. Those gateways only accept connections from inside the Salesforce network. So when a customer org got a 404 (for example, a scratch org that isn't entitled to agent authoring, while /authoring/scripts still works), the retry on test.api hit a connect timeout. Non-404 errors were rethrown immediately, so that timeout replaced the real 404.

Changes (src/utils.ts):

  • Pick hosts from the org's instance. The internal hosts are tried only when the org's instance URL is internal (SfdcUrl.isInternalUrl(): pc-rnd, stm, vpod, crm.dev, localhost). Customer orgs (*.my.salesforce.com, including develop/scratch/sandbox) call api.salesforce.com only.
  • Don't let an unreachable fallback hide the real error. If a fallback host gives no HTTP response (DNS failure, refused/reset/timed-out connection; detected by error code, walking cause), it's skipped. HTTP errors from any host (401/403/5xx, INVALID_SESSION_ID), and network errors on api.salesforce.com itself, are still thrown right away, as before. Fallback hosts get maxRetries: 0 so an unreachable host is skipped quickly.
  • SF_AGENT_API_ENDPOINTS override. Comma-separated fallback gateway prefixes, for example stage.,test.. It applies to every org, internal or not, and replaces the default chain; none disables the fallback. It's for internal orgs whose domain isn't recognized as internal (for example stage orgs on a customer-style domain).
  • Behavior change for internal users: orgs on customer-style domains now stop after api.salesforce.com instead of trying test./dev./stage.. Internal-instance orgs keep the full chain.
  • Actionable AgentApiNotFound. The error keeps its name, because scriptAgent.ts matches on it. It now names the method and path, the hosts that returned 404 and any unreachable ones, keeps the first 404 as cause, and puts attemptedEndpoints/unreachableEndpoints in data. Its actions say to check Agentforce enablement and licensing (Einstein1AIPlatform for scratch orgs) and user permissions, and to confirm the org's SFAP gateway (Setup > GatewayHawkingInfo, or set SF_AGENT_API_ENDPOINTS). For /authoring/agents, they also note that publishing calls a different Agent API endpoint that may need extra Agentforce entitlements, so validate can pass where publish can't. Query strings are kept out of the message.

Example for a customer org, before and after:

TypeError: fetch failed  [cause]: ConnectTimeoutError ... 34.210.29.116:443 ...
Error (AgentApiNotFound): Unable to access the Salesforce Agent APIs: POST /einstein/ai-agent/v1.1/authoring/agents returned 404 (Not Found) from api.salesforce.com.

Testing

  • yarn compile, yarn lint (0 errors), yarn test:only: 533 passing, 0 failing.
  • New cases in test/utils.test.ts (5 fail on main without this change): an unreachable fallback is skipped; unreachable test./dev. don't hide the prod 404; an unreachable api.salesforce.com is still thrown immediately; a prod org makes one call and gets the new message and actions; the publish hint shows only for /authoring/agents; a test.-prefixed URL is normalized on prod orgs; a missing instanceUrl is treated as prod; an HTTP error without a statusCode (INVALID_SESSION_ID), a 503, and UND_ERR_INVALID_ARG from a fallback host are rethrown; all three fallbacks unreachable gives the exact message; *.stm/*.crm.dev get the chain; fallback hosts get no retries; SF_AGENT_API_ENDPOINTS overrides and none. The existing api→test→dev→stage chain tests now use an internal pc-rnd instance URL.
  • Live, with a CLI built on this branch and test./dev./stage.api made unreachable to mimic a customer network: publishing to a customer-domain org (Agentforce enabled) succeeded and the debug log shows only api.salesforce.com calls. On a scratch org without Einstein1AIPlatform, released 2.5.0 fails with TypeError: fetch failed and this branch with the clear AgentApiNotFound 404.
  • Not tested live: a customer-domain org that 404s on /authoring/agents only (the reporter's exact case; my scratch org landed on an internal domain), and a stage org.

Review note

This assumes aws-stage1 org domains count as internal under SfdcUrl.isInternalUrl(). If they don't, those orgs would lose the stage. fallback added in #365 unless SF_AGENT_API_ENDPOINTS=stage. is set. Atul Kshirsagar (atulkc), can you confirm?

No overlap with #398: different files, and #398 deliberately leaves a failed publish POST unannotated.

What issues does this PR fix or reference?

Fixes forcedotcom/cli#3634
@W-24023175@

…-24023175@

requestWithEndpointFallback retried every 404 from api.salesforce.com on
test./dev./stage.api.salesforce.com. Those gateways only accept connections
from inside the Salesforce network, so for a customer org the fallback hit a
connect timeout, and because non-404 errors were rethrown immediately the
user saw a bare "TypeError: fetch failed" instead of the real 404.

- Only try the internal hosts when the org's instance URL is internal
  (SfdcUrl.isInternalUrl: pc-rnd, stm, crm.dev, ...). Customer orgs use
  api.salesforce.com only.
- Skip a fallback host that can't be reached instead of letting its
  connection error replace the 404.
- AgentApiNotFound now names the request, the hosts tried and any
  unreachable ones, keeps the 404 as the cause, and suggests checking the
  org's Agentforce entitlement and user permissions (plus a publish-specific
  hint for /authoring/agents).

Fixes forcedotcom/cli#3634
@nhalko-sf
nhalko-sf requested a review from a team as a code owner November 20, 2026 00:23

@nhalko-sf nhalko-sf left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pre-review, round 1 of 2 (an extra pair of eyes, not a gate). Verdict: approve with nits, no blockers for customers.

The fix is right for customers. *.my.salesforce.com orgs (develop, scratch, sandbox, prod) now call only api.salesforce.com, so a connect timeout on test.api can't replace the real 404. The new AgentApiNotFound message, which names the method, path and hosts, is a big improvement. Two things to settle before merge: the SfdcUrl.isInternalUrl() gate is unverified for aws-stage1 orgs, the #365 case (inline 1), and "unreachable" is inferred from statusCode === undefined, which also matches real jsforce HTTP errors whose JSON body has a message (inline 2).

General (no line anchor)

  • Behavior change for internal users (by design, worth stating in the PR): internal users on prod orgs (org62, GUS) used to fall through to test./dev.. Now they stop after api., which is correct. Internal orgs off VPN now get AgentApiNotFound with "Couldn't connect to …" instead of a bare fetch failed.
  • Retry cost: connection.request runs with maxRetries: 3, so on internal orgs each unreachable fallback can still take several connect timeouts. Consider maxRetries: 0 for the fallback hosts.
  • Compatibility: scriptAgent.ts still matches name === 'AgentApiNotFound', so the exit code is unchanged. data and actions are additive.
  • Not verified live: no customer-domain org reproducing the 404 was available, and no stage org was tested.

What's good: precise root-cause write-up and the smallest fix that solves it. notFoundError ??= error keeps the first 404 as cause. A network error on api. itself still throws immediately, and a test covers it. attemptedEndpoints/unreachableEndpoints in data help triage. The chain tests were moved to a realistic pc-rnd instance URL instead of being deleted.

Comment thread src/utils.ts Outdated
Comment on lines +753 to +780
const INTERNAL_API_ENDPOINTS = ['test.', 'dev.', 'stage.'];

const isInternalOrg = (connection: Connection): boolean => {
try {
return new SfdcUrl(connection.instanceUrl).isInternalUrl();
} catch {
return false;
}
};

/**
* Makes an API request with automatic endpoint fallback.
* Tries api.salesforce.com first, then test., dev., and stage.api.salesforce.com on 404.
* Tries api.salesforce.com first. For orgs on internal instances only, then tries test., dev., and
* stage.api.salesforce.com on 404. A fallback host that can't be reached is skipped, so its connection
* error never hides the 404 from api.salesforce.com.
*
* @param connection - The Salesforce connection
* @param requestInfo - The request information (url, method, headers, body, etc.)
* @param options - Optional retry/timeout options
* @returns The API response
* @throws SfError if all endpoints return 404, or immediately on non-404 errors
* @throws SfError if all endpoints return 404 or are unreachable, or immediately on other errors
*/
export async function requestWithEndpointFallback<T>(
connection: Connection,
requestInfo: RequestInfo,
options?: { retry?: { maxRetries?: number } }
): Promise<T> {
const endpoints = ['', 'test.', 'dev.', 'stage.']; // Try production, test, dev, stage in that order
const endpoints = isInternalOrg(connection) ? ['', ...INTERNAL_API_ENDPOINTS] : [''];

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1. Worth addressing: the isInternalUrl() gate is unverified for stage orgs. SfdcUrl.isInternalUrl() (sfdx-core) matches only .vpod.*, .stm.*, .blitz.salesforce.com, .pc-rnd.*, .crm.dev, gs1.salesforce.com, and the localhost/.internal.salesforce.com suffixes. That covers test1/dev1 orgfarm orgs (*.test1.my.pc-rnd.salesforce.com). Nothing confirms that aws-stage1-useast2 orgs (forcedotcom/cli#3645, the reason stage. was added in #365) have a My Domain under one of those suffixes. If they look like customer domains, this PR silently brings the #3645 regression back.

Options, best first:

  • The named-user JWT bootstrap already returns api_instance_url (NamedUserJwtResponse in src/types.ts), which is unused today. If it holds https://stage.api.salesforce.com on stage orgs, it names the right gateway with no guessing. Worth checking what it returns on a test1 org and a stage org.
  • At minimum, an env override (e.g. SF_AGENT_API_ENDPOINTS=test.,dev.,stage.) as a way out for internal users.
  • Keep the confirmation request to the fix: @W-24143688 add stage.api.salesforce.com to Agent API endpoint fallback #365 author in the PR description, and don't merge until it's answered.

Customer sandboxes, scratch/develop orgs, Hyperforce orgs, and enhanced or custom domains all correctly go to api. only.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly fixed in 4f81ac1. api_instance_url from the named-user JWT is the org My Domain (the test fixture uses https://test.my.salesforce.com), not the gateway, so it cannot pick the gateway. Added the SF_AGENT_API_ENDPOINTS override (comma-separated prefixes, applies to any org, none disables) with tests. The #365 question for atulkc is in the PR body.

Comment thread src/utils.ts Outdated
continue; // Try next endpoint
}
// Not a 404, throw immediately
if (endpoint !== '' && statusCode === undefined) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2. Worth addressing: statusCode === undefined doesn't mean "no HTTP response." In jsforce (http-api.js getError), an error body that is JSON with a message becomes an HttpApiError whose name is the body's errorCode (e.g. INVALID_SESSION_ID). That error has no statusCode, and getHttpStatusCode falls back to ERROR_HTTP_* only when the body has no message. So a real 401/403/500 with a JSON body from test./dev./stage. is swallowed and reported as "Couldn't connect to …". That contradicts the PR description's claim that HTTP errors from any host are still thrown right away. Detect network failures directly instead:

const NETWORK_ERROR_CODES = new Set([
  'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET', 'UND_ERR_HEADERS_TIMEOUT',
  'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH',
]);
const isNetworkError = (err: unknown, depth = 0): boolean => {
  if (!err || typeof err !== 'object' || depth > 5) return false;
  const e = err as { code?: unknown; message?: unknown; cause?: unknown };
  if (typeof e.code === 'string' && NETWORK_ERROR_CODES.has(e.code)) return true;
  if (err instanceof TypeError && e.message === 'fetch failed') return true;
  return isNetworkError(e.cause, depth + 1);
};
Suggested change
if (endpoint !== '' && statusCode === undefined) {
if (endpoint !== '' && statusCode === undefined && isNetworkError(error)) {

Add a test: on an internal org, api. returns 404 and test. rejects with Object.assign(new Error('Session expired'), { name: 'INVALID_SESSION_ID', errorCode: 'INVALID_SESSION_ID' }). Assert that error is rethrown, not converted to AgentApiNotFound.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f81ac1. Added isNetworkError (connection error codes or TypeError: fetch failed, walking cause to depth 5); only those are skipped. INVALID_SESSION_ID and other HTTP errors from a fallback host are rethrown, with a test.

Comment thread test/utils.test.ts
expect(requestStub.callCount).to.equal(4);
});

it('should throw immediately when api.salesforce.com itself is unreachable', async () => {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3. Nit: missing branch tests.
(a) A non-404 HTTP error (e.g. ERROR_HTTP_500) on a fallback host is still rethrown. The current non-404 tests only fail on the primary host.
(b) On an internal org, all three fallbacks are unreachable. The message should read …from api.salesforce.com. Couldn't connect to test.api.salesforce.com, dev.api.salesforce.com, stage.api.salesforce.com.
(c) The case from inline 2.
(d) Optional: an *.stm.salesforce.com or *.crm.dev instance gets the fallback chain.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f81ac1. Added tests for a 503 and an INVALID_SESSION_ID error on a fallback host, all three fallbacks unreachable (exact message), and *.stm / *.crm.dev getting the chain. 2f0ab1c adds one for UND_ERR_INVALID_ARG.

Comment thread src/utils.ts Outdated
Comment on lines +836 to +838
if (requestPath.includes('/authoring/agents')) {
actions.push(
"'sf agent validate authoring-bundle' can pass on an org that can't publish: publishing uses a separate API that needs the org to be entitled to create agents."

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4. Nit: the publish hint states an unverified cause. "Needs the org to be entitled to create agents" comes from one repro (cli#3634), and nobody has confirmed it with the backend. Suggest hedging:

Suggested change
if (requestPath.includes('/authoring/agents')) {
actions.push(
"'sf agent validate authoring-bundle' can pass on an org that can't publish: publishing uses a separate API that needs the org to be entitled to create agents."
if (requestPath.includes('/authoring/agents')) {
actions.push(
"'sf agent validate authoring-bundle' can succeed on an org that can't publish: publishing calls a different Agent API endpoint, which may require additional Agentforce entitlements on the org."
);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f81ac1. The hint now reads "publishing calls a different Agent API endpoint, which may require additional Agentforce entitlements on the org."

Comment thread src/utils.ts
Comment on lines +832 to +835
const actions = [
'Make sure Agentforce is enabled in Setup and the org is licensed for it. Scratch orgs need the Einstein1AIPlatform feature in their definition file.',
`Make sure the user '${username}' has the necessary permissions and authorization to use Agentforce.`,
];

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5. Nit: for internal orgs a 404 is often routing, not licensing. When isInternalOrg(connection) is true, a 404 on every gateway is often the #3645 routing case. Consider adding an action such as "This org is on an internal instance; confirm which SFAP gateway it uses (Setup > GatewayHawkingInfo)". That keeps #365's intent of not misreading routing failures as auth failures.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f81ac1. Internal orgs get a routing action (confirm the SFAP gateway in Setup > GatewayHawkingInfo, or set SF_AGENT_API_ENDPOINTS). 2f0ab1c shows it for every org.

Comment thread src/utils.ts Outdated
unreachableEndpoints,
});
const username = connection.getUsername() ?? '';
const requestPath = requestInfo.url.replace(/^https:\/\/[^/]+/, '');

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6. Nit: requestPath keeps the query string. requestInfo.url.replace(/^https:\/\/[^/]+/, '') keeps ?… in the user-facing message. That's harmless today, but if a future caller puts IDs or tokens in the query, they'd end up in the error text. new URL(requestInfo.url).pathname, with a try/catch fallback, is safer.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f81ac1. The path now comes from new URL(url).pathname, with a regex fallback that drops the query string. Tested with ?a=b.

Detect real network errors instead of a missing statusCode, add the SF_AGENT_API_ENDPOINTS override, drop retries on fallback hosts, strip query strings from the error path, and add tests.

@nhalko-sf nhalko-sf left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pre-review, round 2 of 2 (an extra pair of eyes, not a gate). Verdict: approve with nits, no blockers.

4f81ac1 fixes all six round-1 findings, and the suggested maxRetries: 0 for fallback hosts is in and tested.

# Round-1 finding Status
1 isInternalUrl() gate unverified for stage orgs Mitigated: the SF_AGENT_API_ENDPOINTS override (with none to disable) is tested. The stage-domain question in the PR body is still open
2 statusCode === undefined swallows real HTTP errors Fixed: isNetworkError walks cause, and INVALID_SESSION_ID is rethrown and tested
3 Missing branch tests Fixed: 503 on a fallback host, all fallbacks unreachable, invalid session, .stm and .crm.dev
4 Publish hint stated an unverified cause Fixed (hedged)
5 Internal-org 404 is often routing, not licensing Fixed: the GatewayHawkingInfo action is added and tested
6 requestPath keeps the query string Fixed

The new findings are inline (1 worth addressing, 2 nits).

General (no line anchor)

  • PR body is stale: it doesn't mention the env override, the zero-retry fallback, or the GatewayHawkingInfo action, and "524 passing" predates the new tests.
  • CI: the unit-test jobs were still running at review time. Everything else is green.

Comment thread src/utils.ts Outdated
Comment on lines +884 to +886
if (fallbackEndpoints.length) {
actions.push(
'Confirm which SFAP gateway the org uses (Setup > GatewayHawkingInfo). To try specific gateways, set SF_AGENT_API_ENDPOINTS, for example "stage.,test.".'

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth addressing: the override hint never reaches the orgs that need it most. The SF_AGENT_API_ENDPOINTS / GatewayHawkingInfo hint only shows when fallbackEndpoints.length > 0. A stage org on a customer-style domain, which isn't recognized as internal (the #3645 case), gets [], so its 404 never mentions the override. Consider adding a short hint whenever the final error is a 404 and no fallbacks were tried. For example: "If this org is on an internal gateway (for example stage), set SF_AGENT_API_ENDPOINTS=stage. and retry." Add a test for a customer-domain org.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2f0ab1c. The gateway / SF_AGENT_API_ENDPOINTS action is now on every AgentApiNotFound, including customer-domain orgs. The production-org test asserts it.

Comment thread src/utils.ts
};

/**
* The fallback gateway prefixes to try after api.salesforce.com. SF_AGENT_API_ENDPOINTS (comma-separated,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: document the new knob. SF_AGENT_API_ENDPOINTS is user-facing but is only documented in this JSDoc and the error hint. Please add it to the PR body (and to the README or env-var docs, if the repo lists them). Mention that none disables the fallback and that it applies to every org, not just internal ones.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2f0ab1c. The JSDoc now says it applies to every org and that none disables the fallback, and the PR body documents it. The repo has no README or env-var list to extend.

Comment thread src/utils.ts Outdated
return isInternalOrg(connection) ? INTERNAL_API_ENDPOINTS : [];
};

const NETWORK_ERROR_CODES = /^(UND_ERR_|ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH)/;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: UND_ERR_ is broader than connect failures. It also matches UND_ERR_ABORTED, UND_ERR_INVALID_ARG, UND_ERR_RESPONSE_STATUS_CODE, and so on. An explicit list (UND_ERR_CONNECT_TIMEOUT, UND_ERR_SOCKET, UND_ERR_HEADERS_TIMEOUT, UND_ERR_BODY_TIMEOUT) keeps "Couldn't connect" accurate.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2f0ab1c. Explicit list: UND_ERR_CONNECT_TIMEOUT|SOCKET|HEADERS_TIMEOUT|BODY_TIMEOUT plus the ECONN*/ENOTFOUND/EAI_AGAIN/ETIMEDOUT/EHOSTUNREACH/ENETUNREACH codes. A test confirms UND_ERR_INVALID_ARG is rethrown.

@nhalko-sf

Copy link
Copy Markdown
Collaborator Author

Moved to a fork so it can be merged: continued in #404 (same commits).

@nhalko-sf nhalko-sf closed this Nov 21, 2026
@nhalko-sf
nhalko-sf deleted the nh/W-24023175-endpoint-fallback branch November 21, 2026 03:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants