@oxyhq/contracts 0.28.0 → 0.30.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 (43) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/identity.js +33 -1
  3. package/dist/cjs/index.js +20 -7
  4. package/dist/cjs/inference/aliaModelRelease.js +250 -0
  5. package/dist/cjs/inference/catalogue.js +1 -4
  6. package/dist/cjs/inference/errors.js +108 -9
  7. package/dist/cjs/inference/identifiers.js +23 -3
  8. package/dist/cjs/inference/request.js +188 -5
  9. package/dist/cjs/inference/routingPolicy.js +81 -2
  10. package/dist/cjs/inference/streamEvents.js +38 -1
  11. package/dist/cjs/inference/usage.js +32 -1
  12. package/dist/cjs/inference/version.js +24 -4
  13. package/dist/esm/.tsbuildinfo +1 -1
  14. package/dist/esm/identity.js +32 -0
  15. package/dist/esm/index.js +8 -3
  16. package/dist/esm/inference/aliaModelRelease.js +247 -0
  17. package/dist/esm/inference/catalogue.js +2 -5
  18. package/dist/esm/inference/errors.js +108 -9
  19. package/dist/esm/inference/identifiers.js +22 -2
  20. package/dist/esm/inference/request.js +189 -6
  21. package/dist/esm/inference/routingPolicy.js +81 -2
  22. package/dist/esm/inference/streamEvents.js +38 -1
  23. package/dist/esm/inference/usage.js +32 -1
  24. package/dist/esm/inference/version.js +24 -4
  25. package/dist/types/.tsbuildinfo +1 -1
  26. package/dist/types/identity.d.ts +59 -1
  27. package/dist/types/index.d.ts +7 -5
  28. package/dist/types/inference/accountBilling.d.ts +26 -26
  29. package/dist/types/inference/aliaModelRelease.d.ts +597 -0
  30. package/dist/types/inference/catalogue.d.ts +6 -6
  31. package/dist/types/inference/entitlement.d.ts +4 -4
  32. package/dist/types/inference/errors.d.ts +46 -10
  33. package/dist/types/inference/identifiers.d.ts +20 -2
  34. package/dist/types/inference/money.d.ts +4 -4
  35. package/dist/types/inference/priceVersion.d.ts +14 -14
  36. package/dist/types/inference/providerConnection.d.ts +4 -4
  37. package/dist/types/inference/request.d.ts +291 -5
  38. package/dist/types/inference/routingPolicy.d.ts +109 -13
  39. package/dist/types/inference/streamEvents.d.ts +84 -48
  40. package/dist/types/inference/usage.d.ts +103 -79
  41. package/dist/types/inference/version.d.ts +24 -4
  42. package/dist/types/keyRecovery.d.ts +4 -4
  43. package/package.json +1 -1
@@ -204,6 +204,37 @@ export const exportAttestationSchema = z.object({
204
204
  signature: z.string(),
205
205
  signedAt: z.number(),
206
206
  });
207
+ export const exportUsageReceiptSchema = z.object({
208
+ receiptId: z.string(),
209
+ requestId: z.string(),
210
+ settledAt: z.string(),
211
+ billedAmount: z.string(),
212
+ currency: z.string(),
213
+ outcome: z.string(),
214
+ resolvedModelReference: z.string(),
215
+ servingProvider: z.string(),
216
+ platformFeeOnly: z.boolean(),
217
+ });
218
+ export const exportLedgerEntrySchema = z.object({
219
+ entryId: z.string(),
220
+ kind: z.string(),
221
+ currency: z.string(),
222
+ createdAt: z.string(),
223
+ });
224
+ export const exportUsageReservationSchema = z.object({
225
+ reservationId: z.string(),
226
+ requestId: z.string(),
227
+ status: z.string(),
228
+ reservedAmount: z.string(),
229
+ currency: z.string(),
230
+ createdAt: z.string(),
231
+ expiresAt: z.string(),
232
+ });
233
+ export const exportFinancialSectionSchema = z.object({
234
+ receipts: z.array(exportUsageReceiptSchema),
235
+ ledgerEntries: z.array(exportLedgerEntrySchema),
236
+ reservations: z.array(exportUsageReservationSchema),
237
+ });
207
238
  export const exportBundleSchema = z.object({
208
239
  '$schema': z.string(),
209
240
  exportedAt: z.string(),
@@ -218,6 +249,7 @@ export const exportBundleSchema = z.object({
218
249
  following: z.array(z.string()),
219
250
  followers: z.array(z.string()),
220
251
  }),
252
+ financial: exportFinancialSectionSchema,
221
253
  attestation: exportAttestationSchema.nullable(),
222
254
  proof: exportAttestationSchema.optional(),
223
255
  });
package/dist/esm/index.js CHANGED
@@ -30,7 +30,7 @@ export {
30
30
  recommendationExcludeTypeSchema, recommendationBoostSchema, recommendationSignalWeightsSchema, recommendationRequestSchema, recommendationCountSchema, recommendationItemSchema, recommendationResponseSchema, appEndorsementInputSchema, appInterestInputSchema, appUserSignalIngestSchema, appAffinityEventTypeSchema, appAffinityEventSchema, appAffinityEventsIngestSchema, } from './recommendations.js';
31
31
  export {
32
32
  // Schemas
33
- verificationMethodSchema, didServiceSchema, didDocumentSchema, signedRecordEnvelopeSchema, verifiedDomainSchema, domainVerificationRequestSchema, domainVerificationInstructionsSchema, authMethodEntrySchema, authMethodsResponseSchema, exportAttestationSchema, exportBundleSchema, } from './identity.js';
33
+ verificationMethodSchema, didServiceSchema, didDocumentSchema, signedRecordEnvelopeSchema, verifiedDomainSchema, domainVerificationRequestSchema, domainVerificationInstructionsSchema, authMethodEntrySchema, authMethodsResponseSchema, exportAttestationSchema, exportUsageReceiptSchema, exportLedgerEntrySchema, exportUsageReservationSchema, exportFinancialSectionSchema, exportBundleSchema, } from './identity.js';
34
34
  export {
35
35
  // Schemas
36
36
  oxySignedRecordTypeSchema, } from './oxyRecordTypes.js';
@@ -113,7 +113,7 @@ export {
113
113
  // are branded apart so a delegated end user can never become the payer.
114
114
  oxyAccountIdSchema, delegatedUserIdSchema, oxyApplicationIdSchema, oxyCredentialIdSchema, requestIdSchema, generationIdSchema, idempotencyKeySchema, inferenceEnvironmentSchema,
115
115
  // Wire primitives
116
- inferenceTimestampSchema, inferenceDateSchema, inferenceHttpsUrlSchema,
116
+ inferenceTimestampSchema, inferenceDateSchema, inferenceHttpsUrlSchema, sha256DigestSchema,
117
117
  // Catalogue references
118
118
  publisherSlugSchema, modelSlugSchema, modelIdSchema, modelRevisionLabelSchema, modelReferenceSchema, routingProfileSlugSchema, inferenceProviderSlugSchema, deploymentIdSchema, inferenceRegionSchema, RESERVED_ALIA_PUBLISHER, } from './inference/identifiers.js';
119
119
  export {
@@ -134,7 +134,12 @@ inferenceModalitySchema, modelCapabilitiesSchema, modelLicenseSchema, modelProve
134
134
  export {
135
135
  // Routing policy: every control, plus the refinement that rejects a policy
136
136
  // no route could ever satisfy.
137
- routingTargetSchema, routingPolicyScopeSchema, routingFallbackPolicySchema, routingPolicySchema, routingPolicyReferenceSchema, } from './inference/routingPolicy.js';
137
+ routingTargetSchema, routingPolicyScopeSchema, routingFallbackPolicySchema, routingPolicySchema, routingPolicyReferenceSchema,
138
+ // What the data plane actually receives: the routes the policy authorized.
139
+ authorizedRouteSchema, } from './inference/routingPolicy.js';
140
+ export {
141
+ // The signed Alia model release manifest (ingestion contract; no endpoint).
142
+ aliaReleaseArtifactSchema, aliaReleaseSignatureSchema, aliaModelReleaseManifestSchema, } from './inference/aliaModelRelease.js';
138
143
  export {
139
144
  // The normalized Oxy→data-plane request envelope.
140
145
  inferenceContentSourceSchema, inferenceContentPartSchema, inferenceToolCallSchema, inferenceMessageRoleSchema, inferenceMessageSchema, inferenceInputSchema, samplingParametersSchema, toolDefinitionSchema, toolChoiceSchema, responseFormatSchema, clientRequestMetadataSchema, inferenceRequestSchema, } from './inference/request.js';
@@ -0,0 +1,247 @@
1
+ /**
2
+ * The signed Alia model release manifest — the ingestion contract for a
3
+ * first-party model release.
4
+ *
5
+ * The catalogue already STORES everything such a manifest carries: the model
6
+ * card, the licence block, the provenance and base model, the evaluation table,
7
+ * the safety metadata, and an artifact digest with a `sha256:<64 hex>` CHECK.
8
+ * What did not exist was the manifest itself — a single document Alia SIGNS,
9
+ * asserting all of it at once — and that is the gap this shape closes. Nothing
10
+ * here re-declares a catalogue field; the manifest COMPOSES the published shapes
11
+ * so a manifest and the catalogue row it produces cannot describe a release
12
+ * differently.
13
+ *
14
+ * ## The manifest tightens the revision it carries
15
+ *
16
+ * `modelRevisionSchema` makes `modelCardUrl`, `artifactDigest`, `evaluations`
17
+ * and `safety` optional, because a third-party route legitimately has none of
18
+ * them — Oxy did not train those weights and cannot publish a card for them. A
19
+ * FIRST-PARTY release has no such excuse: the documentation trail is the reason
20
+ * a release manifest exists at all, and a model Alia ships without one is not a
21
+ * release, it is a deployment. So the refinement below requires all four,
22
+ * without changing the catalogue shape that a third-party entry still parses
23
+ * through.
24
+ *
25
+ * ## `.strict()` at the top level, and here that is forced rather than chosen
26
+ *
27
+ * The shapes exchanged with the data plane tolerate an unknown field, because
28
+ * refusing a producer one minor version ahead is a worse failure than ignoring
29
+ * its addition (`version.ts`). A SIGNED document inverts that: the signature is
30
+ * over the canonical bytes of the manifest, so a field silently stripped at this
31
+ * parse is a field missing from the bytes Oxy re-canonicalizes, and verification
32
+ * fails. A tolerant parse would therefore report "the signature is invalid" for
33
+ * what is really "this build does not understand this manifest" — the wrong
34
+ * diagnosis of the right problem. Strict says the true thing, and the cost is
35
+ * bounded: ingestion is a release-time operation an operator retries once Oxy
36
+ * takes the newer contract, not a served request that becomes unsettleable.
37
+ *
38
+ * ## What is deliberately NOT here
39
+ *
40
+ * **No HTTP write path.** The catalogue's emptiness is currently a safety
41
+ * property — `scripts/seed-inference-catalogue.ts` refuses to invent a licence
42
+ * or a retention flag because "a plausible invented value in a catalogue is
43
+ * worse than an absent one" — and a staff write path into it with nothing to
44
+ * ingest is an unexercised hazard. The schema lands; the endpoint waits for a
45
+ * real manifest to ingest.
46
+ *
47
+ * **No `payloadDigest` field.** The signature is over the canonical
48
+ * serialization of this manifest with `signatures` removed, and a verifier
49
+ * recomputes it. Storing the digest beside the document it digests would be a
50
+ * second source of truth for one fact, and a verifier that compared the
51
+ * signature against the DECLARED digest rather than the recomputed one would
52
+ * verify nothing at all.
53
+ *
54
+ * **No verification RESULT.** Whether a signature checked out is Oxy's finding
55
+ * about the document, not a claim the document makes about itself; a `verified`
56
+ * field inside a signed manifest is the signer asserting its own signature.
57
+ *
58
+ * ## The open owner decision this shape does not take
59
+ *
60
+ * **What signs, and what verifies, is not decided.** Oxy holds no Alia signing
61
+ * key, and whether to resolve `keyId` through the existing attestation machinery
62
+ * (`services/oxyVerificationResolver.ts`, the civic attestation code) or to
63
+ * introduce a dedicated Alia release key is a real choice with different
64
+ * custody, rotation and revocation consequences. So `keyId` is an OPAQUE
65
+ * identifier and this file names no registry that resolves it: either answer
66
+ * fits, and neither is presupposed. Until it is answered a manifest can be
67
+ * parsed and cannot be verified, which is the second reason no endpoint ships.
68
+ *
69
+ * Decided in: docs/adr/0008-catalogue-concept-separation.md,
70
+ * docs/adr/0017-authorized-routes-in-the-envelope.md, issue #972 §12.
71
+ */
72
+ import { z } from 'zod';
73
+ import { modelLicenseSchema, modelProvenanceSchema, modelRevisionSchema, } from './catalogue.js';
74
+ import { inferenceTimestampSchema, RESERVED_ALIA_PUBLISHER, sha256DigestSchema, } from './identifiers.js';
75
+ /**
76
+ * One artifact of a release, by path and digest.
77
+ *
78
+ * `sizeBytes` is required beside the digest so a verifier can refuse a stream
79
+ * that is the wrong length before reading it to the end, rather than only after.
80
+ */
81
+ export const aliaReleaseArtifactSchema = z
82
+ .object({
83
+ /** Path within the release, e.g. `model-00001-of-00004.safetensors`. */
84
+ path: z.string().min(1).max(512),
85
+ digest: sha256DigestSchema,
86
+ sizeBytes: z.number().int().positive().safe(),
87
+ mediaType: z.string().min(1).max(255).optional(),
88
+ })
89
+ .strict();
90
+ /**
91
+ * One detached signature over the manifest.
92
+ *
93
+ * `algorithm` is a CLOSED enum with one member, and both halves of that are
94
+ * deliberate. Closed, because a verifier that trusts a document's own algorithm
95
+ * name accepts whatever that document nominates, `none` included. One member,
96
+ * because Ed25519 is the scheme ADR 0012 already chose for asymmetric
97
+ * verification on this platform, and naming a scheme nothing here can check
98
+ * would be advertising a capability that does not exist. A second member lands
99
+ * when a verifier for it does — which is a closed enum gaining a member, and
100
+ * therefore a MINOR contract-set change the handshake surfaces (`version.ts`).
101
+ *
102
+ * `keyId` is opaque on purpose: see the header. It identifies the public key
103
+ * without saying what resolves it.
104
+ *
105
+ * The signature covers the canonical serialization (RFC 8785 JCS) of the
106
+ * manifest with `signatures` removed. The canonicalization is NAMED rather than
107
+ * left implicit because a digest over "the manifest" is not verifiable by two
108
+ * implementations that serialize JSON differently; naming it is a mechanical
109
+ * necessity and is independent of the open question of which key signs.
110
+ */
111
+ export const aliaReleaseSignatureSchema = z
112
+ .object({
113
+ algorithm: z.enum(['ed25519']),
114
+ canonicalization: z.enum(['jcs']),
115
+ /** Opaque identifier of the public key. Resolving it is undecided. */
116
+ keyId: z.string().min(1).max(256),
117
+ /**
118
+ * Unpadded base64url. Exactly 86 characters, which is a 64-byte Ed25519
119
+ * signature — the one algorithm above. A second algorithm moves this length
120
+ * into a refinement keyed on `algorithm`.
121
+ */
122
+ signature: z
123
+ .string()
124
+ .regex(/^[A-Za-z0-9_-]{86}$/, 'signature must be a 64-byte ed25519 signature in unpadded base64url'),
125
+ signedAt: inferenceTimestampSchema,
126
+ })
127
+ .strict();
128
+ /**
129
+ * A signed release of an `alia/*` model revision.
130
+ *
131
+ * `signatures` is a LIST rather than one signature, because "what signs" is
132
+ * undecided: a single field would presuppose one signer, while a list lets an
133
+ * Alia release key and an existing attestation co-sign the same document without
134
+ * either being retrofitted later.
135
+ */
136
+ export const aliaModelReleaseManifestSchema = z
137
+ .object({
138
+ /** See `version.ts`: an ingestion payload is a whole message on the wire. */
139
+ schemaVersion: z.literal(1),
140
+ /** The release's own identity, so ingestion is idempotent on it. */
141
+ releaseId: z.string().min(1).max(128),
142
+ issuedAt: inferenceTimestampSchema,
143
+ /**
144
+ * The revision being released. Carries its OWN `schemaVersion`, like
145
+ * `billingProfileSchema` inside `accountBillingStateSchema`: the manifest's
146
+ * version governs the manifest and the revision's governs the revision,
147
+ * which is two versions of two things rather than two versions of one.
148
+ */
149
+ revision: modelRevisionSchema,
150
+ /** On the MODEL rather than the revision in the catalogue, so carried here. */
151
+ provenance: modelProvenanceSchema,
152
+ license: modelLicenseSchema,
153
+ artifacts: z.array(aliaReleaseArtifactSchema).min(1),
154
+ signatures: z.array(aliaReleaseSignatureSchema).min(1),
155
+ })
156
+ .strict()
157
+ .superRefine((manifest, ctx) => {
158
+ // The same rule `catalogueModelSchema` enforces on a model, applied to the
159
+ // carrier that creates one: `alia/*` names models Alia actually owns or
160
+ // derived, and a manifest is the document that would launder somebody else's
161
+ // weights into the namespace.
162
+ const publisher = manifest.revision.modelId.slice(0, manifest.revision.modelId.indexOf('/'));
163
+ if (publisher !== RESERVED_ALIA_PUBLISHER) {
164
+ ctx.addIssue({
165
+ code: z.ZodIssueCode.custom,
166
+ path: ['revision', 'modelId'],
167
+ message: `an Alia release manifest releases a ${RESERVED_ALIA_PUBLISHER}/* model`,
168
+ });
169
+ }
170
+ if (manifest.provenance.releaseKind !== 'first_party_original' &&
171
+ manifest.provenance.releaseKind !== 'first_party_derived') {
172
+ ctx.addIssue({
173
+ code: z.ZodIssueCode.custom,
174
+ path: ['provenance', 'releaseKind'],
175
+ message: 'an Alia release manifest describes a first-party release',
176
+ });
177
+ }
178
+ // A derived model's base is the licence-attribution trail. Recording the
179
+ // derivation without naming what it derives from loses exactly the fact
180
+ // attribution needs.
181
+ if (manifest.provenance.releaseKind === 'first_party_derived' &&
182
+ manifest.provenance.baseModelId === undefined) {
183
+ ctx.addIssue({
184
+ code: z.ZodIssueCode.custom,
185
+ path: ['provenance', 'baseModelId'],
186
+ message: 'a derived release names the model it derives from',
187
+ });
188
+ }
189
+ // The four fields a third-party catalogue entry may omit and a first-party
190
+ // release may not. See the header.
191
+ if (manifest.revision.modelCardUrl === undefined) {
192
+ ctx.addIssue({
193
+ code: z.ZodIssueCode.custom,
194
+ path: ['revision', 'modelCardUrl'],
195
+ message: 'a first-party release publishes a model card',
196
+ });
197
+ }
198
+ if (manifest.revision.safety === undefined) {
199
+ ctx.addIssue({
200
+ code: z.ZodIssueCode.custom,
201
+ path: ['revision', 'safety'],
202
+ message: 'a first-party release publishes its safety metadata',
203
+ });
204
+ }
205
+ if (manifest.revision.evaluations.length === 0) {
206
+ ctx.addIssue({
207
+ code: z.ZodIssueCode.custom,
208
+ path: ['revision', 'evaluations'],
209
+ message: 'a first-party release publishes at least one evaluation result',
210
+ });
211
+ }
212
+ // The digest the catalogue will serve has to be one of the digests this
213
+ // manifest signed. Otherwise the signature covers a set of artifacts that
214
+ // does not include the weights anybody runs.
215
+ if (manifest.revision.artifactDigest === undefined) {
216
+ ctx.addIssue({
217
+ code: z.ZodIssueCode.custom,
218
+ path: ['revision', 'artifactDigest'],
219
+ message: 'a first-party release names the digest of the artifact it serves',
220
+ });
221
+ }
222
+ else if (!manifest.artifacts.some((artifact) => artifact.digest === manifest.revision.artifactDigest)) {
223
+ ctx.addIssue({
224
+ code: z.ZodIssueCode.custom,
225
+ path: ['revision', 'artifactDigest'],
226
+ message: 'the served artifact digest must appear among the signed artifacts',
227
+ });
228
+ }
229
+ const paths = manifest.artifacts.map((artifact) => artifact.path);
230
+ if (new Set(paths).size !== paths.length) {
231
+ ctx.addIssue({
232
+ code: z.ZodIssueCode.custom,
233
+ path: ['artifacts'],
234
+ message: 'each artifact path appears once in a release',
235
+ });
236
+ }
237
+ // Two signatures from one key are one signature written twice, and a
238
+ // duplicate would make a "two independent signers" check pass on one signer.
239
+ const keyIds = manifest.signatures.map((signature) => signature.keyId);
240
+ if (new Set(keyIds).size !== keyIds.length) {
241
+ ctx.addIssue({
242
+ code: z.ZodIssueCode.custom,
243
+ path: ['signatures'],
244
+ message: 'each signing key signs a manifest once',
245
+ });
246
+ }
247
+ });
@@ -27,7 +27,7 @@
27
27
  * Decided in: docs/adr/0008-catalogue-concept-separation.md.
28
28
  */
29
29
  import { z } from 'zod';
30
- import { deploymentIdSchema, inferenceDateSchema, inferenceHttpsUrlSchema, inferenceProviderSlugSchema, inferenceRegionSchema, inferenceTimestampSchema, modelIdSchema, modelReferenceSchema, modelRevisionLabelSchema, modelSlugSchema, publisherSlugSchema, RESERVED_ALIA_PUBLISHER, routingProfileSlugSchema, } from './identifiers.js';
30
+ import { deploymentIdSchema, inferenceDateSchema, inferenceHttpsUrlSchema, inferenceProviderSlugSchema, inferenceRegionSchema, inferenceTimestampSchema, modelIdSchema, modelReferenceSchema, modelRevisionLabelSchema, modelSlugSchema, publisherSlugSchema, RESERVED_ALIA_PUBLISHER, routingProfileSlugSchema, sha256DigestSchema, } from './identifiers.js';
31
31
  import { priceSnapshotSchema } from './priceVersion.js';
32
32
  /* -------------------------------------------------------------------------- */
33
33
  /* Shared catalogue vocabulary */
@@ -279,10 +279,7 @@ export const modelRevisionSchema = z
279
279
  releasedAt: inferenceTimestampSchema,
280
280
  retiredAt: inferenceTimestampSchema.optional(),
281
281
  /** Digest of the served artifact, where Oxy hosts the weights itself. */
282
- artifactDigest: z
283
- .string()
284
- .regex(/^sha256:[a-f0-9]{64}$/, 'artifact digest must be sha256:<64 lowercase hex>')
285
- .optional(),
282
+ artifactDigest: sha256DigestSchema.optional(),
286
283
  modelCardUrl: inferenceHttpsUrlSchema.optional(),
287
284
  evaluations: z.array(modelEvaluationResultSchema).default([]),
288
285
  safety: modelSafetyMetadataSchema.optional(),
@@ -38,6 +38,11 @@ import { inferenceProviderSlugSchema, requestIdSchema } from './identifiers.js';
38
38
  * PLATFORM's own credential fails every identical retry until an operator
39
39
  * rotates a key, so classifying it as `provider_error` would send every client
40
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.
41
46
  */
42
47
  export const INFERENCE_ERROR_CODES = [
43
48
  'invalid_request',
@@ -65,6 +70,7 @@ export const INFERENCE_ERROR_CODES = [
65
70
  'provider_timeout',
66
71
  'provider_overloaded',
67
72
  'provider_credential_invalid',
73
+ 'provider_billing_refused',
68
74
  'service_unavailable',
69
75
  'internal_error',
70
76
  ];
@@ -84,6 +90,12 @@ export const inferenceErrorCodeSchema = z.enum(INFERENCE_ERROR_CODES);
84
90
  * one because only the first names an action the customer can take. Both are
85
91
  * non-retryable for the same reason: a credential an upstream has refused keeps
86
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.
87
99
  */
88
100
  export const NON_RETRYABLE_INFERENCE_ERROR_CODES = [
89
101
  'invalid_request',
@@ -106,27 +118,114 @@ export const NON_RETRYABLE_INFERENCE_ERROR_CODES = [
106
118
  'upstream_content_filtered',
107
119
  'cancelled',
108
120
  'provider_credential_invalid',
121
+ 'provider_billing_refused',
109
122
  ];
110
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._~+/=-]';
111
136
  /**
112
- * Text that looks like it carries a credential.
137
+ * Words a producer substitutes FOR a credential.
113
138
  *
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.
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.
118
145
  */
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;
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)`;
120
149
  /**
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
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
123
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/Relay#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.
124
223
  */
125
224
  export const safeErrorTextSchema = z
126
225
  .string()
127
226
  .min(1)
128
227
  .max(2000)
129
- .refine((value) => !CREDENTIAL_LIKE_TEXT.test(value), 'error text must not contain credential-shaped material');
228
+ .refine((value) => !CREDENTIAL_PATTERNS.some((pattern) => pattern.test(value)), 'error text must not contain credential-shaped material');
130
229
  /**
131
230
  * A coarse classification of an upstream failure (ADR 0010's `upstreamCategory`).
132
231
  *
@@ -59,8 +59,16 @@ export const oxyCredentialIdSchema = z.string().min(1).max(64);
59
59
  * traceable as one that was served (ADR 0007, and step 1 of ADR 0010's edge
60
60
  * order). It is required on the inbound envelope, which is what makes the data
61
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.
62
+ * on every stream event, on the usage report, in its response header and on
63
+ * anything it can be asked about later. It never mints one for a request it
64
+ * received.
65
+ *
66
+ * The one case that is NOT an exception to that: an envelope the data plane
67
+ * cannot read or authenticate carries no id to echo, so its rejection is
68
+ * labelled with an id of the data plane's own — visibly local, and never
69
+ * correlated with an Oxy request, because there is no Oxy request it belongs to.
70
+ * Saying so is what stops "consumer, not source" from being read as forbidding
71
+ * the only id such a rejection could have.
64
72
  *
65
73
  * Correlates the Oxy edge, the data plane, the financial ledger and the
66
74
  * customer-visible receipt, so it appears on every stream event and every
@@ -106,6 +114,18 @@ export const inferenceHttpsUrlSchema = z
106
114
  .string()
107
115
  .max(2048)
108
116
  .regex(/^https:\/\/[^\s]+$/, 'must be an absolute https URL');
117
+ /**
118
+ * A content digest, `sha256:<64 lowercase hex>`.
119
+ *
120
+ * ONE spelling, because a digest is compared for equality and nothing else: an
121
+ * uppercase or unprefixed variant of the same hash is a different string, so two
122
+ * records describing the same bytes would not match. Lowercase hex with the
123
+ * algorithm prefix is what the `inference_model_revisions` CHECK stores and what
124
+ * every artifact registry emits.
125
+ */
126
+ export const sha256DigestSchema = z
127
+ .string()
128
+ .regex(/^sha256:[a-f0-9]{64}$/, 'digest must be sha256:<64 lowercase hex>');
109
129
  /* -------------------------------------------------------------------------- */
110
130
  /* Catalogue references */
111
131
  /* -------------------------------------------------------------------------- */