@oxyhq/contracts 0.27.0 → 0.29.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 (34) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/index.js +44 -1
  3. package/dist/cjs/inference/accountBilling.js +334 -0
  4. package/dist/cjs/inference/attribution.js +9 -4
  5. package/dist/cjs/inference/entitlement.js +217 -0
  6. package/dist/cjs/inference/errors.js +123 -9
  7. package/dist/cjs/inference/identifiers.js +11 -3
  8. package/dist/cjs/inference/money.js +43 -0
  9. package/dist/cjs/inference/streamEvents.js +11 -1
  10. package/dist/cjs/inference/usage.js +6 -0
  11. package/dist/cjs/inference/version.js +38 -3
  12. package/dist/esm/.tsbuildinfo +1 -1
  13. package/dist/esm/index.js +9 -0
  14. package/dist/esm/inference/accountBilling.js +331 -0
  15. package/dist/esm/inference/attribution.js +9 -4
  16. package/dist/esm/inference/entitlement.js +214 -0
  17. package/dist/esm/inference/errors.js +123 -9
  18. package/dist/esm/inference/identifiers.js +11 -3
  19. package/dist/esm/inference/money.js +43 -0
  20. package/dist/esm/inference/streamEvents.js +11 -1
  21. package/dist/esm/inference/usage.js +6 -0
  22. package/dist/esm/inference/version.js +38 -3
  23. package/dist/types/.tsbuildinfo +1 -1
  24. package/dist/types/index.d.ts +4 -0
  25. package/dist/types/inference/accountBilling.d.ts +738 -0
  26. package/dist/types/inference/attribution.d.ts +9 -4
  27. package/dist/types/inference/entitlement.d.ts +519 -0
  28. package/dist/types/inference/errors.d.ts +59 -10
  29. package/dist/types/inference/identifiers.d.ts +11 -3
  30. package/dist/types/inference/money.d.ts +43 -0
  31. package/dist/types/inference/streamEvents.d.ts +31 -22
  32. package/dist/types/inference/usage.d.ts +6 -0
  33. package/dist/types/inference/version.d.ts +38 -3
  34. package/package.json +1 -1
@@ -35,6 +35,17 @@ const identifiers_1 = require("./identifiers");
35
35
  * `quota_exceeded`, `byok_credential_invalid`), routing/permission policy
36
36
  * (`policy_violation`, `commercial_permission_denied`, `no_route_available`),
37
37
  * and the platform or its upstreams (everything from `deployment_unavailable`).
38
+ *
39
+ * The platform group is NOT uniformly retryable, and that is the point of
40
+ * `provider_credential_invalid` sitting in it: an upstream that refuses the
41
+ * PLATFORM's own credential fails every identical retry until an operator
42
+ * rotates a key, so classifying it as `provider_error` would send every client
43
+ * into a retry loop against a request that cannot succeed.
44
+ *
45
+ * `provider_billing_refused` is in that group for the same reason and was found
46
+ * the same way — an upstream declining to bill OXY (Anthropic answers 402) has
47
+ * to be distinguishable from the customer's own balance running out, or the
48
+ * error tells them to go and top up an account that is not the one at fault.
38
49
  */
39
50
  exports.INFERENCE_ERROR_CODES = [
40
51
  'invalid_request',
@@ -61,6 +72,8 @@ exports.INFERENCE_ERROR_CODES = [
61
72
  'provider_error',
62
73
  'provider_timeout',
63
74
  'provider_overloaded',
75
+ 'provider_credential_invalid',
76
+ 'provider_billing_refused',
64
77
  'service_unavailable',
65
78
  'internal_error',
66
79
  ];
@@ -73,6 +86,19 @@ exports.inferenceErrorCodeSchema = zod_1.z.enum(exports.INFERENCE_ERROR_CODES);
73
86
  * names, while a quota is an account-level ceiling that only a human raises.
74
87
  * `cancelled` is here because the caller already withdrew the request; a client
75
88
  * that retries it is contradicting its own cancellation.
89
+ *
90
+ * `byok_credential_invalid` and `provider_credential_invalid` are the same
91
+ * failure seen from the two sides of the BYOK boundary — the customer's own
92
+ * upstream credential and the platform's — and they are two codes rather than
93
+ * one because only the first names an action the customer can take. Both are
94
+ * non-retryable for the same reason: a credential an upstream has refused keeps
95
+ * being refused until somebody replaces it.
96
+ *
97
+ * `quota_exceeded` and `provider_billing_refused` divide along the same line:
98
+ * both are money, but one is the CUSTOMER's ceiling and the other is Oxy's
99
+ * account with an upstream. Reporting the second as the first is retryability-
100
+ * correct and diagnostically wrong, which is the worst combination — it reads
101
+ * as actionable and the action does nothing.
76
102
  */
77
103
  exports.NON_RETRYABLE_INFERENCE_ERROR_CODES = [
78
104
  'invalid_request',
@@ -94,27 +120,115 @@ exports.NON_RETRYABLE_INFERENCE_ERROR_CODES = [
94
120
  'no_route_available',
95
121
  'upstream_content_filtered',
96
122
  'cancelled',
123
+ 'provider_credential_invalid',
124
+ 'provider_billing_refused',
97
125
  ];
98
126
  const NON_RETRYABLE_CODE_SET = new Set(exports.NON_RETRYABLE_INFERENCE_ERROR_CODES);
127
+ /* -------------------------------------------------------------------------- */
128
+ /* Credential-shaped text */
129
+ /* -------------------------------------------------------------------------- */
130
+ /**
131
+ * A run of characters long enough and opaque enough to BE a credential.
132
+ *
133
+ * The alphabet every bearer token, API key and base64/base64url secret is
134
+ * written in. The LENGTH floors below are what keep this from being an entropy
135
+ * heuristic: nothing here fires on a short word, so `authorization: none` and
136
+ * `api_key=***` read as what they are.
137
+ */
138
+ const OPAQUE_ALPHABET = '[A-Za-z0-9][A-Za-z0-9._~+/=-]';
139
+ /**
140
+ * Words a producer substitutes FOR a credential.
141
+ *
142
+ * Excluded at the value position so a message whose secret has already been
143
+ * replaced is accepted. That acceptance is deliberate and is half the fix for
144
+ * issue #1027: the previous pattern refused `Authorization: [redacted]` — a
145
+ * correctly redacted string — which is precisely what pushed a producer into
146
+ * redacting the MARKER instead, and a marker-redacted string carries the secret
147
+ * and passes.
148
+ */
149
+ const PLACEHOLDER_WORDS = 'redacted|removed|hidden|masked|scrubbed|elided|omitted|filtered|sanitized|sanitised|none|null|undefined|empty';
150
+ /** A value position whose contents are a placeholder rather than a secret. */
151
+ const NOT_A_PLACEHOLDER = `(?!(?:${PLACEHOLDER_WORDS})\\b)`;
99
152
  /**
100
- * Text that looks like it carries a credential.
153
+ * Header and parameter names that carry a credential, as any provider spells
154
+ * them.
101
155
  *
102
- * A deliberately narrow set of literal markers the shapes upstream providers
103
- * actually echo rather than an entropy heuristic, which would reject
104
- * legitimate error text (a request id, a base64 image fragment) and teach
105
- * producers to strip messages until they pass.
156
+ * The prefix group is the whole point of the rewrite: `authorization` and
157
+ * `api_key` were matched literally, so `x-api-key`, `anthropic-api-key`,
158
+ * `x-goog-api-key` and `proxy-authorization` the spellings an upstream
159
+ * actually echoes went unrecognised.
106
160
  */
107
- 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;
161
+ 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?)';
162
+ /** An auth scheme sitting between the marker and the value. */
163
+ const AUTH_SCHEME = '(?:(?:bearer|basic|token|apikey|digest)\\s+)?';
108
164
  /**
109
- * Free text that is safe to hand a customer: bounded, and refused outright if a
110
- * credential marker appears in it. Applied to BOTH the Oxy message and the
165
+ * The four ways a credential is recognisable in free text.
166
+ *
167
+ * Each is checked independently, so removing one signal does not clear the
168
+ * string — which is the failure #1027 reported. All four are load-bearing:
169
+ * `inference.errors.test.ts` has a case that only one of them catches, and
170
+ * deleting any one entry turns a test red.
171
+ */
172
+ const CREDENTIAL_PATTERNS = [
173
+ // 1. A credential-bearing name ASSIGNED a value that is long enough to be a
174
+ // credential. The value is anchored to the separator so a placeholder at
175
+ // that position ends the match rather than being skipped over.
176
+ new RegExp(`(?:^|[^a-z0-9])${CREDENTIAL_NAME}["']?\\s*[:=]\\s*["']?${AUTH_SCHEME}${NOT_A_PLACEHOLDER}${OPAQUE_ALPHABET}{7,}`, 'i'),
177
+ // 2. A bearer token with no marker in front of it, which is how an upstream
178
+ // quotes the header value alone.
179
+ new RegExp(`\\bbearer\\s+${NOT_A_PLACEHOLDER}${OPAQUE_ALPHABET}{7,}`, 'i'),
180
+ // 3. Token grammars that ARE credentials wherever they appear, marker or not.
181
+ // This is the layer that survives a producer stripping the marker, and it
182
+ // is a closed list of issued shapes rather than an entropy score, so a
183
+ // request id or a base64 image fragment is unaffected.
184
+ //
185
+ // Case-SENSITIVE on purpose: `AKIA`, `AIza` and `gh[pousr]_` are issued in
186
+ // exactly that case, and matching them case-insensitively would start
187
+ // firing on ordinary words.
188
+ /\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,})/,
189
+ // 4. A redaction placeholder standing NEXT TO a surviving opaque value — the
190
+ // exact residue of the span redaction in #1027 (`{x-[redacted] <key>}`).
191
+ // A correct redaction puts the placeholder WHERE the value was, so the two
192
+ // never appear side by side; a marker-span redaction leaves them adjacent.
193
+ // Both signals are required, which is what keeps an ordinary redacted
194
+ // message from being refused.
195
+ new RegExp(`(?:[[<({]\\s*(?:${PLACEHOLDER_WORDS})[^\\])}>]{0,16}[\\])}>]|\\*{3,})[^A-Za-z0-9]{0,4}${OPAQUE_ALPHABET}{11,}`, 'i'),
196
+ ];
197
+ /**
198
+ * Free text that is safe to hand a customer: bounded, and refused if it still
199
+ * looks like it carries a credential. Applied to BOTH the Oxy message and the
111
200
  * upstream one — a leak is no less a leak for having been written by a provider.
201
+ *
202
+ * ## This is a last-resort REFUSAL, not protection
203
+ *
204
+ * A pattern over the OUTPUT cannot be the control that keeps a credential out of
205
+ * an error, and a producer that treats it as one has the hole #1027 reported.
206
+ * The only reliable control is redacting the KNOWN SECRET VALUE at the point
207
+ * where the producer still holds the bytes it sent — which is an adapter's job
208
+ * and is available to nobody else. This refinement exists to catch what that
209
+ * control missed, and nothing here is a licence to skip it.
210
+ *
211
+ * Two rules follow, and they are the whole reason this text is longer than the
212
+ * pattern it describes:
213
+ *
214
+ * - **Never redact by replacing the span this pattern matched.** The span is
215
+ * the MARKER; the secret is what follows it. OxyHQ/Relay#3 measured the
216
+ * result: `{x-api-key: <key>}` is refused, `{x-[redacted] <key>}` was
217
+ * accepted, and both carry the key. Redaction made the leak worse by
218
+ * converting "this string is dangerous" into "this string is fine".
219
+ * - **This package deliberately ships no redaction helper.** One keyed on these
220
+ * patterns would rebuild the same defect one layer up, and one that took the
221
+ * secret as an argument would only restate what the producer already has.
222
+ *
223
+ * What it still cannot see, stated so nobody relies on it: a credential with no
224
+ * marker, no issued-token prefix and no placeholder beside it is bytes that look
225
+ * like a request id, and refusing those means refusing request ids.
112
226
  */
113
227
  exports.safeErrorTextSchema = zod_1.z
114
228
  .string()
115
229
  .min(1)
116
230
  .max(2000)
117
- .refine((value) => !CREDENTIAL_LIKE_TEXT.test(value), 'error text must not contain credential-shaped material');
231
+ .refine((value) => !CREDENTIAL_PATTERNS.some((pattern) => pattern.test(value)), 'error text must not contain credential-shaped material');
118
232
  /**
119
233
  * A coarse classification of an upstream failure (ADR 0010's `upstreamCategory`).
120
234
  *
@@ -57,9 +57,17 @@ exports.oxyApplicationIdSchema = zod_1.z.string().min(1).max(64);
57
57
  /** An Oxy `ApplicationCredential._id` — the credential used for this request. */
58
58
  exports.oxyCredentialIdSchema = zod_1.z.string().min(1).max(64);
59
59
  /**
60
- * A request id generated by the data plane. Correlates the Oxy edge, the data
61
- * plane, the financial ledger and the customer-visible receipt, so it appears on
62
- * every stream event and every ledger record.
60
+ * A request id allocated by the Oxy EDGE, at admission and BEFORE
61
+ * authentication, so that a request rejected for a bad credential is as
62
+ * traceable as one that was served (ADR 0007, and step 1 of ADR 0010's edge
63
+ * order). It is required on the inbound envelope, which is what makes the data
64
+ * plane a consumer of this id rather than its source: the data plane echoes it
65
+ * on every stream event, on the usage report and on anything it can be asked
66
+ * about later.
67
+ *
68
+ * Correlates the Oxy edge, the data plane, the financial ledger and the
69
+ * customer-visible receipt, so it appears on every stream event and every
70
+ * ledger record.
63
71
  */
64
72
  exports.requestIdSchema = zod_1.z.string().min(1).max(128);
65
73
  /**
@@ -88,6 +88,49 @@ exports.moneySchema = zod_1.z
88
88
  /**
89
89
  * The closed set of units inference is metered in.
90
90
  *
91
+ * **The units PARTITION a request: every unit counts material no other unit
92
+ * counts.** `cached_input_tokens` is not part of `input_tokens`, and
93
+ * `reasoning_tokens` is not part of `output_tokens` — they are siblings, not
94
+ * subsets. A request whose 10 000-token prompt was served 9 000 tokens from
95
+ * cache is reported as `input_tokens: 1000` beside `cached_input_tokens: 9000`,
96
+ * never as `input_tokens: 10000` beside it.
97
+ *
98
+ * That belongs to the definition rather than to a convention somewhere else,
99
+ * because settlement applies a price to EVERY reported unit and sums them
100
+ * (`inferenceLedger.service.ts`'s `computeCharge`). Under the partition rule
101
+ * that sum IS the request's cost, and a cached token can carry its own — lower
102
+ * — price. Under the nested reading the same sum charges the cached and
103
+ * reasoning tokens twice: once inside their parent and once on their own line.
104
+ * It fails silently, because every total still looks plausible and the receipt
105
+ * is still internally consistent, and on a reasoning model the reasoning tokens
106
+ * can dominate the completion, so the error is not marginal.
107
+ *
108
+ * **Every OpenAI-compatible provider reports the other way round**:
109
+ * `prompt_tokens` INCLUDES `prompt_tokens_details.cached_tokens`, and
110
+ * `completion_tokens` INCLUDES `completion_tokens_details.reasoning_tokens`.
111
+ * Normalising is the data plane's job and it is subtraction:
112
+ *
113
+ * ```text
114
+ * input_tokens = prompt_tokens - prompt_tokens_details.cached_tokens
115
+ * output_tokens = completion_tokens - completion_tokens_details.reasoning_tokens
116
+ * ```
117
+ *
118
+ * No refinement in this package can enforce it, and saying so is part of the
119
+ * rule: a nested report and a disjoint one are the same four non-negative
120
+ * integers, so no predicate over a single report can tell them apart. The two
121
+ * structural guards that DO exist — refining `cached <= input` and
122
+ * `reasoning <= output`, or deriving the parents instead of reporting them —
123
+ * both encode the nested reading, which is the one this rule rejects. What IS
124
+ * enforceable is the arithmetic that depends on the rule, and that is where the
125
+ * enforcement lives — `inferenceLedger.service.test.ts` prices a report in
126
+ * which cached and reasoning tokens are both non-zero and asserts the exact
127
+ * total, which the nested reading cannot produce.
128
+ *
129
+ * Where the public surface has to speak a nested dialect, the sum is put back
130
+ * at the boundary rather than the internal reading being bent to it
131
+ * (`routes/inferenceEdge.ts` renders `prompt_tokens` as
132
+ * `input_tokens + cached_input_tokens`).
133
+ *
91
134
  * Time is carried in integer MILLISECONDS rather than seconds so that no unit
92
135
  * quantity is ever fractional: a 12.5-second transcription is `12500`, exactly,
93
136
  * and the "units are integers" rule holds for every modality instead of holding
@@ -177,12 +177,22 @@ exports.inferenceStreamErrorEventSchema = zod_1.z.object({
177
177
  /** Carries its own `schemaVersion`: the same body is returned non-streaming. */
178
178
  error: errors_1.inferenceErrorSchema,
179
179
  });
180
- /** Why generation stopped. */
180
+ /**
181
+ * Why generation stopped.
182
+ *
183
+ * `refusal` and `content_filter` are separate members because they are separate
184
+ * events: the MODEL declining to answer is a property of the answer, while a
185
+ * filter is an upstream system removing one. The delta channels already carry
186
+ * that distinction (`channel: 'refusal'` beside the filter's own error code),
187
+ * so collapsing it here would have made the terminal event less specific than
188
+ * the stream that produced it.
189
+ */
181
190
  exports.inferenceFinishReasonSchema = zod_1.z.enum([
182
191
  'stop',
183
192
  'length',
184
193
  'tool_calls',
185
194
  'content_filter',
195
+ 'refusal',
186
196
  'cancelled',
187
197
  ]);
188
198
  /**
@@ -131,6 +131,12 @@ exports.inferenceRequestOutcomeSchema = zod_1.z.enum([
131
131
  * `usageSource` is load-bearing when a provider returns no usage at all: the
132
132
  * report still arrives, marked `estimated`, so settlement can apply the
133
133
  * estimation policy knowingly instead of treating a reconstruction as fact.
134
+ *
135
+ * `units` is a PARTITION of what the request consumed, not a set of totals with
136
+ * details hanging off them — see `USAGE_UNITS` in `money.ts`. Reporting a provider's
137
+ * nested `prompt_tokens`/`completion_tokens` verbatim charges the cached and
138
+ * reasoning tokens twice, so subtracting the children out is part of what
139
+ * "normalized" means in this shape's name.
134
140
  */
135
141
  exports.normalizedUsageReportSchema = zod_1.z
136
142
  .object({
@@ -35,6 +35,34 @@
35
35
  * field is additive and does not bump it, because a consumer on the previous
36
36
  * version parses the message correctly and simply does not read the new field.
37
37
  *
38
+ * ## Which shapes reject an unknown field
39
+ *
40
+ * That last rule is why the shapes EXCHANGED WITH THE DATA PLANE are not
41
+ * `.strict()` at their top level — the request envelope, the four usage records,
42
+ * the stream events, the error body, the catalogue descriptors, the price
43
+ * version. The split is a decision rather than an omission: `.strict()` and
44
+ * "adding an optional field is additive" cannot both hold on one shape, because
45
+ * a producer one minor version ahead would have its whole message REFUSED
46
+ * rather than its new field ignored. For a usage report that means a request
47
+ * already served upstream can never be settled and Oxy absorbs its cost, which
48
+ * is a worse failure than the one strictness would have caught.
49
+ *
50
+ * Their LEAVES are strict, and that is where the protection lives: a stripped
51
+ * field is the worse outcome exactly where it would be a leak or a second
52
+ * source of truth, because it disappears at this parse and survives in the
53
+ * producer, which is where somebody eventually reads it. So
54
+ * `clientRequestMetadataSchema` (no IP, ever), `moneySchema` (no convenience
55
+ * float beside the exact decimal), `providerErrorPassthroughSchema` (no
56
+ * upstream request or headers beside the message), `usageQuantitySchema` and
57
+ * `unitPriceSchema` all refuse an unknown field, while the envelope carrying
58
+ * them tolerates an additive one.
59
+ *
60
+ * A shape Oxy does NOT exchange with the data plane is strict at its top level
61
+ * too, since nothing there can run ahead of this package:
62
+ * `providerConnectionSchema`, where an unknown field is how a BYOK credential
63
+ * escapes, and the billing and entitlement records, where one is a second
64
+ * number beside an exact amount.
65
+ *
38
66
  * Decided in: docs/adr/0006-oxy-relay-boundary.md, docs/adr/0010-public-api-compatibility.md.
39
67
  */
40
68
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -46,12 +74,19 @@ exports.INFERENCE_CONTRACT_VERSION = void 0;
46
74
  *
47
75
  * MAJOR is bumped when any individual shape's `schemaVersion` increments (at
48
76
  * least one message is now read differently by the two sides); MINOR when a
49
- * shape or an optional field is added; PATCH for documentation-only changes
50
- * that leave every parsed byte identical.
77
+ * shape or an optional field is added, when a CLOSED ENUM gains a member, or
78
+ * when a refinement changes which bytes parse; PATCH for documentation-only
79
+ * changes that leave every parsed byte identical.
80
+ *
81
+ * The last two are MINOR rather than PATCH because both produce the same
82
+ * failure: a producer on the newer set emits something the older set refuses,
83
+ * with no `schemaVersion` difference to explain it. A new enum member and a
84
+ * loosened refinement are exactly what the handshake exists to surface — a
85
+ * skew the per-message version cannot express.
51
86
  *
52
87
  * This constant is deliberately NOT embedded in the request envelope. Pinning a
53
88
  * request to the version of the whole set would make an unrelated additive
54
89
  * change to, say, the catalogue reject every in-flight inference request; the
55
90
  * per-shape `schemaVersion` is what a message is validated against.
56
91
  */
57
- exports.INFERENCE_CONTRACT_VERSION = '1.0.0';
92
+ exports.INFERENCE_CONTRACT_VERSION = '1.1.0';