@oxvo/ai-live-assist 7.5.27 → 7.5.29

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 (53) hide show
  1. package/cjs/AiLiveAssist.d.ts +3 -1
  2. package/cjs/AiLiveAssist.js +24 -0
  3. package/cjs/client.d.ts +5 -0
  4. package/cjs/client.js +6 -0
  5. package/cjs/commerce/cartRecovery.d.ts +26 -0
  6. package/cjs/commerce/cartRecovery.js +96 -0
  7. package/cjs/commerce/cartSession.d.ts +7 -1
  8. package/cjs/commerce/cartSession.js +61 -5
  9. package/cjs/commerce/realtimeCommerce.d.ts +1 -0
  10. package/cjs/commerce/realtimeCommerce.js +1 -0
  11. package/cjs/commerce/shopifyCart.d.ts +3 -0
  12. package/cjs/commerce/shopifyCart.js +26 -0
  13. package/cjs/guideAdmission.d.ts +1 -0
  14. package/cjs/guideAdmission.js +3 -0
  15. package/cjs/guideMeasurement.d.ts +1 -1
  16. package/cjs/guideMeasurement.js +1 -1
  17. package/cjs/liveControlChannel.d.ts +1 -1
  18. package/cjs/liveGuideWidget.d.ts +2 -0
  19. package/cjs/liveGuideWidget.js +6 -0
  20. package/cjs/merchantPreviewAdmission.d.ts +1 -0
  21. package/cjs/merchantPreviewAdmission.js +2 -0
  22. package/cjs/merchantPreviewStorage.js +12 -0
  23. package/cjs/ui.d.ts +3 -1
  24. package/cjs/ui.js +7 -5
  25. package/cjs/version.d.ts +1 -1
  26. package/cjs/version.js +1 -1
  27. package/lib/AiLiveAssist.d.ts +3 -1
  28. package/lib/AiLiveAssist.js +24 -0
  29. package/lib/client.d.ts +5 -0
  30. package/lib/client.js +6 -0
  31. package/lib/commerce/cartRecovery.d.ts +26 -0
  32. package/lib/commerce/cartRecovery.js +93 -0
  33. package/lib/commerce/cartSession.d.ts +7 -1
  34. package/lib/commerce/cartSession.js +61 -5
  35. package/lib/commerce/realtimeCommerce.d.ts +1 -0
  36. package/lib/commerce/realtimeCommerce.js +1 -0
  37. package/lib/commerce/shopifyCart.d.ts +3 -0
  38. package/lib/commerce/shopifyCart.js +26 -0
  39. package/lib/guideAdmission.d.ts +1 -0
  40. package/lib/guideAdmission.js +3 -0
  41. package/lib/guideMeasurement.d.ts +1 -1
  42. package/lib/guideMeasurement.js +1 -1
  43. package/lib/liveControlChannel.d.ts +1 -1
  44. package/lib/liveGuideWidget.d.ts +2 -0
  45. package/lib/liveGuideWidget.js +6 -0
  46. package/lib/merchantPreviewAdmission.d.ts +1 -0
  47. package/lib/merchantPreviewAdmission.js +2 -0
  48. package/lib/merchantPreviewStorage.js +12 -0
  49. package/lib/ui.d.ts +3 -1
  50. package/lib/ui.js +7 -5
  51. package/lib/version.d.ts +1 -1
  52. package/lib/version.js +1 -1
  53. package/package.json +1 -1
@@ -34,7 +34,7 @@ export declare const normalizeAiGuideOpenInput: (input?: AiGuideOpenInput) => Re
34
34
  export declare const resolveAiGuideProtocolVersion: (bootstrap: Pick<BootstrapConfig, "experienceMode" | "minimumProtocolVersion" | "protocol">) => 1 | 2;
35
35
  export default class AiLiveAssist {
36
36
  private readonly options;
37
- readonly version = "7.5.27";
37
+ readonly version = "7.5.29";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
@@ -128,6 +128,7 @@ export default class AiLiveAssist {
128
128
  private media;
129
129
  private context;
130
130
  private commerce;
131
+ private idleCartRecovery;
131
132
  private commerceReadyChannel;
132
133
  private pendingCommerceGeneration;
133
134
  private presentation;
@@ -453,6 +454,7 @@ export default class AiLiveAssist {
453
454
  private waitForPendingContextNavigationAcknowledgements;
454
455
  private commerceBootstrap;
455
456
  private commerceCartEnabled;
457
+ private refreshIdleCartRecovery;
456
458
  private startRealtimeCommerce;
457
459
  private startContext;
458
460
  private startPresentation;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveAiGuideProtocolVersion = exports.normalizeAiGuideOpenInput = exports.resolveAiGuideLocale = exports.confirmationReplyIntent = exports.ReplaySessionReadiness = exports.REPLAY_SESSION_READY_TIMEOUT_MS = void 0;
4
+ const cartSession_js_1 = require("./commerce/cartSession.js");
4
5
  const guideHost_js_1 = require("./guideHost.js");
5
6
  const guideMount_js_1 = require("./guideMount.js");
6
7
  const client_js_1 = require("./client.js");
@@ -1427,6 +1428,7 @@ class AiLiveAssist {
1427
1428
  this.media = null;
1428
1429
  this.context = null;
1429
1430
  this.commerce = null;
1431
+ this.idleCartRecovery = null;
1430
1432
  this.commerceReadyChannel = null;
1431
1433
  this.pendingCommerceGeneration = null;
1432
1434
  this.presentation = null;
@@ -2060,6 +2062,8 @@ class AiLiveAssist {
2060
2062
  this.clearReconnectTimer();
2061
2063
  if (this.destroyed)
2062
2064
  return;
2065
+ this.idleCartRecovery?.destroy();
2066
+ this.idleCartRecovery = null;
2063
2067
  this.commerce?.destroy();
2064
2068
  this.commerce = null;
2065
2069
  this.liveWidget?.destroy();
@@ -2250,6 +2254,7 @@ class AiLiveAssist {
2250
2254
  this.view = voicePresenceView
2251
2255
  ? new voicePresenceUi_js_1.VoicePresenceView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.tabId, (fallback) => void this.activateFallback(fallback), this.options.visualTestMode === true)
2252
2256
  : new ui_js_1.WidgetView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.standardWidgetViewOptions(effectiveBootstrap));
2257
+ this.refreshIdleCartRecovery();
2253
2258
  this.syncCompanionView();
2254
2259
  this.initializePageAssistancePreference(effectiveBootstrap);
2255
2260
  this.startMessengerIntegration(effectiveBootstrap);
@@ -8351,6 +8356,19 @@ class AiLiveAssist {
8351
8356
  commerceCartEnabled(bootstrap = this.bootstrap) {
8352
8357
  return bootstrap?.capabilities?.commerceCart === true && (0, contracts_js_1.parseCommerceBootstrap)(bootstrap.commerce, bootstrap.guideId, window.location.origin)?.cartEnabled === true;
8353
8358
  }
8359
+ refreshIdleCartRecovery() {
8360
+ this.idleCartRecovery?.destroy();
8361
+ this.idleCartRecovery = null;
8362
+ const bootstrap = this.commerceBootstrap();
8363
+ if (this.destroyed || this.liveWidget || this.commerce || !this.guideAdmission || !bootstrap?.cartEnabled || !(this.view instanceof ui_js_1.WidgetView))
8364
+ return;
8365
+ this.idleCartRecovery = new cartSession_js_1.CartSession({ bootstrap, recovery: this.guideAdmission.cartRecovery(),
8366
+ view: () => !this.destroyed && this.view instanceof ui_js_1.WidgetView ? this.view : null,
8367
+ current: () => null, selection: () => null,
8368
+ send: () => { throw new Error('Cart recovery has no mutation transport.'); },
8369
+ });
8370
+ this.idleCartRecovery.refreshControls();
8371
+ }
8354
8372
  startRealtimeCommerce(preserveProvider = false) {
8355
8373
  const authority = this.commerceBootstrap();
8356
8374
  const sessionId = this.result?.sessionId;
@@ -8361,7 +8379,10 @@ class AiLiveAssist {
8361
8379
  }
8362
8380
  if (this.commerce?.sessionId !== sessionId) {
8363
8381
  this.commerce?.destroy();
8382
+ this.idleCartRecovery?.destroy();
8383
+ this.idleCartRecovery = null;
8364
8384
  this.commerce = new realtimeCommerce_js_1.RealtimeCommerce(sessionId, authority, {
8385
+ ...(this.guideAdmission ? { recovery: this.guideAdmission.cartRecovery() } : {}),
8365
8386
  channel: () => this.channel,
8366
8387
  view: () => this.view instanceof ui_js_1.WidgetView ? this.view : null,
8367
8388
  isCurrent: () => this.result?.sessionId === sessionId && !this.ended && !this.destroyed &&
@@ -15457,6 +15478,7 @@ class AiLiveAssist {
15457
15478
  else {
15458
15479
  this.view?.showResumeStopped?.();
15459
15480
  }
15481
+ this.refreshIdleCartRecovery();
15460
15482
  this.state("ended");
15461
15483
  }
15462
15484
  captureTerminalAuthorizedResult(result, sourceRecord = null) {
@@ -15755,6 +15777,7 @@ class AiLiveAssist {
15755
15777
  else {
15756
15778
  this.view?.showResumeStopped?.();
15757
15779
  }
15780
+ this.refreshIdleCartRecovery();
15758
15781
  this.state("ended");
15759
15782
  }
15760
15783
  presentTerminalEnding(error) {
@@ -15976,6 +15999,7 @@ class AiLiveAssist {
15976
15999
  quiesceLocalEffectsForTerminalRequest() {
15977
16000
  this.commerce?.destroy();
15978
16001
  this.commerce = null;
16002
+ this.refreshIdleCartRecovery();
15979
16003
  this.clearCtaAuthority();
15980
16004
  this.queuedLaunchToken = null;
15981
16005
  this.launchGeneration += 1;
package/cjs/client.d.ts CHANGED
@@ -98,6 +98,11 @@ export declare class RuntimeClient {
98
98
  providerProtocol: "live";
99
99
  }>;
100
100
  launchLiveGuide(intent: LiveGuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<LiveControlAuthorization>;
101
+ inspectCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput, signal: AbortSignal): Promise<unknown>;
102
+ reportCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput & {
103
+ recoveryReceipt: string;
104
+ result: import('./commerce/cartContracts.js').CommerceCartExecutionResult;
105
+ }, signal: AbortSignal): Promise<unknown>;
101
106
  endLiveGuide(input: GuideLaunchRecoveryInput, signal?: AbortSignal): Promise<{
102
107
  schemaVersion: 3;
103
108
  protocolVersion: 2;
package/cjs/client.js CHANGED
@@ -193,6 +193,12 @@ class RuntimeClient {
193
193
  async launchLiveGuide(intent, admissionGrant, signal, measurementBridge) {
194
194
  return this.postGuideLaunch("/ai-live-assist/v1/public/live/launch", intent, admissionGrant, signal, measurementBridge);
195
195
  }
196
+ async inspectCartRecovery(input, signal) {
197
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/inspect', JSON.stringify(input), {}, signal, false, false, true);
198
+ }
199
+ async reportCartRecovery(input, signal) {
200
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/report', JSON.stringify(input), {}, signal, false, false, true);
201
+ }
196
202
  async endLiveGuide(input, signal) {
197
203
  return this.postJson("/ai-live-assist/v1/public/live/launches/end", input, {}, signal, true);
198
204
  }
@@ -0,0 +1,26 @@
1
+ import type { RuntimeClient } from '../client.js';
2
+ import type { GuideSubjectStore } from '../guideSubjectStore.js';
3
+ import { type CommerceCartExecutionResult } from './cartContracts.js';
4
+ import type { PreparedShopifyCartAddition, ShopifyCartExecutionEvidence } from './shopifyCart.js';
5
+ export type CartRecoveryInput = {
6
+ schemaVersion: 1;
7
+ installKey: string;
8
+ subjectCredential: string;
9
+ originalSessionId: string;
10
+ operationId: string;
11
+ executionId: string;
12
+ cartDigest: string;
13
+ };
14
+ export type CartRecoveryInspection = {
15
+ recoveryReceipt: string;
16
+ expiresAt: string;
17
+ executionResult: CommerceCartExecutionResult | null;
18
+ };
19
+ export type CartRecovery = {
20
+ available(): boolean;
21
+ inspect(prepared: PreparedShopifyCartAddition, execution: ShopifyCartExecutionEvidence): Promise<CartRecoveryInspection>;
22
+ report(prepared: PreparedShopifyCartAddition, inspection: CartRecoveryInspection, result: CommerceCartExecutionResult): Promise<boolean>;
23
+ };
24
+ /** One possession adapter for Live, Realtime and the isolated preview store.
25
+ * It cannot create a visitor, launch, grant, provider or paid session. */
26
+ export declare function createCartRecovery(runtime: RuntimeClient, installKey: string, store: GuideSubjectStore): CartRecovery;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCartRecovery = createCartRecovery;
4
+ const contracts_js_1 = require("./contracts.js");
5
+ const cartContracts_js_1 = require("./cartContracts.js");
6
+ const commerceObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ const stable = (value) => JSON.stringify(value, (_key, item) => commerceObject(item)
8
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
9
+ const same = (a, b) => stable(a) === stable(b);
10
+ const unavailable = () => new Error('The original cart addition could not be checked.');
11
+ async function bounded(work, ms = 5000) {
12
+ const controller = new AbortController();
13
+ const timer = setTimeout(() => controller.abort(), ms);
14
+ try {
15
+ return await work(controller.signal);
16
+ }
17
+ finally {
18
+ clearTimeout(timer);
19
+ }
20
+ }
21
+ /** One possession adapter for Live, Realtime and the isolated preview store.
22
+ * It cannot create a visitor, launch, grant, provider or paid session. */
23
+ function createCartRecovery(runtime, installKey, store) {
24
+ const subject = () => {
25
+ const value = store.readSubject();
26
+ return value && value.origin === location.origin && Date.parse(value.expiresAt) > Date.now() ? value : null;
27
+ };
28
+ const input = (prepared, execution) => {
29
+ const owner = subject();
30
+ if (!owner || !prepared.reportScope || !(0, contracts_js_1.commerceUuid)(prepared.reportSessionId) || prepared.guideId !== owner.guideId ||
31
+ prepared.store.origin !== location.origin)
32
+ throw unavailable();
33
+ return { schemaVersion: 1, installKey, subjectCredential: owner.credential, originalSessionId: prepared.reportSessionId,
34
+ operationId: prepared.operationId, executionId: execution.executionId, cartDigest: execution.cartDigest };
35
+ };
36
+ const possessions = new WeakMap();
37
+ return {
38
+ available: () => subject() !== null,
39
+ async inspect(prepared, execution) {
40
+ const body = input(prepared, execution);
41
+ const value = await bounded(signal => runtime.inspectCartRecovery(body, signal));
42
+ if (!commerceObject(value) || Object.keys(value).length !== 5 || value.schemaVersion !== 1 ||
43
+ !commerceObject(value.descriptor) || typeof value.recoveryReceipt !== 'string' ||
44
+ !/^\d{13}\.\d{13}\.[A-Za-z0-9_-]{32,86}$/u.test(value.recoveryReceipt) || typeof value.expiresAt !== 'string' ||
45
+ !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now() || Date.parse(value.expiresAt) > Date.now() + 8000 ||
46
+ input(prepared, execution).subjectCredential !== body.subjectCredential)
47
+ throw unavailable();
48
+ const descriptor = value.descriptor;
49
+ if (!commerceObject(descriptor.item) || typeof descriptor.item.title !== 'string' || descriptor.item.title.length > 1000)
50
+ throw unavailable();
51
+ const { title: _title, ...item } = descriptor.item;
52
+ void _title;
53
+ const expected = { schemaVersion: 1, originalSessionId: prepared.reportSessionId, guideId: prepared.guideId,
54
+ scope: prepared.reportScope, store: prepared.store, market: prepared.market, operationMarker: prepared.operationMarker,
55
+ executionId: execution.executionId, cartDigest: execution.cartDigest, expiresAt: prepared.expiresAt,
56
+ item: { productRef: prepared.productRef, variantRef: prepared.variantRef, shopifyVariantId: prepared.shopifyVariantId,
57
+ productUrl: prepared.productUrl, selectedOptions: prepared.selectedOptions, quantity: prepared.quantity,
58
+ unitPrice: prepared.unitPrice, quantityRule: prepared.quantityRule, requiresSellingPlan: false, requiresComponents: false } };
59
+ if (!same({ ...descriptor, item }, expected))
60
+ throw unavailable();
61
+ let known = null;
62
+ if (value.executionResult !== null) {
63
+ const result = value.executionResult;
64
+ if (!commerceObject(result))
65
+ throw unavailable();
66
+ const { request, observation, ...correlation } = result;
67
+ if (!same(correlation, { ...prepared.reportScope, executionId: execution.executionId, cartDigest: execution.cartDigest }) ||
68
+ !commerceObject(request) || (request.outcome === 'response'
69
+ ? Object.keys(request).length !== 2 || !Number.isInteger(request.httpStatus) || Number(request.httpStatus) < 100 || Number(request.httpStatus) > 599
70
+ : Object.keys(request).length !== 1 || !['unknown', 'timeout', 'aborted', 'network_error'].includes(String(request.outcome))))
71
+ throw unavailable();
72
+ if (observation !== null) {
73
+ if (!commerceObject(observation) || !(0, cartContracts_js_1.parseCommerceCartResult)({ schemaVersion: 1, requestId: prepared.reportScope.requestId,
74
+ operationId: prepared.operationId, executionId: execution.executionId, status: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed',
75
+ code: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed', observation }) || observation.operationMarker !== prepared.operationMarker ||
76
+ observation.shopifyVariantId !== prepared.shopifyVariantId || observation.currency !== prepared.unitPrice.currency ||
77
+ Number(observation.quantity) > prepared.quantity)
78
+ throw unavailable();
79
+ }
80
+ known = result;
81
+ }
82
+ const inspection = { recoveryReceipt: value.recoveryReceipt, expiresAt: value.expiresAt, executionResult: known };
83
+ possessions.set(inspection, body.subjectCredential);
84
+ return inspection;
85
+ },
86
+ async report(prepared, inspection, result) {
87
+ const body = input(prepared, result);
88
+ if (possessions.get(inspection) !== body.subjectCredential || Date.parse(inspection.expiresAt) <= Date.now())
89
+ return false;
90
+ const response = (0, cartContracts_js_1.parseCommerceCartResult)(await bounded(signal => runtime.reportCartRecovery({ ...body, recoveryReceipt: inspection.recoveryReceipt, result }, signal), Math.max(1, Math.min(5000, Date.parse(inspection.expiresAt) - Date.now()))));
91
+ return response !== null && response.requestId === result.requestId && response.operationId === result.operationId &&
92
+ response.executionId === result.executionId && ['observed', 'partial', 'unconfirmed'].includes(response.status) &&
93
+ (response.status === 'unconfirmed' || same(response.observation, result.observation)) && subject()?.credential === body.subjectCredential;
94
+ },
95
+ };
96
+ }
@@ -3,6 +3,7 @@ import type { CommerceAddHandler, CommerceCanAdd } from './productPanel.js';
3
3
  import type { CommerceBootstrap, CommerceCartSelection, CommerceContext, CommerceProduct, LiveCommerceDisplayed, RealtimeCommerceDisplayed } from './contracts.js';
4
4
  import { type CommerceCartProvider } from './cartContracts.js';
5
5
  import { type ShopifyCartOutcome } from './shopifyCart.js';
6
+ import type { CartRecovery } from './cartRecovery.js';
6
7
  export type CartSessionSnapshot = {
7
8
  sessionId: string;
8
9
  context: CommerceContext;
@@ -23,11 +24,14 @@ export type CommerceCartView = {
23
24
  setCommerceCartActionHandler(handler: CommerceAddHandler | null, canAdd?: CommerceCanAdd): void;
24
25
  showCommerceCartConfirmation(value: CommerceCartConfirmationView, onDecision: (approved: boolean) => void): void;
25
26
  clearCommerceCartConfirmation(operationId?: string): void;
26
- setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>): void;
27
+ setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>, options?: {
28
+ readOnlyRecovery?: boolean;
29
+ }): void;
27
30
  clearCommerceCartStatus(): void;
28
31
  };
29
32
  export type CartSessionOptions = {
30
33
  bootstrap: CommerceBootstrap;
34
+ recovery?: CartRecovery;
31
35
  view: () => CommerceCartView | null;
32
36
  /** Null unless disclosure, dedicated cart consent, cart negotiation and the
33
37
  * current session/provider fence are all effective. */
@@ -50,6 +54,7 @@ export declare class CartSession {
50
54
  private readonly retiredRequests;
51
55
  private recoveryOutcome;
52
56
  private recoveryInFlight;
57
+ private recoveryEpoch;
53
58
  private recoveryGrant;
54
59
  private recoveryBegin;
55
60
  private pendingReport;
@@ -76,6 +81,7 @@ export declare class CartSession {
76
81
  private report;
77
82
  private showRecovery;
78
83
  private checkCart;
84
+ private checkRetainedCart;
79
85
  private recoveryHandle;
80
86
  private beginRecovery;
81
87
  private begin;
@@ -38,6 +38,7 @@ class CartSession {
38
38
  this.retiredRequests = new Set();
39
39
  this.recoveryOutcome = null;
40
40
  this.recoveryInFlight = null;
41
+ this.recoveryEpoch = 0;
41
42
  // At most one original grant, held only by this live instance. The public
42
43
  // recovery ledger deliberately contains no mutation credentials.
43
44
  this.recoveryGrant = null;
@@ -80,6 +81,16 @@ class CartSession {
80
81
  this.checkCart = () => {
81
82
  if (this.recoveryInFlight)
82
83
  return this.recoveryInFlight;
84
+ if (this.options.recovery?.available() && !this.destroyed && !this.pending) {
85
+ // Assign before work begins, including synchronous early returns. Every
86
+ // simultaneous Check shares this promise and one inspect/read/report.
87
+ this.recoveryInFlight = Promise.resolve().then(() => this.checkRetainedCart()).catch(() => this.showRecovery()).finally(() => {
88
+ this.recoveryInFlight = null;
89
+ if (!this.destroyed)
90
+ this.refreshControls();
91
+ });
92
+ return this.recoveryInFlight;
93
+ }
83
94
  const current = this.options.current();
84
95
  if (this.destroyed || this.pending || !current)
85
96
  return Promise.resolve();
@@ -141,13 +152,13 @@ class CartSession {
141
152
  this.refreshControls();
142
153
  }
143
154
  };
144
- this.recoveryInFlight = work();
155
+ this.recoveryInFlight = Promise.resolve().then(work);
145
156
  return this.recoveryInFlight;
146
157
  };
147
158
  }
148
159
  /** A catalog replaces the panel; install again after its visible receipt. */
149
160
  refreshControls() {
150
- if (!this.destroyed && !this.pending && this.options.current() && this.hasUnresolved())
161
+ if (!this.destroyed && !this.pending && (this.options.current() || this.options.recovery?.available()) && this.hasUnresolved())
151
162
  this.showRecovery();
152
163
  this.options.view()?.setCommerceCartActionHandler(this.destroyed || !this.options.bootstrap.cartEnabled ||
153
164
  !this.options.current() ? null : this.add, this.canAdd);
@@ -169,6 +180,7 @@ class CartSession {
169
180
  this.result(payload);
170
181
  }
171
182
  cut() {
183
+ this.recoveryEpoch++;
172
184
  this.recoveryGrant = null;
173
185
  this.recoveryBegin?.resolve(null);
174
186
  this.pendingReport?.resolve(false);
@@ -397,9 +409,53 @@ class CartSession {
397
409
  const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
398
410
  const current = this.options.current();
399
411
  const prepared = retained?.prepared;
400
- const canRecover = current && prepared && prepared.reportSessionId === current.sessionId &&
401
- (observed && prepared.reportScope || this.recoveryHandle(current, prepared));
402
- this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined);
412
+ const canRecover = prepared && (this.options.recovery?.available() || current && prepared.reportSessionId === current.sessionId &&
413
+ (observed && prepared.reportScope || this.recoveryHandle(current, prepared)));
414
+ const readOnly = this.options.recovery?.available() ? [{ readOnlyRecovery: true }] : [];
415
+ this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined, ...readOnly);
416
+ }
417
+ async checkRetainedCart() {
418
+ const recovery = this.options.recovery;
419
+ const epoch = this.recoveryEpoch;
420
+ const stillCurrent = () => !this.destroyed && !this.pending && this.recoveryEpoch === epoch && recovery?.available() === true;
421
+ const executor = this.recoveryExecutor(stillCurrent);
422
+ const retained = executor.peekPending(this.recoveryScope());
423
+ const prepared = retained?.prepared;
424
+ if (!recovery || !prepared?.reportScope || !prepared.reportSessionId || !retained?.outcome?.execution || !stillCurrent())
425
+ return;
426
+ const inspection = await recovery.inspect(prepared, retained.outcome.execution);
427
+ if (!stillCurrent() || Date.parse(inspection.expiresAt) <= Date.now())
428
+ return;
429
+ const known = inspection.executionResult;
430
+ let outcome = retained.outcome;
431
+ let report;
432
+ if (known?.observation && known.observation.quantity > 0) {
433
+ report = known;
434
+ }
435
+ else {
436
+ const read = this.recoveryExecutor(() => stillCurrent() && Date.now() < Date.parse(inspection.expiresAt));
437
+ outcome = await read.reconcile(prepared, retained.outcome.execution.executionId, { state: 'already_started',
438
+ executionId: retained.outcome.execution.executionId, cartDigest: retained.outcome.execution.cartDigest,
439
+ expiresAt: inspection.expiresAt }, { refreshObservation: true });
440
+ if (!outcome.execution || !stillCurrent())
441
+ return;
442
+ report = { ...scopeOf(prepared.reportScope), ...outcome.execution,
443
+ ...(known ? { request: known.request } : {}) };
444
+ }
445
+ if (!stillCurrent() || !await recovery.report(prepared, inspection, report) || !stillCurrent())
446
+ return;
447
+ const accepted = await executor.acceptRecoveryReport(prepared, report);
448
+ if (!stillCurrent())
449
+ return;
450
+ if (accepted)
451
+ outcome = { ...accepted, local: outcome.local };
452
+ this.recoveryOutcome = outcome;
453
+ if (this.hasUnresolved())
454
+ this.showRecovery();
455
+ else {
456
+ this.recoveryOutcome = null;
457
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl(), undefined, { readOnlyRecovery: true });
458
+ }
403
459
  }
404
460
  recoveryHandle(snapshot, prepared) {
405
461
  const retained = this.recoveryGrant;
@@ -47,6 +47,7 @@ export declare class RealtimeCommerce {
47
47
  isCurrent: () => boolean;
48
48
  sharePage: () => boolean;
49
49
  cartConsent?: () => boolean;
50
+ recovery?: import('./cartRecovery.js').CartRecovery;
50
51
  submit: (text: string) => boolean;
51
52
  });
52
53
  /** Called only after media.connect and the real provider's fence proof. */
@@ -39,6 +39,7 @@ class RealtimeCommerce {
39
39
  this.publishContext();
40
40
  });
41
41
  this.cart = new cartSession_js_1.CartSession({ bootstrap, view: options.view,
42
+ ...(options.recovery ? { recovery: options.recovery } : {}),
42
43
  transportSessionId: () => options.channel()?.sessionId ?? null,
43
44
  current: () => this.cartSnapshot(), selection: (productRef, variantRef) => this.currentCartSelection(productRef, variantRef),
44
45
  send: (type, payload) => {
@@ -110,6 +110,9 @@ export declare class ShopifyCartExecutor {
110
110
  peekPending(scope: LedgerScope): ShopifyCartRecovery | null;
111
111
  /** Call only after native accepted this exact report. Browser observation alone is not delivery. */
112
112
  acknowledgeReport(scope: LedgerScope, report: CommerceCartExecutionResult): boolean;
113
+ /** Called only after authenticated inspect/report of this exact original
114
+ * descriptor. Replays server-retained positive evidence without a new Add. */
115
+ acceptRecoveryReport(prepared: PreparedShopifyCartAddition, report: CommerceCartExecutionResult): Promise<ShopifyCartOutcome | null>;
113
116
  /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
114
117
  reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
118
  execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;
@@ -704,6 +704,32 @@ class ShopifyCartExecutor {
704
704
  return false;
705
705
  }
706
706
  }
707
+ /** Called only after authenticated inspect/report of this exact original
708
+ * descriptor. Replays server-retained positive evidence without a new Add. */
709
+ async acceptRecoveryReport(prepared, report) {
710
+ try {
711
+ if (!validPrepared(prepared) || !prepared.reportScope || !validRequestOutcome(report.request) ||
712
+ !validSavedObservation(report.observation, prepared) || !await this.authority.assertCurrent(prepared))
713
+ return null;
714
+ const { executionId, cartDigest, request, observation, ...scope } = report;
715
+ if (reportScopeIdentity(scope) !== reportScopeIdentity(prepared.reportScope))
716
+ return null;
717
+ const key = ledgerKey(prepared), entries = readLedger(key);
718
+ const entry = entries.find(value => value.operationId === prepared.operationId);
719
+ if (!entry || entry.intentDigest !== await sha(intent(prepared)) || entry.executionId !== executionId || entry.cartDigest !== cartDigest ||
720
+ !await this.authority.assertCurrent(prepared))
721
+ return null;
722
+ entry.request = request;
723
+ entry.observation = observation;
724
+ entry.resolved = true;
725
+ entry.reportAccepted = true;
726
+ saveLedger(key, entries);
727
+ return retainedOutcome(prepared, entry);
728
+ }
729
+ catch {
730
+ return null;
731
+ }
732
+ }
707
733
  /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
708
734
  async reconcilePending(scope) {
709
735
  const failure = (reason, prepared = null) => ({
@@ -15,6 +15,7 @@ export declare class GuideAdmission {
15
15
  readonly store: GuideSubjectStore;
16
16
  private readonly runtime;
17
17
  private guideMeasurementBridge?;
18
+ cartRecovery(): import("./commerce/cartRecovery.js").CartRecovery;
18
19
  private initialBootstrap;
19
20
  private currentBootstrap;
20
21
  private activeAdmission;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GuideAdmission = void 0;
4
4
  exports.validateGuideBootstrap = validateGuideBootstrap;
5
+ const cartRecovery_js_1 = require("./commerce/cartRecovery.js");
5
6
  const client_js_1 = require("./client.js");
6
7
  const guideTypes_js_1 = require("./guideTypes.js");
7
8
  const guideMeasurement_js_1 = require("./guideMeasurement.js");
@@ -30,6 +31,7 @@ function validateGuideBootstrap(value, installKey) {
30
31
  }
31
32
  /** Server admission and local cancellation fences; no recorder or crypto substitute. */
32
33
  class GuideAdmission {
34
+ cartRecovery() { return (0, cartRecovery_js_1.createCartRecovery)(this.runtime, this.identity.installKey, this.store); }
33
35
  constructor(identity, store, runtime, bootstrap, recordingAdapter = null, guideMeasurementBridge) {
34
36
  this.identity = identity;
35
37
  this.store = store;
@@ -174,6 +176,7 @@ class GuideAdmission {
174
176
  throw new client_js_1.RuntimeClientError("GUIDE_LAUNCH_PENDING", "Finish the previous AI Guide session before starting another.", true, null, 409);
175
177
  }
176
178
  const prior = previous.intent;
179
+ intent.clientVersion = prior.clientVersion;
177
180
  // Recovery keeps the original assignment even after consent/bridge expiry.
178
181
  if (prior.guideMeasurement)
179
182
  intent.guideMeasurement = { ...prior.guideMeasurement };
@@ -1,5 +1,5 @@
1
1
  import type { GuideMeasurementBridge, GuideMeasurementIntent } from './guideTypes.js';
2
- export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.27";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.29";
3
3
  export declare function isGuideMeasurementIntent(value: unknown): value is GuideMeasurementIntent;
4
4
  /** The managed analytics owner supplies possession; this check grants no authority. */
5
5
  export declare function currentGuideMeasurementBridge(value: unknown): value is GuideMeasurementBridge;
@@ -4,7 +4,7 @@ exports.GUIDE_MEASUREMENT_CLIENT_VERSION = void 0;
4
4
  exports.isGuideMeasurementIntent = isGuideMeasurementIntent;
5
5
  exports.currentGuideMeasurementBridge = currentGuideMeasurementBridge;
6
6
  exports.prepareGuideMeasurementBridge = prepareGuideMeasurementBridge;
7
- exports.GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.27';
7
+ exports.GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.29';
8
8
  function isGuideMeasurementIntent(value) {
9
9
  if (!value || typeof value !== 'object' || Array.isArray(value))
10
10
  return false;
@@ -1,7 +1,7 @@
1
1
  import { type MerchantPreviewRuntimePolicy } from './merchantPreviewOrigins.js';
2
2
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
3
3
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
4
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.27";
4
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.29";
5
5
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
6
6
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
7
7
  export type LiveControlState = {
@@ -4,10 +4,12 @@ import type { GuideAdmission } from './guideAdmission.js';
4
4
  import { RuntimeClient } from './client.js';
5
5
  import { type LiveGuideLaunchIntent } from './liveGuideAdmission.js';
6
6
  import { type LiveControlChannelOptions, type LiveControlAuthorization } from './liveControlChannel.js';
7
+ import type { CartRecovery } from './commerce/cartRecovery.js';
7
8
  export type LiveGuideStartIntent = Omit<LiveGuideLaunchIntent, 'installKey' | 'guideMeasurement'>;
8
9
  export type LiveGuideSessionAdmission = {
9
10
  readonly recoveryOnly?: boolean;
10
11
  readonly endMessage?: string;
12
+ cartRecovery?(): CartRecovery;
11
13
  canStart?(): boolean;
12
14
  hasPendingLaunch(): boolean;
13
15
  pendingLaunchId(): string | null;
@@ -69,6 +69,7 @@ class LiveGuideWidget {
69
69
  const publicAdmission = options.admission;
70
70
  const live = new liveGuideAdmission_js_1.LiveGuideAdmission(publicAdmission.identity, publicAdmission.store, options.runtime, publicAdmission);
71
71
  this.admission = {
72
+ cartRecovery: () => publicAdmission.cartRecovery(),
72
73
  hasPendingLaunch: () => live.hasPendingLaunch(),
73
74
  pendingLaunchId: () => live.pendingLaunchId(),
74
75
  launch: (intent, signal) => live.launch({ ...intent, installKey: publicAdmission.identity.installKey }, signal),
@@ -118,6 +119,7 @@ class LiveGuideWidget {
118
119
  this.commerceCart = this.commerce?.cartEnabled && config.capabilities?.commerceCart === true ? new cartSession_js_1.CartSession({
119
120
  bootstrap: this.commerce, view: () => this.destroyed ? null : this.view,
120
121
  current: () => this.currentCartSnapshot(),
122
+ ...(this.admission.cartRecovery ? { recovery: this.admission.cartRecovery() } : {}),
121
123
  transportSessionId: () => this.channel?.sessionId ?? null,
122
124
  selection: (productRef, variantRef) => {
123
125
  this.commerceContext?.refresh();
@@ -134,6 +136,7 @@ class LiveGuideWidget {
134
136
  },
135
137
  }) : null;
136
138
  this.commerceContext?.start();
139
+ this.commerceCart?.refreshControls();
137
140
  if (this.admission.hasPendingLaunch()) {
138
141
  if (this.acquireLock()) {
139
142
  this.ownedLaunchId = this.admission.pendingLaunchId();
@@ -161,6 +164,7 @@ class LiveGuideWidget {
161
164
  this.requestIds.delete(this.requestIds.values().next().value);
162
165
  }
163
166
  this.view.open(input.mode ?? this.mode);
167
+ this.commerceCart?.refreshControls();
164
168
  if (input.question) {
165
169
  if (this.active)
166
170
  this.submitText(input.question, true);
@@ -602,6 +606,7 @@ class LiveGuideWidget {
602
606
  this.view.showLaunchUnavailable(this.admission.endMessage);
603
607
  else
604
608
  this.view.showResumeStopped();
609
+ this.commerceCart?.refreshControls();
605
610
  }
606
611
  this.options.onState();
607
612
  }).catch(error => {
@@ -670,6 +675,7 @@ class LiveGuideWidget {
670
675
  channel?.end();
671
676
  this.operation?.abort();
672
677
  this.operation = null;
678
+ this.commerceCart?.refreshControls();
673
679
  }
674
680
  destroy() {
675
681
  if (this.destroyed)
@@ -9,6 +9,7 @@ export declare class MerchantPreviewAdmission implements LiveGuideSessionAdmissi
9
9
  private readonly runtime;
10
10
  private readonly storage;
11
11
  readonly recoveryOnly: boolean;
12
+ cartRecovery(): import("./commerce/cartRecovery.js").CartRecovery;
12
13
  readonly endMessage = "Preview ended. Return to Console to open another preview.";
13
14
  private readonly store;
14
15
  private readonly originalKey;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MerchantPreviewAdmission = exports.merchantPreviewNamespace = void 0;
4
+ const cartRecovery_js_1 = require("./commerce/cartRecovery.js");
4
5
  const client_js_1 = require("./client.js");
5
6
  const guideSubjectStore_js_1 = require("./guideSubjectStore.js");
6
7
  const guideTypes_js_1 = require("./guideTypes.js");
@@ -9,6 +10,7 @@ var merchantPreviewStorage_js_2 = require("./merchantPreviewStorage.js");
9
10
  Object.defineProperty(exports, "merchantPreviewNamespace", { enumerable: true, get: function () { return merchantPreviewStorage_js_2.merchantPreviewNamespace; } });
10
11
  const unavailable = () => new client_js_1.RuntimeClientError('MERCHANT_PREVIEW_UNAVAILABLE', 'This preview is no longer available. Open a new preview from OXVO.', false, null, 409);
11
12
  class MerchantPreviewAdmission {
13
+ cartRecovery() { return (0, cartRecovery_js_1.createCartRecovery)(this.runtime, this.bootstrap.installKey, this.store); }
12
14
  constructor(preview, bootstrap, runtime, storage = sessionStorage, recoveryOnly = false) {
13
15
  this.preview = preview;
14
16
  this.bootstrap = bootstrap;