@oxyhq/contracts 0.26.0 → 0.28.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 (52) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/accountGraph.js +4 -3
  3. package/dist/cjs/index.js +186 -1
  4. package/dist/cjs/inference/accountBilling.js +334 -0
  5. package/dist/cjs/inference/attribution.js +106 -0
  6. package/dist/cjs/inference/catalogue.js +482 -0
  7. package/dist/cjs/inference/entitlement.js +217 -0
  8. package/dist/cjs/inference/errors.js +210 -0
  9. package/dist/cjs/inference/identifiers.js +197 -0
  10. package/dist/cjs/inference/money.js +188 -0
  11. package/dist/cjs/inference/priceVersion.js +110 -0
  12. package/dist/cjs/inference/providerConnection.js +142 -0
  13. package/dist/cjs/inference/request.js +288 -0
  14. package/dist/cjs/inference/routingPolicy.js +213 -0
  15. package/dist/cjs/inference/streamEvents.js +219 -0
  16. package/dist/cjs/inference/usage.js +297 -0
  17. package/dist/cjs/inference/version.js +85 -0
  18. package/dist/esm/.tsbuildinfo +1 -1
  19. package/dist/esm/accountGraph.js +4 -3
  20. package/dist/esm/index.js +54 -0
  21. package/dist/esm/inference/accountBilling.js +331 -0
  22. package/dist/esm/inference/attribution.js +103 -0
  23. package/dist/esm/inference/catalogue.js +479 -0
  24. package/dist/esm/inference/entitlement.js +214 -0
  25. package/dist/esm/inference/errors.js +207 -0
  26. package/dist/esm/inference/identifiers.js +194 -0
  27. package/dist/esm/inference/money.js +185 -0
  28. package/dist/esm/inference/priceVersion.js +107 -0
  29. package/dist/esm/inference/providerConnection.js +139 -0
  30. package/dist/esm/inference/request.js +285 -0
  31. package/dist/esm/inference/routingPolicy.js +210 -0
  32. package/dist/esm/inference/streamEvents.js +216 -0
  33. package/dist/esm/inference/usage.js +294 -0
  34. package/dist/esm/inference/version.js +82 -0
  35. package/dist/types/.tsbuildinfo +1 -1
  36. package/dist/types/accountGraph.d.ts +6 -5
  37. package/dist/types/index.d.ts +27 -0
  38. package/dist/types/inference/accountBilling.d.ts +738 -0
  39. package/dist/types/inference/attribution.d.ts +176 -0
  40. package/dist/types/inference/catalogue.d.ts +1612 -0
  41. package/dist/types/inference/entitlement.d.ts +519 -0
  42. package/dist/types/inference/errors.d.ts +206 -0
  43. package/dist/types/inference/identifiers.d.ts +157 -0
  44. package/dist/types/inference/money.d.ts +185 -0
  45. package/dist/types/inference/priceVersion.d.ts +182 -0
  46. package/dist/types/inference/providerConnection.d.ts +297 -0
  47. package/dist/types/inference/request.d.ts +2364 -0
  48. package/dist/types/inference/routingPolicy.d.ts +426 -0
  49. package/dist/types/inference/streamEvents.d.ts +906 -0
  50. package/dist/types/inference/usage.d.ts +1139 -0
  51. package/dist/types/inference/version.d.ts +82 -0
  52. package/package.json +1 -1
@@ -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,207 @@
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
+ export const INFERENCE_ERROR_CODES = [
43
+ 'invalid_request',
44
+ 'authentication_failed',
45
+ 'permission_denied',
46
+ 'insufficient_scope',
47
+ 'model_not_found',
48
+ 'unsupported_modality',
49
+ 'context_length_exceeded',
50
+ 'request_too_large',
51
+ 'output_limit_exceeded',
52
+ 'idempotency_conflict',
53
+ 'insufficient_balance',
54
+ 'spending_limit_exceeded',
55
+ 'quota_exceeded',
56
+ 'byok_credential_invalid',
57
+ 'policy_violation',
58
+ 'commercial_permission_denied',
59
+ 'no_route_available',
60
+ 'upstream_content_filtered',
61
+ 'cancelled',
62
+ 'rate_limited',
63
+ 'deployment_unavailable',
64
+ 'provider_error',
65
+ 'provider_timeout',
66
+ 'provider_overloaded',
67
+ 'provider_credential_invalid',
68
+ 'service_unavailable',
69
+ 'internal_error',
70
+ ];
71
+ export const inferenceErrorCodeSchema = z.enum(INFERENCE_ERROR_CODES);
72
+ /**
73
+ * Codes for which an identical retried request cannot succeed.
74
+ *
75
+ * `rate_limited` and `quota_exceeded` sit on opposite sides of this line
76
+ * deliberately: a rate limit clears on its own within the window the response
77
+ * names, while a quota is an account-level ceiling that only a human raises.
78
+ * `cancelled` is here because the caller already withdrew the request; a client
79
+ * that retries it is contradicting its own cancellation.
80
+ *
81
+ * `byok_credential_invalid` and `provider_credential_invalid` are the same
82
+ * failure seen from the two sides of the BYOK boundary — the customer's own
83
+ * upstream credential and the platform's — and they are two codes rather than
84
+ * one because only the first names an action the customer can take. Both are
85
+ * non-retryable for the same reason: a credential an upstream has refused keeps
86
+ * being refused until somebody replaces it.
87
+ */
88
+ export const NON_RETRYABLE_INFERENCE_ERROR_CODES = [
89
+ 'invalid_request',
90
+ 'authentication_failed',
91
+ 'permission_denied',
92
+ 'insufficient_scope',
93
+ 'model_not_found',
94
+ 'unsupported_modality',
95
+ 'context_length_exceeded',
96
+ 'request_too_large',
97
+ 'output_limit_exceeded',
98
+ 'idempotency_conflict',
99
+ 'insufficient_balance',
100
+ 'spending_limit_exceeded',
101
+ 'quota_exceeded',
102
+ 'byok_credential_invalid',
103
+ 'policy_violation',
104
+ 'commercial_permission_denied',
105
+ 'no_route_available',
106
+ 'upstream_content_filtered',
107
+ 'cancelled',
108
+ 'provider_credential_invalid',
109
+ ];
110
+ const NON_RETRYABLE_CODE_SET = new Set(NON_RETRYABLE_INFERENCE_ERROR_CODES);
111
+ /**
112
+ * Text that looks like it carries a credential.
113
+ *
114
+ * A deliberately narrow set of literal markers — the shapes upstream providers
115
+ * actually echo — rather than an entropy heuristic, which would reject
116
+ * legitimate error text (a request id, a base64 image fragment) and teach
117
+ * producers to strip messages until they pass.
118
+ */
119
+ const CREDENTIAL_LIKE_TEXT = /(?:bearer\s+[a-z0-9._~+/=-]{8,}|authorization\s*[:=]|api[_-]?key\s*[:=]|\bsk-[a-z0-9_-]{8,}|\bsk_(?:live|test)_[a-z0-9]{8,})/i;
120
+ /**
121
+ * Free text that is safe to hand a customer: bounded, and refused outright if a
122
+ * credential marker appears in it. Applied to BOTH the Oxy message and the
123
+ * upstream one — a leak is no less a leak for having been written by a provider.
124
+ */
125
+ export const safeErrorTextSchema = z
126
+ .string()
127
+ .min(1)
128
+ .max(2000)
129
+ .refine((value) => !CREDENTIAL_LIKE_TEXT.test(value), 'error text must not contain credential-shaped material');
130
+ /**
131
+ * A coarse classification of an upstream failure (ADR 0010's `upstreamCategory`).
132
+ *
133
+ * Distinct from {@link providerErrorPassthroughSchema}, which carries the
134
+ * upstream's OWN code and text: this is Oxy's reading of what kind of failure it
135
+ * was, in a vocabulary that is the same across every provider, so a client can
136
+ * branch on it without knowing who served the request.
137
+ */
138
+ export const upstreamErrorCategorySchema = z.enum([
139
+ 'rate_limit',
140
+ 'quota',
141
+ 'timeout',
142
+ 'overloaded',
143
+ 'server_error',
144
+ 'content_filter',
145
+ 'invalid_request',
146
+ 'authentication',
147
+ 'unknown',
148
+ ]);
149
+ /**
150
+ * What the upstream provider said, reduced to the four fields a customer can
151
+ * act on.
152
+ *
153
+ * `.strict()` is the security control here, not a tidiness preference: it means
154
+ * a producer cannot widen this by attaching `requestHeaders`, `curl`, `body` or
155
+ * `raw` and have it silently pass. Adding a field is a contract change with a
156
+ * version bump and a review, which is the point.
157
+ */
158
+ export const providerErrorPassthroughSchema = z
159
+ .object({
160
+ provider: inferenceProviderSlugSchema,
161
+ /** The upstream HTTP status, when the upstream spoke HTTP. */
162
+ status: z.number().int().min(100).max(599).optional(),
163
+ /** The upstream's own error code, verbatim and uninterpreted. */
164
+ code: z.string().max(128).optional(),
165
+ /** The upstream's message, subject to the same credential refusal. */
166
+ message: safeErrorTextSchema.optional(),
167
+ })
168
+ .strict();
169
+ /**
170
+ * The error body every inference surface returns and every stream error event
171
+ * carries.
172
+ *
173
+ * `requestId` is always present — an error a customer cannot correlate with a
174
+ * log line is an error they have to reproduce to report.
175
+ */
176
+ export const inferenceErrorSchema = z
177
+ .object({
178
+ /** See `version.ts`: this shape appears alone on the wire, so it is versioned. */
179
+ schemaVersion: z.literal(1),
180
+ code: inferenceErrorCodeSchema,
181
+ message: safeErrorTextSchema,
182
+ retryable: z.boolean(),
183
+ requestId: requestIdSchema,
184
+ /** How long to wait before retrying. Only meaningful when `retryable`. */
185
+ retryAfterMs: z.number().int().nonnegative().safe().optional(),
186
+ /** The request field at fault, for `invalid_request`. */
187
+ param: z.string().max(128).optional(),
188
+ /** Present only when an upstream provider was reached and failed. */
189
+ upstreamCategory: upstreamErrorCategorySchema.optional(),
190
+ providerError: providerErrorPassthroughSchema.optional(),
191
+ })
192
+ .superRefine((error, ctx) => {
193
+ if (error.retryable && NON_RETRYABLE_CODE_SET.has(error.code)) {
194
+ ctx.addIssue({
195
+ code: z.ZodIssueCode.custom,
196
+ path: ['retryable'],
197
+ message: `${error.code} can never succeed on an identical retry, so it cannot be retryable`,
198
+ });
199
+ }
200
+ if (error.retryAfterMs !== undefined && !error.retryable) {
201
+ ctx.addIssue({
202
+ code: z.ZodIssueCode.custom,
203
+ path: ['retryAfterMs'],
204
+ message: 'retryAfterMs tells a client when to retry, so it requires retryable: true',
205
+ });
206
+ }
207
+ });
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Identifiers, references and wire primitives shared by every Oxy↔data-plane
3
+ * inference contract.
4
+ *
5
+ * Two kinds of identifier live here, and the difference matters:
6
+ *
7
+ * - **Principal identifiers** owned by Oxy (`accountId`, `applicationId`,
8
+ * `credentialId`, the optional delegated `userId`). The data plane may store
9
+ * them as immutable references; it never owns, mints or mutates them.
10
+ * - **Catalogue references** (`<publisher>/<model>`, `<publisher>/<model>@<revision>`,
11
+ * a routing-profile slug). These are the strings a customer types, so their
12
+ * grammar is part of the public contract, not an implementation detail.
13
+ *
14
+ * Platform-agnostic — zod only. Every regex here is plain ASCII: this package
15
+ * is imported by React Native apps running on Hermes, which rejects Unicode
16
+ * property escapes (`\p{…}`) at runtime.
17
+ *
18
+ * Decided in: docs/adr/0007-canonical-request-attribution.md, docs/adr/0008-catalogue-concept-separation.md.
19
+ */
20
+ import { z } from 'zod';
21
+ /* -------------------------------------------------------------------------- */
22
+ /* Principal identifiers */
23
+ /* -------------------------------------------------------------------------- */
24
+ /**
25
+ * An Oxy account id — the account that owns the workload and is financially
26
+ * responsible for it.
27
+ *
28
+ * Branded, and that brand is load-bearing rather than decorative: it is the
29
+ * type-level half of the rule that a delegated end-user identity can never
30
+ * become the billing identity (see {@link delegatedUserIdSchema} and
31
+ * `billingPrincipalSchema`). A plain `string` — and therefore any id read out
32
+ * of a header, a JWT claim or a request body — is not assignable to it; the
33
+ * only way to obtain one is to parse a value through this schema.
34
+ */
35
+ export const oxyAccountIdSchema = z.string().min(1).max(64).brand();
36
+ /**
37
+ * A delegated end-user identity (Alia's `X-Oxy-User-Id`), branded with a
38
+ * DIFFERENT brand from {@link oxyAccountIdSchema} so the two cannot be
39
+ * substituted for one another in either direction, in any consumer, without a
40
+ * cast that review would catch.
41
+ *
42
+ * It exists for attribution and product-side personalisation only. It is never
43
+ * a billing principal, never an access-control principal, and its presence
44
+ * never changes which account is charged.
45
+ */
46
+ export const delegatedUserIdSchema = z.string().min(1).max(64).brand();
47
+ /**
48
+ * An Oxy `Application._id`. Not branded: no invariant in this contract turns on
49
+ * confusing it with another id, and brand inflation costs every producer a
50
+ * parse call for no safety. The two ids above are branded because ADR 0007's
51
+ * rule is exactly that they must not be interchangeable.
52
+ */
53
+ export const oxyApplicationIdSchema = z.string().min(1).max(64);
54
+ /** An Oxy `ApplicationCredential._id` — the credential used for this request. */
55
+ export const oxyCredentialIdSchema = z.string().min(1).max(64);
56
+ /**
57
+ * A request id allocated by the Oxy EDGE, at admission and BEFORE
58
+ * authentication, so that a request rejected for a bad credential is as
59
+ * traceable as one that was served (ADR 0007, and step 1 of ADR 0010's edge
60
+ * order). It is required on the inbound envelope, which is what makes the data
61
+ * plane a consumer of this id rather than its source: the data plane echoes it
62
+ * on every stream event, on the usage report and on anything it can be asked
63
+ * about later.
64
+ *
65
+ * Correlates the Oxy edge, the data plane, the financial ledger and the
66
+ * customer-visible receipt, so it appears on every stream event and every
67
+ * ledger record.
68
+ */
69
+ export const requestIdSchema = z.string().min(1).max(128);
70
+ /**
71
+ * A generation id generated by the data plane, present when a request produced
72
+ * a generation that can be looked up later (`GET /v1/generations/:id`).
73
+ */
74
+ export const generationIdSchema = z.string().min(1).max(128);
75
+ /**
76
+ * A caller-supplied idempotency key. Every reserve/settle/refund call is keyed
77
+ * on one so a retry, a redelivered event or a duplicated webhook can never
78
+ * charge twice.
79
+ */
80
+ export const idempotencyKeySchema = z.string().min(1).max(255);
81
+ /** Credential environments. A credential is issued into exactly one of them. */
82
+ export const inferenceEnvironmentSchema = z.enum(['development', 'staging', 'production']);
83
+ /* -------------------------------------------------------------------------- */
84
+ /* Wire primitives */
85
+ /* -------------------------------------------------------------------------- */
86
+ /**
87
+ * An instant, as an ISO 8601 string in UTC (`2026-08-15T09:41:00.000Z`).
88
+ *
89
+ * Validated rather than left free-form — unlike the session contracts, which
90
+ * carry legacy expiry strings no consumer interprets, every instant here is
91
+ * read: a reservation expires, a price version starts applying, a receipt is
92
+ * settled. One canonical spelling (UTC, `Z`) so two records that describe the
93
+ * same moment compare and sort as equal, which a mix of offsets would not.
94
+ */
95
+ export const inferenceTimestampSchema = z.string().datetime();
96
+ /**
97
+ * A calendar DATE with no instant attached (`2026-05-01`) — a knowledge cutoff
98
+ * or a release date, which are published as days and become wrong when a
99
+ * timezone is invented for them.
100
+ */
101
+ export const inferenceDateSchema = z
102
+ .string()
103
+ .regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/, 'must be an ISO 8601 calendar date (YYYY-MM-DD)');
104
+ /** An absolute https URL, for model cards, licenses and provider documentation. */
105
+ export const inferenceHttpsUrlSchema = z
106
+ .string()
107
+ .max(2048)
108
+ .regex(/^https:\/\/[^\s]+$/, 'must be an absolute https URL');
109
+ /* -------------------------------------------------------------------------- */
110
+ /* Catalogue references */
111
+ /* -------------------------------------------------------------------------- */
112
+ /** One path segment of a canonical model id: a lowercase, URL-safe slug. */
113
+ const SLUG_PATTERN = '[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?';
114
+ /** A revision label. Case-preserving, because upstream revisions often are. */
115
+ const REVISION_PATTERN = '[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?';
116
+ /** A publisher slug, e.g. `openai`, `anthropic`, `meta`, `alia`. */
117
+ export const publisherSlugSchema = z
118
+ .string()
119
+ .max(64)
120
+ .regex(new RegExp(`^${SLUG_PATTERN}$`), 'publisher must be a lowercase URL-safe slug');
121
+ /** A model slug within its publisher's namespace, e.g. `gpt-5`, `llama-3.1-70b`. */
122
+ export const modelSlugSchema = z
123
+ .string()
124
+ .max(64)
125
+ .regex(new RegExp(`^${SLUG_PATTERN}$`), 'model must be a lowercase URL-safe slug');
126
+ /**
127
+ * A canonical model id, `<publisher>/<model>`. This names a MODEL — a
128
+ * long-lived product identity whose behaviour changes as revisions ship. It
129
+ * does not name a revision, a deployment or a provider.
130
+ */
131
+ export const modelIdSchema = z
132
+ .string()
133
+ .max(129)
134
+ .regex(new RegExp(`^${SLUG_PATTERN}/${SLUG_PATTERN}$`), 'model id must be <publisher>/<model>');
135
+ /** An immutable revision label, unique within its model, e.g. `2026-05-01`. */
136
+ export const modelRevisionLabelSchema = z
137
+ .string()
138
+ .max(64)
139
+ .regex(new RegExp(`^${REVISION_PATTERN}$`), 'revision must be a URL-safe label');
140
+ /**
141
+ * A model reference as a customer writes it: `<publisher>/<model>` (the model's
142
+ * current revision, chosen by Oxy) or `<publisher>/<model>@<revision>` (an
143
+ * immutable revision the customer pinned).
144
+ *
145
+ * Both forms name a CONCRETE MODEL. Neither can name a routing profile — see
146
+ * {@link routingProfileSlugSchema} — which is what makes "a request for a
147
+ * concrete model is never silently replaced with a different model" a
148
+ * distinction the type system can carry rather than a convention.
149
+ */
150
+ export const modelReferenceSchema = z
151
+ .string()
152
+ .max(194)
153
+ .regex(new RegExp(`^${SLUG_PATTERN}/${SLUG_PATTERN}(?:@${REVISION_PATTERN})?$`), 'model reference must be <publisher>/<model> or <publisher>/<model>@<revision>');
154
+ /**
155
+ * A routing-profile slug, e.g. `auto`, `fast`, `quality`.
156
+ *
157
+ * Deliberately refuses a `/`, so a profile can never be written in the shape of
158
+ * a model id and no caller can be confused about whether they asked for a
159
+ * concrete model or for Oxy to choose one. Modes like `auto`/`fast`/`quality`
160
+ * are profiles or product presets; they are never model objects.
161
+ */
162
+ export const routingProfileSlugSchema = z
163
+ .string()
164
+ .max(64)
165
+ .regex(new RegExp(`^${SLUG_PATTERN}$`), 'routing profile must be a lowercase URL-safe slug');
166
+ /** An inference provider slug, e.g. `openai`, `bedrock`, `oxy-hosted`. */
167
+ export const inferenceProviderSlugSchema = z
168
+ .string()
169
+ .max(64)
170
+ .regex(new RegExp(`^${SLUG_PATTERN}$`), 'provider must be a lowercase URL-safe slug');
171
+ /**
172
+ * A deployment/endpoint id. Opaque to customers: which concrete endpoint served
173
+ * a request is the data plane's operational detail, and only the customer-safe
174
+ * subset of it is ever attributed back (see the catalogue's serving-boundary
175
+ * rules).
176
+ */
177
+ export const deploymentIdSchema = z.string().min(1).max(128);
178
+ /**
179
+ * A region identifier, e.g. `us-west-2`, `eu-central-1`. Free-form rather than
180
+ * a closed enum because the set is provider-defined and grows without any
181
+ * contract change; residency policies match on exact strings.
182
+ */
183
+ export const inferenceRegionSchema = z
184
+ .string()
185
+ .max(64)
186
+ .regex(new RegExp(`^${SLUG_PATTERN}$`), 'region must be a lowercase URL-safe slug');
187
+ /**
188
+ * The publisher namespace reserved for models Alia actually owns or derives.
189
+ *
190
+ * `alia/*` is never a re-badged third-party route and never a prompt preset —
191
+ * enforcing that is the job of `modelSchema`'s provenance refinement, which
192
+ * this constant exists to be checked against.
193
+ */
194
+ export const RESERVED_ALIA_PUBLISHER = 'alia';