@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,326 @@
1
+ /**
2
+ * The reserve → settle → refund protocol.
3
+ *
4
+ * Four records, in the order they happen:
5
+ *
6
+ * 1. **Reservation** — before a request enters the data plane, Oxy holds the
7
+ * MAXIMUM the request could cost (input units + maximum output + the
8
+ * allowed route's price ceiling). A request whose account cannot cover that
9
+ * hold is rejected before anything is spent upstream.
10
+ * 2. **Usage report** — the data plane's technical account of what was
11
+ * consumed. Units and route, never money: the data plane measures, the
12
+ * control plane prices.
13
+ * 3. **Receipt** — the immutable settlement. Carries the exact units, a COPY
14
+ * of the prices they were charged at, and the amount booked. It is never
15
+ * edited afterwards.
16
+ * 4. **Refund/reversal** — an equally immutable entry that releases an unused
17
+ * hold or reverses a settled charge. Settled history is compensated, never
18
+ * rewritten, because an invoice a customer already received must remain
19
+ * reconstructible.
20
+ *
21
+ * Every one of them is keyed by an idempotency key, so a retried call, a
22
+ * redelivered event or a duplicated webhook produces the same record rather than
23
+ * a second charge.
24
+ *
25
+ * Money is an exact decimal string throughout (ADR 0009 — never integer minor
26
+ * units, never a float), and unit counts are carried separately from it (see
27
+ * `money.ts`).
28
+ *
29
+ * Decided in: docs/adr/0009-usage-reservation-and-settlement.md.
30
+ */
31
+ import { z } from 'zod';
32
+ import { inferenceAttributionSchema } from './attribution.js';
33
+ import { deploymentIdSchema, generationIdSchema, idempotencyKeySchema, inferenceProviderSlugSchema, inferenceTimestampSchema, modelReferenceSchema, requestIdSchema, } from './identifiers.js';
34
+ import { currencyCodeSchema, exactDecimalSchema, usageQuantitySchema, usageSourceSchema, } from './money.js';
35
+ import { priceSnapshotSchema } from './priceVersion.js';
36
+ /* -------------------------------------------------------------------------- */
37
+ /* 1. Reservation */
38
+ /* -------------------------------------------------------------------------- */
39
+ /**
40
+ * Ask the ledger to hold the maximum a request could cost.
41
+ *
42
+ * `maxAmount` is the number the balance check is made against, and it is
43
+ * computed from the three inputs beside it rather than guessed: the units
44
+ * already known (the prompt), the ceiling on units still to come
45
+ * (`maxOutputTokens`), and the most expensive route the policy allows. Sizing a
46
+ * hold from a typical response rather than the worst allowed one is how a
47
+ * balance goes negative on a long generation.
48
+ */
49
+ export const usageReservationRequestSchema = z.object({
50
+ /** See `version.ts`: exchanged between the edge and the ledger on its own. */
51
+ schemaVersion: z.literal(1),
52
+ idempotencyKey: idempotencyKeySchema,
53
+ attribution: inferenceAttributionSchema,
54
+ /** Units already determined by the request itself, e.g. input tokens. */
55
+ knownUnits: z.array(usageQuantitySchema).default([]),
56
+ /** The ceiling on generated output, when the request set one. */
57
+ maxOutputTokens: z.number().int().positive().safe().optional(),
58
+ /** The price version of the most expensive route the policy permits. */
59
+ ceilingPriceVersionId: z.string().min(1).max(128),
60
+ maxAmount: exactDecimalSchema,
61
+ currency: currencyCodeSchema,
62
+ expiresInSeconds: z.number().int().positive().max(86400),
63
+ });
64
+ /** Lifecycle of a hold. Terminal states are `settled`, `released`, `expired`. */
65
+ export const usageReservationStatusSchema = z.enum([
66
+ 'held',
67
+ 'settled',
68
+ 'released',
69
+ 'expired',
70
+ ]);
71
+ /**
72
+ * A hold placed against an account's balance.
73
+ *
74
+ * Reserved amounts are shown to customers distinctly from settled charges: a
75
+ * reservation is not money spent, and presenting the two as one number makes a
76
+ * balance appear to drop and then recover for every request.
77
+ */
78
+ export const usageReservationSchema = z
79
+ .object({
80
+ /** See `version.ts`: read back by the edge and the Console on its own. */
81
+ schemaVersion: z.literal(1),
82
+ reservationId: z.string().min(1).max(128),
83
+ idempotencyKey: idempotencyKeySchema,
84
+ attribution: inferenceAttributionSchema,
85
+ status: usageReservationStatusSchema,
86
+ reservedAmount: exactDecimalSchema,
87
+ currency: currencyCodeSchema,
88
+ ceilingPriceVersionId: z.string().min(1).max(128),
89
+ createdAt: inferenceTimestampSchema,
90
+ expiresAt: inferenceTimestampSchema,
91
+ /** The receipt that consumed this hold. Present exactly when `settled`. */
92
+ settledReceiptId: z.string().min(1).max(128).optional(),
93
+ })
94
+ .superRefine((reservation, ctx) => {
95
+ if (reservation.status === 'settled' && reservation.settledReceiptId === undefined) {
96
+ ctx.addIssue({
97
+ code: z.ZodIssueCode.custom,
98
+ path: ['settledReceiptId'],
99
+ message: 'a settled reservation must name the receipt that settled it',
100
+ });
101
+ }
102
+ if (reservation.status !== 'settled' && reservation.settledReceiptId !== undefined) {
103
+ ctx.addIssue({
104
+ code: z.ZodIssueCode.custom,
105
+ path: ['settledReceiptId'],
106
+ message: 'only a settled reservation has a settling receipt',
107
+ });
108
+ }
109
+ });
110
+ /* -------------------------------------------------------------------------- */
111
+ /* 2. Usage report (data plane → Oxy) */
112
+ /* -------------------------------------------------------------------------- */
113
+ /** How a request ended, from the data plane's point of view. */
114
+ export const inferenceRequestOutcomeSchema = z.enum([
115
+ 'completed',
116
+ 'partial',
117
+ 'cancelled',
118
+ 'failed',
119
+ ]);
120
+ /**
121
+ * The data plane's technical account of one request, and the ONLY shape a
122
+ * settlement is written from.
123
+ *
124
+ * `inferenceStreamUsageEventSchema` is not a narrower version of this one that
125
+ * could be widened into it — see that event's own comment. Its units are exact
126
+ * and settleable; the record around them is not inferable, so an edge settling
127
+ * from a stream event supplies the outcome itself and never promotes the event.
128
+ *
129
+ * No money and no price: the data plane measures units and names the route it
130
+ * used, and the control plane decides what that costs. Keeping the two apart is
131
+ * what allows a price to be corrected after the fact without re-running or
132
+ * re-measuring anything.
133
+ *
134
+ * `usageSource` is load-bearing when a provider returns no usage at all: the
135
+ * report still arrives, marked `estimated`, so settlement can apply the
136
+ * estimation policy knowingly instead of treating a reconstruction as fact.
137
+ *
138
+ * `units` is a PARTITION of what the request consumed, not a set of totals with
139
+ * details hanging off them — see `USAGE_UNITS` in `money.ts`. Reporting a provider's
140
+ * nested `prompt_tokens`/`completion_tokens` verbatim charges the cached and
141
+ * reasoning tokens twice, so subtracting the children out is part of what
142
+ * "normalized" means in this shape's name.
143
+ *
144
+ * **A `completed` report carries at least one unit, and the other outcomes need
145
+ * not.** `completed` is the one outcome that asserts the customer received the
146
+ * whole answer, so "delivered in full, consumed nothing measurable" is a
147
+ * contradiction — and it is one that BILLS NOTHING: settlement prices every
148
+ * reported unit and sums, so an empty list is a free request produced by a
149
+ * provider that simply omitted its usage block. The refinement makes that shape
150
+ * unparseable, and the policy behind it is refuse-and-release: the report is
151
+ * rejected and the hold is released, never estimated and charged.
152
+ *
153
+ * The three other outcomes legitimately carry none, which is why the rule is
154
+ * conditional rather than a `.min(1)` on the field. In the reference data plane
155
+ * `failed` is DERIVED from having no units — `outcomeFor` in
156
+ * Kaana's `internal/kaana/executor.go` returns `partial` when units exist and `failed`
157
+ * when they do not — and `cancelled` is reported for a client that stopped
158
+ * before anything was measured. An unconditional minimum would refuse those
159
+ * reports, and a refused report is a request that ran, cost money upstream and
160
+ * can never be settled or refunded.
161
+ */
162
+ export const normalizedUsageReportSchema = z
163
+ .object({
164
+ /** See `version.ts`: emitted by the data plane as a whole message. */
165
+ schemaVersion: z.literal(2),
166
+ requestId: requestIdSchema,
167
+ generationId: generationIdSchema.optional(),
168
+ attribution: inferenceAttributionSchema,
169
+ outcome: inferenceRequestOutcomeSchema,
170
+ units: z.array(usageQuantitySchema),
171
+ usageSource: usageSourceSchema,
172
+ resolvedModelReference: modelReferenceSchema,
173
+ servingProvider: inferenceProviderSlugSchema,
174
+ /** Exact Kaana deployment that attempted the request; never inferred from names. */
175
+ deploymentId: deploymentIdSchema,
176
+ /** How many allowed route switches occurred while serving this request. */
177
+ routeSwitches: z.number().int().nonnegative().max(100),
178
+ startedAt: inferenceTimestampSchema,
179
+ completedAt: inferenceTimestampSchema,
180
+ timeToFirstTokenMs: z.number().int().nonnegative().safe().optional(),
181
+ })
182
+ .superRefine((report, ctx) => {
183
+ // Compared as instants: two spellings of one moment sort differently as text.
184
+ if (Date.parse(report.completedAt) < Date.parse(report.startedAt)) {
185
+ ctx.addIssue({
186
+ code: z.ZodIssueCode.custom,
187
+ path: ['completedAt'],
188
+ message: 'a request cannot complete before it started',
189
+ });
190
+ }
191
+ const units = report.units.map((quantity) => quantity.unit);
192
+ if (new Set(units).size !== units.length) {
193
+ ctx.addIssue({
194
+ code: z.ZodIssueCode.custom,
195
+ path: ['units'],
196
+ message: 'each unit is reported once, as a total',
197
+ });
198
+ }
199
+ if (report.outcome === 'completed' && report.units.length === 0) {
200
+ ctx.addIssue({
201
+ code: z.ZodIssueCode.custom,
202
+ path: ['units'],
203
+ message: 'a completed request consumed something; report at least one unit',
204
+ });
205
+ }
206
+ });
207
+ /* -------------------------------------------------------------------------- */
208
+ /* 3. Receipt (settlement) */
209
+ /* -------------------------------------------------------------------------- */
210
+ /**
211
+ * The immutable record of what a request was actually charged.
212
+ *
213
+ * `priceSnapshot` is a COPY of the unit prices applied, not just the id of the
214
+ * price version they came from, so the arithmetic on this receipt can be
215
+ * checked years later without depending on any other record still existing.
216
+ *
217
+ * `platformFeeOnly` marks a BYOK request: the upstream provider billed the
218
+ * customer's own account directly, and `billedAmount` is Oxy's service fee
219
+ * rather than the cost of the tokens. Without the flag, the two look identical
220
+ * and a BYOK customer appears to have been charged twice for one request.
221
+ */
222
+ export const usageReceiptSchema = z
223
+ .object({
224
+ /** See `version.ts`: returned to customers by `GET /v1/generations/:id`. */
225
+ schemaVersion: z.literal(1),
226
+ receiptId: z.string().min(1).max(128),
227
+ /** The hold this settled against. Absent for a charge with no reservation. */
228
+ reservationId: z.string().min(1).max(128).optional(),
229
+ idempotencyKey: idempotencyKeySchema,
230
+ attribution: inferenceAttributionSchema,
231
+ outcome: inferenceRequestOutcomeSchema,
232
+ units: z.array(usageQuantitySchema).min(1),
233
+ usageSource: usageSourceSchema,
234
+ priceSnapshot: priceSnapshotSchema,
235
+ billedAmount: exactDecimalSchema,
236
+ currency: currencyCodeSchema,
237
+ platformFeeOnly: z.boolean(),
238
+ resolvedModelReference: modelReferenceSchema,
239
+ servingProvider: inferenceProviderSlugSchema,
240
+ settledAt: inferenceTimestampSchema,
241
+ })
242
+ .superRefine((receipt, ctx) => {
243
+ if (receipt.currency !== receipt.priceSnapshot.currency) {
244
+ ctx.addIssue({
245
+ code: z.ZodIssueCode.custom,
246
+ path: ['priceSnapshot', 'currency'],
247
+ message: 'a receipt must be settled in the currency it was priced in',
248
+ });
249
+ }
250
+ const units = receipt.units.map((quantity) => quantity.unit);
251
+ if (new Set(units).size !== units.length) {
252
+ ctx.addIssue({
253
+ code: z.ZodIssueCode.custom,
254
+ path: ['units'],
255
+ message: 'each unit is settled once, as a total',
256
+ });
257
+ }
258
+ });
259
+ /* -------------------------------------------------------------------------- */
260
+ /* 4. Refund / reversal */
261
+ /* -------------------------------------------------------------------------- */
262
+ /**
263
+ * What a reversal acts on: an unused hold, or a settled charge.
264
+ *
265
+ * A discriminated union, so "release the rest of the hold" and "give back money
266
+ * already booked" can never be confused for one another — they hit different
267
+ * ledger accounts and only the second one is visible on an invoice.
268
+ */
269
+ export const usageRefundSubjectSchema = z.discriminatedUnion('kind', [
270
+ z
271
+ .object({ kind: z.literal('reservation'), reservationId: z.string().min(1).max(128) })
272
+ .strict(),
273
+ z.object({ kind: z.literal('receipt'), receiptId: z.string().min(1).max(128) }).strict(),
274
+ ]);
275
+ /** Why money was given back or a hold was released. */
276
+ export const usageRefundReasonSchema = z.enum([
277
+ 'unused_reservation',
278
+ 'client_cancelled',
279
+ 'upstream_failure',
280
+ 'partial_stream',
281
+ 'usage_unavailable',
282
+ 'billing_correction',
283
+ 'duplicate_charge',
284
+ ]);
285
+ /** Reasons that can only ever act on a settled charge. */
286
+ const RECEIPT_ONLY_REFUND_REASONS = new Set([
287
+ 'billing_correction',
288
+ 'duplicate_charge',
289
+ ]);
290
+ /**
291
+ * An immutable reversal entry.
292
+ *
293
+ * `amount` is non-negative like every other amount in this contract: the
294
+ * direction is carried by the record being a refund, not by a sign that a
295
+ * consumer could read the wrong way round. Idempotent by key, so a retried
296
+ * refund releases the same money once.
297
+ */
298
+ export const usageRefundSchema = z
299
+ .object({
300
+ /** See `version.ts`: a ledger record read back on its own. */
301
+ schemaVersion: z.literal(1),
302
+ refundId: z.string().min(1).max(128),
303
+ idempotencyKey: idempotencyKeySchema,
304
+ attribution: inferenceAttributionSchema,
305
+ subject: usageRefundSubjectSchema,
306
+ reason: usageRefundReasonSchema,
307
+ amount: exactDecimalSchema,
308
+ currency: currencyCodeSchema,
309
+ createdAt: inferenceTimestampSchema,
310
+ })
311
+ .superRefine((refund, ctx) => {
312
+ if (refund.reason === 'unused_reservation' && refund.subject.kind !== 'reservation') {
313
+ ctx.addIssue({
314
+ code: z.ZodIssueCode.custom,
315
+ path: ['reason'],
316
+ message: 'an unused reservation is released against the reservation, not a receipt',
317
+ });
318
+ }
319
+ if (RECEIPT_ONLY_REFUND_REASONS.has(refund.reason) && refund.subject.kind !== 'receipt') {
320
+ ctx.addIssue({
321
+ code: z.ZodIssueCode.custom,
322
+ path: ['reason'],
323
+ message: `${refund.reason} reverses a settled charge, so it acts on a receipt`,
324
+ });
325
+ }
326
+ });
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Version rule for the Oxy↔data-plane inference contracts.
3
+ *
4
+ * Oxy is the control plane; the inference data plane is a separate service.
5
+ * They are deployed independently, in different repositories, possibly in
6
+ * different languages.
7
+ * Every shape they exchange therefore carries its version IN THE PARSED DATA,
8
+ * never as a comment or an out-of-band assumption, so a producer running ahead
9
+ * of a consumer fails loudly at the parse instead of being silently reinterpreted.
10
+ *
11
+ * The rule, enforced by `src/__tests__/inference.compatibility.test.ts`:
12
+ *
13
+ * - A schema carries `schemaVersion: z.literal(<n>)` **if and only if** it can
14
+ * appear on the wire as a whole message — a request envelope, a stream event,
15
+ * a catalogue descriptor, a ledger record, an error body.
16
+ * - A schema that only ever appears EMBEDDED inside such a message (the
17
+ * attribution block, one message part, one usage quantity, a data-retention
18
+ * policy) carries no version of its own: it inherits the version of the
19
+ * envelope it rides in. Versioning it separately would create two versions
20
+ * that can disagree about one byte stream.
21
+ * - A shape that is BOTH — `inferenceErrorSchema` is returned as an HTTP body
22
+ * and also rides inside the stream's error event — keeps its own version.
23
+ * The envelope's version then governs the envelope and the payload's governs
24
+ * the payload, which is two versions of two things rather than two versions
25
+ * of one.
26
+ * - Every exported object schema in `src/inference/` must fall into exactly one
27
+ * of those groups. The compatibility test holds both lists as exact
28
+ * equalities, so a new shape that is in neither fails the build rather than
29
+ * quietly shipping unversioned.
30
+ *
31
+ * A shape's own version is bumped when its meaning changes in a way a consumer
32
+ * pinned to the previous version would misread — a field removed, a field's
33
+ * units changed, a closed enum's member given a new meaning. Adding an OPTIONAL
34
+ * field is additive and does not bump it, because a consumer on the previous
35
+ * version parses the message correctly and simply does not read the new field.
36
+ *
37
+ * ## Which shapes reject an unknown field
38
+ *
39
+ * That last rule is why the shapes EXCHANGED WITH THE DATA PLANE are not
40
+ * `.strict()` at their top level — the request envelope, the four usage records,
41
+ * the stream events, the error body, the catalogue descriptors, the price
42
+ * version. The split is a decision rather than an omission: `.strict()` and
43
+ * "adding an optional field is additive" cannot both hold on one shape, because
44
+ * a producer one minor version ahead would have its whole message REFUSED
45
+ * rather than its new field ignored. For a usage report that means a request
46
+ * already served upstream can never be settled and Oxy absorbs its cost, which
47
+ * is a worse failure than the one strictness would have caught.
48
+ *
49
+ * Their LEAVES are strict, and that is where the protection lives: a stripped
50
+ * field is the worse outcome exactly where it would be a leak or a second
51
+ * source of truth, because it disappears at this parse and survives in the
52
+ * producer, which is where somebody eventually reads it. So
53
+ * `clientRequestMetadataSchema` (no IP, ever), `moneySchema` (no convenience
54
+ * float beside the exact decimal), `providerErrorPassthroughSchema` (no
55
+ * upstream request or headers beside the message), `usageQuantitySchema` and
56
+ * `unitPriceSchema` all refuse an unknown field, while the envelope carrying
57
+ * them tolerates an additive one.
58
+ *
59
+ * A shape Oxy does NOT exchange with the data plane is strict at its top level
60
+ * too, since nothing there can run ahead of this package:
61
+ * `providerConnectionSchema`, where an unknown field is how a BYOK credential
62
+ * escapes, and the billing and entitlement records, where one is a second
63
+ * number beside an exact amount.
64
+ *
65
+ * A SIGNED document is strict at its top level for a third reason, and there it
66
+ * is forced rather than chosen. `aliaModelReleaseManifestSchema` carries
67
+ * signatures over its own canonical bytes, so a field stripped at this parse is a
68
+ * field missing from the bytes a verifier re-canonicalizes: a tolerant parse
69
+ * would report an invalid SIGNATURE where the truth is that this build does not
70
+ * understand the DOCUMENT. Its producer can run ahead of this package — Alia's
71
+ * release tooling is deployed independently — so the usual argument applies here
72
+ * and is outweighed, because the refusal costs an operator one retry after Oxy
73
+ * takes the newer contract, while the tolerant parse costs a misdiagnosis of a
74
+ * cryptographic failure.
75
+ *
76
+ * Decided in: docs/adr/0006-oxy-kaana-boundary.md,
77
+ * docs/adr/0010-public-api-compatibility.md,
78
+ * docs/adr/0017-authorized-routes-in-the-envelope.md.
79
+ */
80
+ /**
81
+ * Version of the contract SET as a whole — the value the control plane and the
82
+ * data plane exchange in a startup/health handshake to establish that they were built against
83
+ * compatible definitions before a single inference request is served.
84
+ *
85
+ * MAJOR is bumped when any individual shape's `schemaVersion` increments (at
86
+ * least one message is now read differently by the two sides); MINOR when a
87
+ * shape or an optional field is added, when a CLOSED ENUM gains a member, or
88
+ * when a refinement changes which bytes parse; PATCH for documentation-only
89
+ * changes that leave every parsed byte identical.
90
+ *
91
+ * The last two are MINOR rather than PATCH because both produce the same
92
+ * failure: a producer on the newer set emits something the older set refuses,
93
+ * with no `schemaVersion` difference to explain it. A new enum member and a
94
+ * loosened refinement are exactly what the handshake exists to surface — a
95
+ * skew the per-message version cannot express.
96
+ *
97
+ * This constant is deliberately NOT embedded in the request envelope. Pinning a
98
+ * request to the version of the whole set would make an unrelated additive
99
+ * change to, say, the catalogue reject every in-flight inference request; the
100
+ * per-shape `schemaVersion` is what a message is validated against.
101
+ */
102
+ export const INFERENCE_CONTRACT_VERSION = '2.0.0';
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Encrypted off-device identity backup contract (b3 Feature 1).
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the "encrypted identity backup" flow, where a
5
+ * client stores an encrypted copy of its self-custody identity key off-device so
6
+ * a lost/wiped device can be recovered from the recovery phrase ALONE — without
7
+ * the platform ever seeing the phrase, the derived encryption key, or the
8
+ * plaintext private key.
9
+ *
10
+ * Zero-knowledge design (mirrors the zero-cookie `DeviceSession.secretHash`
11
+ * pattern): the client derives, from the FULL 64-byte BIP-39 seed, both an
12
+ * encryption key (`backupKey`) and a locator (`lookupId`) via HKDF with
13
+ * domain-separated `info` labels. It uploads ONLY the XChaCha20-Poly1305
14
+ * ciphertext plus the raw `lookupId`; the server stores the ciphertext and
15
+ * `sha256(lookupId)` (never the raw `lookupId`). Restoration re-derives both
16
+ * from the phrase, fetches the envelope by `lookupId`, and decrypts locally.
17
+ *
18
+ * The server can neither locate a backup (it lacks the seed to compute the
19
+ * lookup id) nor decrypt one (it lacks the seed to compute the backup key) — a
20
+ * DB dump yields only opaque ciphertext keyed by an un-invertible hash.
21
+ *
22
+ * The producer (`@oxy.so/api`) validates its request/response against these
23
+ * schemas; the consumer (`@oxy.so/core` identity-backup mixin) validates its
24
+ * input against the same definitions, so the wire shape cannot drift.
25
+ *
26
+ * All shapes here are FLAT (no nested objects), so `z.infer<>` is safe under a
27
+ * consumer's node10 `moduleResolution`. Platform-agnostic — zod only, ESM-safe
28
+ * (no `require()`).
29
+ */
30
+ import { z } from 'zod';
31
+ /** 256-bit backup locator (32 bytes), lowercase/uppercase hex. */
32
+ export const backupLookupIdSchema = z
33
+ .string()
34
+ .trim()
35
+ .regex(/^[0-9a-fA-F]{64}$/, 'lookupId must be 64 hex characters');
36
+ /**
37
+ * The stored, self-describing encrypted backup as it lives at rest and travels
38
+ * on the public restore endpoint. Contains NO secret and NO locator: the
39
+ * `lookupId` is uploaded separately (see {@link backupUploadRequestSchema}) and
40
+ * only its hash is ever persisted.
41
+ *
42
+ * - `version` — envelope/KDF version, so a future scheme migration is
43
+ * distinguishable at rest.
44
+ * - `algorithm` — the AEAD used. Pinned literal so a mismatched decryptor
45
+ * fails loudly rather than silently.
46
+ * - `kdfInfo` — the HKDF `info` label used to derive the encryption key
47
+ * (domain-separation tag; documents exactly which context produced the key).
48
+ * - `nonce` — the 24-byte XChaCha20-Poly1305 nonce, hex.
49
+ * - `ciphertext` — the encrypted `{privateKey, publicKey, createdAt}` payload
50
+ * with the appended Poly1305 tag, hex.
51
+ * - `publicKeyHint` — a short, non-sensitive prefix of the backed-up identity's
52
+ * public key, so the owner can recognise WHICH identity a backup belongs to
53
+ * without exposing the full key. Bound into the AEAD associated data.
54
+ * - `createdAt` — ISO-8601 creation timestamp.
55
+ */
56
+ export const encryptedBackupEnvelopeSchema = z.object({
57
+ version: z.number().int().positive(),
58
+ algorithm: z.literal('xchacha20poly1305'),
59
+ kdfInfo: z.string().min(1),
60
+ nonce: z.string().trim().min(1),
61
+ ciphertext: z.string().trim().min(1),
62
+ publicKeyHint: z.string().trim().min(1),
63
+ createdAt: z.string().trim().min(1),
64
+ });
65
+ /**
66
+ * Request body of `POST /identity/backup` — the envelope PLUS the raw
67
+ * `lookupId`. The server sha256-hashes `lookupId` before storing it (it never
68
+ * persists the raw value), and upserts by the authenticated user id so a
69
+ * re-upload REPLACES the prior backup rather than accumulating duplicates.
70
+ */
71
+ export const backupUploadRequestSchema = encryptedBackupEnvelopeSchema.extend({
72
+ /**
73
+ * The raw 256-bit backup locator (hex), derived client-side from the seed
74
+ * with a domain-separated HKDF `info`. The server stores ONLY its sha256; a
75
+ * DB dump therefore cannot recompute a locator to enumerate backups.
76
+ */
77
+ lookupId: backupLookupIdSchema,
78
+ });
79
+ /**
80
+ * Response of `GET /identity/backup/status` (and the write/delete acks): whether
81
+ * the authenticated user has a stored backup, plus the non-sensitive hint +
82
+ * timestamp when one exists. Carries no ciphertext and no locator.
83
+ */
84
+ export const backupStatusResponseSchema = z.object({
85
+ exists: z.boolean(),
86
+ publicKeyHint: z.string().optional(),
87
+ createdAt: z.string().optional(),
88
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Key-rotation contract (b3 Feature 3 — key rotation + last-credential replacement).
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the atomic key-rotation flow:
5
+ * - `POST /auth/rotate/challenge` — mint a single-use `rotate_key` challenge.
6
+ * - `POST /auth/rotate/complete` — prove control of the CURRENT (old) key and
7
+ * atomically swap in the new one.
8
+ *
9
+ * Rotation is an atomic REPLACE of the single identity key, never a
10
+ * remove-then-add, so it never passes through a zero-auth-method state and is
11
+ * independent of the unlink guards. Because the client proves possession of the
12
+ * current key (from SecureStore OR a recovery-phrase re-derivation), the LAST
13
+ * remaining credential can be replaced — the server only cares that the
14
+ * signature validates against the current `publicKey`.
15
+ *
16
+ * The API validates its output against these schemas; `@oxy.so/core`'s identity
17
+ * mixin validates its input against the same definitions, so producer and
18
+ * consumer cannot drift.
19
+ *
20
+ * All shapes here are FLAT (no nested objects), so `z.infer<>` is safe under a
21
+ * consumer's node10 `moduleResolution` — no interface-pinning needed.
22
+ *
23
+ * Platform-agnostic — zod only, ESM-safe (no `require()`).
24
+ */
25
+ import { z } from 'zod';
26
+ /**
27
+ * Response of `POST /auth/rotate/challenge`: the single-use `rotate_key`
28
+ * challenge the client must sign with its CURRENT key, plus its expiry.
29
+ */
30
+ export const rotateKeyChallengeResponseSchema = z.object({
31
+ challenge: z.string(),
32
+ /** ISO-8601 expiry timestamp. */
33
+ expiresAt: z.string(),
34
+ });
35
+ /**
36
+ * Request body of `POST /auth/rotate/complete`.
37
+ *
38
+ * Two proofs are required:
39
+ * - `signature` — the CURRENT (old) key signs
40
+ * `JSON.stringify({ action: 'rotate_key', userId, oldPublicKey, newPublicKey,
41
+ * challenge, timestamp })` (proves control of the key being replaced).
42
+ * - `newKeyProof` — the NEW key signs
43
+ * `JSON.stringify({ action: 'rotate_key_new', userId, newPublicKey, challenge,
44
+ * timestamp })` (proof-of-possession of the key being rotated IN; prevents an
45
+ * attacker rotating their account to a re-encoding of someone else's key they
46
+ * do not control).
47
+ *
48
+ * The request carries ONLY `newPublicKey` — `oldPublicKey` and `userId` are
49
+ * derived server-side from the authenticated user document (never
50
+ * client-supplied), so a caller cannot prove control of key X while rotating
51
+ * key Y.
52
+ */
53
+ export const rotateKeyCompleteRequestSchema = z.object({
54
+ newPublicKey: z.string().trim().min(1),
55
+ challenge: z.string().trim().min(1),
56
+ signature: z.string().trim().min(1),
57
+ /** Proof-of-possession: the NEW key signs the rotate_key_new payload. */
58
+ newKeyProof: z.string().trim().min(1),
59
+ timestamp: z.number(),
60
+ /**
61
+ * When true, all OTHER active sessions for the account are revoked after a
62
+ * successful rotation (the rotating device stays signed in). Use it when the
63
+ * old key is presumed compromised.
64
+ */
65
+ signOutEverywhere: z.boolean().optional(),
66
+ });
67
+ /** Response of `POST /auth/rotate/complete`: the account's new (rotated) public key. */
68
+ export const rotateKeyCompleteResponseSchema = z.object({
69
+ success: z.boolean(),
70
+ publicKey: z.string(),
71
+ message: z.string(),
72
+ });
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Link-preview / unfurl API contracts.
3
+ *
4
+ * SINGLE SOURCE OF TRUTH for the wire shape of Oxy's link-preview ("unfurl")
5
+ * resolution surface: the single `GET` lookup and the `POST` batch lookup that
6
+ * every app calls through the SDK so apps stop duplicating their own
7
+ * link-metadata fetching. The API validates its OUTPUT against these schemas;
8
+ * every consumer (`@oxy.so/core`'s link mixin and the apps that call it)
9
+ * validates its INPUT against the same definitions, so producer and consumers
10
+ * cannot drift.
11
+ *
12
+ * Design anchors:
13
+ * - Oxy owns resolution. The `image` (and `favicon`) URLs a preview carries are
14
+ * re-hosted on Oxy media (`cloud.oxy.so/<fileId>`), never raw remote URLs —
15
+ * apps render them directly with no per-app proxy.
16
+ * - Resolution is best-effort and asynchronous. A preview is `'resolved'` once
17
+ * metadata is materialised, `'pending'` while a first-seen URL is being
18
+ * fetched in the background, or `'empty'` when the target yielded no usable
19
+ * metadata. `resolvedAt` (ISO datetime) is present only once `'resolved'`.
20
+ * - The batch response is keyed by the REQUESTED url (the exact string the
21
+ * caller sent), not the canonical/final URL, so a caller can always look its
22
+ * own input back up; the canonical URL lives on `LinkPreview.url`.
23
+ *
24
+ * The `LinkPreview` / `LinkPreviewBatchResponse` exports are declared as explicit
25
+ * `interface`s (with their runtime schemas annotated `z.ZodType<Interface>`),
26
+ * following the same rationale as `UserNameResponse` in `./userResponse`: a
27
+ * `z.infer<>` of a nested-object schema can degrade to `{}` under a consumer's
28
+ * `moduleResolution: "node"` (node10) resolution. A literal interface emits the
29
+ * field types verbatim in the `.d.ts` and survives BOTH `node` and `bundler`
30
+ * resolution. The flat batch-request schema (no nested-object hazard) is inferred
31
+ * via `z.infer<>`.
32
+ *
33
+ * Platform-agnostic — zod only, no react/react-native/expo. ESM-safe (no
34
+ * `require()`).
35
+ */
36
+ import { z } from 'zod';
37
+ export const linkPreviewSchema = z.object({
38
+ url: z.string(),
39
+ status: z.enum(['resolved', 'pending', 'empty']),
40
+ title: z.string().optional(),
41
+ description: z.string().optional(),
42
+ image: z.string().optional(),
43
+ siteName: z.string().optional(),
44
+ favicon: z.string().optional(),
45
+ resolvedAt: z.string().optional(),
46
+ });
47
+ /* -------------------------------------------------------------------------- */
48
+ /* Batch request / response */
49
+ /* -------------------------------------------------------------------------- */
50
+ /**
51
+ * Request body for the batch unfurl endpoint. Between 1 and 50 URLs per call;
52
+ * the server resolves each (returning a `'pending'` placeholder for any URL it
53
+ * has not seen before and is fetching in the background).
54
+ */
55
+ export const linkPreviewBatchRequestSchema = z.object({
56
+ urls: z.array(z.string().max(2048)).min(1).max(50),
57
+ });
58
+ export const linkPreviewBatchResponseSchema = z.object({
59
+ data: z.record(z.string(), linkPreviewSchema),
60
+ });
61
+ /**
62
+ * Wire shape of the single-URL unfurl lookup (`GET`) — a bare
63
+ * {@link LinkPreview}.
64
+ */
65
+ export const linkPreviewResponseSchema = linkPreviewSchema;