@alytegen/sdk 0.7.0 → 0.9.0-next.1

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.
package/BROWSER.md CHANGED
@@ -93,8 +93,10 @@ const attempt = { agentId, tierId, quantity: 1, attemptId: crypto.randomUUID() }
93
93
  // across reloads and reconnects. Namespace it to this buyer/shop/cart.
94
94
  await attempts.save(attempt);
95
95
  const purchase = await buyer.buy(attempt);
96
- if (purchase.status === 'pending') {
97
- const receipt = await buyer.payment(purchase.intentId); // refresh later if pending
96
+ if (purchase.status === 'pending' && 'purchaseId' in purchase && purchase.purchaseId) {
97
+ const state = await buyer.resumePurchase(purchase.purchaseId); // same purchase, never buy again
98
+ } else if (purchase.status === 'pending' && 'intentId' in purchase) {
99
+ const receipt = await buyer.payment(purchase.intentId); // legacy receipt
98
100
  }
99
101
  ```
100
102
 
@@ -102,8 +104,8 @@ The UUID is required; the SDK never invents one or retries requests automaticall
102
104
  After a network failure, resume with the **same saved attempt**, including agent,
103
105
  tier, quantity and ID. Never create a fresh attempt to retry an uncertain charge.
104
106
  `settled` is success; `pending` remains unresolved. `sca_required` is an authentication
105
- continuation requirement; browser SCA resume is not yet available. Do not treat it
106
- as success or dispatch a new purchase. Non-2xx responses throw `AlyteApiError` with
107
+ continuation requirement: use `openChallenge` when a `purchaseId` is present. Do not
108
+ treat it as success or dispatch a new purchase. Non-2xx responses throw `AlyteApiError` with
107
109
  `status`, `code` and `details`; purchase `402` outcome bodies are in `details`.
108
110
 
109
111
  Other methods: `me()`, `catalog()`, `agents()`, `instruments()`, `instrumentCaps()`,
@@ -114,3 +116,82 @@ live availability. An ordinary bounded bearer cannot create or widen spending au
114
116
 
115
117
  Your backend still fulfills from verified settlement webhooks, idempotently.
116
118
  Browser completion messages are presentation state, not fulfillment evidence.
119
+
120
+ ## Finish a bank challenge for an existing purchase
121
+
122
+ On deployments supporting buyer-present purchases, `buy()` can return
123
+ `{ status: 'sca_required', purchaseId, challenge: { expiresAt } }`. Keep the opaque
124
+ `purchaseId` alongside the original attempt. Do not call `buy()` again or allocate
125
+ another attempt ID to handle the challenge.
126
+
127
+ ```ts
128
+ import { createBuyerClient, openChallenge } from '@alytegen/sdk/browser';
129
+
130
+ const client = createBuyerClient({ baseUrl, bearer });
131
+ const purchase = await client.buy(savedAttempt);
132
+ if (['sca_required', 'pending'].includes(purchase.status) && 'purchaseId' in purchase && purchase.purchaseId) {
133
+ const result = await openChallenge({
134
+ baseUrl, merchantId, bearer, purchaseId: purchase.purchaseId,
135
+ container: document.querySelector('#bank-approval')!,
136
+ signal: modalAbortController.signal,
137
+ onStatus: ({ purchaseId, status }) => showPurchaseStatus(purchaseId, status),
138
+ });
139
+ // result has only purchaseId and the server's terminal status:
140
+ // settled | refused | cancelled | expired.
141
+ }
142
+ ```
143
+
144
+ The launcher uses the same registered parent origin, in-memory bounded bearer,
145
+ shop binding and optional theme/language parameters as `openConsent`. It opens a
146
+ separate challenge view. Only the Alyte frame retrieves provider action material.
147
+ Stripe uses `handleNextAction`; Adyen sandbox native 3DS2 uses the pinned Adyen Web
148
+ component, real browser information, and the server's bound action round. The
149
+ server verifies the original payment and its details proof. No browser `approved` flag is accepted. Parent callbacks
150
+ contain only the purchase ID and safe status, never provider secrets or receipts.
151
+
152
+ `openChallenge` remains open for pending or action-required purchases. It polls
153
+ `resume` at a bounded interval while visible, with at most one request in flight,
154
+ and pauses polling during issuer interaction. Aborting removes the frame and
155
+ rejects with `challenge_closed`; it does not cancel or retry the purchase.
156
+ Reopening with the same purchase ID recovers it. The buyer can explicitly request
157
+ cancellation inside the frame; the UI waits for the server's verified outcome.
158
+
159
+ For status outside the frame, use `client.purchase(purchaseId)` (read the durable
160
+ state), `client.resumePurchase(purchaseId)` (ask the server to retrieve/advance the
161
+ same payment), or `client.cancelPurchase(purchaseId)` (request verified
162
+ cancellation). Resume and cancel send an empty body and are never automatically
163
+ retried by these client methods. The SDK intentionally exposes no action-material
164
+ method. Older mock flows may return `sca_required` without a purchase ID; this
165
+ launcher does not turn those mock tokens into real bank authentication.
166
+
167
+
168
+ ## Recover a queued purchase
169
+
170
+ A watch can become `awaiting_sca`. Its safe `result` carries `purchaseId` and
171
+ `challenge.expiresAt`. A `firing` watch can also carry a pending `purchaseId` while
172
+ its provider outcome is uncertain. Open that existing purchase with `openChallenge`;
173
+ do not call `buy`, create another watch, or infer cancellation from the deadline.
174
+ `observeWatch` keeps reading until the server reports a terminal watch state.
175
+
176
+ ```ts
177
+ const { watch } = await client.getWatch(savedWatchId);
178
+ if (['awaiting_sca', 'firing'].includes(watch.status) && watch.result?.purchaseId) {
179
+ await openChallenge({ baseUrl, merchantId, bearer,
180
+ purchaseId: watch.result.purchaseId, container: challengeContainer,
181
+ signal: modalAbortController.signal });
182
+ }
183
+ ```
184
+
185
+ The merchant webhook SDK exposes `onWatchActionRequired` for signed
186
+ `watch.action_required` deliveries. The event contains safe watch/purchase IDs,
187
+ `buyerRef`, merchant/tenant scope, and the original deadline. Deduplicate by
188
+ `eventId` and relay the action through the merchant's own buyer channel; the SDK
189
+ deliberately passes redeliveries to the handler. A link grants no authority: the
190
+ buyer still needs their own shop-bound session. This event is never fulfilment.
191
+ A verified `approval_expired` or `buyer_cancelled` outcome ends the watch without
192
+ automatically starting another purchase.
193
+
194
+ Adyen action/details remain exclusive to the Alyte challenge frame. The public
195
+ browser client exposes safe status/resume/cancel only. Native sandbox actions are
196
+ supported by this slice; redirect actions, production activation, and real-provider
197
+ qualification remain separate gates. Closing the frame preserves the purchase.
package/QUICKSTART.md CHANGED
@@ -31,7 +31,12 @@ const { tier } = await alyte.createTier({ eventId: event.id, title: 'GA', priceM
31
31
 
32
32
  Money is **integer minor units** everywhere (`4900` = €49.00). Floats are refused.
33
33
 
34
- SDK 0.7.0 also includes `alyte.accessRules` and `alyte.memberships` for
34
+ SDK 0.8.0 adds per-event ticket limits (`setEventPurchaseLimit`, `getEventPurchaseLimit`,
35
+ `clearEventPurchaseLimit`), idempotent pool creation (`createPool({ externalRef })`),
36
+ all-or-nothing basket checkout on `AlyteAgent` (`reserveBasket`, `getReservation`,
37
+ `quoteReservation`, `confirmReservation`, `releaseReservation`, `resolveBasketSca`), and
38
+ browser queue-place / bank-challenge continuation (`createWatch`, `observeWatch`,
39
+ `openChallenge`). SDK 0.7.0 added `alyte.accessRules` and `alyte.memberships` for
35
40
  merchant-controlled early access: save a draft, preview, schedule or cancel, and attest or
36
41
  revoke membership. They require a server at or after sandbox revision `alyte-sandbox-00133-v77`.
37
42
  See [the access-rule workflow](./README.md#access-rules-and-membership)
package/README.md CHANGED
@@ -21,9 +21,10 @@ npm install @alytegen/sdk
21
21
  | `AlyteMerchant` | API token (console → API keys) | your server only | shops, events, tiers, PSP links, buyer-session mint, payments visibility |
22
22
  | `AlyteAgent` | agent JWT | your agent runtime | discover → quote → hold → confirm |
23
23
  | `createWebhookHandler` / `verifyWebhookSignature` | webhook secret | your server | signed, at-least-once purchase events with typed dispatch |
24
- | `exchangeBuyerSession` / `createBuyerClient` / `openConsent` from `@alytegen/sdk/browser` | bounded buyer bearer | partner browser/chat | isolated consent, then buy/watch/list/revoke within existing authority |
24
+ | `exchangeBuyerSession` / `createBuyerClient` / `openConsent` / `openChallenge` from `@alytegen/sdk/browser` | bounded buyer bearer | partner browser/chat | isolated consent and challenge continuation, then buy/watch/list/revoke within existing authority |
25
25
 
26
- The browser entry arrived in 0.4.0; 0.7.0 is the current release. See [the chat integration](./BROWSER.md) for setup,
26
+ The browser entry arrived in 0.4.0; 0.8.0 is the current release, and `0.9.0-next` is the preview
27
+ (`npm install @alytegen/sdk@next`, see [Preview](#preview-090-next)). See [the chat integration](./BROWSER.md) for setup,
27
28
  cookie-independent consent, reconnecting and handling uncertain purchases.
28
29
 
29
30
  ## Merchant: onboard in four calls
@@ -91,6 +92,12 @@ with `catalog_too_large` if any source relation exceeds 2,000 rows, including pr
91
92
  eligibility rows. `listLocations` has a separate 2,000-row bound. Neither returns a
92
93
  truncated result.
93
94
 
95
+ Use `setEventPurchaseLimit`, `getEventPurchaseLimit` and `clearEventPurchaseLimit` to
96
+ cap the tickets one customer can hold or buy across an event (`maxPerCustomer`, optional
97
+ `maxHeldPerCustomer` for unpaid holds, and optional `countWaitingWatches` for queued
98
+ purchases). `PUT` replaces the whole limit, and the first `PUT` counts earlier sales on
99
+ the event.
100
+
94
101
  ## Access rules and membership
95
102
 
96
103
  Available since SDK 0.7.0; requires a server at or after sandbox revision
@@ -184,6 +191,43 @@ Two kinds of session, decided by how you mint:
184
191
  ceilings answers `403 merchant_consent_ceiling_exceeded` and Alyte's screen falls back to the
185
192
  buyer's own code; without the enablement, the mint answers `403 merchant_consent_not_enabled`.
186
193
 
194
+ ## Queue a buyer's agent and show their place in line
195
+
196
+ Available since SDK 0.8.0 (requires a server with `GET /v1/buyer/watch-capabilities`). From the browser entry point,
197
+ with the bounded buyer bearer:
198
+
199
+ ```ts
200
+ import { createBuyerClient, observeWatch } from '@alytegen/sdk/browser';
201
+
202
+ const buyer = createBuyerClient({ baseUrl: ALYTE_URL, bearer });
203
+ // Save the whole instruction (never the bearer) BEFORE sending; resend the SAME one after a timeout.
204
+ const instruction = {
205
+ requestId: crypto.randomUUID(),
206
+ agentId,
207
+ request: { kind: 'ticketing' as const, tierId, quantity: 2 },
208
+ condition: { kind: 'price_at_or_below' as const, maxChargeMinor: 10_000, currency: 'EUR' as const },
209
+ expiresAt: '2026-12-01T12:00:00Z',
210
+ };
211
+ await saved.put(instruction);
212
+ const { watch } = await buyer.createWatch(instruction);
213
+
214
+ const stop = new AbortController();
215
+ observeWatch({ client: buyer, watchId: watch.id, signal: stop.signal,
216
+ onUpdate: (w) => render(w.queue), // { place: { kind, position, requestsAhead }, waitingReason, … }
217
+ onError: (_e, last, stopped) => showStale(last, stopped) });
218
+ ```
219
+
220
+ `maxChargeMinor` is the most the buyer pays **for the whole charge**, tax and buyer fees included;
221
+ equality qualifies. `{ kind: 'available' }` buys as soon as the units are there. An older server
222
+ refuses `createWatch` — it never falls back to the legacy `watch()`, which would drop the condition.
223
+
224
+ The place comes from Alyte's dispatcher, never from counting a list: one place per request (four
225
+ tickets are one place), counted within the capacity the requests compete for and within the
226
+ buyer's access window (`queue.phaseLabel`). The order is oldest first; a smaller request may be
227
+ served past an older, larger one at most three times, then the line holds for it. A request
228
+ waiting on its own price target has no place until it qualifies. A place is not a reservation or
229
+ a promise of tickets.
230
+
187
231
  ## Receive purchases
188
232
 
189
233
  ```ts
@@ -212,9 +256,109 @@ const out = await agent.confirm(hold.id,
212
256
  No amount is passed at confirm — the charge is the locked quote. A spend-cap refusal means
213
257
  the buyer's mandate said no: surface it, don't retry.
214
258
 
259
+ ## Agent: baskets with one payment
260
+
261
+ Available since SDK 0.8.0. Use `reserveBasket`, `getReservation`, `quoteReservation`,
262
+ `confirmReservation`, `releaseReservation` and `resolveBasketSca` for the existing
263
+ `/v1/reservations/*` API. Reading a reservation requires `payments:read`; the other
264
+ methods require `payments:write`. Discovery also exposes tier `role`, `category`,
265
+ `countsTowardPartySize` and `linkRule` so an agent can include required parent tickets.
266
+
267
+ ```ts
268
+ const reservation = await agent.reserveBasket({
269
+ lines: [{ tierId: adultTierId, quantity: 2 }, { tierId: childTierId, quantity: 1 }],
270
+ scheme: 'visa', geo: 'DE',
271
+ });
272
+ const quote = await agent.quoteReservation(reservation.id);
273
+ // Persist the reservation ID, these inputs and the key BEFORE confirming.
274
+ const input = { quoteId: quote.id, instrumentToken, scheme: 'visa' as const, geo: 'DE' };
275
+ const options = { idempotencyKey: crypto.randomUUID() };
276
+ const outcome = await agent.confirmReservation(reservation.id, input, options);
277
+ if (outcome.status === 'settled' && outcome.result.status === 'authorized'
278
+ && outcome.reservationStatus === 'confirmed') {
279
+ // The complete basket was paid and confirmed.
280
+ }
281
+ ```
282
+
283
+ A basket holds 1–20 lines from one merchant in one currency, atomically. In 0.8.0 every line
284
+ must fit in full; the preview adds baskets that may shrink within limits you set and seat
285
+ requests (see [Preview](#preview-090-next)). The server enforces link rules,
286
+ party-size limits, add-on permission and spending caps across the whole basket.
287
+ The `BasketQuote` has `lines` and one `chargeMinor`; it has no single `unitPriceMinor`.
288
+
289
+ Both confirmation and SCA resolution return the complete `ConfirmReservationOutcome`,
290
+ including HTTP 402 business outcomes. `sca_required` keeps the basket held; continue
291
+ the original challenge with `resolveBasketSca(continueToken, outcome)` using the
292
+ same authenticated agent and the server's verified challenge flow. `sca_failed`
293
+ releases it. A settled decline is a known refusal. `payment_pending`, or a settled
294
+ error with `reservationStatus: 'reconcile'`, needs payment recovery; do not fulfil,
295
+ release stock, or create a new purchase to retry it. Ordinary API refusals still
296
+ throw `AlyteApiError` with their code and details.
297
+
298
+ The client never retries automatically. After a lost confirmation response, reuse
299
+ the saved reservation, inputs and idempotency key. Reserve is not idempotent: retrying
300
+ it creates another hold. If a buyer abandons a known unpaid basket, call
301
+ `releaseReservation(reservation.id)`; the server refuses release during payment.
302
+ See [`examples/agent-basket.ts`](./examples/agent-basket.ts) for a runnable example.
303
+
304
+ ## Preview: 0.9.0-next
305
+
306
+ `npm install @alytegen/sdk@next`. The preview works against Alyte's development environment
307
+ (`https://dev.alytegen.com`); the stable environment does not run these features yet, and names
308
+ may still change before 0.9.0.
309
+
310
+ **Baskets that may shrink.** A line may carry `minQuantity` (fewest units worth having),
311
+ `required: false` (the line may be left out) and `step` (keep a multiple, e.g. `2` for pairs).
312
+ Alyte reserves the largest basket that fits the stock, the link rules and the buyer's
313
+ permission, in your line order. `reservation.lineOutcomes` lists every requested line as
314
+ `filled`, `reduced` or `dropped` with a `reason`; `reservation.lines` holds only what was reserved.
315
+
316
+ ```ts
317
+ const reservation = await agent.reserveBasket({ lines: [
318
+ { tierId: adultTierId, quantity: 4, minQuantity: 2, step: 2 },
319
+ { tierId: parkingTierId, quantity: 1, required: false },
320
+ ] });
321
+ for (const o of reservation.lineOutcomes ?? []) console.log(o.tierId, o.status, o.quantity, o.reason);
322
+ ```
323
+
324
+ **Seat requests.** On a seated ticket type whose shop has a verified venue chart, a line may carry
325
+ `seatRequest` instead of exact `seats`. `limits` are enforced (`sections`, `rows`, `traits`,
326
+ `together`, `allowSplit`, `blockSize`); `preferences` only rank what the limits allow.
327
+ `blockSize: 2` (pairs only) needs `allowSplit: true`.
328
+
329
+ **Seat offers.** Reserve with `deferAllocation: true`, then `requestOffers(reservation.id)` returns
330
+ up to five sets of concrete seats, held for at most 60 seconds (`holdMs`, `deadline`).
331
+ `selectOffer(reservation.id, offerId)` puts the chosen seats on the reservation; then quote and
332
+ confirm as usual. One offer set is open per buyer and event; asking again replaces it. After the
333
+ deadline the call is refused with `seating_offer_expired`: ask for new offers, never assume the seats.
334
+
335
+ ```ts
336
+ const held = await agent.reserveBasket({ deferAllocation: true, lines: [{ tierId, quantity: 2,
337
+ seatRequest: { limits: { sections: ['A'], together: true, allowSplit: false } } }] });
338
+ const { offers } = await agent.requestOffers(held.id, { maxOffers: 3 });
339
+ const reservation = await agent.selectOffer(held.id, offers[0]!.offerId);
340
+ ```
341
+
342
+ **Browser (`@alytegen/sdk/browser`).** `buyBasket` lines take the same `minQuantity`, `required`,
343
+ `step` and `seatRequest`; the result adds `lineOutcomes` and, when Alyte's agent chose between
344
+ offers, `seatDecision`. A retry with the saved `attemptId` buys the same resolved basket or is
345
+ refused with `basket_result_unavailable`: show that as final, never start a new buy for it.
346
+ `watch` and `createWatch` take `lines` for a basket bought when it goes on sale
347
+ (`watchCapabilities().basketLines` says whether the server supports it).
348
+
349
+ **Merchant.** `seatingProvider.put / get / test` connect your seating system, including the
350
+ optional `chartUrl`, `offersUrl` and `partialAllocate`. `buyerSessions.mint` takes `eventId` and
351
+ `lines` to open Alyte's page on one event with a basket already filled in.
352
+
215
353
  ## Current API and console capabilities
216
354
 
217
- SDK **0.7.0** adds merchant-controlled early access: `accessRules` (`list`, `get`,
355
+ SDK **0.8.0** adds:
356
+ - **Per-event customer ticket limits (`AlyteMerchant`):** `setEventPurchaseLimit`, `getEventPurchaseLimit` and `clearEventPurchaseLimit`, plus idempotent pool creation via `createPool({ externalRef })`.
357
+ - **All-or-nothing basket checkout (`AlyteAgent`):** `reserveBasket`, `getReservation`, `quoteReservation`, `confirmReservation`, `releaseReservation` and `resolveBasketSca`, plus tier `role`, `category`, `categoryLabel`, `countsTowardPartySize` and `linkRule` on discovery/catalogue reads.
358
+ - **Buyer queue place & price targets (`@alytegen/sdk/browser`):** `watchCapabilities`, `createWatch`, `getWatch` and `observeWatch`, plus `watches[].waiting` on `AlyteMerchant.insights`.
359
+ - **Buyer-present bank challenge continuation (`@alytegen/sdk/browser` & webhooks):** `openChallenge`, `purchase`, `resumePurchase` and `cancelPurchase` (with `authenticationRetry` on `BuyerPurchaseState`, `awaiting_sca` on `BuyerWatch`, and `onWatchActionRequired` on `createWebhookHandler`; server-side buyer-present payment flags remain gated on deployment qualification).
360
+
361
+ SDK **0.7.0** added merchant-controlled early access: `accessRules` (`list`, `get`,
218
362
  `createDraft`, `updateDraft`, `preview`, `schedule`, `cancel`) and `memberships`
219
363
  (`createProgram`, `upsert`). **0.6.0** added inventory management: shared pools (`createPool`, `listPools`, `updatePool`),
220
364
  optional venue locations with pinned versions (`createLocation`, `listLocations`, `updateLocation`,
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type ClientOptions } from './http.js';
2
2
  import type { ConfirmOutcome, DiscoveredEvent, Hold, Merchant, Quote, Scheme } from './types.js';
3
+ import { type BasketQuote, type ConfirmReservationInput, type ConfirmReservationOutcome, type RequestSeatOffersInput, type Reservation, type ReserveBasketInput, type SeatOfferSet } from './baskets.js';
3
4
  /**
4
5
  * Agent buy-path client — the discover → quote → hold → confirm flow, with an
5
6
  * agent JWT (`catalog:read` / `payments:write` scopes).
@@ -43,7 +44,8 @@ export declare class AlyteAgent {
43
44
  /**
44
45
  * Pay the locked quote and confirm the hold. Pass a stable `idempotencyKey`
45
46
  * per purchase intent so retries can NEVER double-charge. Outcomes:
46
- * `settled` · `sca_required` (resume via `resolveSca`) · a thrown
47
+ * `settled` · `sca_required` (purchaseId → buyer openChallenge; legacy mock
48
+ * continueToken → resolveSca) · a thrown
47
49
  * AlyteApiError on refusal (stable `code`, e.g. spend-cap or scheme refusals).
48
50
  */
49
51
  confirm(holdId: string, input: {
@@ -54,8 +56,34 @@ export declare class AlyteAgent {
54
56
  }, opts?: {
55
57
  idempotencyKey?: string;
56
58
  }): Promise<ConfirmOutcome>;
57
- /** Resolve a pending SCA challenge (bound to the creating agent) and resume. */
59
+ /** Legacy mock challenge only. A durable purchaseId must be completed by the buyer
60
+ * through openChallenge; a caller-supplied outcome cannot authenticate a real payment. */
58
61
  resolveSca(continueToken: string, outcome: 'approved' | 'failed'): Promise<ConfirmOutcome>;
62
+ /** Hold all basket lines atomically. The server checks links, party size and add-on
63
+ * permission across the entire basket. This call does not charge or auto-retry. */
64
+ reserveBasket(input: ReserveBasketInput): Promise<Reservation>;
65
+ /** Read the current basket and every line, including any reconciliation state. Requires payments:read. */
66
+ getReservation(reservationId: string): Promise<Reservation>;
67
+ /** BSR-4a · ask for held seat offers under an offer-mode reservation (max 5 offers, max 60s hold). */
68
+ requestOffers(reservationId: string, input?: RequestSeatOffersInput): Promise<SeatOfferSet>;
69
+ /** BSR-4a · choose one held seat offer and promote its seats onto the reservation before quoting/confirming. */
70
+ selectOffer(reservationId: string, offerId: string): Promise<Reservation>;
71
+ /** Lock one total for all held lines; the response retains each line's price. */
72
+ quoteReservation(reservationId: string): Promise<BasketQuote>;
73
+ /** Confirm the entire basket as one payment. Persist and reuse the same
74
+ * idempotency key and inputs after a lost response; never create a new purchase
75
+ * to retry an uncertain result. HTTP 402 basket outcomes are returned intact. */
76
+ confirmReservation(reservationId: string, input: ConfirmReservationInput, opts?: {
77
+ idempotencyKey?: string;
78
+ }): Promise<ConfirmReservationOutcome>;
79
+ /** Release every line early. The server refuses release while payment is in flight. */
80
+ releaseReservation(reservationId: string): Promise<{
81
+ ok: true;
82
+ }>;
83
+ /** Legacy mock basket challenge only, bound to its creating principal. A durable
84
+ * purchaseId uses buyer openChallenge, never this caller-supplied outcome. */
85
+ resolveBasketSca(continueToken: string, outcome: 'approved' | 'failed'): Promise<ConfirmReservationOutcome>;
86
+ private reservationOutcome;
59
87
  /** Vaulted payment instruments this agent may spend from (opaque tokens only). */
60
88
  listInstruments(): Promise<{
61
89
  instruments: Array<{
package/dist/agent.js CHANGED
@@ -1,4 +1,5 @@
1
- import { Transport } from './http.js';
1
+ import { AlyteApiError, Transport } from './http.js';
2
+ import { isReservationRefusal } from './baskets.js';
2
3
  /**
3
4
  * Agent buy-path client — the discover → quote → hold → confirm flow, with an
4
5
  * agent JWT (`catalog:read` / `payments:write` scopes).
@@ -39,16 +40,65 @@ export class AlyteAgent {
39
40
  /**
40
41
  * Pay the locked quote and confirm the hold. Pass a stable `idempotencyKey`
41
42
  * per purchase intent so retries can NEVER double-charge. Outcomes:
42
- * `settled` · `sca_required` (resume via `resolveSca`) · a thrown
43
+ * `settled` · `sca_required` (purchaseId → buyer openChallenge; legacy mock
44
+ * continueToken → resolveSca) · a thrown
43
45
  * AlyteApiError on refusal (stable `code`, e.g. spend-cap or scheme refusals).
44
46
  */
45
47
  confirm(holdId, input, opts) {
46
48
  return this.t.request('POST', `/v1/holds/${encodeURIComponent(holdId)}/confirm`, input, opts?.idempotencyKey ? { 'idempotency-key': opts.idempotencyKey } : undefined);
47
49
  }
48
- /** Resolve a pending SCA challenge (bound to the creating agent) and resume. */
50
+ /** Legacy mock challenge only. A durable purchaseId must be completed by the buyer
51
+ * through openChallenge; a caller-supplied outcome cannot authenticate a real payment. */
49
52
  resolveSca(continueToken, outcome) {
50
53
  return this.t.request('POST', `/v1/sca/${encodeURIComponent(continueToken)}/resolve`, { outcome });
51
54
  }
55
+ /** Hold all basket lines atomically. The server checks links, party size and add-on
56
+ * permission across the entire basket. This call does not charge or auto-retry. */
57
+ reserveBasket(input) {
58
+ return this.t.request('POST', '/v1/reservations', input);
59
+ }
60
+ /** Read the current basket and every line, including any reconciliation state. Requires payments:read. */
61
+ getReservation(reservationId) {
62
+ return this.t.request('GET', `/v1/reservations/${encodeURIComponent(reservationId)}`);
63
+ }
64
+ /** BSR-4a · ask for held seat offers under an offer-mode reservation (max 5 offers, max 60s hold). */
65
+ requestOffers(reservationId, input = {}) {
66
+ return this.t.request('POST', `/v1/reservations/${encodeURIComponent(reservationId)}/offers`, input);
67
+ }
68
+ /** BSR-4a · choose one held seat offer and promote its seats onto the reservation before quoting/confirming. */
69
+ selectOffer(reservationId, offerId) {
70
+ return this.t.request('POST', `/v1/reservations/${encodeURIComponent(reservationId)}/offers/${encodeURIComponent(offerId)}/select`, {});
71
+ }
72
+ /** Lock one total for all held lines; the response retains each line's price. */
73
+ quoteReservation(reservationId) {
74
+ return this.t.request('POST', `/v1/reservations/${encodeURIComponent(reservationId)}/quotes`, {});
75
+ }
76
+ /** Confirm the entire basket as one payment. Persist and reuse the same
77
+ * idempotency key and inputs after a lost response; never create a new purchase
78
+ * to retry an uncertain result. HTTP 402 basket outcomes are returned intact. */
79
+ confirmReservation(reservationId, input, opts) {
80
+ return this.reservationOutcome(`/v1/reservations/${encodeURIComponent(reservationId)}/confirm`, input, opts?.idempotencyKey ? { 'idempotency-key': opts.idempotencyKey } : undefined);
81
+ }
82
+ /** Release every line early. The server refuses release while payment is in flight. */
83
+ releaseReservation(reservationId) {
84
+ return this.t.request('DELETE', `/v1/reservations/${encodeURIComponent(reservationId)}`);
85
+ }
86
+ /** Legacy mock basket challenge only, bound to its creating principal. A durable
87
+ * purchaseId uses buyer openChallenge, never this caller-supplied outcome. */
88
+ resolveBasketSca(continueToken, outcome) {
89
+ return this.reservationOutcome(`/v1/reservations/sca/${encodeURIComponent(continueToken)}/resolve`, { outcome });
90
+ }
91
+ async reservationOutcome(path, input, headers) {
92
+ try {
93
+ return await this.t.request('POST', path, input, headers);
94
+ }
95
+ catch (error) {
96
+ if (error instanceof AlyteApiError && error.status === 402 && error.code === 'http_402'
97
+ && isReservationRefusal(error.details))
98
+ return error.details;
99
+ throw error;
100
+ }
101
+ }
52
102
  /** Vaulted payment instruments this agent may spend from (opaque tokens only). */
53
103
  listInstruments() {
54
104
  return this.t.request('GET', '/v1/instruments');
@@ -0,0 +1,216 @@
1
+ import type { Hold, PaymentResult, Quote, Scheme } from './types.js';
2
+ export interface SeatRowRange {
3
+ from?: string;
4
+ to?: string;
5
+ exclude?: string[];
6
+ }
7
+ export interface SeatRequestLimits {
8
+ zones?: string[];
9
+ sections?: string[];
10
+ rows?: Record<string, SeatRowRange>;
11
+ traits?: {
12
+ require?: string[];
13
+ exclude?: string[];
14
+ };
15
+ together?: boolean;
16
+ allowSplit?: boolean;
17
+ blockSize?: number;
18
+ }
19
+ export interface SeatRequestPreferences {
20
+ zoneOrder?: string[];
21
+ rowPosition?: 'front' | 'middle' | 'back';
22
+ traits?: {
23
+ prefer?: string[];
24
+ avoid?: string[];
25
+ };
26
+ tradeoff?: 'cheaper' | 'better_seats' | 'balanced';
27
+ }
28
+ export interface SeatRequest {
29
+ limits: SeatRequestLimits;
30
+ preferences?: SeatRequestPreferences;
31
+ }
32
+ export interface AllocatedSeat {
33
+ seatId: string;
34
+ section?: string;
35
+ row?: string;
36
+ number?: string;
37
+ label?: string;
38
+ traits?: string[];
39
+ }
40
+ /** One requested tier in a basket. Repeated tiers are merged when no per-line limits/seats are given. */
41
+ export interface BasketLineInput {
42
+ tierId: string;
43
+ /** Whole units, 1..999 per submitted line. */
44
+ quantity: number;
45
+ /** BSR-1 · fewest acceptable units if retained; defaults to quantity. */
46
+ minQuantity?: number;
47
+ /** BSR-1 · false permits dropping this line; defaults to true. */
48
+ required?: boolean;
49
+ /** D14 · retained quantity must be a positive multiple of step. */
50
+ step?: number;
51
+ /** SB-4b · exact chosen seat ids (provider-seated tiers only; mutually exclusive with seatRequest). */
52
+ seats?: string[];
53
+ /** BSR-3 · structured seat limits & preferences (provider-seated tiers with verified chart). */
54
+ seatRequest?: SeatRequest;
55
+ }
56
+ export interface ReserveBasketInput {
57
+ /** 1..20 lines from one merchant, in one currency. */
58
+ lines: BasketLineInput[];
59
+ scheme?: Scheme;
60
+ geo?: string;
61
+ /** BSR-4a · reserve counts without immediate seat allocation so offers can be requested first. */
62
+ deferAllocation?: boolean;
63
+ }
64
+ export interface RequestSeatOffersInput {
65
+ /** Maximum offers to return (default 3, max 5). */
66
+ maxOffers?: number;
67
+ /** Maximum hold duration in milliseconds (default 60000, max 60000). */
68
+ maxHoldMs?: number;
69
+ }
70
+ export interface SeatOfferLine {
71
+ lineNo: number;
72
+ tierId: string;
73
+ status: 'filled' | 'reduced' | 'dropped';
74
+ quantity: number;
75
+ seats: AllocatedSeat[];
76
+ reason?: string;
77
+ }
78
+ export interface SeatOffer {
79
+ offerId: string;
80
+ adjacency: 'together' | 'split';
81
+ lines: SeatOfferLine[];
82
+ }
83
+ export interface SeatOfferSet {
84
+ offerSetId: string;
85
+ reservationId: string;
86
+ holdMs: number;
87
+ deadline: string;
88
+ offersLimited?: boolean;
89
+ chartVersion?: string;
90
+ offers: SeatOffer[];
91
+ }
92
+ export type ReservationStatus = 'held' | 'confirmed' | 'released' | 'expired' | 'reconcile';
93
+ /** A reservation line is a hold; reconcile protects stock while a payment is uncertain. */
94
+ export interface ReservationLine extends Omit<Hold, 'status'> {
95
+ tenantId: string;
96
+ reservationId?: string;
97
+ status: ReservationStatus;
98
+ confirmToken?: string;
99
+ seats?: AllocatedSeat[];
100
+ /** 1-based position of this line in the reservation. */
101
+ lineNo?: number;
102
+ }
103
+ export interface Reservation {
104
+ id: string;
105
+ tenantId: string;
106
+ merchantId: string;
107
+ /** Derived from the lines, including reconciliation protection. */
108
+ status: ReservationStatus;
109
+ lines: ReservationLine[];
110
+ /** Original number of lines; fewer remaining lines means an incomplete basket. */
111
+ lineCount?: number;
112
+ expiresAt: string;
113
+ createdAt: string;
114
+ confirmToken?: string;
115
+ /** Every line you asked for, including dropped ones; `lines` holds only what was reserved.
116
+ * Present when a line carried `minQuantity`, `required: false` or `step`. */
117
+ lineOutcomes?: BasketLineOutcome[];
118
+ /** Seats held in several zones while offers are open; they are not reserved lines until an offer is selected. */
119
+ provisionalClaims?: ProvisionalClaim[];
120
+ }
121
+ /** Why a line was reduced or dropped. Treat an unknown value as a generic reason. */
122
+ export type BasketLineOutcomeReason = 'sold_out' | 'not_available' | 'shared_capacity' | 'per_purchase_limit' | 'link_rule' | 'step' | 'spend_cap' | 'addon_cap' | 'addon_not_permitted' | 'party_quantity_limit' | 'purchase_limit' | 'held_limit' | 'mandate_scope' | 'no_adjacent_seats' | 'seats_unavailable' | 'no_matching_seats' | (string & {});
123
+ /** What happened to one requested line of a basket that allowed a smaller result. */
124
+ export interface BasketLineOutcome {
125
+ tierId: string;
126
+ requestedQuantity: number;
127
+ minQuantity: number;
128
+ required: boolean;
129
+ /** Units reserved; 0 when dropped. */
130
+ quantity: number;
131
+ status: 'filled' | 'reduced' | 'dropped';
132
+ reason?: BasketLineOutcomeReason;
133
+ }
134
+ export interface ProvisionalClaim {
135
+ lineNo: number;
136
+ primaryTierId?: string;
137
+ tierIds: string[];
138
+ quantity: number;
139
+ status: 'held' | 'promoted' | 'released' | 'expired';
140
+ }
141
+ /** How Alyte's agent picked between held seat offers. Structured only: no free text is recorded. */
142
+ export interface SeatDecision {
143
+ version: 1;
144
+ chooserKind: 'rules' | 'model';
145
+ modelId?: string;
146
+ fallbackReason?: string;
147
+ chosenOfferId: string;
148
+ chosenProbability: number;
149
+ offerCount: number;
150
+ chosen: {
151
+ offerId: string;
152
+ totalPriceMinor: number;
153
+ currency: string;
154
+ adjacency: 'together' | 'split';
155
+ seatCount: number;
156
+ section?: string;
157
+ sectionLabel?: string;
158
+ row?: string;
159
+ traits: string[];
160
+ seats: AllocatedSeat[];
161
+ };
162
+ alternatives: Array<Record<string, unknown>>;
163
+ decidedAt: string;
164
+ }
165
+ export interface BasketQuoteLine {
166
+ lineNo: number;
167
+ tierId: string;
168
+ holdId?: string;
169
+ quantity: number;
170
+ unitPriceMinor: number;
171
+ subtotalMinor: number;
172
+ }
173
+ /** One locked total, with per-line prices. A basket has no single unit price or tier ID. */
174
+ export interface BasketQuote extends Omit<Quote, 'tierId' | 'unitPriceMinor'> {
175
+ reservationId: string;
176
+ lines: BasketQuoteLine[];
177
+ }
178
+ /** The server derives the amount and authority from the quote and authenticated principal. */
179
+ export interface ConfirmReservationInput {
180
+ quoteId: string;
181
+ instrumentToken: string;
182
+ scheme: Scheme;
183
+ geo: string;
184
+ }
185
+ /** Fulfil only a settled/authorized result with confirmed inventory. An error result
186
+ * with reconcile inventory is uncertain, not a known decline or permission to re-charge. */
187
+ export type ConfirmReservationOutcome = {
188
+ status: 'settled';
189
+ result: PaymentResult;
190
+ reservationStatus: string;
191
+ reservation?: Reservation;
192
+ } | {
193
+ status: 'payment_pending';
194
+ result: PaymentResult;
195
+ reservationStatus: string;
196
+ } | {
197
+ status: 'sca_required';
198
+ purchaseId: string;
199
+ challenge: {
200
+ expiresAt: string;
201
+ };
202
+ reservationStatus: 'reconcile';
203
+ } | {
204
+ status: 'sca_required';
205
+ challenge: {
206
+ continueToken: string;
207
+ [k: string]: unknown;
208
+ };
209
+ reservationStatus: 'held';
210
+ } | {
211
+ status: 'sca_failed';
212
+ reservationStatus: 'released';
213
+ };
214
+ /** REST deliberately sends completed refusals and uncertain outcomes as HTTP 402.
215
+ * Only recognize that documented union; ordinary error envelopes still throw. */
216
+ export declare function isReservationRefusal(value: unknown): value is ConfirmReservationOutcome;
@@ -0,0 +1,13 @@
1
+ /** REST deliberately sends completed refusals and uncertain outcomes as HTTP 402.
2
+ * Only recognize that documented union; ordinary error envelopes still throw. */
3
+ export function isReservationRefusal(value) {
4
+ if (!value || typeof value !== 'object')
5
+ return false;
6
+ const body = value;
7
+ if (body.status === 'sca_failed')
8
+ return body.reservationStatus === 'released';
9
+ if (body.status !== 'settled' || typeof body.reservationStatus !== 'string' || !body.result || typeof body.result !== 'object')
10
+ return false;
11
+ const result = body.result;
12
+ return typeof result.intentId === 'string' && (result.status === 'declined' || result.status === 'error');
13
+ }