@oxvo/ai-live-assist 7.5.23 → 7.5.26

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.
@@ -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.23";
37
+ readonly version = "7.5.26";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
@@ -50,6 +50,9 @@ export declare class CartSession {
50
50
  private readonly retiredRequests;
51
51
  private recoveryOutcome;
52
52
  private recoveryInFlight;
53
+ private recoveryGrant;
54
+ private recoveryBegin;
55
+ private pendingReport;
53
56
  constructor(options: CartSessionOptions);
54
57
  /** A catalog replaces the panel; install again after its visible receipt. */
55
58
  refreshControls(): void;
@@ -73,7 +76,10 @@ export declare class CartSession {
73
76
  private report;
74
77
  private showRecovery;
75
78
  private checkCart;
79
+ private recoveryHandle;
80
+ private beginRecovery;
76
81
  private begin;
82
+ private awaitAdmission;
77
83
  private ready;
78
84
  private result;
79
85
  private decline;
@@ -38,6 +38,11 @@ class CartSession {
38
38
  this.retiredRequests = new Set();
39
39
  this.recoveryOutcome = null;
40
40
  this.recoveryInFlight = null;
41
+ // At most one original grant, held only by this live instance. The public
42
+ // recovery ledger deliberately contains no mutation credentials.
43
+ this.recoveryGrant = null;
44
+ this.recoveryBegin = null;
45
+ this.pendingReport = null;
41
46
  this.canAdd = (productRef, variantRef, quantity) => {
42
47
  if (this.destroyed || this.pending || this.recoveryInFlight || !this.options.bootstrap.cartEnabled ||
43
48
  !this.options.current() || this.hasUnresolved())
@@ -82,21 +87,40 @@ class CartSession {
82
87
  const stillCurrent = () => !this.destroyed && !this.pending && stable(this.options.current()) === stable(snapshot);
83
88
  const work = async () => {
84
89
  try {
85
- const executor = this.recoveryExecutor();
86
- const recovered = await executor.reconcilePending({ ...this.recoveryScope(snapshot.sessionId), market: snapshot.context.market });
87
- const outcome = recovered.outcome;
88
- const prepared = recovered.prepared;
90
+ let recoveryDeadline = null;
91
+ const executor = this.recoveryExecutor(() => stillCurrent() && (recoveryDeadline === null || Date.now() < recoveryDeadline));
92
+ const retained = executor.peekPending(this.recoveryScope(snapshot.sessionId));
93
+ const prepared = retained?.prepared;
94
+ let outcome = retained?.outcome;
95
+ if (!prepared || !outcome?.execution || !stillCurrent())
96
+ return;
97
+ const positive = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
98
+ // Retained positive evidence may already be terminal on native: replay
99
+ // it unchanged before asking for any recovery admission or cart read.
100
+ let reported = positive ? await this.report(prepared, outcome, executor) : false;
101
+ if (!stillCurrent())
102
+ return;
103
+ if (!reported) {
104
+ const ready = await this.beginRecovery(snapshot, prepared, outcome.execution);
105
+ if (!ready || !stillCurrent() || Date.parse(ready.expiresAt) <= Date.now())
106
+ return;
107
+ recoveryDeadline = Date.parse(ready.expiresAt);
108
+ outcome = await executor.reconcile(prepared, outcome.execution.executionId, ready, { refreshObservation: !!positive });
109
+ reported = false;
110
+ }
111
+ if (!stillCurrent())
112
+ return;
89
113
  if (outcome)
90
114
  this.recoveryOutcome = outcome;
91
115
  // Only an original public scope stored with the original executor
92
116
  // record can report recovery. It confers no permission to POST.
93
- if (prepared && outcome && !this.destroyed && this.options.current()?.sessionId === snapshot.sessionId) {
117
+ if (!reported && prepared && outcome && stillCurrent()) {
94
118
  if (prepared.reportSessionId === snapshot.sessionId)
95
119
  await this.report(prepared, outcome, executor);
96
120
  }
97
121
  if (prepared && outcome)
98
122
  await (0, shopifyCartPresentation_js_1.refreshShopifyCartPresentation)(prepared, outcome, { assertCurrent: stillCurrent }).catch(() => undefined);
99
- if (this.destroyed)
123
+ if (!stillCurrent())
100
124
  return;
101
125
  if (this.hasUnresolved())
102
126
  this.showRecovery();
@@ -145,6 +169,9 @@ class CartSession {
145
169
  this.result(payload);
146
170
  }
147
171
  cut() {
172
+ this.recoveryGrant = null;
173
+ this.recoveryBegin?.resolve(null);
174
+ this.pendingReport?.resolve(false);
148
175
  const pending = this.pending;
149
176
  if (!pending)
150
177
  return;
@@ -161,6 +188,7 @@ class CartSession {
161
188
  destroy() {
162
189
  this.cut();
163
190
  this.destroyed = true;
191
+ this.pendingReport?.resolve(false);
164
192
  this.options.view()?.setCommerceCartActionHandler(null);
165
193
  }
166
194
  createPending(intentKind, requestId, snapshot, selection, quantity) {
@@ -257,6 +285,7 @@ class CartSession {
257
285
  pending.approved = true;
258
286
  }
259
287
  pending.grant = copy(grant);
288
+ this.recoveryGrant = { grant: copy(grant), snapshot: copy(pending.snapshot) };
260
289
  pending.executing = true;
261
290
  if (pending.timer)
262
291
  clearTimeout(pending.timer);
@@ -301,8 +330,8 @@ class CartSession {
301
330
  await (0, shopifyCartPresentation_js_1.refreshShopifyCartPresentation)(prepared, outcome, { assertCurrent: () => this.current(pending) }).catch(() => undefined);
302
331
  this.finish(pending);
303
332
  }
304
- recoveryExecutor() {
305
- return new shopifyCart_js_1.ShopifyCartExecutor({ assertCurrent: () => !this.destroyed && this.options.current() !== null,
333
+ recoveryExecutor(assertCurrent = () => !this.destroyed && this.options.current() !== null) {
334
+ return new shopifyCart_js_1.ShopifyCartExecutor({ assertCurrent,
306
335
  beginExecution: async () => { throw new Error('Cart recovery cannot admit a new write.'); } });
307
336
  }
308
337
  hasUnresolved() {
@@ -318,17 +347,37 @@ class CartSession {
318
347
  ...(sessionId ? { sessionId } : {}) };
319
348
  }
320
349
  async report(prepared, outcome, executor) {
321
- if (!prepared.reportScope || !prepared.reportSessionId || !outcome.execution ||
350
+ if (this.destroyed || !prepared.reportScope || !prepared.reportSessionId || !outcome.execution ||
322
351
  prepared.reportScope.operationId !== prepared.operationId || prepared.guideId !== this.options.bootstrap.guideId ||
323
352
  stable(prepared.store) !== stable(this.options.bootstrap.store))
324
- return;
353
+ return false;
325
354
  const transportSessionId = this.options.transportSessionId ? this.options.transportSessionId() :
326
355
  this.options.current()?.sessionId ?? prepared.reportSessionId;
327
356
  if (transportSessionId !== prepared.reportSessionId)
328
- return;
357
+ return false;
329
358
  const report = { ...scopeOf(prepared.reportScope), ...outcome.execution };
330
- if (await this.send('commerce.cart.execution.result', report)) {
331
- executor.acknowledgeReport(this.recoveryScope(prepared.reportSessionId), report);
359
+ let resolve;
360
+ const response = new Promise(done => { resolve = done; });
361
+ const pending = { report, resolve };
362
+ this.pendingReport = pending;
363
+ try {
364
+ const [delivered, accepted] = await Promise.all([
365
+ this.send('commerce.cart.execution.result', report), this.boundedAccepted(response, 10000),
366
+ ]);
367
+ const currentSessionId = this.options.transportSessionId ? this.options.transportSessionId() :
368
+ this.options.current()?.sessionId ?? prepared.reportSessionId;
369
+ if (!delivered || !accepted || this.destroyed || currentSessionId !== prepared.reportSessionId)
370
+ return false;
371
+ const acknowledged = executor.acknowledgeReport(this.recoveryScope(prepared.reportSessionId), report);
372
+ if (acknowledged && this.recoveryGrant?.grant.operationId === prepared.operationId)
373
+ this.recoveryGrant = null;
374
+ // Native acceptance and durable local acknowledgement are separate. A
375
+ // storage failure must retain local debt, not reopen a settled operation.
376
+ return true;
377
+ }
378
+ finally {
379
+ if (this.pendingReport === pending)
380
+ this.pendingReport = null;
332
381
  }
333
382
  }
334
383
  showRecovery() {
@@ -343,10 +392,43 @@ class CartSession {
343
392
  ? { ...retained.outcome, local: local.local } : retained.outcome;
344
393
  }
345
394
  const outcome = this.recoveryOutcome ?? failure('transport', true);
346
- // An unresolved conflict/zero observation still needs a read-only check;
347
- // retain its receipt and evidence rather than claiming that no effect ran.
395
+ // Retain uncertain evidence without offering a no-op Check after the
396
+ // original instance/authority needed to reconcile it is gone.
348
397
  const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
349
- this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), this.checkCart);
398
+ const current = this.options.current();
399
+ 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);
403
+ }
404
+ recoveryHandle(snapshot, prepared) {
405
+ const retained = this.recoveryGrant;
406
+ if (!retained || stable(retained.snapshot) !== stable(snapshot) || prepared.reportSessionId !== snapshot.sessionId ||
407
+ !prepared.reportScope || stable(prepared.reportScope) !== stable(scopeOf(retained.grant)) ||
408
+ prepared.operationId !== retained.grant.operationId)
409
+ return null;
410
+ return retained;
411
+ }
412
+ async beginRecovery(snapshot, prepared, execution) {
413
+ const retained = this.recoveryHandle(snapshot, prepared);
414
+ if (!retained)
415
+ return null;
416
+ let resolve;
417
+ const response = new Promise(done => { resolve = done; });
418
+ const begin = { messageId: null, executionId: execution.executionId, cartDigest: execution.cartDigest,
419
+ ready: null, resolve, operationId: prepared.operationId };
420
+ this.recoveryBegin = begin;
421
+ try {
422
+ return await this.awaitAdmission(begin, response, { schemaVersion: 1, operationId: prepared.operationId,
423
+ grant: retained.grant.grant, executionId: execution.executionId, cartDigest: execution.cartDigest });
424
+ }
425
+ catch {
426
+ return null;
427
+ }
428
+ finally {
429
+ if (this.recoveryBegin === begin)
430
+ this.recoveryBegin = null;
431
+ }
350
432
  }
351
433
  async begin(pending, executionId, cartDigest) {
352
434
  if (!pending.grant || !this.current(pending))
@@ -355,19 +437,22 @@ class CartSession {
355
437
  const ready = new Promise(done => { resolve = done; });
356
438
  pending.begin = { messageId: null, executionId, cartDigest, ready: null, resolve };
357
439
  pending.started = true;
440
+ return this.awaitAdmission(pending.begin, ready, { schemaVersion: 1,
441
+ operationId: pending.grant.operationId, grant: pending.grant.grant, executionId, cartDigest });
442
+ }
443
+ async awaitAdmission(begin, ready, payload) {
358
444
  let delivery;
359
445
  try {
360
- delivery = this.options.send('commerce.cart.execution.begin', { schemaVersion: 1,
361
- operationId: pending.grant.operationId, grant: pending.grant.grant, executionId, cartDigest });
362
- pending.begin.messageId = delivery.messageId;
446
+ delivery = this.options.send('commerce.cart.execution.begin', payload);
447
+ begin.messageId = delivery.messageId;
363
448
  }
364
449
  catch {
365
- pending.begin.resolve(null);
450
+ begin.resolve(null);
366
451
  throw new Error('The cart admission could not be sent.');
367
452
  }
368
453
  // Admission can race expiry. A fresh already_started reply has its own
369
454
  // short recovery window and can only lead to read-only reconciliation.
370
- const timeout = setTimeout(() => resolve(null), 10000);
455
+ const timeout = setTimeout(() => begin.resolve(null), 10000);
371
456
  try {
372
457
  const [accepted, observed] = await Promise.all([this.boundedAccepted(delivery.accepted, 10000), ready]);
373
458
  if (!accepted || !observed)
@@ -379,6 +464,16 @@ class CartSession {
379
464
  }
380
465
  }
381
466
  ready(payload) {
467
+ const recovery = this.recoveryBegin;
468
+ if (recovery?.messageId && !recovery.ready) {
469
+ const ready = (0, cartContracts_js_1.parseCommerceCartExecutionReady)(payload, { operationId: recovery.operationId,
470
+ requestMessageId: recovery.messageId, executionId: recovery.executionId, cartDigest: recovery.cartDigest });
471
+ if (ready?.state === 'already_started') {
472
+ recovery.ready = copy(ready);
473
+ recovery.resolve(ready);
474
+ }
475
+ return;
476
+ }
382
477
  const pending = this.pending;
383
478
  const begin = pending?.begin;
384
479
  if (!pending?.grant || !begin?.messageId || begin.ready)
@@ -391,6 +486,14 @@ class CartSession {
391
486
  begin.resolve(ready);
392
487
  }
393
488
  result(payload) {
489
+ const waiting = this.pendingReport;
490
+ if (waiting) {
491
+ const result = (0, cartContracts_js_1.parseCommerceCartResult)(payload, { requestId: waiting.report.requestId,
492
+ operationId: waiting.report.operationId, executionId: waiting.report.executionId });
493
+ if (result)
494
+ waiting.resolve((result.status === 'observed' || result.status === 'partial') &&
495
+ stable(result.observation) === stable(waiting.report.observation));
496
+ }
394
497
  const pending = this.pending;
395
498
  if (!pending)
396
499
  return;
@@ -114,7 +114,9 @@ export declare class ShopifyCartExecutor {
114
114
  reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
115
  execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;
116
116
  /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
117
- reconcile(input: PreparedShopifyCartAddition, executionId: string, recoveredReady?: ShopifyCartExecutionReady): Promise<ShopifyCartOutcome>;
117
+ reconcile(input: PreparedShopifyCartAddition, executionId: string, recoveredReady?: ShopifyCartExecutionReady, options?: {
118
+ refreshObservation?: boolean;
119
+ }): Promise<ShopifyCartOutcome>;
118
120
  /** Ajax change.js sets an absolute quantity and offers no conditional delta/CAS.
119
121
  * A read then change can overwrite the shopper's concurrent edit even by line key.
120
122
  * https://shopify.dev/docs/api/ajax/reference/cart#post-locale-cart-change-js
@@ -217,7 +217,9 @@ async function request(path, body, onResponse) {
217
217
  response.status > 599)
218
218
  throw new AjaxTransportError("network_error");
219
219
  onResponse?.(response.status);
220
- if (!/^application\/json(?:;|$)/iu.test(response.headers.get("content-type") ?? "") ||
220
+ if (
221
+ // Shopify's Ajax .js endpoints also serve JSON as text/javascript.
222
+ !/^(?:application\/json|text\/javascript)(?:;|$)/iu.test(response.headers.get("content-type") ?? "") ||
221
223
  Number(response.headers.get("content-length") ?? "0") > RESPONSE_BYTES ||
222
224
  response.redirected)
223
225
  throw new Error("transport");
@@ -296,6 +298,7 @@ function parseCart(value) {
296
298
  items,
297
299
  };
298
300
  }
301
+ const emptyCart = (cart) => cart.itemCount === 0 && cart.items.length === 0;
299
302
  async function readCart(root) {
300
303
  const response = await request(`${root}cart.js`);
301
304
  if (response.status !== 200)
@@ -475,6 +478,15 @@ function readLedger(key) {
475
478
  /^[0-9a-f]{64}$/u.test(entry.intentDigest) &&
476
479
  typeof entry.cartDigest === "string" &&
477
480
  /^[0-9a-f]{64}$/u.test(entry.cartDigest) &&
481
+ (entry.initialCartEmpty === undefined ||
482
+ typeof entry.initialCartEmpty === "boolean") &&
483
+ (entry.initialCartEmpty !== true || entry.prepared != null) &&
484
+ (entry.materializedCartDigest === undefined ||
485
+ (entry.initialCartEmpty === true &&
486
+ entry.resolved === true &&
487
+ entry.observation != null &&
488
+ typeof entry.materializedCartDigest === "string" &&
489
+ /^[0-9a-f]{64}$/u.test(entry.materializedCartDigest))) &&
478
490
  count(entry.expiresAt) &&
479
491
  (entry.request == null || validRequestOutcome(entry.request)) &&
480
492
  (entry.prepared == null ||
@@ -786,12 +798,14 @@ class ShopifyCartExecutor {
786
798
  BigInt(Number.MAX_SAFE_INTEGER))
787
799
  return result("unavailable", "invalid_request");
788
800
  let cartDigest;
801
+ let initialCartEmpty = false;
789
802
  let operationAlreadyVisible = false;
790
803
  try {
791
804
  const cart = await readCart(paths.root);
792
805
  if (cart.currency !== prepared.market.currency)
793
806
  return result("conflict", "cart_changed");
794
807
  cartDigest = await sha(cart.token);
808
+ initialCartEmpty = emptyCart(cart);
795
809
  operationAlreadyVisible = cart.items.some((line) => object(line.properties) &&
796
810
  line.properties[PROPERTY] === prepared.operationMarker);
797
811
  // An existing marker is reconciliation-only. Native must identify the original admission.
@@ -829,6 +843,7 @@ class ShopifyCartExecutor {
829
843
  executionId,
830
844
  intentDigest: digest,
831
845
  cartDigest,
846
+ initialCartEmpty,
832
847
  expiresAt: Date.parse(prepared.expiresAt),
833
848
  request: null,
834
849
  prepared: publicPrepared(prepared),
@@ -845,12 +860,16 @@ class ShopifyCartExecutor {
845
860
  if (Date.parse(claim.expiresAt) <= Date.now() ||
846
861
  Date.parse(prepared.expiresAt) <= Date.now())
847
862
  return abort("uncertain", "expired");
863
+ let cartChanged = false;
848
864
  try {
849
- // Product/native reads take time. Refuse a known cart switch; Ajax still has a cookie TOCTOU.
865
+ // An unmaterialized empty Shopify cart can receive a new opaque token on every GET.
866
+ // Both reads must still be empty. Nonempty carts retain strict token identity.
850
867
  const finalCart = await readCart(paths.root);
851
- if (finalCart.currency !== prepared.market.currency ||
852
- (await sha(finalCart.token)) !== cartDigest)
853
- return abort("conflict", "cart_changed");
868
+ cartChanged =
869
+ finalCart.currency !== prepared.market.currency ||
870
+ (initialCartEmpty
871
+ ? !emptyCart(finalCart)
872
+ : (await sha(finalCart.token)) !== cartDigest);
854
873
  operationAlreadyVisible || (operationAlreadyVisible = finalCart.items.some((line) => object(line.properties) &&
855
874
  line.properties[PROPERTY] === prepared.operationMarker));
856
875
  }
@@ -875,6 +894,8 @@ class ShopifyCartExecutor {
875
894
  : abort("conflict", "invalid_request");
876
895
  if (entries.some((entry) => pendingEntry(entry, prepared.reportSessionId)))
877
896
  return abort("uncertain", "previous_operation_unresolved");
897
+ if (cartChanged)
898
+ return abort("conflict", "cart_changed");
878
899
  if (operationAlreadyVisible)
879
900
  return abort("uncertain", "execution_unverified");
880
901
  saveStarted(key, entries, original);
@@ -908,7 +929,7 @@ class ShopifyCartExecutor {
908
929
  return this.observe(prepared, evidence({ ...original, request: requestOutcome }));
909
930
  }
910
931
  /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
911
- async reconcile(input, executionId, recoveredReady) {
932
+ async reconcile(input, executionId, recoveredReady, options = {}) {
912
933
  let prepared;
913
934
  try {
914
935
  const text = JSON.stringify(input);
@@ -917,9 +938,11 @@ class ShopifyCartExecutor {
917
938
  prepared = JSON.parse(text);
918
939
  if (!(0, contracts_js_1.commerceUuid)(executionId) || !validPrepared(prepared))
919
940
  return result("unavailable", "invalid_request");
920
- if (recoveredReady &&
921
- (!validReady(recoveredReady) ||
922
- recoveredReady.state !== "already_started"))
941
+ if ((options.refreshObservation && (!recoveredReady || recoveredReady.executionId !== executionId ||
942
+ Date.parse(recoveredReady.expiresAt) <= Date.now())) ||
943
+ recoveredReady &&
944
+ (!validReady(recoveredReady) ||
945
+ recoveredReady.state !== "already_started"))
923
946
  return result("uncertain", "grant_unavailable");
924
947
  const digest = await sha(intent(prepared));
925
948
  let started;
@@ -956,7 +979,9 @@ class ShopifyCartExecutor {
956
979
  /* Read-only recovery remains valid; unavailable storage still disables new effects. */
957
980
  }
958
981
  }
959
- if (started?.resolved && started.prepared?.reportScope)
982
+ // Exact terminal report replay remains the default. Only a fresh,
983
+ // correlated already_started admission may request a new observation.
984
+ if (started?.resolved && started.prepared?.reportScope && !options.refreshObservation)
960
985
  return retainedOutcome(prepared, started);
961
986
  const execution = started
962
987
  ? evidence(started)
@@ -967,7 +992,7 @@ class ShopifyCartExecutor {
967
992
  request: null,
968
993
  })
969
994
  : null;
970
- return this.observe(prepared, execution);
995
+ return this.observe(prepared, execution, options.refreshObservation === true);
971
996
  }
972
997
  catch {
973
998
  return result("uncertain", "invalid_request");
@@ -992,7 +1017,7 @@ class ShopifyCartExecutor {
992
1017
  return false;
993
1018
  }
994
1019
  }
995
- async observe(prepared, execution) {
1020
+ async observe(prepared, execution, refreshUnacceptedObservation = false) {
996
1021
  const paths = route(prepared, false);
997
1022
  if (!paths)
998
1023
  return { ...result("uncertain", "context_changed"), execution };
@@ -1011,7 +1036,7 @@ class ShopifyCartExecutor {
1011
1036
  storeRef: prepared.store.storeRef,
1012
1037
  productRef: prepared.productRef,
1013
1038
  variantRef: prepared.variantRef,
1014
- cartDigest,
1039
+ cartDigest: execution?.cartDigest ?? cartDigest,
1015
1040
  lineDigest: line &&
1016
1041
  typeof line.key === "string" &&
1017
1042
  line.key.length > 0 &&
@@ -1026,7 +1051,26 @@ class ShopifyCartExecutor {
1026
1051
  let status = "uncertain";
1027
1052
  let reason = "not_observed";
1028
1053
  const expected = ajaxPrice(prepared.unitPrice.amount, prepared.unitPrice.currency);
1029
- if ((execution && execution.cartDigest !== cartDigest) ||
1054
+ const intentDigest = execution ? await sha(intent(prepared)) : null;
1055
+ let retained;
1056
+ if (execution && intentDigest) {
1057
+ try {
1058
+ retained = readLedger(ledgerKey(prepared)).find((entry) => sameStarted(entry, {
1059
+ ...execution,
1060
+ operationId: prepared.operationId,
1061
+ intentDigest,
1062
+ }));
1063
+ }
1064
+ catch {
1065
+ // Lost/corrupt storage cannot establish an empty start or relax token identity.
1066
+ }
1067
+ }
1068
+ const firstEmptyMaterialization = retained?.initialCartEmpty === true &&
1069
+ retained.materializedCartDigest === undefined &&
1070
+ !retained.resolved;
1071
+ const tokenMatches = !execution ||
1072
+ (retained?.materializedCartDigest ?? execution.cartDigest) === cartDigest;
1073
+ if ((!tokenMatches && !firstEmptyMaterialization) ||
1030
1074
  cart.currency !== prepared.market.currency) {
1031
1075
  status = "conflict";
1032
1076
  reason = "cart_changed";
@@ -1067,9 +1111,13 @@ class ShopifyCartExecutor {
1067
1111
  reason = "line_changed";
1068
1112
  }
1069
1113
  }
1070
- // Missing retained state cannot be replaced by today's token or a caller's
1071
- // new execution ID. Native recovery must provide the original bound values.
1072
- // Wire observations are facts about the original cart, never inferred from a mismatched line.
1114
+ else if (!tokenMatches && !emptyCart(cart)) {
1115
+ status = "conflict";
1116
+ reason = "cart_changed";
1117
+ }
1118
+ // Only a retained empty start permits the first materialized token, and only
1119
+ // the exact marked line above can bind it. Native execution/report identity never changes.
1120
+ // Missing retained state still requires the original native-bound token.
1073
1121
  const observation = execution &&
1074
1122
  (status === "confirmed" ||
1075
1123
  status === "partial" ||
@@ -1085,27 +1133,39 @@ class ShopifyCartExecutor {
1085
1133
  }
1086
1134
  : null;
1087
1135
  if (execution && observation && observation.quantity > 0) {
1136
+ let durablyRetained = false;
1088
1137
  try {
1089
1138
  const key = ledgerKey(prepared);
1090
- const digest = await sha(intent(prepared));
1091
1139
  const entries = readLedger(key);
1092
1140
  const entry = entries.find((candidate) => sameStarted(candidate, {
1093
1141
  operationId: prepared.operationId,
1094
1142
  executionId: execution.executionId,
1095
1143
  cartDigest: execution.cartDigest,
1096
- intentDigest: digest,
1144
+ intentDigest: intentDigest,
1097
1145
  }));
1098
- if (entry && !entry.resolved) {
1146
+ if (entry?.resolved && entry.prepared?.reportScope &&
1147
+ (!refreshUnacceptedObservation || entry.reportAccepted))
1148
+ return retainedOutcome(prepared, entry);
1149
+ if (entry && (!entry.resolved || (refreshUnacceptedObservation && !entry.reportAccepted))) {
1099
1150
  entry.prepared ?? (entry.prepared = publicPrepared(prepared));
1100
1151
  entry.request ?? (entry.request = execution.request);
1101
1152
  entry.observation = observation;
1102
1153
  entry.resolved = true;
1154
+ if (entry.initialCartEmpty === true)
1155
+ entry.materializedCartDigest = cartDigest;
1103
1156
  saveLedger(key, entries);
1157
+ durablyRetained = true;
1104
1158
  }
1105
1159
  }
1106
1160
  catch {
1107
- /* A failed persistence keeps hasPending closed; no retry of the effect. */
1161
+ /* Retain the pending guard when storage cannot keep the observation. */
1108
1162
  }
1163
+ // Every positive native report, including the first observation after
1164
+ // Add or an unknown result, must be replayable after native settles it.
1165
+ // Keep local cart truth but withhold undurable evidence from transport.
1166
+ if (prepared.reportScope && !durablyRetained)
1167
+ return { status, reason: "storage_unavailable", canUndo: false,
1168
+ receipt, execution: null, local: { itemCount: cart.itemCount } };
1109
1169
  }
1110
1170
  if (!execution) {
1111
1171
  status = "uncertain";
@@ -1,5 +1,5 @@
1
1
  import type { GuideMeasurementBridge, GuideMeasurementIntent } from './guideTypes.js';
2
- export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.23";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.26";
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.23';
7
+ exports.GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.26';
8
8
  function isGuideMeasurementIntent(value) {
9
9
  if (!value || typeof value !== 'object' || Array.isArray(value))
10
10
  return false;
@@ -1,6 +1,6 @@
1
1
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
2
2
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
3
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.23";
3
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.26";
4
4
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
5
5
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
6
6
  export type LiveControlState = {
package/cjs/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "7.5.23";
1
+ export declare const VERSION = "7.5.26";
package/cjs/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '7.5.23';
4
+ exports.VERSION = '7.5.26';
@@ -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.23";
37
+ readonly version = "7.5.26";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
@@ -50,6 +50,9 @@ export declare class CartSession {
50
50
  private readonly retiredRequests;
51
51
  private recoveryOutcome;
52
52
  private recoveryInFlight;
53
+ private recoveryGrant;
54
+ private recoveryBegin;
55
+ private pendingReport;
53
56
  constructor(options: CartSessionOptions);
54
57
  /** A catalog replaces the panel; install again after its visible receipt. */
55
58
  refreshControls(): void;
@@ -73,7 +76,10 @@ export declare class CartSession {
73
76
  private report;
74
77
  private showRecovery;
75
78
  private checkCart;
79
+ private recoveryHandle;
80
+ private beginRecovery;
76
81
  private begin;
82
+ private awaitAdmission;
77
83
  private ready;
78
84
  private result;
79
85
  private decline;
@@ -35,6 +35,11 @@ export class CartSession {
35
35
  this.retiredRequests = new Set();
36
36
  this.recoveryOutcome = null;
37
37
  this.recoveryInFlight = null;
38
+ // At most one original grant, held only by this live instance. The public
39
+ // recovery ledger deliberately contains no mutation credentials.
40
+ this.recoveryGrant = null;
41
+ this.recoveryBegin = null;
42
+ this.pendingReport = null;
38
43
  this.canAdd = (productRef, variantRef, quantity) => {
39
44
  if (this.destroyed || this.pending || this.recoveryInFlight || !this.options.bootstrap.cartEnabled ||
40
45
  !this.options.current() || this.hasUnresolved())
@@ -79,21 +84,40 @@ export class CartSession {
79
84
  const stillCurrent = () => !this.destroyed && !this.pending && stable(this.options.current()) === stable(snapshot);
80
85
  const work = async () => {
81
86
  try {
82
- const executor = this.recoveryExecutor();
83
- const recovered = await executor.reconcilePending({ ...this.recoveryScope(snapshot.sessionId), market: snapshot.context.market });
84
- const outcome = recovered.outcome;
85
- const prepared = recovered.prepared;
87
+ let recoveryDeadline = null;
88
+ const executor = this.recoveryExecutor(() => stillCurrent() && (recoveryDeadline === null || Date.now() < recoveryDeadline));
89
+ const retained = executor.peekPending(this.recoveryScope(snapshot.sessionId));
90
+ const prepared = retained?.prepared;
91
+ let outcome = retained?.outcome;
92
+ if (!prepared || !outcome?.execution || !stillCurrent())
93
+ return;
94
+ const positive = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
95
+ // Retained positive evidence may already be terminal on native: replay
96
+ // it unchanged before asking for any recovery admission or cart read.
97
+ let reported = positive ? await this.report(prepared, outcome, executor) : false;
98
+ if (!stillCurrent())
99
+ return;
100
+ if (!reported) {
101
+ const ready = await this.beginRecovery(snapshot, prepared, outcome.execution);
102
+ if (!ready || !stillCurrent() || Date.parse(ready.expiresAt) <= Date.now())
103
+ return;
104
+ recoveryDeadline = Date.parse(ready.expiresAt);
105
+ outcome = await executor.reconcile(prepared, outcome.execution.executionId, ready, { refreshObservation: !!positive });
106
+ reported = false;
107
+ }
108
+ if (!stillCurrent())
109
+ return;
86
110
  if (outcome)
87
111
  this.recoveryOutcome = outcome;
88
112
  // Only an original public scope stored with the original executor
89
113
  // record can report recovery. It confers no permission to POST.
90
- if (prepared && outcome && !this.destroyed && this.options.current()?.sessionId === snapshot.sessionId) {
114
+ if (!reported && prepared && outcome && stillCurrent()) {
91
115
  if (prepared.reportSessionId === snapshot.sessionId)
92
116
  await this.report(prepared, outcome, executor);
93
117
  }
94
118
  if (prepared && outcome)
95
119
  await refreshShopifyCartPresentation(prepared, outcome, { assertCurrent: stillCurrent }).catch(() => undefined);
96
- if (this.destroyed)
120
+ if (!stillCurrent())
97
121
  return;
98
122
  if (this.hasUnresolved())
99
123
  this.showRecovery();
@@ -142,6 +166,9 @@ export class CartSession {
142
166
  this.result(payload);
143
167
  }
144
168
  cut() {
169
+ this.recoveryGrant = null;
170
+ this.recoveryBegin?.resolve(null);
171
+ this.pendingReport?.resolve(false);
145
172
  const pending = this.pending;
146
173
  if (!pending)
147
174
  return;
@@ -158,6 +185,7 @@ export class CartSession {
158
185
  destroy() {
159
186
  this.cut();
160
187
  this.destroyed = true;
188
+ this.pendingReport?.resolve(false);
161
189
  this.options.view()?.setCommerceCartActionHandler(null);
162
190
  }
163
191
  createPending(intentKind, requestId, snapshot, selection, quantity) {
@@ -254,6 +282,7 @@ export class CartSession {
254
282
  pending.approved = true;
255
283
  }
256
284
  pending.grant = copy(grant);
285
+ this.recoveryGrant = { grant: copy(grant), snapshot: copy(pending.snapshot) };
257
286
  pending.executing = true;
258
287
  if (pending.timer)
259
288
  clearTimeout(pending.timer);
@@ -298,8 +327,8 @@ export class CartSession {
298
327
  await refreshShopifyCartPresentation(prepared, outcome, { assertCurrent: () => this.current(pending) }).catch(() => undefined);
299
328
  this.finish(pending);
300
329
  }
301
- recoveryExecutor() {
302
- return new ShopifyCartExecutor({ assertCurrent: () => !this.destroyed && this.options.current() !== null,
330
+ recoveryExecutor(assertCurrent = () => !this.destroyed && this.options.current() !== null) {
331
+ return new ShopifyCartExecutor({ assertCurrent,
303
332
  beginExecution: async () => { throw new Error('Cart recovery cannot admit a new write.'); } });
304
333
  }
305
334
  hasUnresolved() {
@@ -315,17 +344,37 @@ export class CartSession {
315
344
  ...(sessionId ? { sessionId } : {}) };
316
345
  }
317
346
  async report(prepared, outcome, executor) {
318
- if (!prepared.reportScope || !prepared.reportSessionId || !outcome.execution ||
347
+ if (this.destroyed || !prepared.reportScope || !prepared.reportSessionId || !outcome.execution ||
319
348
  prepared.reportScope.operationId !== prepared.operationId || prepared.guideId !== this.options.bootstrap.guideId ||
320
349
  stable(prepared.store) !== stable(this.options.bootstrap.store))
321
- return;
350
+ return false;
322
351
  const transportSessionId = this.options.transportSessionId ? this.options.transportSessionId() :
323
352
  this.options.current()?.sessionId ?? prepared.reportSessionId;
324
353
  if (transportSessionId !== prepared.reportSessionId)
325
- return;
354
+ return false;
326
355
  const report = { ...scopeOf(prepared.reportScope), ...outcome.execution };
327
- if (await this.send('commerce.cart.execution.result', report)) {
328
- executor.acknowledgeReport(this.recoveryScope(prepared.reportSessionId), report);
356
+ let resolve;
357
+ const response = new Promise(done => { resolve = done; });
358
+ const pending = { report, resolve };
359
+ this.pendingReport = pending;
360
+ try {
361
+ const [delivered, accepted] = await Promise.all([
362
+ this.send('commerce.cart.execution.result', report), this.boundedAccepted(response, 10000),
363
+ ]);
364
+ const currentSessionId = this.options.transportSessionId ? this.options.transportSessionId() :
365
+ this.options.current()?.sessionId ?? prepared.reportSessionId;
366
+ if (!delivered || !accepted || this.destroyed || currentSessionId !== prepared.reportSessionId)
367
+ return false;
368
+ const acknowledged = executor.acknowledgeReport(this.recoveryScope(prepared.reportSessionId), report);
369
+ if (acknowledged && this.recoveryGrant?.grant.operationId === prepared.operationId)
370
+ this.recoveryGrant = null;
371
+ // Native acceptance and durable local acknowledgement are separate. A
372
+ // storage failure must retain local debt, not reopen a settled operation.
373
+ return true;
374
+ }
375
+ finally {
376
+ if (this.pendingReport === pending)
377
+ this.pendingReport = null;
329
378
  }
330
379
  }
331
380
  showRecovery() {
@@ -340,10 +389,43 @@ export class CartSession {
340
389
  ? { ...retained.outcome, local: local.local } : retained.outcome;
341
390
  }
342
391
  const outcome = this.recoveryOutcome ?? failure('transport', true);
343
- // An unresolved conflict/zero observation still needs a read-only check;
344
- // retain its receipt and evidence rather than claiming that no effect ran.
392
+ // Retain uncertain evidence without offering a no-op Check after the
393
+ // original instance/authority needed to reconcile it is gone.
345
394
  const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
346
- this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), this.checkCart);
395
+ const current = this.options.current();
396
+ const prepared = retained?.prepared;
397
+ const canRecover = current && prepared && prepared.reportSessionId === current.sessionId &&
398
+ (observed && prepared.reportScope || this.recoveryHandle(current, prepared));
399
+ this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined);
400
+ }
401
+ recoveryHandle(snapshot, prepared) {
402
+ const retained = this.recoveryGrant;
403
+ if (!retained || stable(retained.snapshot) !== stable(snapshot) || prepared.reportSessionId !== snapshot.sessionId ||
404
+ !prepared.reportScope || stable(prepared.reportScope) !== stable(scopeOf(retained.grant)) ||
405
+ prepared.operationId !== retained.grant.operationId)
406
+ return null;
407
+ return retained;
408
+ }
409
+ async beginRecovery(snapshot, prepared, execution) {
410
+ const retained = this.recoveryHandle(snapshot, prepared);
411
+ if (!retained)
412
+ return null;
413
+ let resolve;
414
+ const response = new Promise(done => { resolve = done; });
415
+ const begin = { messageId: null, executionId: execution.executionId, cartDigest: execution.cartDigest,
416
+ ready: null, resolve, operationId: prepared.operationId };
417
+ this.recoveryBegin = begin;
418
+ try {
419
+ return await this.awaitAdmission(begin, response, { schemaVersion: 1, operationId: prepared.operationId,
420
+ grant: retained.grant.grant, executionId: execution.executionId, cartDigest: execution.cartDigest });
421
+ }
422
+ catch {
423
+ return null;
424
+ }
425
+ finally {
426
+ if (this.recoveryBegin === begin)
427
+ this.recoveryBegin = null;
428
+ }
347
429
  }
348
430
  async begin(pending, executionId, cartDigest) {
349
431
  if (!pending.grant || !this.current(pending))
@@ -352,19 +434,22 @@ export class CartSession {
352
434
  const ready = new Promise(done => { resolve = done; });
353
435
  pending.begin = { messageId: null, executionId, cartDigest, ready: null, resolve };
354
436
  pending.started = true;
437
+ return this.awaitAdmission(pending.begin, ready, { schemaVersion: 1,
438
+ operationId: pending.grant.operationId, grant: pending.grant.grant, executionId, cartDigest });
439
+ }
440
+ async awaitAdmission(begin, ready, payload) {
355
441
  let delivery;
356
442
  try {
357
- delivery = this.options.send('commerce.cart.execution.begin', { schemaVersion: 1,
358
- operationId: pending.grant.operationId, grant: pending.grant.grant, executionId, cartDigest });
359
- pending.begin.messageId = delivery.messageId;
443
+ delivery = this.options.send('commerce.cart.execution.begin', payload);
444
+ begin.messageId = delivery.messageId;
360
445
  }
361
446
  catch {
362
- pending.begin.resolve(null);
447
+ begin.resolve(null);
363
448
  throw new Error('The cart admission could not be sent.');
364
449
  }
365
450
  // Admission can race expiry. A fresh already_started reply has its own
366
451
  // short recovery window and can only lead to read-only reconciliation.
367
- const timeout = setTimeout(() => resolve(null), 10000);
452
+ const timeout = setTimeout(() => begin.resolve(null), 10000);
368
453
  try {
369
454
  const [accepted, observed] = await Promise.all([this.boundedAccepted(delivery.accepted, 10000), ready]);
370
455
  if (!accepted || !observed)
@@ -376,6 +461,16 @@ export class CartSession {
376
461
  }
377
462
  }
378
463
  ready(payload) {
464
+ const recovery = this.recoveryBegin;
465
+ if (recovery?.messageId && !recovery.ready) {
466
+ const ready = parseCommerceCartExecutionReady(payload, { operationId: recovery.operationId,
467
+ requestMessageId: recovery.messageId, executionId: recovery.executionId, cartDigest: recovery.cartDigest });
468
+ if (ready?.state === 'already_started') {
469
+ recovery.ready = copy(ready);
470
+ recovery.resolve(ready);
471
+ }
472
+ return;
473
+ }
379
474
  const pending = this.pending;
380
475
  const begin = pending?.begin;
381
476
  if (!pending?.grant || !begin?.messageId || begin.ready)
@@ -388,6 +483,14 @@ export class CartSession {
388
483
  begin.resolve(ready);
389
484
  }
390
485
  result(payload) {
486
+ const waiting = this.pendingReport;
487
+ if (waiting) {
488
+ const result = parseCommerceCartResult(payload, { requestId: waiting.report.requestId,
489
+ operationId: waiting.report.operationId, executionId: waiting.report.executionId });
490
+ if (result)
491
+ waiting.resolve((result.status === 'observed' || result.status === 'partial') &&
492
+ stable(result.observation) === stable(waiting.report.observation));
493
+ }
391
494
  const pending = this.pending;
392
495
  if (!pending)
393
496
  return;
@@ -114,7 +114,9 @@ export declare class ShopifyCartExecutor {
114
114
  reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
115
  execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;
116
116
  /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
117
- reconcile(input: PreparedShopifyCartAddition, executionId: string, recoveredReady?: ShopifyCartExecutionReady): Promise<ShopifyCartOutcome>;
117
+ reconcile(input: PreparedShopifyCartAddition, executionId: string, recoveredReady?: ShopifyCartExecutionReady, options?: {
118
+ refreshObservation?: boolean;
119
+ }): Promise<ShopifyCartOutcome>;
118
120
  /** Ajax change.js sets an absolute quantity and offers no conditional delta/CAS.
119
121
  * A read then change can overwrite the shopper's concurrent edit even by line key.
120
122
  * https://shopify.dev/docs/api/ajax/reference/cart#post-locale-cart-change-js
@@ -213,7 +213,9 @@ async function request(path, body, onResponse) {
213
213
  response.status > 599)
214
214
  throw new AjaxTransportError("network_error");
215
215
  onResponse?.(response.status);
216
- if (!/^application\/json(?:;|$)/iu.test(response.headers.get("content-type") ?? "") ||
216
+ if (
217
+ // Shopify's Ajax .js endpoints also serve JSON as text/javascript.
218
+ !/^(?:application\/json|text\/javascript)(?:;|$)/iu.test(response.headers.get("content-type") ?? "") ||
217
219
  Number(response.headers.get("content-length") ?? "0") > RESPONSE_BYTES ||
218
220
  response.redirected)
219
221
  throw new Error("transport");
@@ -292,6 +294,7 @@ function parseCart(value) {
292
294
  items,
293
295
  };
294
296
  }
297
+ const emptyCart = (cart) => cart.itemCount === 0 && cart.items.length === 0;
295
298
  async function readCart(root) {
296
299
  const response = await request(`${root}cart.js`);
297
300
  if (response.status !== 200)
@@ -471,6 +474,15 @@ function readLedger(key) {
471
474
  /^[0-9a-f]{64}$/u.test(entry.intentDigest) &&
472
475
  typeof entry.cartDigest === "string" &&
473
476
  /^[0-9a-f]{64}$/u.test(entry.cartDigest) &&
477
+ (entry.initialCartEmpty === undefined ||
478
+ typeof entry.initialCartEmpty === "boolean") &&
479
+ (entry.initialCartEmpty !== true || entry.prepared != null) &&
480
+ (entry.materializedCartDigest === undefined ||
481
+ (entry.initialCartEmpty === true &&
482
+ entry.resolved === true &&
483
+ entry.observation != null &&
484
+ typeof entry.materializedCartDigest === "string" &&
485
+ /^[0-9a-f]{64}$/u.test(entry.materializedCartDigest))) &&
474
486
  count(entry.expiresAt) &&
475
487
  (entry.request == null || validRequestOutcome(entry.request)) &&
476
488
  (entry.prepared == null ||
@@ -782,12 +794,14 @@ export class ShopifyCartExecutor {
782
794
  BigInt(Number.MAX_SAFE_INTEGER))
783
795
  return result("unavailable", "invalid_request");
784
796
  let cartDigest;
797
+ let initialCartEmpty = false;
785
798
  let operationAlreadyVisible = false;
786
799
  try {
787
800
  const cart = await readCart(paths.root);
788
801
  if (cart.currency !== prepared.market.currency)
789
802
  return result("conflict", "cart_changed");
790
803
  cartDigest = await sha(cart.token);
804
+ initialCartEmpty = emptyCart(cart);
791
805
  operationAlreadyVisible = cart.items.some((line) => object(line.properties) &&
792
806
  line.properties[PROPERTY] === prepared.operationMarker);
793
807
  // An existing marker is reconciliation-only. Native must identify the original admission.
@@ -825,6 +839,7 @@ export class ShopifyCartExecutor {
825
839
  executionId,
826
840
  intentDigest: digest,
827
841
  cartDigest,
842
+ initialCartEmpty,
828
843
  expiresAt: Date.parse(prepared.expiresAt),
829
844
  request: null,
830
845
  prepared: publicPrepared(prepared),
@@ -841,12 +856,16 @@ export class ShopifyCartExecutor {
841
856
  if (Date.parse(claim.expiresAt) <= Date.now() ||
842
857
  Date.parse(prepared.expiresAt) <= Date.now())
843
858
  return abort("uncertain", "expired");
859
+ let cartChanged = false;
844
860
  try {
845
- // Product/native reads take time. Refuse a known cart switch; Ajax still has a cookie TOCTOU.
861
+ // An unmaterialized empty Shopify cart can receive a new opaque token on every GET.
862
+ // Both reads must still be empty. Nonempty carts retain strict token identity.
846
863
  const finalCart = await readCart(paths.root);
847
- if (finalCart.currency !== prepared.market.currency ||
848
- (await sha(finalCart.token)) !== cartDigest)
849
- return abort("conflict", "cart_changed");
864
+ cartChanged =
865
+ finalCart.currency !== prepared.market.currency ||
866
+ (initialCartEmpty
867
+ ? !emptyCart(finalCart)
868
+ : (await sha(finalCart.token)) !== cartDigest);
850
869
  operationAlreadyVisible || (operationAlreadyVisible = finalCart.items.some((line) => object(line.properties) &&
851
870
  line.properties[PROPERTY] === prepared.operationMarker));
852
871
  }
@@ -871,6 +890,8 @@ export class ShopifyCartExecutor {
871
890
  : abort("conflict", "invalid_request");
872
891
  if (entries.some((entry) => pendingEntry(entry, prepared.reportSessionId)))
873
892
  return abort("uncertain", "previous_operation_unresolved");
893
+ if (cartChanged)
894
+ return abort("conflict", "cart_changed");
874
895
  if (operationAlreadyVisible)
875
896
  return abort("uncertain", "execution_unverified");
876
897
  saveStarted(key, entries, original);
@@ -904,7 +925,7 @@ export class ShopifyCartExecutor {
904
925
  return this.observe(prepared, evidence({ ...original, request: requestOutcome }));
905
926
  }
906
927
  /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
907
- async reconcile(input, executionId, recoveredReady) {
928
+ async reconcile(input, executionId, recoveredReady, options = {}) {
908
929
  let prepared;
909
930
  try {
910
931
  const text = JSON.stringify(input);
@@ -913,9 +934,11 @@ export class ShopifyCartExecutor {
913
934
  prepared = JSON.parse(text);
914
935
  if (!commerceUuid(executionId) || !validPrepared(prepared))
915
936
  return result("unavailable", "invalid_request");
916
- if (recoveredReady &&
917
- (!validReady(recoveredReady) ||
918
- recoveredReady.state !== "already_started"))
937
+ if ((options.refreshObservation && (!recoveredReady || recoveredReady.executionId !== executionId ||
938
+ Date.parse(recoveredReady.expiresAt) <= Date.now())) ||
939
+ recoveredReady &&
940
+ (!validReady(recoveredReady) ||
941
+ recoveredReady.state !== "already_started"))
919
942
  return result("uncertain", "grant_unavailable");
920
943
  const digest = await sha(intent(prepared));
921
944
  let started;
@@ -952,7 +975,9 @@ export class ShopifyCartExecutor {
952
975
  /* Read-only recovery remains valid; unavailable storage still disables new effects. */
953
976
  }
954
977
  }
955
- if (started?.resolved && started.prepared?.reportScope)
978
+ // Exact terminal report replay remains the default. Only a fresh,
979
+ // correlated already_started admission may request a new observation.
980
+ if (started?.resolved && started.prepared?.reportScope && !options.refreshObservation)
956
981
  return retainedOutcome(prepared, started);
957
982
  const execution = started
958
983
  ? evidence(started)
@@ -963,7 +988,7 @@ export class ShopifyCartExecutor {
963
988
  request: null,
964
989
  })
965
990
  : null;
966
- return this.observe(prepared, execution);
991
+ return this.observe(prepared, execution, options.refreshObservation === true);
967
992
  }
968
993
  catch {
969
994
  return result("uncertain", "invalid_request");
@@ -988,7 +1013,7 @@ export class ShopifyCartExecutor {
988
1013
  return false;
989
1014
  }
990
1015
  }
991
- async observe(prepared, execution) {
1016
+ async observe(prepared, execution, refreshUnacceptedObservation = false) {
992
1017
  const paths = route(prepared, false);
993
1018
  if (!paths)
994
1019
  return { ...result("uncertain", "context_changed"), execution };
@@ -1007,7 +1032,7 @@ export class ShopifyCartExecutor {
1007
1032
  storeRef: prepared.store.storeRef,
1008
1033
  productRef: prepared.productRef,
1009
1034
  variantRef: prepared.variantRef,
1010
- cartDigest,
1035
+ cartDigest: execution?.cartDigest ?? cartDigest,
1011
1036
  lineDigest: line &&
1012
1037
  typeof line.key === "string" &&
1013
1038
  line.key.length > 0 &&
@@ -1022,7 +1047,26 @@ export class ShopifyCartExecutor {
1022
1047
  let status = "uncertain";
1023
1048
  let reason = "not_observed";
1024
1049
  const expected = ajaxPrice(prepared.unitPrice.amount, prepared.unitPrice.currency);
1025
- if ((execution && execution.cartDigest !== cartDigest) ||
1050
+ const intentDigest = execution ? await sha(intent(prepared)) : null;
1051
+ let retained;
1052
+ if (execution && intentDigest) {
1053
+ try {
1054
+ retained = readLedger(ledgerKey(prepared)).find((entry) => sameStarted(entry, {
1055
+ ...execution,
1056
+ operationId: prepared.operationId,
1057
+ intentDigest,
1058
+ }));
1059
+ }
1060
+ catch {
1061
+ // Lost/corrupt storage cannot establish an empty start or relax token identity.
1062
+ }
1063
+ }
1064
+ const firstEmptyMaterialization = retained?.initialCartEmpty === true &&
1065
+ retained.materializedCartDigest === undefined &&
1066
+ !retained.resolved;
1067
+ const tokenMatches = !execution ||
1068
+ (retained?.materializedCartDigest ?? execution.cartDigest) === cartDigest;
1069
+ if ((!tokenMatches && !firstEmptyMaterialization) ||
1026
1070
  cart.currency !== prepared.market.currency) {
1027
1071
  status = "conflict";
1028
1072
  reason = "cart_changed";
@@ -1063,9 +1107,13 @@ export class ShopifyCartExecutor {
1063
1107
  reason = "line_changed";
1064
1108
  }
1065
1109
  }
1066
- // Missing retained state cannot be replaced by today's token or a caller's
1067
- // new execution ID. Native recovery must provide the original bound values.
1068
- // Wire observations are facts about the original cart, never inferred from a mismatched line.
1110
+ else if (!tokenMatches && !emptyCart(cart)) {
1111
+ status = "conflict";
1112
+ reason = "cart_changed";
1113
+ }
1114
+ // Only a retained empty start permits the first materialized token, and only
1115
+ // the exact marked line above can bind it. Native execution/report identity never changes.
1116
+ // Missing retained state still requires the original native-bound token.
1069
1117
  const observation = execution &&
1070
1118
  (status === "confirmed" ||
1071
1119
  status === "partial" ||
@@ -1081,27 +1129,39 @@ export class ShopifyCartExecutor {
1081
1129
  }
1082
1130
  : null;
1083
1131
  if (execution && observation && observation.quantity > 0) {
1132
+ let durablyRetained = false;
1084
1133
  try {
1085
1134
  const key = ledgerKey(prepared);
1086
- const digest = await sha(intent(prepared));
1087
1135
  const entries = readLedger(key);
1088
1136
  const entry = entries.find((candidate) => sameStarted(candidate, {
1089
1137
  operationId: prepared.operationId,
1090
1138
  executionId: execution.executionId,
1091
1139
  cartDigest: execution.cartDigest,
1092
- intentDigest: digest,
1140
+ intentDigest: intentDigest,
1093
1141
  }));
1094
- if (entry && !entry.resolved) {
1142
+ if (entry?.resolved && entry.prepared?.reportScope &&
1143
+ (!refreshUnacceptedObservation || entry.reportAccepted))
1144
+ return retainedOutcome(prepared, entry);
1145
+ if (entry && (!entry.resolved || (refreshUnacceptedObservation && !entry.reportAccepted))) {
1095
1146
  entry.prepared ?? (entry.prepared = publicPrepared(prepared));
1096
1147
  entry.request ?? (entry.request = execution.request);
1097
1148
  entry.observation = observation;
1098
1149
  entry.resolved = true;
1150
+ if (entry.initialCartEmpty === true)
1151
+ entry.materializedCartDigest = cartDigest;
1099
1152
  saveLedger(key, entries);
1153
+ durablyRetained = true;
1100
1154
  }
1101
1155
  }
1102
1156
  catch {
1103
- /* A failed persistence keeps hasPending closed; no retry of the effect. */
1157
+ /* Retain the pending guard when storage cannot keep the observation. */
1104
1158
  }
1159
+ // Every positive native report, including the first observation after
1160
+ // Add or an unknown result, must be replayable after native settles it.
1161
+ // Keep local cart truth but withhold undurable evidence from transport.
1162
+ if (prepared.reportScope && !durablyRetained)
1163
+ return { status, reason: "storage_unavailable", canUndo: false,
1164
+ receipt, execution: null, local: { itemCount: cart.itemCount } };
1105
1165
  }
1106
1166
  if (!execution) {
1107
1167
  status = "uncertain";
@@ -1,5 +1,5 @@
1
1
  import type { GuideMeasurementBridge, GuideMeasurementIntent } from './guideTypes.js';
2
- export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.23";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.26";
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;
@@ -1,4 +1,4 @@
1
- export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.23';
1
+ export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.26';
2
2
  export function isGuideMeasurementIntent(value) {
3
3
  if (!value || typeof value !== 'object' || Array.isArray(value))
4
4
  return false;
@@ -1,6 +1,6 @@
1
1
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
2
2
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
3
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.23";
3
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.26";
4
4
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
5
5
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
6
6
  export type LiveControlState = {
package/lib/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "7.5.23";
1
+ export declare const VERSION = "7.5.26";
package/lib/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '7.5.23';
1
+ export const VERSION = '7.5.26';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxvo/ai-live-assist",
3
3
  "description": "Secure AI Guide browser plugin for OXVO Sessions.",
4
- "version": "7.5.23",
4
+ "version": "7.5.26",
5
5
  "keywords": [
6
6
  "ai-live-assist",
7
7
  "webrtc",