@apifuse/provider-sdk 2.2.0-beta.66 → 2.2.0-beta.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/AUTHORING.md +28 -1
  2. package/CHANGELOG.md +8 -0
  3. package/README.md +8 -4
  4. package/bin/apifuse-record.ts +207 -31
  5. package/bin/apifuse-submit-check.ts +273 -74
  6. package/dist/cli/local-connection.d.ts +111 -0
  7. package/dist/cli/local-connection.js +151 -0
  8. package/dist/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
  9. package/dist/cli/templates/provider/README.md.tpl +17 -9
  10. package/dist/config/loader.d.ts +16 -0
  11. package/dist/config/loader.js +25 -8
  12. package/dist/error-resolution.d.ts +13 -0
  13. package/dist/error-resolution.js +72 -35
  14. package/dist/lint.d.ts +2 -0
  15. package/dist/lint.js +493 -2
  16. package/dist/runtime/executor.js +3 -0
  17. package/dist/runtime/http.d.ts +2 -0
  18. package/dist/runtime/http.js +2 -1
  19. package/dist/runtime/provider.d.ts +7 -0
  20. package/dist/runtime/provider.js +14 -0
  21. package/dist/server/index.d.ts +1 -0
  22. package/dist/server/serve-implementation.d.ts +2 -1
  23. package/dist/server/serve-implementation.js +43 -29
  24. package/dist/server/state-backend-report.d.ts +70 -0
  25. package/dist/server/state-backend-report.js +113 -0
  26. package/package.json +1 -1
  27. package/src/cli/local-connection.ts +221 -0
  28. package/src/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
  29. package/src/cli/templates/provider/README.md.tpl +17 -9
  30. package/src/config/loader.ts +49 -12
  31. package/src/error-resolution.ts +89 -35
  32. package/src/lint.ts +541 -1
  33. package/src/runtime/executor.ts +3 -0
  34. package/src/runtime/http.ts +2 -1
  35. package/src/runtime/provider.ts +15 -0
  36. package/src/server/index.ts +4 -0
  37. package/src/server/serve-implementation.ts +56 -30
  38. package/src/server/state-backend-report.ts +185 -0
@@ -1,37 +1,142 @@
1
1
  ---
2
2
  name: health-checks-and-fail-closed
3
- description: Writing health checks that can actually fail, and fail-closed guards at envelope and row level. Load before writing healthCheck blocks or error handling.
3
+ description: Writing health checks the platform monitor actually executes, and fail-closed guards at envelope and row level. Load before writing healthCheck blocks or error handling.
4
4
  ---
5
5
 
6
6
  # Health checks and fail-closed guards
7
7
 
8
- ## Health checks that can actually fail
9
- `Array.isArray(data.items)` alone can never fail. Every list operation's
10
- health check must be able to detect the zero-rows regression.
8
+ ## Only `scenario` is monitored in production
11
9
 
12
- Assertion contract (per SDK `HealthCheckCase`): THROW to fail the case
13
- (recorded as `down`); return `{ status: "degraded", label }` to flag without
14
- failing; return nothing for `ok`. There is no `"down"` return value.
10
+ A `healthCheck` case takes one of two mutually exclusive shapes, and they do
11
+ not run in the same place:
12
+
13
+ | field | executed by | when |
14
+ |---|---|---|
15
+ | `scenario` | the platform health monitor | every suite interval, in production |
16
+ | `assertions` | the provider runtime's own self-test | only when that endpoint is called |
17
+
18
+ The monitor runs a case's SERIALIZED scenario and nothing else: a closure
19
+ cannot cross the registry's serialization boundary. A case that carries only
20
+ `assertions` is still published as a probe, but its outcome is permanently
21
+ `unknown` / `monitoring_unavailable` — the operation reads as monitored on the
22
+ status page while nothing is ever checked. `apifuse check` warns about this
23
+ (`health-check-assertions-not-monitored`).
24
+
25
+ Anything that must be caught in production belongs in `scenario`. Keep
26
+ `assertions` for a local self-test, or drop it.
27
+
28
+ ## A scenario that can actually fail
29
+
30
+ `Array.isArray(data.items)` alone can never fail. Every list operation's probe
31
+ must be able to detect the zero-rows regression AND a mapper regression that
32
+ empties fields on a present row.
33
+
34
+ Step kinds: `operation` invokes, `assert` FAILS the probe (recorded `down`),
35
+ `guard` DEGRADES without failing it.
36
+
37
+ ```ts
38
+ // health-scenarios.ts
39
+ import { type AssertionExpression, defineHealthScenario } from "@apifuse/provider-sdk/provider";
40
+
41
+ export const PROBE_INPUT = { district: "<a guaranteed-dense, stable id>" } as const;
42
+
43
+ const response = (path: readonly (string | number)[]) => ({
44
+ ref: { namespace: "steps" as const, binding: "response", path: [...path] },
45
+ });
46
+
47
+ const evidence: AssertionExpression = {
48
+ kind: "all",
49
+ clauses: [
50
+ { kind: "predicate", operator: "status_2xx", actual: response(["status_code"]) },
51
+ // Dense query MUST return rows; zero rows = upstream contract drift.
52
+ { kind: "predicate", operator: "array_length_gte", actual: response(["data", "items"]), expected: 1 },
53
+ // A semantic field on a real row, so an emptying mapper regression fails too.
54
+ { kind: "predicate", operator: "non_empty", actual: response(["data", "items", 0, "name"]) },
55
+ ],
56
+ };
57
+
58
+ export const listItemsScenario = defineHealthScenario({
59
+ scenarioVersion: 2,
60
+ id: "list-items.dense-district",
61
+ display: {
62
+ titleKey: "health.operations.list-items.dense-district.title",
63
+ descriptionKey: "health.operations.list-items.dense-district.description",
64
+ },
65
+ schedule: { kind: "interval", intervalMs: 60 * 60_000, jitterMs: 0 },
66
+ timeoutMs: 15_000,
67
+ coversOperations: ["list-items"],
68
+ credentialRefs: [],
69
+ steps: [
70
+ { id: "read", result: "response", kind: "operation", operationId: "list-items", inputTemplate: { ...PROBE_INPUT } },
71
+ { id: "verify", result: "verified", kind: "assert", coversOperations: ["list-items"], expression: evidence },
72
+ ],
73
+ });
74
+ ```
15
75
 
16
76
  ```ts
17
- assertions: ({ status, data }) => {
18
- if (status !== 200) {
19
- throw new Error(`<op> request failed with status ${status}`);
20
- }
21
- if (!Array.isArray(data.items)) {
22
- throw new Error("<op> missing items array");
23
- }
24
- // Dense query MUST return rows; zero rows = upstream contract drift
25
- if (data.items.length === 0) {
26
- return { status: "degraded", label: "<op> dense query returned 0 rows" };
27
- }
77
+ // operations/list-items.ts
78
+ healthCheck: {
79
+ interval: "1h",
80
+ timeoutMs: 15_000,
81
+ cases: [{ name: "dense-district", input: { ...PROBE_INPUT }, scenario: listItemsScenario }],
28
82
  }
29
83
  ```
30
84
 
31
- - Choose health-check inputs that are guaranteed-dense (major city district,
32
- a stable well-known entity id). Verify the id still exists when picking it.
33
- - Also assert one semantic field on the first row (e.g. `items[0].name` is a
34
- non-empty string) so a mapper regression that empties fields degrades too.
85
+ - Choose probe inputs that are guaranteed-dense (major city district, a stable
86
+ well-known entity id). Verify the id still exists when picking it.
87
+ - `scenario.coversOperations` may only name the operation that owns the case.
88
+
89
+ ## Stale-if-error serves must be guarded, or an outage reads green
90
+
91
+ If the operation reads its upstream through `ctx.cache.getOrSet(..., {
92
+ staleIfErrorMs })`, an upstream outage is answered with HTTP 200 and a
93
+ well-formed, fully schema-valid body for the whole stale window. Every clause
94
+ over `status_code` and `data` still passes, so the probe rolls up `ok` while
95
+ the upstream is down, and only flips to `down` after the window expires — the
96
+ first minutes of every outage are reported as healthy.
97
+
98
+ `served_stale_cache` on the operation step result is the only operand that
99
+ separates a stale serve from a live read. It is always present, so the
100
+ reference resolves to `false` rather than raising `reference_unresolvable`.
101
+ Add ONE guard step per stale-if-error probe:
102
+
103
+ ```ts
104
+ {
105
+ id: "guard-list-items-freshness",
106
+ result: "freshness-guarded",
107
+ kind: "guard",
108
+ condition: {
109
+ kind: "predicate",
110
+ operator: "not_equals",
111
+ actual: { ref: { namespace: "steps" as const, binding: "response", path: ["served_stale_cache"] } },
112
+ expected: true,
113
+ },
114
+ onFail: {
115
+ attribute: [
116
+ {
117
+ operationId: "list-items",
118
+ status: "degraded",
119
+ reasonCode: "expected_absence",
120
+ reasonKey: "health.operations.list-items.dense-district.servedStaleCache",
121
+ },
122
+ ],
123
+ stop: "scenario",
124
+ },
125
+ }
126
+ ```
127
+
128
+ - `degraded`, not `down`: the cache policy is behaving as promised and callers
129
+ are still served; it is the upstream that is unavailable, and that has to be
130
+ visible instead of green.
131
+ - `expected_absence` is the only `reasonCode` the guard attribution schema
132
+ admits today, and it reads correctly here — the FRESH read is what was
133
+ absent. The tenant-facing wording lives in the localized `reasonKey`.
134
+ - Place the freshness guard BEFORE any row or emptiness guard. A stale serve
135
+ that happens to be empty would otherwise be attributed to the emptiness
136
+ reason, which is a confident answer to the wrong question.
137
+ - Do not change the handler for this. The envelope's `meta.stale` is written
138
+ by the serve layer, so `return result.value` discarding `result.meta` does
139
+ not suppress the signal.
35
140
 
36
141
  ## Fail-closed: envelope level
37
142
  - Upstream error headers/codes → structured `ProviderError` with a stable
@@ -51,6 +156,14 @@ array is non-empty, but every row normalizes to nothing.
51
156
  - Regression-test both layers separately: a bad envelope AND a good envelope
52
157
  with unmappable rows.
53
158
 
159
+ ## Self-test assertions (optional, not monitored)
160
+ A case without a `scenario` may carry an `assertions` lambda, executed only by
161
+ the provider runtime's own self-test. THROW to fail the case (recorded
162
+ `down`); return `{ status: "degraded", label }` to flag without failing;
163
+ return nothing for `ok`. There is no `"down"` return value. It MUST NOT touch
164
+ the scheduler, recorder, or any runtime type. Never use it as the only check
165
+ on an operation you need monitored.
166
+
54
167
  ## Error message hygiene
55
168
  `ProviderError.message` reaches the tenant verbatim. Never interpolate
56
169
  upstream free text that may contain personal data (names, phone numbers,
@@ -58,8 +171,10 @@ addresses); allowlist known code tokens and keep raw bodies in server-side
58
171
  details/logs only.
59
172
 
60
173
  ## Checklist
61
- - [ ] Every list op health check flags 0 rows on a dense query
174
+ - [ ] Every monitored operation's case carries `scenario` (not only `assertions`)
175
+ - [ ] Every list op probe fails on 0 rows for a dense query
62
176
  - [ ] One semantic field asserted on a real row
177
+ - [ ] Every `staleIfErrorMs` read has a `served_stale_cache` guard, placed first
63
178
  - [ ] Swallowed-error test exists (non-ok mock → handler rejects)
64
179
  - [ ] Non-empty upstream → zero normalized rows throws
65
180
  - [ ] No upstream free text in customer-facing error messages
@@ -137,8 +137,8 @@ Structured errors return an `error` object with `code`, `message`,
137
137
  ## Next steps
138
138
 
139
139
  1. Replace the sample `ping` operation with real upstream logic.
140
- 2. Once the real operation declares `upstream.baseUrl` and uses `ctx.http` or
141
- `ctx.stealth`, record a fixture with:
140
+ 2. Once the real operation calls the upstream through `ctx.http` or `ctx.stealth`
141
+ (absolute URLs, or relative ones under its `upstream.baseUrl`), record a fixture with:
142
142
  `bun run record -- --operation <operation> --params '<json-input>'`.
143
143
  3. Replace the starter `healthCheckUnsupported` with a real `healthCheck` for read-only upstream operations when safe.
144
144
  4. Extend tests and operation metadata until the provider is bounty-ready.
@@ -158,8 +158,14 @@ Every operation must declare exactly one of:
158
158
  The generated `ping` operation uses `healthCheckUnsupported` only because it is
159
159
  a local scaffold check, not a real upstream API probe.
160
160
 
161
- `healthCheck.cases[].assertions` receives `{ data, status, durationMs, meta }`.
162
- `data` is the parsed operation output. Use this shape in real operations:
161
+ A case carries either `scenario` or `assertions`, and only `scenario` is
162
+ executed in production: the platform health monitor runs a case's serialized
163
+ scenario and nothing else, because a closure cannot cross the registry's
164
+ serialization boundary. A case with only `assertions` still publishes a probe,
165
+ but its outcome is permanently `unknown` / `monitoring_unavailable` — the
166
+ operation reads as monitored while nothing is checked, and `apifuse check`
167
+ warns about it (`health-check-assertions-not-monitored`). Use this shape in
168
+ real operations:
163
169
 
164
170
  ```ts
165
171
  healthCheck: {
@@ -167,11 +173,13 @@ healthCheck: {
167
173
  cases: [{
168
174
  name: "lookup baseline",
169
175
  input: { q: "btc" },
170
- assertions: ({ data, status, durationMs }) => {
171
- if (status !== 200 || data.results.length === 0 || durationMs > 3000) {
172
- return { status: "degraded", label: "lookup baseline changed" };
173
- }
174
- },
176
+ scenario: lookupBaselineScenario, // defineHealthScenario({ ... })
175
177
  }],
176
178
  }
177
179
  ```
180
+
181
+ If the operation reads through `ctx.cache.getOrSet(..., { staleIfErrorMs })`,
182
+ add a guard step on the operation step result's `served_stale_cache` as well —
183
+ otherwise an upstream outage is answered with a schema-valid 200 and the probe
184
+ reports `ok` for the whole stale window. See
185
+ `.agents/skills/health-checks-and-fail-closed/SKILL.md` for both shapes.
@@ -255,25 +255,62 @@ const SMARTPROXY_ALLOCATOR_RETRY_BASE_MS = 25;
255
255
  const SMARTPROXY_EXTRACTION_CACHE_TTL_MS = 15_000;
256
256
  const SMARTPROXY_EXTRACTION_SOFT_REFRESH_MS = 10_000;
257
257
 
258
+ /** Env names that can supply a provider store's Redis URL. */
259
+ export type ProviderRedisUrlEnvName =
260
+ | typeof PROVIDER_STATE_REDIS_URL_ENV
261
+ | typeof PROVIDER_CACHE_REDIS_URL_ENV
262
+ | typeof REDIS_URL_ENV;
263
+
264
+ /** Which env name supplied a store's Redis URL, alongside the URL itself. */
265
+ export type ProviderRedisUrlResolution = {
266
+ readonly url: string;
267
+ /** The env name that actually supplied `url`. */
268
+ readonly envName: ProviderRedisUrlEnvName;
269
+ /**
270
+ * True when `url` came from a shared fallback env rather than the store's
271
+ * own. A state store on `fallback: true` is sharing an instance that was
272
+ * provisioned for something else (apifuse#2144).
273
+ */
274
+ readonly fallback: boolean;
275
+ };
276
+
277
+ // Precedence is declared once here so the URL accessors, the boot report and
278
+ // any future consumer can never disagree about which env wins.
279
+ const CACHE_REDIS_URL_PRECEDENCE = [PROVIDER_CACHE_REDIS_URL_ENV, REDIS_URL_ENV] as const;
280
+ const STATE_REDIS_URL_PRECEDENCE = [
281
+ PROVIDER_STATE_REDIS_URL_ENV,
282
+ PROVIDER_CACHE_REDIS_URL_ENV,
283
+ REDIS_URL_ENV,
284
+ ] as const;
285
+
286
+ function resolveRedisUrlFromEnv(
287
+ precedence: readonly ProviderRedisUrlEnvName[],
288
+ ): ProviderRedisUrlResolution | undefined {
289
+ for (const [index, envName] of precedence.entries()) {
290
+ const url = readDiagnosticEnv(envName)?.trim();
291
+ if (url) return { url, envName, fallback: index > 0 };
292
+ }
293
+ return undefined;
294
+ }
295
+
258
296
  function redisUrlFromEnv(): string | undefined {
259
- return (
260
- readDiagnosticEnv(PROVIDER_CACHE_REDIS_URL_ENV)?.trim() ||
261
- readDiagnosticEnv(REDIS_URL_ENV)?.trim() ||
262
- undefined
263
- );
297
+ return providerCacheRedisResolutionFromEnv()?.url;
298
+ }
299
+
300
+ export function providerCacheRedisResolutionFromEnv(): ProviderRedisUrlResolution | undefined {
301
+ return resolveRedisUrlFromEnv(CACHE_REDIS_URL_PRECEDENCE);
302
+ }
303
+
304
+ export function providerStateRedisResolutionFromEnv(): ProviderRedisUrlResolution | undefined {
305
+ return resolveRedisUrlFromEnv(STATE_REDIS_URL_PRECEDENCE);
264
306
  }
265
307
 
266
308
  export function providerCacheRedisUrlFromEnv(): string | undefined {
267
- return redisUrlFromEnv();
309
+ return providerCacheRedisResolutionFromEnv()?.url;
268
310
  }
269
311
 
270
312
  export function providerStateRedisUrlFromEnv(): string | undefined {
271
- return (
272
- readDiagnosticEnv(PROVIDER_STATE_REDIS_URL_ENV)?.trim() ||
273
- readDiagnosticEnv(PROVIDER_CACHE_REDIS_URL_ENV)?.trim() ||
274
- readDiagnosticEnv(REDIS_URL_ENV)?.trim() ||
275
- undefined
276
- );
313
+ return providerStateRedisResolutionFromEnv()?.url;
277
314
  }
278
315
 
279
316
  /** @internal Test-only hook for exercising shared proxy-cache behavior. */
@@ -1,3 +1,4 @@
1
+ import type { ProviderErrorCategory } from "./observability.js";
1
2
  import type { ProviderErrorStatus } from "./types.js";
2
3
 
3
4
  // This set suppresses the unregistered-provider-error-code signal for codes
@@ -120,11 +121,89 @@ export const SDK_RUNTIME_OWNED_ERROR_CODES = new Set([
120
121
  "not_found",
121
122
  ]);
122
123
 
124
+ /** One registered upstream code: the status the SDK serves and who failed. */
125
+ export type SdkUpstreamErrorCodeRegistration = {
126
+ readonly status: ProviderErrorStatus;
127
+ readonly category: ProviderErrorCategory;
128
+ };
129
+
130
+ // Registered codes that name an upstream outcome. A row states the status the
131
+ // SDK serves and the observability category together, so an upstream code
132
+ // cannot be registered without saying who failed. Serve reads the category
133
+ // for a `ProviderError` that carries one of these codes and no explicit
134
+ // `category`, and the public `source` follows from it (`sourceForCategory`).
135
+ // Without a row the category defaults to `provider_error` → `source:
136
+ // "apifuse"`, and the health monitor cannot tie a real upstream failure to the
137
+ // upstream: it publishes `monitoring_unavailable` instead of `down`.
138
+ //
139
+ // The category is `categoryForStatus(status)` unless the code names a
140
+ // narrower class than its status can: a schema change, a bot wall, an
141
+ // upstream refusal of the platform-managed key (served 400, see below).
142
+ // Every row is a code the fleet throws for something the upstream did or
143
+ // said; caller-side and SDK-internal codes stay in the table below.
144
+ export const SDK_UPSTREAM_ERROR_CODE_REGISTRY: ReadonlyMap<
145
+ string,
146
+ SdkUpstreamErrorCodeRegistration
147
+ > = new Map<string, SdkUpstreamErrorCodeRegistration>([
148
+ // The SDK's own unknown-operation and unknown-route throws reuse the
149
+ // not-found spellings; they set an explicit category and stay APIFuse's.
150
+ ["NOT_FOUND", { status: 404, category: "upstream_http" }],
151
+ ["not_found", { status: 404, category: "upstream_http" }],
152
+ ["NO_DATA", { status: 404, category: "upstream_http" }],
153
+ ["RATE_LIMITED", { status: 429, category: "upstream_rate_limited" }],
154
+ ["UPSTREAM_RATE_LIMIT", { status: 429, category: "upstream_rate_limited" }],
155
+ [
156
+ "LIMITED_NUMBER_OF_SERVICE_REQUESTS_EXCEEDS_ERROR",
157
+ { status: 429, category: "upstream_rate_limited" },
158
+ ],
159
+ // Deterministic upstream business refusal (honest-provider-error-
160
+ // contract): the upstream evaluated the request and said no under its
161
+ // own rules — a conflict with upstream state, never a 5xx.
162
+ ["UPSTREAM_REJECTED", { status: 409, category: "upstream_rejected" }],
163
+ ["UPSTREAM_ERROR", { status: 502, category: "upstream_http" }],
164
+ // The upstream's bot wall or request protection refused the request. The
165
+ // status says only "upstream"; the code says which kind.
166
+ ["BLOCKED", { status: 502, category: "anti_bot_blocked" }],
167
+ // Fleet-consensus provider codes. These are thrown by provider code, not
168
+ // by the SDK, so they are registered here (status mapping) and not in
169
+ // SDK_RUNTIME_OWNED_ERROR_CODES: an operation-declared status still wins,
170
+ // exactly as it does for UPSTREAM_ERROR and BLOCKED above. Registering
171
+ // them stops the fleet from re-declaring the same rows on every
172
+ // operation, and stops an undeclared throw from being served as 500.
173
+ //
174
+ // A platform-managed upstream service key the upstream refuses. With
175
+ // `auth.mode: "platform-managed"` the caller holds no credential, so 401
176
+ // ("re-authenticate") tells the caller to do something it cannot do, and
177
+ // 502 ("upstream is sick") promises a recovery that will never come. It is
178
+ // a deployment/config defect — the same class as MISSING_SECRET below,
179
+ // which is already an explicit 400 for that reason. The upstream is still
180
+ // the one refusing, so the category is `upstream_auth`; the gateway
181
+ // records it as `provider_error` for every non-`required` connection mode
182
+ // so the refusal stays provider-alertable.
183
+ ["UPSTREAM_AUTH_ERROR", { status: 400, category: "upstream_auth" }],
184
+ // The upstream changed its response shape and the provider cannot
185
+ // normalize it. 502 because the fault is upstream of us, non-retryable
186
+ // because a retry returns the same broken payload.
187
+ ["UPSTREAM_SCHEMA_ERROR", { status: 502, category: "upstream_schema_drift" }],
188
+ ]);
189
+
190
+ /**
191
+ * The category a registered upstream code carries when its `ProviderError`
192
+ * sets none. `undefined` for every other code, which keeps its existing
193
+ * default.
194
+ */
195
+ export function registeredUpstreamErrorCategory(
196
+ code: string | undefined,
197
+ ): ProviderErrorCategory | undefined {
198
+ return code === undefined ? undefined : SDK_UPSTREAM_ERROR_CODE_REGISTRY.get(code)?.category;
199
+ }
200
+
123
201
  // Canonical SDK status mapping for recognized provider-thrown error codes.
124
202
  // serve.ts toStatusCode consults this map (after operation-declared overrides
125
203
  // for non-SDK-owned codes), and the authoring lint treats these codes as
126
204
  // SDK-registered. Add new codes here instead of duplicating literals in
127
- // either consumer.
205
+ // either consumer — an upstream-attributed code goes in
206
+ // SDK_UPSTREAM_ERROR_CODE_REGISTRY above, which feeds this map.
128
207
  export const SDK_STATUS_MAPPED_PROVIDER_ERROR_CODES: ReadonlyMap<string, ProviderErrorStatus> =
129
208
  new Map<string, ProviderErrorStatus>([
130
209
  ["AUTH_REQUIRED", 401],
@@ -132,16 +211,6 @@ export const SDK_STATUS_MAPPED_PROVIDER_ERROR_CODES: ReadonlyMap<string, Provide
132
211
  // Unprovisioned declared secret: a deployment/config defect, never an
133
212
  // upstream failure — explicit 400.
134
213
  ["MISSING_SECRET", 400],
135
- ["NOT_FOUND", 404],
136
- ["not_found", 404],
137
- ["NO_DATA", 404],
138
- ["RATE_LIMITED", 429],
139
- ["UPSTREAM_RATE_LIMIT", 429],
140
- ["LIMITED_NUMBER_OF_SERVICE_REQUESTS_EXCEEDS_ERROR", 429],
141
- // Deterministic upstream business refusal (honest-provider-error-
142
- // contract): the upstream evaluated the request and said no under its
143
- // own rules — a conflict with upstream state, never a 5xx.
144
- ["UPSTREAM_REJECTED", 409],
145
214
  // Only an unverifiable or foreign handle is the caller's: key and binding
146
215
  // faults stay unmapped (500) because the engine host, not the caller, owns them.
147
216
  ["EGRESS_LEASE_INVALID", 409],
@@ -157,30 +226,11 @@ export const SDK_STATUS_MAPPED_PROVIDER_ERROR_CODES: ReadonlyMap<string, Provide
157
226
  ["HANDLE_EXPIRED", 410],
158
227
  ["HANDLE_COMMITTED", 409],
159
228
  ["HANDLE_BUSY", 409],
160
- ["UPSTREAM_ERROR", 502],
161
- ["BLOCKED", 502],
162
- // Fleet-consensus provider codes. These are thrown by provider code, not
163
- // by the SDK, so they are registered here (status mapping) and not in
164
- // SDK_RUNTIME_OWNED_ERROR_CODES: an operation-declared status still wins,
165
- // exactly as it does for UPSTREAM_ERROR and BLOCKED above. Registering
166
- // them stops the fleet from re-declaring the same three rows on every
167
- // operation, and stops an undeclared throw from being served as 500.
168
- //
169
- // A platform-managed upstream service key the upstream refuses. With
170
- // `auth.mode: "platform-managed"` the caller holds no credential, so 401
171
- // ("re-authenticate") tells the caller to do something it cannot do, and
172
- // 502 ("upstream is sick") promises a recovery that will never come. It is
173
- // a deployment/config defect — the same class as MISSING_SECRET above,
174
- // which is already an explicit 400 for that reason.
175
- ["UPSTREAM_AUTH_ERROR", 400],
176
- // The upstream changed its response shape and the provider cannot
177
- // normalize it. 502 because the fault is upstream of us, non-retryable
178
- // because a retry returns the same broken payload.
179
- ["UPSTREAM_SCHEMA_ERROR", 502],
180
- // Caller-side bad input rejected by the provider. The minority spellings
181
- // (INVALID_INPUT / VALIDATION_ERROR / BAD_REQUEST) are deliberately not
182
- // registered: they migrate to this spelling on the contract track, and
183
- // registering them here would freeze the divergence.
229
+ // Caller-side bad input rejected by the provider (fleet consensus, like
230
+ // UPSTREAM_AUTH_ERROR and UPSTREAM_SCHEMA_ERROR above). The minority
231
+ // spellings (INVALID_INPUT / VALIDATION_ERROR / BAD_REQUEST) are
232
+ // deliberately not registered: they migrate to this spelling on the
233
+ // contract track, and registering them here would freeze the divergence.
184
234
  ["INVALID_REQUEST", 400],
185
235
  ["OCR_UNAVAILABLE", 503],
186
236
  ["UNSUPPORTED_OCR_BACKEND", 503],
@@ -194,6 +244,10 @@ export const SDK_STATUS_MAPPED_PROVIDER_ERROR_CODES: ReadonlyMap<string, Provide
194
244
  // retry can clear, and a retryable 5xx there would turn one bad rollout
195
245
  // into gateway-driven load.
196
246
  ["PROVIDER_ENGINE_UNAVAILABLE", 503],
247
+ ...Array.from(
248
+ SDK_UPSTREAM_ERROR_CODE_REGISTRY,
249
+ ([code, registration]) => [code, registration.status] as const,
250
+ ),
197
251
  ]);
198
252
 
199
253
  // Canonical retryability for the fleet-consensus codes registered above.