@oxy.so/contracts 1.0.0

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 (147) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/dist/cjs/.tsbuildinfo +1 -0
  4. package/dist/cjs/accountGraph.js +489 -0
  5. package/dist/cjs/agency.js +439 -0
  6. package/dist/cjs/browserHub.js +215 -0
  7. package/dist/cjs/civic.js +163 -0
  8. package/dist/cjs/commonsSignIn.js +59 -0
  9. package/dist/cjs/deviceBoot.js +50 -0
  10. package/dist/cjs/deviceDirectory.js +189 -0
  11. package/dist/cjs/devicePairing.js +138 -0
  12. package/dist/cjs/deviceSession.js +164 -0
  13. package/dist/cjs/emailAgentContext.js +32 -0
  14. package/dist/cjs/followGraph.js +28 -0
  15. package/dist/cjs/identity.js +258 -0
  16. package/dist/cjs/inboxPush.js +24 -0
  17. package/dist/cjs/index.js +618 -0
  18. package/dist/cjs/inference/accountBilling.js +334 -0
  19. package/dist/cjs/inference/aliaModelRelease.js +262 -0
  20. package/dist/cjs/inference/attribution.js +106 -0
  21. package/dist/cjs/inference/catalogue.js +487 -0
  22. package/dist/cjs/inference/entitlement.js +217 -0
  23. package/dist/cjs/inference/errors.js +309 -0
  24. package/dist/cjs/inference/identifiers.js +224 -0
  25. package/dist/cjs/inference/inbox.js +105 -0
  26. package/dist/cjs/inference/modelDocumentation.js +433 -0
  27. package/dist/cjs/inference/money.js +188 -0
  28. package/dist/cjs/inference/priceVersion.js +110 -0
  29. package/dist/cjs/inference/providerConnection.js +455 -0
  30. package/dist/cjs/inference/request.js +477 -0
  31. package/dist/cjs/inference/routingPolicy.js +318 -0
  32. package/dist/cjs/inference/streamEvents.js +258 -0
  33. package/dist/cjs/inference/usage.js +329 -0
  34. package/dist/cjs/inference/version.js +105 -0
  35. package/dist/cjs/keyRecovery.js +91 -0
  36. package/dist/cjs/keyRotation.js +75 -0
  37. package/dist/cjs/links.js +68 -0
  38. package/dist/cjs/moderationReputation.js +298 -0
  39. package/dist/cjs/oauth.js +66 -0
  40. package/dist/cjs/oxyRecordTypes.js +71 -0
  41. package/dist/cjs/protocol.js +53 -0
  42. package/dist/cjs/recommendations.js +168 -0
  43. package/dist/cjs/reputation.js +297 -0
  44. package/dist/cjs/sessionStatus.js +121 -0
  45. package/dist/cjs/transparency.js +89 -0
  46. package/dist/cjs/updates.js +252 -0
  47. package/dist/cjs/userInvalidation.js +89 -0
  48. package/dist/cjs/userResponse.js +245 -0
  49. package/dist/cjs/username.js +290 -0
  50. package/dist/cjs/webauthn.js +71 -0
  51. package/dist/esm/.tsbuildinfo +1 -0
  52. package/dist/esm/accountGraph.js +480 -0
  53. package/dist/esm/agency.js +436 -0
  54. package/dist/esm/browserHub.js +212 -0
  55. package/dist/esm/civic.js +160 -0
  56. package/dist/esm/commonsSignIn.js +56 -0
  57. package/dist/esm/deviceBoot.js +47 -0
  58. package/dist/esm/deviceDirectory.js +186 -0
  59. package/dist/esm/devicePairing.js +135 -0
  60. package/dist/esm/deviceSession.js +161 -0
  61. package/dist/esm/emailAgentContext.js +29 -0
  62. package/dist/esm/followGraph.js +27 -0
  63. package/dist/esm/identity.js +255 -0
  64. package/dist/esm/inboxPush.js +21 -0
  65. package/dist/esm/index.js +172 -0
  66. package/dist/esm/inference/accountBilling.js +331 -0
  67. package/dist/esm/inference/aliaModelRelease.js +259 -0
  68. package/dist/esm/inference/attribution.js +103 -0
  69. package/dist/esm/inference/catalogue.js +484 -0
  70. package/dist/esm/inference/entitlement.js +214 -0
  71. package/dist/esm/inference/errors.js +306 -0
  72. package/dist/esm/inference/identifiers.js +221 -0
  73. package/dist/esm/inference/inbox.js +102 -0
  74. package/dist/esm/inference/modelDocumentation.js +430 -0
  75. package/dist/esm/inference/money.js +185 -0
  76. package/dist/esm/inference/priceVersion.js +107 -0
  77. package/dist/esm/inference/providerConnection.js +452 -0
  78. package/dist/esm/inference/request.js +474 -0
  79. package/dist/esm/inference/routingPolicy.js +315 -0
  80. package/dist/esm/inference/streamEvents.js +255 -0
  81. package/dist/esm/inference/usage.js +326 -0
  82. package/dist/esm/inference/version.js +102 -0
  83. package/dist/esm/keyRecovery.js +88 -0
  84. package/dist/esm/keyRotation.js +72 -0
  85. package/dist/esm/links.js +65 -0
  86. package/dist/esm/moderationReputation.js +295 -0
  87. package/dist/esm/oauth.js +63 -0
  88. package/dist/esm/oxyRecordTypes.js +68 -0
  89. package/dist/esm/protocol.js +50 -0
  90. package/dist/esm/recommendations.js +165 -0
  91. package/dist/esm/reputation.js +293 -0
  92. package/dist/esm/sessionStatus.js +118 -0
  93. package/dist/esm/transparency.js +86 -0
  94. package/dist/esm/updates.js +249 -0
  95. package/dist/esm/userInvalidation.js +85 -0
  96. package/dist/esm/userResponse.js +240 -0
  97. package/dist/esm/username.js +283 -0
  98. package/dist/esm/webauthn.js +68 -0
  99. package/dist/types/.tsbuildinfo +1 -0
  100. package/dist/types/accountGraph.d.ts +378 -0
  101. package/dist/types/agency.d.ts +2162 -0
  102. package/dist/types/browserHub.d.ts +856 -0
  103. package/dist/types/civic.d.ts +338 -0
  104. package/dist/types/commonsSignIn.d.ts +58 -0
  105. package/dist/types/deviceBoot.d.ts +74 -0
  106. package/dist/types/deviceDirectory.d.ts +1317 -0
  107. package/dist/types/devicePairing.d.ts +130 -0
  108. package/dist/types/deviceSession.d.ts +411 -0
  109. package/dist/types/emailAgentContext.d.ts +248 -0
  110. package/dist/types/followGraph.d.ts +150 -0
  111. package/dist/types/identity.d.ts +402 -0
  112. package/dist/types/inboxPush.d.ts +30 -0
  113. package/dist/types/index.d.ts +100 -0
  114. package/dist/types/inference/accountBilling.d.ts +738 -0
  115. package/dist/types/inference/aliaModelRelease.d.ts +609 -0
  116. package/dist/types/inference/attribution.d.ts +176 -0
  117. package/dist/types/inference/catalogue.d.ts +1618 -0
  118. package/dist/types/inference/entitlement.d.ts +519 -0
  119. package/dist/types/inference/errors.d.ts +242 -0
  120. package/dist/types/inference/identifiers.d.ts +182 -0
  121. package/dist/types/inference/inbox.d.ts +374 -0
  122. package/dist/types/inference/modelDocumentation.d.ts +1603 -0
  123. package/dist/types/inference/money.d.ts +185 -0
  124. package/dist/types/inference/priceVersion.d.ts +182 -0
  125. package/dist/types/inference/providerConnection.d.ts +968 -0
  126. package/dist/types/inference/request.d.ts +2800 -0
  127. package/dist/types/inference/routingPolicy.d.ts +616 -0
  128. package/dist/types/inference/streamEvents.d.ts +950 -0
  129. package/dist/types/inference/usage.d.ts +1164 -0
  130. package/dist/types/inference/version.d.ts +102 -0
  131. package/dist/types/keyRecovery.d.ts +138 -0
  132. package/dist/types/keyRotation.d.ts +103 -0
  133. package/dist/types/links.d.ts +96 -0
  134. package/dist/types/moderationReputation.d.ts +487 -0
  135. package/dist/types/oauth.d.ts +86 -0
  136. package/dist/types/oxyRecordTypes.d.ts +62 -0
  137. package/dist/types/protocol.d.ts +86 -0
  138. package/dist/types/recommendations.d.ts +542 -0
  139. package/dist/types/reputation.d.ts +457 -0
  140. package/dist/types/sessionStatus.d.ts +231 -0
  141. package/dist/types/transparency.d.ts +392 -0
  142. package/dist/types/updates.d.ts +545 -0
  143. package/dist/types/userInvalidation.d.ts +94 -0
  144. package/dist/types/userResponse.d.ts +1706 -0
  145. package/dist/types/username.d.ts +265 -0
  146. package/dist/types/webauthn.d.ts +77 -0
  147. package/package.json +87 -0
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Product entitlements — the interface a first-party product (Alia) queries to
3
+ * learn what an account is entitled to, WITHOUT learning anything it could
4
+ * mistake for a balance.
5
+ *
6
+ * ## The separation this file is
7
+ *
8
+ * #972 states the failure mode outright: confusing a product subscription with
9
+ * pay-as-you-go inference usage. So the two live in disjoint shapes here, and
10
+ * the separation is structural rather than documented:
11
+ *
12
+ * - {@link productEntitlementSchema} carries PLAN and ALLOWANCES. Allowances
13
+ * are whole integer counts of a product entitlement (API credits, included
14
+ * requests) — `z.number().int()`, never `exactDecimalSchema`, so an allowance
15
+ * is not even the same TYPE as money and cannot be added to one.
16
+ * - `accountBalanceSchema` (in `accountBilling.ts`) carries MONEY, as exact
17
+ * decimal strings.
18
+ *
19
+ * There is no field anywhere that is both, and no schema that sums them. A
20
+ * consumer wanting "what can this account do right now" reads both sections and
21
+ * presents both; a consumer that only wanted one is not handed the other in a
22
+ * form it can accidentally arithmetic.
23
+ *
24
+ * ## Allowances do not change what a request COSTS
25
+ *
26
+ * An Alia plan may include an allowance of inference. Oxy still records the
27
+ * exact underlying cost of every request against the account's ledger — the
28
+ * allowance is a PRODUCT-side entitlement that decides what Alia charges its
29
+ * user, not a discount applied to the receipt. That is why
30
+ * {@link productEntitlementSchema} names no price and no currency: a plan that
31
+ * could restate the cost of a request would be a second pricing authority, and
32
+ * a receipt has exactly one.
33
+ *
34
+ * ## Cost centres
35
+ *
36
+ * A first-party cost centre IS an Oxy project account — `users.kind` already has
37
+ * `project`, and an application's `ownerAccountId` already points at one. So a
38
+ * cost centre adds a LABEL and a slug to an account rather than a parallel
39
+ * hierarchy, which is the epic's "do not add a second organization model" rule
40
+ * applied to internal accounting.
41
+ *
42
+ * Decided in: docs/adr/0014-account-billing-and-entitlements.md.
43
+ */
44
+ import { z } from 'zod';
45
+ import { oxyAccountIdSchema } from './identifiers.js';
46
+ import { billingModeSchema } from './accountBilling.js';
47
+ import { currencyCodeSchema, exactDecimalSchema } from './money.js';
48
+ /* -------------------------------------------------------------------------- */
49
+ /* Plans and allowances */
50
+ /* -------------------------------------------------------------------------- */
51
+ /**
52
+ * The statuses a subscription may be mirrored in.
53
+ *
54
+ * All of the processor's, not just the ones this platform sells: a mirror that
55
+ * cannot represent what it mirrors freezes at its previous value, and a
56
+ * subscription the processor moved to `paused` would keep granting a plan
57
+ * nobody is paying for.
58
+ */
59
+ export const PRODUCT_PLAN_STATUSES = [
60
+ 'active',
61
+ 'canceled',
62
+ 'incomplete',
63
+ 'incomplete_expired',
64
+ 'past_due',
65
+ 'paused',
66
+ 'trialing',
67
+ 'unpaid',
68
+ ];
69
+ export const productPlanStatusSchema = z.enum(PRODUCT_PLAN_STATUSES);
70
+ /**
71
+ * The statuses that mean the plan is LIVE.
72
+ *
73
+ * Exported because "is this entitlement in force" must have one answer across
74
+ * Oxy and every product consuming it — a consumer deriving its own list is how
75
+ * `past_due` comes to be honoured in one place and refused in another.
76
+ */
77
+ export const LIVE_PRODUCT_PLAN_STATUSES = ['active', 'trialing'];
78
+ /**
79
+ * One allowance included in a plan.
80
+ *
81
+ * `remaining` is optional and absent means "not metered against this allowance
82
+ * here" — NOT zero. A consumer that read an absent allowance as exhausted would
83
+ * refuse a user who has spent nothing.
84
+ */
85
+ export const planAllowanceSchema = z
86
+ .object({
87
+ /** A stable machine name, e.g. `api_credits_per_month`. */
88
+ key: z.string().regex(/^[a-z][a-z0-9_]{0,62}$/),
89
+ /** Whole units included per period. Never money. */
90
+ included: z.number().int().nonnegative().safe(),
91
+ remaining: z.number().int().nonnegative().safe().optional(),
92
+ })
93
+ .strict();
94
+ /**
95
+ * The plan an account is on, if any.
96
+ *
97
+ * `price` is deliberately absent. What a customer pays for their plan is the
98
+ * processor's record and this platform's `billing_transactions`; restating it
99
+ * here would put a second price authority in the one interface whose whole job
100
+ * is to keep product pricing and inference cost apart.
101
+ */
102
+ export const productPlanSchema = z
103
+ .object({
104
+ id: z.string().min(1).max(64),
105
+ name: z.string().min(1).max(120),
106
+ status: productPlanStatusSchema,
107
+ live: z.boolean(),
108
+ currentPeriodStart: z.string().datetime(),
109
+ currentPeriodEnd: z.string().datetime(),
110
+ cancelAtPeriodEnd: z.boolean(),
111
+ allowances: z.array(planAllowanceSchema),
112
+ })
113
+ .strict();
114
+ /* -------------------------------------------------------------------------- */
115
+ /* Pay-as-you-go position */
116
+ /* -------------------------------------------------------------------------- */
117
+ /**
118
+ * The account's inference-spend position, summarised for a product consumer.
119
+ *
120
+ * A REDUCTION of `accountBillingStateSchema`, not a copy: a product asking "may
121
+ * this account run another request" needs to know whether spending is possible
122
+ * and roughly how much room is left, and does not need the bucket breakdown.
123
+ * `promotionalBalance` and `purchasedBalance` are still separate — the rule that
124
+ * a grant and a purchase are never one number does not relax because the
125
+ * consumer is first-party.
126
+ */
127
+ export const payAsYouGoEntitlementSchema = z
128
+ .object({
129
+ /** The account that actually pays — the nearest ancestor with a profile. */
130
+ billingAccountId: oxyAccountIdSchema,
131
+ currency: currencyCodeSchema,
132
+ billingMode: billingModeSchema,
133
+ purchasedBalance: exactDecimalSchema,
134
+ promotionalBalance: exactDecimalSchema,
135
+ availableToSpend: exactDecimalSchema,
136
+ /** False when the profile is suspended, closed, or out of room. */
137
+ canSpend: z.boolean(),
138
+ })
139
+ .strict();
140
+ /* -------------------------------------------------------------------------- */
141
+ /* Cost centres */
142
+ /* -------------------------------------------------------------------------- */
143
+ export const COST_CENTER_STATUSES = ['active', 'retired'];
144
+ export const costCenterStatusSchema = z.enum(COST_CENTER_STATUSES);
145
+ /**
146
+ * An internal cost centre — an Oxy account that first-party spend is attributed
147
+ * to, with a stable slug so a report can name it without an id.
148
+ *
149
+ * The account IS the cost centre; this shape only labels it. There is no
150
+ * `parentId` here for the same reason: the account graph already has one, and a
151
+ * second parent link would be a second hierarchy that can disagree with it.
152
+ */
153
+ export const costCenterSchema = z
154
+ .object({
155
+ /** See `version.ts`: this shape is served to Console and to Alia. */
156
+ schemaVersion: z.literal(1),
157
+ accountId: oxyAccountIdSchema,
158
+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/),
159
+ label: z.string().min(1).max(120),
160
+ status: costCenterStatusSchema,
161
+ createdAt: z.string().datetime(),
162
+ updatedAt: z.string().datetime(),
163
+ })
164
+ .strict();
165
+ /**
166
+ * What one cost centre spent over a window.
167
+ *
168
+ * `billedAmount` comes from settled receipts — the FINANCIAL ledger — never from
169
+ * telemetry sums, per #972 workstream 8. `requestCount` is a count of receipts,
170
+ * so the two are always about the same set of rows.
171
+ */
172
+ export const costCenterSpendSchema = z
173
+ .object({
174
+ /** See `version.ts`: this shape is served to Console and to Alia. */
175
+ schemaVersion: z.literal(1),
176
+ costCenter: costCenterSchema,
177
+ currency: currencyCodeSchema,
178
+ periodStart: z.string().datetime(),
179
+ periodEnd: z.string().datetime(),
180
+ billedAmount: exactDecimalSchema,
181
+ requestCount: z.number().int().nonnegative().safe(),
182
+ })
183
+ .strict();
184
+ /* -------------------------------------------------------------------------- */
185
+ /* The interface Alia queries */
186
+ /* -------------------------------------------------------------------------- */
187
+ /**
188
+ * Everything a product needs to decide what an account may do, in one read.
189
+ *
190
+ * The three sections never merge:
191
+ *
192
+ * - `plan` + `allowances` — the product subscription.
193
+ * - `payAsYouGo` — inference money. `null` when the account has no billing
194
+ * profile anywhere up its ancestry, which is a REAL and distinct state from a
195
+ * zero balance: nobody has decided who pays for this account yet.
196
+ * - `costCenter` — where first-party spend is booked, `null` for a customer.
197
+ */
198
+ export const productEntitlementSchema = z
199
+ .object({
200
+ /** See `version.ts`: this shape is served to Console and to Alia. */
201
+ schemaVersion: z.literal(1),
202
+ accountId: oxyAccountIdSchema,
203
+ plan: productPlanSchema.nullable(),
204
+ /**
205
+ * Allowances in force right now, whether they came from a plan or from the
206
+ * platform's own free tier. Whole counts; never money.
207
+ */
208
+ allowances: z.array(planAllowanceSchema),
209
+ payAsYouGo: payAsYouGoEntitlementSchema.nullable(),
210
+ costCenter: costCenterSchema.nullable(),
211
+ /** When this view was computed. Entitlements are eventually consistent. */
212
+ resolvedAt: z.string().datetime(),
213
+ })
214
+ .strict();
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Inference errors and retryability.
3
+ *
4
+ * One closed set of codes, shared by the Oxy public edge, the data plane and
5
+ * every SDK.
6
+ * Closed because the alternative — a free-form `code` string — makes a client's
7
+ * error handling a guess about the producer's spelling, and makes "is this
8
+ * worth retrying" a decision every consumer re-derives from prose.
9
+ *
10
+ * Retryability is carried explicitly and is CONSTRAINED by the code: a code
11
+ * that can never succeed on a bare retry (an invalid request, a denied
12
+ * permission, an insufficient balance) cannot claim `retryable: true`. Without
13
+ * that constraint the field is advisory, and one producer setting it optimistically
14
+ * turns every client into a retry storm against a request that will never pass.
15
+ *
16
+ * The provider passthrough exists so a customer can see what the upstream said
17
+ * without Oxy having to interpret every provider's error vocabulary — but it is
18
+ * the single most likely place for an upstream credential to escape, because
19
+ * provider errors routinely echo the request that caused them. It is therefore
20
+ * a `.strict()` object of four fields with no room for headers or a request
21
+ * body, and its free text is refused if it looks like it contains a credential.
22
+ *
23
+ * Decided in: docs/adr/0010-public-api-compatibility.md.
24
+ */
25
+ import { z } from 'zod';
26
+ import { inferenceProviderSlugSchema, requestIdSchema } from './identifiers.js';
27
+ /**
28
+ * The closed set of inference error codes.
29
+ *
30
+ * Grouped by who must act: the caller (`invalid_request` … `idempotency_conflict`),
31
+ * the account owner (`insufficient_balance`, `spending_limit_exceeded`,
32
+ * `quota_exceeded`, `byok_credential_invalid`), routing/permission policy
33
+ * (`policy_violation`, `commercial_permission_denied`, `no_route_available`),
34
+ * and the platform or its upstreams (everything from `deployment_unavailable`).
35
+ *
36
+ * The platform group is NOT uniformly retryable, and that is the point of
37
+ * `provider_credential_invalid` sitting in it: an upstream that refuses the
38
+ * PLATFORM's own credential fails every identical retry until an operator
39
+ * rotates a key, so classifying it as `provider_error` would send every client
40
+ * into a retry loop against a request that cannot succeed.
41
+ *
42
+ * `provider_billing_refused` is in that group for the same reason and was found
43
+ * the same way — an upstream declining to bill OXY (Anthropic answers 402) has
44
+ * to be distinguishable from the customer's own balance running out, or the
45
+ * error tells them to go and top up an account that is not the one at fault.
46
+ */
47
+ export const INFERENCE_ERROR_CODES = [
48
+ 'invalid_request',
49
+ 'authentication_failed',
50
+ 'permission_denied',
51
+ 'insufficient_scope',
52
+ 'model_not_found',
53
+ 'unsupported_modality',
54
+ 'context_length_exceeded',
55
+ 'request_too_large',
56
+ 'output_limit_exceeded',
57
+ 'idempotency_conflict',
58
+ 'insufficient_balance',
59
+ 'spending_limit_exceeded',
60
+ 'quota_exceeded',
61
+ 'byok_credential_invalid',
62
+ 'policy_violation',
63
+ 'commercial_permission_denied',
64
+ 'no_route_available',
65
+ 'upstream_content_filtered',
66
+ 'cancelled',
67
+ 'rate_limited',
68
+ 'deployment_unavailable',
69
+ 'provider_error',
70
+ 'provider_timeout',
71
+ 'provider_overloaded',
72
+ 'provider_credential_invalid',
73
+ 'provider_billing_refused',
74
+ 'service_unavailable',
75
+ 'internal_error',
76
+ ];
77
+ export const inferenceErrorCodeSchema = z.enum(INFERENCE_ERROR_CODES);
78
+ /**
79
+ * Codes for which an identical retried request cannot succeed.
80
+ *
81
+ * `rate_limited` and `quota_exceeded` sit on opposite sides of this line
82
+ * deliberately: a rate limit clears on its own within the window the response
83
+ * names, while a quota is an account-level ceiling that only a human raises.
84
+ * `cancelled` is here because the caller already withdrew the request; a client
85
+ * that retries it is contradicting its own cancellation.
86
+ *
87
+ * `byok_credential_invalid` and `provider_credential_invalid` are the same
88
+ * failure seen from the two sides of the BYOK boundary — the customer's own
89
+ * upstream credential and the platform's — and they are two codes rather than
90
+ * one because only the first names an action the customer can take. Both are
91
+ * non-retryable for the same reason: a credential an upstream has refused keeps
92
+ * being refused until somebody replaces it.
93
+ *
94
+ * `quota_exceeded` and `provider_billing_refused` divide along the same line:
95
+ * both are money, but one is the CUSTOMER's ceiling and the other is Oxy's
96
+ * account with an upstream. Reporting the second as the first is retryability-
97
+ * correct and diagnostically wrong, which is the worst combination — it reads
98
+ * as actionable and the action does nothing.
99
+ */
100
+ export const NON_RETRYABLE_INFERENCE_ERROR_CODES = [
101
+ 'invalid_request',
102
+ 'authentication_failed',
103
+ 'permission_denied',
104
+ 'insufficient_scope',
105
+ 'model_not_found',
106
+ 'unsupported_modality',
107
+ 'context_length_exceeded',
108
+ 'request_too_large',
109
+ 'output_limit_exceeded',
110
+ 'idempotency_conflict',
111
+ 'insufficient_balance',
112
+ 'spending_limit_exceeded',
113
+ 'quota_exceeded',
114
+ 'byok_credential_invalid',
115
+ 'policy_violation',
116
+ 'commercial_permission_denied',
117
+ 'no_route_available',
118
+ 'upstream_content_filtered',
119
+ 'cancelled',
120
+ 'provider_credential_invalid',
121
+ 'provider_billing_refused',
122
+ ];
123
+ const NON_RETRYABLE_CODE_SET = new Set(NON_RETRYABLE_INFERENCE_ERROR_CODES);
124
+ /* -------------------------------------------------------------------------- */
125
+ /* Credential-shaped text */
126
+ /* -------------------------------------------------------------------------- */
127
+ /**
128
+ * A run of characters long enough and opaque enough to BE a credential.
129
+ *
130
+ * The alphabet every bearer token, API key and base64/base64url secret is
131
+ * written in. The LENGTH floors below are what keep this from being an entropy
132
+ * heuristic: nothing here fires on a short word, so `authorization: none` and
133
+ * `api_key=***` read as what they are.
134
+ */
135
+ const OPAQUE_ALPHABET = '[A-Za-z0-9][A-Za-z0-9._~+/=-]';
136
+ /**
137
+ * Words a producer substitutes FOR a credential.
138
+ *
139
+ * Excluded at the value position so a message whose secret has already been
140
+ * replaced is accepted. That acceptance is deliberate and is half the fix for
141
+ * issue #1027: the previous pattern refused `Authorization: [redacted]` — a
142
+ * correctly redacted string — which is precisely what pushed a producer into
143
+ * redacting the MARKER instead, and a marker-redacted string carries the secret
144
+ * and passes.
145
+ */
146
+ const PLACEHOLDER_WORDS = 'redacted|removed|hidden|masked|scrubbed|elided|omitted|filtered|sanitized|sanitised|none|null|undefined|empty';
147
+ /** A value position whose contents are a placeholder rather than a secret. */
148
+ const NOT_A_PLACEHOLDER = `(?!(?:${PLACEHOLDER_WORDS})\\b)`;
149
+ /**
150
+ * Header and parameter names that carry a credential, as any provider spells
151
+ * them.
152
+ *
153
+ * The prefix group is the whole point of the rewrite: `authorization` and
154
+ * `api_key` were matched literally, so `x-api-key`, `anthropic-api-key`,
155
+ * `x-goog-api-key` and `proxy-authorization` — the spellings an upstream
156
+ * actually echoes — went unrecognised.
157
+ */
158
+ const CREDENTIAL_NAME = '(?:[a-z0-9]{1,20}[-_]){0,3}(?:api[-_]?(?:key|token|secret)|authorization|auth[-_]?(?:token|key)?|access[-_]?token|id[-_]?token|refresh[-_]?token|bearer[-_]?token|secret[-_]?key|private[-_]?key|client[-_]?secret|session[-_]?(?:id|key|token)|passwords?|passwd|cookie|credentials?|tokens?|secrets?)';
159
+ /** An auth scheme sitting between the marker and the value. */
160
+ const AUTH_SCHEME = '(?:(?:bearer|basic|token|apikey|digest)\\s+)?';
161
+ /**
162
+ * The four ways a credential is recognisable in free text.
163
+ *
164
+ * Each is checked independently, so removing one signal does not clear the
165
+ * string — which is the failure #1027 reported. All four are load-bearing:
166
+ * `inference.errors.test.ts` has a case that only one of them catches, and
167
+ * deleting any one entry turns a test red.
168
+ */
169
+ const CREDENTIAL_PATTERNS = [
170
+ // 1. A credential-bearing name ASSIGNED a value that is long enough to be a
171
+ // credential. The value is anchored to the separator so a placeholder at
172
+ // that position ends the match rather than being skipped over.
173
+ new RegExp(`(?:^|[^a-z0-9])${CREDENTIAL_NAME}["']?\\s*[:=]\\s*["']?${AUTH_SCHEME}${NOT_A_PLACEHOLDER}${OPAQUE_ALPHABET}{7,}`, 'i'),
174
+ // 2. A bearer token with no marker in front of it, which is how an upstream
175
+ // quotes the header value alone.
176
+ new RegExp(`\\bbearer\\s+${NOT_A_PLACEHOLDER}${OPAQUE_ALPHABET}{7,}`, 'i'),
177
+ // 3. Token grammars that ARE credentials wherever they appear, marker or not.
178
+ // This is the layer that survives a producer stripping the marker, and it
179
+ // is a closed list of issued shapes rather than an entropy score, so a
180
+ // request id or a base64 image fragment is unaffected.
181
+ //
182
+ // Case-SENSITIVE on purpose: `AKIA`, `AIza` and `gh[pousr]_` are issued in
183
+ // exactly that case, and matching them case-insensitively would start
184
+ // firing on ordinary words.
185
+ /\b(?:sk-[A-Za-z0-9_-]{8,}|[sprk]k_(?:live|test)_[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|ASIA[0-9A-Z]{12,}|AIza[0-9A-Za-z_-]{20,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|xox[abeprs]-[A-Za-z0-9-]{10,}|glpat-[A-Za-z0-9_-]{16,}|npm_[A-Za-z0-9]{20,}|eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,})/,
186
+ // 4. A redaction placeholder standing NEXT TO a surviving opaque value — the
187
+ // exact residue of the span redaction in #1027 (`{x-[redacted] <key>}`).
188
+ // A correct redaction puts the placeholder WHERE the value was, so the two
189
+ // never appear side by side; a marker-span redaction leaves them adjacent.
190
+ // Both signals are required, which is what keeps an ordinary redacted
191
+ // message from being refused.
192
+ new RegExp(`(?:[[<({]\\s*(?:${PLACEHOLDER_WORDS})[^\\])}>]{0,16}[\\])}>]|\\*{3,})[^A-Za-z0-9]{0,4}${OPAQUE_ALPHABET}{11,}`, 'i'),
193
+ ];
194
+ /**
195
+ * Free text that is safe to hand a customer: bounded, and refused if it still
196
+ * looks like it carries a credential. Applied to BOTH the Oxy message and the
197
+ * upstream one — a leak is no less a leak for having been written by a provider.
198
+ *
199
+ * ## This is a last-resort REFUSAL, not protection
200
+ *
201
+ * A pattern over the OUTPUT cannot be the control that keeps a credential out of
202
+ * an error, and a producer that treats it as one has the hole #1027 reported.
203
+ * The only reliable control is redacting the KNOWN SECRET VALUE at the point
204
+ * where the producer still holds the bytes it sent — which is an adapter's job
205
+ * and is available to nobody else. This refinement exists to catch what that
206
+ * control missed, and nothing here is a licence to skip it.
207
+ *
208
+ * Two rules follow, and they are the whole reason this text is longer than the
209
+ * pattern it describes:
210
+ *
211
+ * - **Never redact by replacing the span this pattern matched.** The span is
212
+ * the MARKER; the secret is what follows it. OxyHQ/Kaana#3 measured the
213
+ * result: `{x-api-key: <key>}` is refused, `{x-[redacted] <key>}` was
214
+ * accepted, and both carry the key. Redaction made the leak worse by
215
+ * converting "this string is dangerous" into "this string is fine".
216
+ * - **This package deliberately ships no redaction helper.** One keyed on these
217
+ * patterns would rebuild the same defect one layer up, and one that took the
218
+ * secret as an argument would only restate what the producer already has.
219
+ *
220
+ * What it still cannot see, stated so nobody relies on it: a credential with no
221
+ * marker, no issued-token prefix and no placeholder beside it is bytes that look
222
+ * like a request id, and refusing those means refusing request ids.
223
+ */
224
+ export const safeErrorTextSchema = z
225
+ .string()
226
+ .min(1)
227
+ .max(2000)
228
+ .refine((value) => !CREDENTIAL_PATTERNS.some((pattern) => pattern.test(value)), 'error text must not contain credential-shaped material');
229
+ /**
230
+ * A coarse classification of an upstream failure (ADR 0010's `upstreamCategory`).
231
+ *
232
+ * Distinct from {@link providerErrorPassthroughSchema}, which carries the
233
+ * upstream's OWN code and text: this is Oxy's reading of what kind of failure it
234
+ * was, in a vocabulary that is the same across every provider, so a client can
235
+ * branch on it without knowing who served the request.
236
+ */
237
+ export const upstreamErrorCategorySchema = z.enum([
238
+ 'rate_limit',
239
+ 'quota',
240
+ 'timeout',
241
+ 'overloaded',
242
+ 'server_error',
243
+ 'content_filter',
244
+ 'invalid_request',
245
+ 'authentication',
246
+ 'unknown',
247
+ ]);
248
+ /**
249
+ * What the upstream provider said, reduced to the four fields a customer can
250
+ * act on.
251
+ *
252
+ * `.strict()` is the security control here, not a tidiness preference: it means
253
+ * a producer cannot widen this by attaching `requestHeaders`, `curl`, `body` or
254
+ * `raw` and have it silently pass. Adding a field is a contract change with a
255
+ * version bump and a review, which is the point.
256
+ */
257
+ export const providerErrorPassthroughSchema = z
258
+ .object({
259
+ provider: inferenceProviderSlugSchema,
260
+ /** The upstream HTTP status, when the upstream spoke HTTP. */
261
+ status: z.number().int().min(100).max(599).optional(),
262
+ /** The upstream's own error code, verbatim and uninterpreted. */
263
+ code: z.string().max(128).optional(),
264
+ /** The upstream's message, subject to the same credential refusal. */
265
+ message: safeErrorTextSchema.optional(),
266
+ })
267
+ .strict();
268
+ /**
269
+ * The error body every inference surface returns and every stream error event
270
+ * carries.
271
+ *
272
+ * `requestId` is always present — an error a customer cannot correlate with a
273
+ * log line is an error they have to reproduce to report.
274
+ */
275
+ export const inferenceErrorSchema = z
276
+ .object({
277
+ /** See `version.ts`: this shape appears alone on the wire, so it is versioned. */
278
+ schemaVersion: z.literal(1),
279
+ code: inferenceErrorCodeSchema,
280
+ message: safeErrorTextSchema,
281
+ retryable: z.boolean(),
282
+ requestId: requestIdSchema,
283
+ /** How long to wait before retrying. Only meaningful when `retryable`. */
284
+ retryAfterMs: z.number().int().nonnegative().safe().optional(),
285
+ /** The request field at fault, for `invalid_request`. */
286
+ param: z.string().max(128).optional(),
287
+ /** Present only when an upstream provider was reached and failed. */
288
+ upstreamCategory: upstreamErrorCategorySchema.optional(),
289
+ providerError: providerErrorPassthroughSchema.optional(),
290
+ })
291
+ .superRefine((error, ctx) => {
292
+ if (error.retryable && NON_RETRYABLE_CODE_SET.has(error.code)) {
293
+ ctx.addIssue({
294
+ code: z.ZodIssueCode.custom,
295
+ path: ['retryable'],
296
+ message: `${error.code} can never succeed on an identical retry, so it cannot be retryable`,
297
+ });
298
+ }
299
+ if (error.retryAfterMs !== undefined && !error.retryable) {
300
+ ctx.addIssue({
301
+ code: z.ZodIssueCode.custom,
302
+ path: ['retryAfterMs'],
303
+ message: 'retryAfterMs tells a client when to retry, so it requires retryable: true',
304
+ });
305
+ }
306
+ });