@oxvo/ai-live-assist 7.5.20 → 7.5.21

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 (99) hide show
  1. package/cjs/AiLiveAssist.d.ts +8 -1
  2. package/cjs/AiLiveAssist.js +113 -8
  3. package/cjs/client.d.ts +5 -3
  4. package/cjs/client.js +44 -5
  5. package/cjs/commerce/cartContracts.d.ts +158 -0
  6. package/cjs/commerce/cartContracts.js +228 -0
  7. package/cjs/commerce/cartSession.d.ts +86 -0
  8. package/cjs/commerce/cartSession.js +475 -0
  9. package/cjs/commerce/contracts.d.ts +152 -0
  10. package/cjs/commerce/contracts.js +322 -0
  11. package/cjs/commerce/pageContext.d.ts +50 -0
  12. package/cjs/commerce/pageContext.js +173 -0
  13. package/cjs/commerce/productPanel.d.ts +65 -0
  14. package/cjs/commerce/productPanel.js +662 -0
  15. package/cjs/commerce/realtimeCommerce.d.ts +73 -0
  16. package/cjs/commerce/realtimeCommerce.js +342 -0
  17. package/cjs/commerce/shopifyCart.d.ts +130 -0
  18. package/cjs/commerce/shopifyCart.js +1135 -0
  19. package/cjs/commerce/shopifyCartPresentation.d.ts +12 -0
  20. package/cjs/commerce/shopifyCartPresentation.js +379 -0
  21. package/cjs/commerce/shoppingNotes.d.ts +61 -0
  22. package/cjs/commerce/shoppingNotes.js +313 -0
  23. package/cjs/commerce/shoppingNotesView.d.ts +46 -0
  24. package/cjs/commerce/shoppingNotesView.js +269 -0
  25. package/cjs/control.d.ts +9 -1
  26. package/cjs/control.js +51 -1
  27. package/cjs/guideAdmission.d.ts +5 -2
  28. package/cjs/guideAdmission.js +21 -2
  29. package/cjs/guideInstaller.js +1 -1
  30. package/cjs/guideMeasurement.d.ts +5 -0
  31. package/cjs/guideMeasurement.js +29 -0
  32. package/cjs/guideSubjectStore.js +2 -0
  33. package/cjs/guideTypes.d.ts +18 -0
  34. package/cjs/liveControlChannel.d.ts +43 -1
  35. package/cjs/liveControlChannel.js +166 -14
  36. package/cjs/liveGuideAdmission.d.ts +3 -2
  37. package/cjs/liveGuideAdmission.js +10 -2
  38. package/cjs/liveGuideWidget.d.ts +18 -0
  39. package/cjs/liveGuideWidget.js +228 -23
  40. package/cjs/locales/resources.js +2240 -0
  41. package/cjs/messages.js +56 -0
  42. package/cjs/tabLock.d.ts +2 -0
  43. package/cjs/tabLock.js +11 -1
  44. package/cjs/types.d.ts +6 -2
  45. package/cjs/types.js +56 -0
  46. package/cjs/ui.d.ts +37 -0
  47. package/cjs/ui.js +259 -9
  48. package/cjs/version.d.ts +1 -1
  49. package/cjs/version.js +1 -1
  50. package/lib/AiLiveAssist.d.ts +8 -1
  51. package/lib/AiLiveAssist.js +113 -8
  52. package/lib/client.d.ts +5 -3
  53. package/lib/client.js +44 -5
  54. package/lib/commerce/cartContracts.d.ts +158 -0
  55. package/lib/commerce/cartContracts.js +221 -0
  56. package/lib/commerce/cartSession.d.ts +86 -0
  57. package/lib/commerce/cartSession.js +471 -0
  58. package/lib/commerce/contracts.d.ts +152 -0
  59. package/lib/commerce/contracts.js +300 -0
  60. package/lib/commerce/pageContext.d.ts +50 -0
  61. package/lib/commerce/pageContext.js +168 -0
  62. package/lib/commerce/productPanel.d.ts +65 -0
  63. package/lib/commerce/productPanel.js +657 -0
  64. package/lib/commerce/realtimeCommerce.d.ts +73 -0
  65. package/lib/commerce/realtimeCommerce.js +337 -0
  66. package/lib/commerce/shopifyCart.d.ts +130 -0
  67. package/lib/commerce/shopifyCart.js +1130 -0
  68. package/lib/commerce/shopifyCartPresentation.d.ts +12 -0
  69. package/lib/commerce/shopifyCartPresentation.js +376 -0
  70. package/lib/commerce/shoppingNotes.d.ts +61 -0
  71. package/lib/commerce/shoppingNotes.js +307 -0
  72. package/lib/commerce/shoppingNotesView.d.ts +46 -0
  73. package/lib/commerce/shoppingNotesView.js +265 -0
  74. package/lib/control.d.ts +9 -1
  75. package/lib/control.js +51 -1
  76. package/lib/guideAdmission.d.ts +5 -2
  77. package/lib/guideAdmission.js +21 -2
  78. package/lib/guideInstaller.js +1 -1
  79. package/lib/guideMeasurement.d.ts +5 -0
  80. package/lib/guideMeasurement.js +24 -0
  81. package/lib/guideSubjectStore.js +2 -0
  82. package/lib/guideTypes.d.ts +18 -0
  83. package/lib/liveControlChannel.d.ts +43 -1
  84. package/lib/liveControlChannel.js +166 -14
  85. package/lib/liveGuideAdmission.d.ts +3 -2
  86. package/lib/liveGuideAdmission.js +10 -2
  87. package/lib/liveGuideWidget.d.ts +18 -0
  88. package/lib/liveGuideWidget.js +228 -23
  89. package/lib/locales/resources.js +2240 -0
  90. package/lib/messages.js +56 -0
  91. package/lib/tabLock.d.ts +2 -0
  92. package/lib/tabLock.js +11 -1
  93. package/lib/types.d.ts +6 -2
  94. package/lib/types.js +56 -0
  95. package/lib/ui.d.ts +37 -0
  96. package/lib/ui.js +259 -9
  97. package/lib/version.d.ts +1 -1
  98. package/lib/version.js +1 -1
  99. package/package.json +1 -1
@@ -3,6 +3,8 @@ import { claimGuideMount } from "./guideMount.js";
3
3
  import { RuntimeClient, RuntimeClientError, idempotencyKey, isValidAssistSessionGrant, isValidReplaySessionId, } from "./client.js";
4
4
  import { ControlChannel, } from "./control.js";
5
5
  import { PageContextCollector } from "./context.js";
6
+ import { parseCommerceBootstrap } from "./commerce/contracts.js";
7
+ import { RealtimeCommerce, realtimeCommerceRequiredDigest } from "./commerce/realtimeCommerce.js";
6
8
  import { RealtimeMedia } from "./media.js";
7
9
  import { loadMessengerWebWidget, normalizeMessengerWebWidgetDescriptor, } from "./messengerLoader.js";
8
10
  import { MAX_PAGE_ASSISTANCE_RECOVERY_TTL_MS, PageAssistancePreferenceStore, PageAssistanceRecoveryStore, digestPageAssistanceVisitor, } from "./pageAssistancePreference.js";
@@ -253,6 +255,7 @@ const CONSENT_SCOPES = new Set([
253
255
  "microphone",
254
256
  "page_context",
255
257
  "browser_control",
258
+ "commerce_cart",
256
259
  "visual_context",
257
260
  "handoff_context",
258
261
  "retained_transcript",
@@ -1415,6 +1418,9 @@ export default class AiLiveAssist {
1415
1418
  this.channel = null;
1416
1419
  this.media = null;
1417
1420
  this.context = null;
1421
+ this.commerce = null;
1422
+ this.commerceReadyChannel = null;
1423
+ this.pendingCommerceGeneration = null;
1418
1424
  this.presentation = null;
1419
1425
  this.connectionAbort = null;
1420
1426
  this.connectionGeneration = 0;
@@ -1587,7 +1593,11 @@ export default class AiLiveAssist {
1587
1593
  this.onMessengerReturnRequested = (event) => {
1588
1594
  this.handleMessengerReturnRequested(event);
1589
1595
  };
1596
+ this.handledPageHide = null;
1590
1597
  this.onPageHide = (event) => {
1598
+ if (this.handledPageHide === event)
1599
+ return;
1600
+ this.handledPageHide = event;
1591
1601
  const recoveryWasBusy = !event.persisted && (this.reconnecting || this.reconnectTimer !== null);
1592
1602
  const resumeAtHide = recoveryWasBusy ? this.readResume() : null;
1593
1603
  const ordinaryRecoveryPending = recoveryWasBusy &&
@@ -1783,6 +1793,12 @@ export default class AiLiveAssist {
1783
1793
  document.documentElement.lang ||
1784
1794
  "en");
1785
1795
  this.lock = new TabActivityLock(this.storageNamespace, this.windowId, (active) => this.handleTabActivityChange(active), (requesterId, requestId) => this.handoffToFocusedTab(requesterId, requestId), (payload, authority, sourceOwnerId) => this.prepareFocusedTabHandoff(payload, authority, sourceOwnerId), {
1796
+ onBeforePageHideRelease: (event) => {
1797
+ if (this.liveWidget)
1798
+ void this.liveWidget.end().catch(() => undefined);
1799
+ else
1800
+ this.onPageHide(event);
1801
+ },
1786
1802
  onCommitting: (payload, authority) => this.commitStagedPendingLaunch(payload, authority),
1787
1803
  onCommitted: (payload, authority) => void this.commitFocusedTabHandoff(payload, authority),
1788
1804
  onRelinquished: (payload) => this.completeFocusedTabRelinquish(payload),
@@ -2036,6 +2052,8 @@ export default class AiLiveAssist {
2036
2052
  this.clearReconnectTimer();
2037
2053
  if (this.destroyed)
2038
2054
  return;
2055
+ this.commerce?.destroy();
2056
+ this.commerce = null;
2039
2057
  this.liveWidget?.destroy();
2040
2058
  this.liveWidget = null;
2041
2059
  const recoveringModeUpgrade = this.relinquishModeUpgradeForRecovery(true, true);
@@ -2169,7 +2187,8 @@ export default class AiLiveAssist {
2169
2187
  this.bootstrap = bootstrap;
2170
2188
  this.liveWidget = new LiveGuideWidget({ bootstrap, admission: this.guideAdmission, runtime: this.runtime,
2171
2189
  tabId: this.tabId, locale: this.locale, messages: this.options.messages, viewOptions: this.widgetViewOptions,
2172
- acquire: () => this.lock.acquire(), release: () => this.lock.release(), onState: () => this.emitStateEvent() });
2190
+ acquire: () => this.lock.acquire(), release: () => this.lock.release(),
2191
+ ownsActivity: () => this.lock.ownsActivity(), onState: () => this.emitStateEvent() });
2173
2192
  this.view = this.liveWidget.view;
2174
2193
  this.lifecyclePhase = "ready";
2175
2194
  return;
@@ -7940,6 +7959,8 @@ export default class AiLiveAssist {
7940
7959
  let recoveryPath = null;
7941
7960
  const channel = new ControlChannel(result, this.tabId, VERSION, () => this.scheduleReconnect(true), this.readResume()?.clientSequence ?? 0, (sequence) => this.updateResumeSequence(sequence), () => this.handleControlSequenceGap(), {
7942
7961
  canRecover: () => {
7962
+ this.commerceReadyChannel = null;
7963
+ this.commerce?.suspend();
7943
7964
  const currentPath = path();
7944
7965
  if (!this.canRecoverControlTransport(channel, result, media) ||
7945
7966
  (recoveryPath !== null && recoveryPath !== currentPath))
@@ -7953,15 +7974,19 @@ export default class AiLiveAssist {
7953
7974
  channel.startHeartbeat(this.heartbeatSeconds);
7954
7975
  await this.replayPreFenceAuthorityEnvelopes(channel, fencingToken, assertCurrent);
7955
7976
  assertCurrent();
7977
+ this.startRealtimeCommerce(true);
7956
7978
  await this.context?.captureAndPublish();
7957
7979
  assertCurrent();
7958
7980
  this.flushPlaybackState();
7959
7981
  this.reapplyConservativePreFencePresence(channel, fencingToken);
7982
+ void this.flushPendingQuestion();
7960
7983
  },
7961
- });
7984
+ }, result.protocolVersion === 2 && this.commerceBootstrap() ? 1 : undefined, result.protocolVersion === 2 && this.commerceCartEnabled());
7962
7985
  const pauseHelloStateSignal = deferredSignal();
7963
7986
  (this.pauseHelloStateSignals ?? (this.pauseHelloStateSignals = new WeakMap())).set(channel, pauseHelloStateSignal);
7964
7987
  this.handoffContextPromptReceiptChannel = null;
7988
+ this.commerceReadyChannel = null;
7989
+ this.pendingCommerceGeneration = null;
7965
7990
  this.channel = channel;
7966
7991
  this.committedHandoffRecoveryChannel = null;
7967
7992
  this.committedHandoffRecoveryExpiresAt = 0;
@@ -8059,6 +8084,7 @@ export default class AiLiveAssist {
8059
8084
  // delivery is acknowledged so its fresh snapshot remains authoritative.
8060
8085
  assertCurrent();
8061
8086
  this.startContext(activeScopes);
8087
+ this.startRealtimeCommerce();
8062
8088
  assertCurrent();
8063
8089
  await this.replayPreFenceAuthorityEnvelopes(channel, fencingToken, assertCurrent);
8064
8090
  assertCurrent();
@@ -8311,6 +8337,38 @@ export default class AiLiveAssist {
8311
8337
  const outcomes = await Promise.all(pending.map((entry) => entry.outcome));
8312
8338
  return outcomes.every((outcome) => outcome.status === "ack");
8313
8339
  }
8340
+ commerceBootstrap() {
8341
+ return parseCommerceBootstrap(this.bootstrap?.commerce, this.bootstrap?.guideId, window.location.origin);
8342
+ }
8343
+ commerceCartEnabled(bootstrap = this.bootstrap) {
8344
+ return bootstrap?.capabilities?.commerceCart === true && parseCommerceBootstrap(bootstrap.commerce, bootstrap.guideId, window.location.origin)?.cartEnabled === true;
8345
+ }
8346
+ startRealtimeCommerce(preserveProvider = false) {
8347
+ const authority = this.commerceBootstrap();
8348
+ const sessionId = this.result?.sessionId;
8349
+ if (!authority || !sessionId || !(this.view instanceof WidgetView) ||
8350
+ !this.channel?.hasFencedAuthority || this.channel.negotiatedCommerceVersion !== 1) {
8351
+ this.commerce?.suspend();
8352
+ return;
8353
+ }
8354
+ if (this.commerce?.sessionId !== sessionId) {
8355
+ this.commerce?.destroy();
8356
+ this.commerce = new RealtimeCommerce(sessionId, authority, {
8357
+ channel: () => this.channel,
8358
+ view: () => this.view instanceof WidgetView ? this.view : null,
8359
+ isCurrent: () => this.result?.sessionId === sessionId && !this.ended && !this.destroyed &&
8360
+ !this.terminalRequestPending && !this.messengerTransferred && !this.messengerTransferPending,
8361
+ sharePage: () => this.bootstrap?.capabilities?.pageContext === true && this.scopes.includes("page_context"),
8362
+ cartConsent: () => this.commerceCartEnabled() &&
8363
+ this.scopes.includes("ai_disclosure") && this.scopes.includes("commerce_cart"),
8364
+ submit: text => this.sendText(text),
8365
+ });
8366
+ }
8367
+ this.commerceReadyChannel = this.channel;
8368
+ const pending = this.pendingCommerceGeneration;
8369
+ this.pendingCommerceGeneration = null;
8370
+ this.commerce.activate(pending?.channel === this.channel ? pending.digest : undefined, preserveProvider);
8371
+ }
8314
8372
  startContext(scopes) {
8315
8373
  this.context?.stop();
8316
8374
  this.context = null;
@@ -8611,7 +8669,9 @@ export default class AiLiveAssist {
8611
8669
  this.terminalRequestPending ||
8612
8670
  this.ended ||
8613
8671
  !channel?.isOpen ||
8614
- channel.leaseToken < 1) {
8672
+ channel.leaseToken < 1 ||
8673
+ (channel.negotiatedCommerceVersion === 1 && this.commerceBootstrap() &&
8674
+ this.commerceReadyChannel !== channel)) {
8615
8675
  return;
8616
8676
  }
8617
8677
  const confirmationDecisionMessageId = pending.confirmationDecisionMessageId;
@@ -8635,7 +8695,9 @@ export default class AiLiveAssist {
8635
8695
  this.terminalRequestPending ||
8636
8696
  this.ended ||
8637
8697
  this.channel !== channel ||
8638
- !channel.isOpen) {
8698
+ !channel.isOpen ||
8699
+ (channel.negotiatedCommerceVersion === 1 && this.commerceBootstrap() &&
8700
+ this.commerceReadyChannel !== channel)) {
8639
8701
  return;
8640
8702
  }
8641
8703
  if (!pending.shown) {
@@ -8644,6 +8706,10 @@ export default class AiLiveAssist {
8644
8706
  this.rememberTranscript(pending.submissionId, "user", pending.text);
8645
8707
  (this.renderedTranscriptIds ?? (this.renderedTranscriptIds = new Set())).add(pending.submissionId);
8646
8708
  }
8709
+ if (this.commerce?.beforeInput() === false) {
8710
+ this.scheduleReconnect(true);
8711
+ return;
8712
+ }
8647
8713
  let messageId;
8648
8714
  let sentSequence = 0;
8649
8715
  try {
@@ -9607,7 +9673,8 @@ export default class AiLiveAssist {
9607
9673
  !scopes.includes("text") ||
9608
9674
  typeof payload.browserControl !== "boolean" ||
9609
9675
  payload.browserControl !== scopes.includes("browser_control") ||
9610
- (scopes.includes("browser_control") && !scopes.includes("page_context"))) {
9676
+ (scopes.includes("browser_control") && !scopes.includes("page_context")) ||
9677
+ (scopes.includes("commerce_cart") && !this.commerceCartEnabled())) {
9611
9678
  return null;
9612
9679
  }
9613
9680
  return scopes;
@@ -9936,7 +10003,15 @@ export default class AiLiveAssist {
9936
10003
  // A delayed receipt cannot restore recording after the visitor opted out.
9937
10004
  if (this.guideAdmission && !this.guideAdmission.recordingAllowed)
9938
10005
  scopes = scopes.filter(scope => scope !== "session_recording");
10006
+ const sharedPage = this.scopes.includes("page_context");
10007
+ const cartConsent = this.scopes.includes("ai_disclosure") && this.scopes.includes("commerce_cart");
9939
10008
  this.scopes = [...scopes];
10009
+ const nextCartConsent = scopes.includes("ai_disclosure") && scopes.includes("commerce_cart");
10010
+ if (cartConsent !== nextCartConsent)
10011
+ this.commerce?.consentChanged(nextCartConsent);
10012
+ if (sharedPage !== scopes.includes("page_context")) {
10013
+ this.commerce?.permissionChanged(scopes.includes("page_context"));
10014
+ }
9940
10015
  if (this.guideAdmission && this.result) {
9941
10016
  this.guideAdmission.syncRecording(this.result, scopes, this.tabId);
9942
10017
  if (this.view instanceof WidgetView)
@@ -10283,6 +10358,15 @@ export default class AiLiveAssist {
10283
10358
  this.invalidateCtaAuthority();
10284
10359
  }
10285
10360
  const fencedAuthorityAtIngress = this.channel?.hasFencedAuthority === true;
10361
+ if (message.type === "commerce.context.required" && this.channel?.negotiatedCommerceVersion === 1 &&
10362
+ this.commerceReadyChannel !== this.channel) {
10363
+ const digest = realtimeCommerceRequiredDigest(message.payload);
10364
+ if (digest)
10365
+ this.pendingCommerceGeneration = { channel: this.channel, digest };
10366
+ }
10367
+ else {
10368
+ this.commerce?.observeIngress(message, fencedAuthorityAtIngress);
10369
+ }
10286
10370
  (this.fencedAuthorityAtIngressByEnvelope ?? (this.fencedAuthorityAtIngressByEnvelope = new WeakMap())).set(message, fencedAuthorityAtIngress);
10287
10371
  if (message.type === "handoff.state" &&
10288
10372
  message.payload.state === "prepared") {
@@ -10712,6 +10796,12 @@ export default class AiLiveAssist {
10712
10796
  return;
10713
10797
  const payload = message.payload;
10714
10798
  switch (message.type) {
10799
+ case "commerce.catalog":
10800
+ case "commerce.cart.confirmation":
10801
+ case "commerce.cart.grant":
10802
+ case "commerce.cart.result":
10803
+ this.commerce?.receive(message);
10804
+ return;
10715
10805
  case "cta.offer": {
10716
10806
  // CTA has its own ingress fence. Browser-action generations also move
10717
10807
  // on unchanged consent, which must not discard a queued native link.
@@ -13300,6 +13390,7 @@ export default class AiLiveAssist {
13300
13390
  void this.performPageAssistanceRevocation();
13301
13391
  }
13302
13392
  handleControlSequenceGap() {
13393
+ this.commerce?.suspend();
13303
13394
  // The socket is no longer authoritative, so revoke every executable
13304
13395
  // action immediately. A causal navigation/result envelope records an
13305
13396
  // action that already happened and remains bounded by its original grant;
@@ -15875,6 +15966,8 @@ export default class AiLiveAssist {
15875
15966
  });
15876
15967
  }
15877
15968
  quiesceLocalEffectsForTerminalRequest() {
15969
+ this.commerce?.destroy();
15970
+ this.commerce = null;
15878
15971
  this.clearCtaAuthority();
15879
15972
  this.queuedLaunchToken = null;
15880
15973
  this.launchGeneration += 1;
@@ -15941,6 +16034,9 @@ export default class AiLiveAssist {
15941
16034
  this.messengerOpenAckInFlight = null;
15942
16035
  }
15943
16036
  cleanupTransport(options = {}) {
16037
+ this.commerceReadyChannel = null;
16038
+ this.pendingCommerceGeneration = null;
16039
+ this.commerce?.suspend();
15944
16040
  this.voicePlaybackInterruptBarrier = null;
15945
16041
  this.voicePlaybackAdmissionAfterSequence = 0;
15946
16042
  this.invalidateVoicePlaybackRearm();
@@ -16046,6 +16142,12 @@ export default class AiLiveAssist {
16046
16142
  if (this.manualPushRequest && ["session.interrupt", "session.mode", "voice.turn_mode", "session.pause", "session.end", "experience.end"].includes(type)) {
16047
16143
  this.stopManualPushToTalk(false);
16048
16144
  }
16145
+ if (type === "session.pause")
16146
+ this.commerce?.pause();
16147
+ if (["session.end", "experience.end"].includes(type))
16148
+ this.commerce?.suspend();
16149
+ if (type === "session.interrupt")
16150
+ this.commerce?.cut();
16049
16151
  if (this.terminalRequestPending && type !== "experience.end")
16050
16152
  return null;
16051
16153
  if (!this.channel?.isOpen)
@@ -17575,9 +17677,8 @@ export default class AiLiveAssist {
17575
17677
  return connection?.saveData === true || connection?.effectiveType === "2g";
17576
17678
  }
17577
17679
  bindWindowLifecycle() {
17578
- // Run transport cleanup before TabActivityLock's own pagehide listener
17579
- // releases cross-tab authority. Pagehide targets Window, where capture
17580
- // listeners are invoked before the lock's non-capture listener.
17680
+ // The lock's explicit lifecycle hook captures owned cleanup before release;
17681
+ // this listener also cleans up inactive pages without relying on event order.
17581
17682
  window.addEventListener("pagehide", this.onPageHide, true);
17582
17683
  window.addEventListener("pageshow", this.onPageShow);
17583
17684
  window.addEventListener("online", this.onOnline);
@@ -17611,6 +17712,10 @@ export default class AiLiveAssist {
17611
17712
  return this.terminalRequestPending;
17612
17713
  }
17613
17714
  handleTabActivityChange(active) {
17715
+ if (this.liveWidget) {
17716
+ this.liveWidget.onTabActivityChange(active);
17717
+ return;
17718
+ }
17614
17719
  this.view?.showActiveElsewhere(false);
17615
17720
  if (!active ||
17616
17721
  this.terminalRequestPending ||
package/lib/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AssistMode, AiGuideCompanionState, BootstrapConfig, ConsentScope, HandoffRecoveryResult, LaunchResult, ExperienceMode, MessengerConversationState } from "./types.js";
2
- import { type GuideAdmissionResult, type GuideLaunchIntent, type GuideLaunchRecoveryInput, type GuideLaunchRecoveryResult, type GuideLaunchResult, type GuideRecordingLinkInput, type GuideRecordingLinkResult } from "./guideTypes.js";
2
+ import { type GuideAdmissionResult, type GuideLaunchIntent, type GuideLaunchRecoveryInput, type GuideLaunchRecoveryResult, type GuideLaunchResult, type GuideRecordingLinkInput, type GuideRecordingLinkResult, type GuideMeasurementBridge } from "./guideTypes.js";
3
3
  import type { LiveControlAuthorization } from "./liveControlChannel.js";
4
4
  import type { LiveGuideLaunchIntent } from "./liveGuideAdmission.js";
5
5
  export declare class RuntimeClientError extends Error {
@@ -96,7 +96,7 @@ export declare class RuntimeClient {
96
96
  admitLiveGuide(intent: LiveGuideLaunchIntent, subjectCredential: string | undefined, signal: AbortSignal): Promise<GuideAdmissionResult & {
97
97
  providerProtocol: "live";
98
98
  }>;
99
- launchLiveGuide(intent: LiveGuideLaunchIntent, admissionGrant: string, signal: AbortSignal): Promise<LiveControlAuthorization>;
99
+ launchLiveGuide(intent: LiveGuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<LiveControlAuthorization>;
100
100
  endLiveGuide(input: GuideLaunchRecoveryInput, signal?: AbortSignal): Promise<{
101
101
  schemaVersion: 3;
102
102
  protocolVersion: 2;
@@ -104,7 +104,7 @@ export declare class RuntimeClient {
104
104
  status: "end_requested";
105
105
  launchRequestId: string;
106
106
  }>;
107
- launchGuide(intent: GuideLaunchIntent, admissionGrant: string, signal: AbortSignal): Promise<GuideLaunchResult>;
107
+ launchGuide(intent: GuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<GuideLaunchResult>;
108
108
  recoverGuideLaunch(input: GuideLaunchRecoveryInput, signal?: AbortSignal, keepalive?: boolean): Promise<GuideLaunchRecoveryResult>;
109
109
  linkGuideRecording(sessionId: string, input: GuideRecordingLinkInput, signal: AbortSignal): Promise<GuideRecordingLinkResult>;
110
110
  resume(sessionId: string, credential: string, path: string, protocolVersion: 1 | 2, signal: AbortSignal): Promise<LaunchResult>;
@@ -127,7 +127,9 @@ export declare class RuntimeClient {
127
127
  private postEmpty;
128
128
  private parseCompanionState;
129
129
  private parseMessengerConversation;
130
+ private postGuideLaunch;
130
131
  private postJson;
132
+ private postRawJson;
131
133
  private parseJson;
132
134
  private throwResponse;
133
135
  }
package/lib/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { GUIDE_INSTALL_KEY_PATTERN, } from "./guideTypes.js";
2
+ import { currentGuideMeasurementBridge, GUIDE_MEASUREMENT_CLIENT_VERSION } from './guideMeasurement.js';
2
3
  export class RuntimeClientError extends Error {
3
4
  constructor(code, message, retryable, retryAfterMs, status) {
4
5
  super(message);
@@ -182,14 +183,14 @@ export class RuntimeClient {
182
183
  async admitLiveGuide(intent, subjectCredential, signal) {
183
184
  return this.postJson("/ai-live-assist/v1/public/live/admissions", { ...intent, ...(subjectCredential ? { subjectCredential } : {}) }, {}, signal);
184
185
  }
185
- async launchLiveGuide(intent, admissionGrant, signal) {
186
- return this.postJson("/ai-live-assist/v1/public/live/launch", { ...intent, admissionGrant }, { "Idempotency-Key": intent.launchRequestId }, signal);
186
+ async launchLiveGuide(intent, admissionGrant, signal, measurementBridge) {
187
+ return this.postGuideLaunch("/ai-live-assist/v1/public/live/launch", intent, admissionGrant, signal, measurementBridge);
187
188
  }
188
189
  async endLiveGuide(input, signal) {
189
190
  return this.postJson("/ai-live-assist/v1/public/live/launches/end", input, {}, signal, true);
190
191
  }
191
- async launchGuide(intent, admissionGrant, signal) {
192
- return this.postJson("/ai-live-assist/v1/public/launch", { ...intent, admissionGrant }, { "Idempotency-Key": intent.launchRequestId }, signal);
192
+ async launchGuide(intent, admissionGrant, signal, measurementBridge) {
193
+ return this.postGuideLaunch("/ai-live-assist/v1/public/launch", intent, admissionGrant, signal, measurementBridge);
193
194
  }
194
195
  async recoverGuideLaunch(input, signal, keepalive = false) {
195
196
  return this.postJson("/ai-live-assist/v1/public/launches/recover", input, {}, signal, keepalive);
@@ -455,7 +456,44 @@ export class RuntimeClient {
455
456
  inboxId: candidate.inboxId,
456
457
  };
457
458
  }
459
+ async postGuideLaunch(path, intent, admissionGrant, signal, bridge) {
460
+ // Serialize once: possession signs these exact bytes, including the native grant.
461
+ const rawBody = JSON.stringify({ ...intent, admissionGrant });
462
+ const headers = { 'Idempotency-Key': intent.launchRequestId };
463
+ if (intent.guideMeasurement !== undefined) {
464
+ const unavailable = () => new RuntimeClientError('GUIDE_MEASUREMENT_UNAVAILABLE', 'AI Guide could not secure this conversation. Please try again.', true, null, 409);
465
+ const assignment = intent.guideMeasurement.assignment;
466
+ const current = () => !signal.aborted && intent.clientVersion === GUIDE_MEASUREMENT_CLIENT_VERSION &&
467
+ this.clientVersion === GUIDE_MEASUREMENT_CLIENT_VERSION && currentGuideMeasurementBridge(bridge) && bridge.assignment === assignment;
468
+ if (!current() || !bridge)
469
+ throw unavailable();
470
+ try {
471
+ const authorization = await bridge.authorizeLaunch(`${this.baseUrl}${path}`, rawBody, signal);
472
+ if (!current() || !authorization || typeof authorization.current !== 'function')
473
+ throw unavailable();
474
+ // The bridge supplies only the two possession headers, never arbitrary request authority.
475
+ const names = ['X-Oxvo-Analytics-Receipt', 'X-Oxvo-Analytics-Proof'];
476
+ if (!authorization.headers || Object.keys(authorization.headers).length !== names.length)
477
+ throw unavailable();
478
+ for (const name of names) {
479
+ const value = authorization.headers[name];
480
+ if (typeof value !== 'string' || value.length < 1 || value.length > 8192 || !/^[\x21-\x7e]+$/.test(value))
481
+ throw unavailable();
482
+ headers[name] = value;
483
+ }
484
+ if (!current() || authorization.current() !== true || signal.aborted)
485
+ throw unavailable();
486
+ }
487
+ catch {
488
+ throw unavailable();
489
+ }
490
+ }
491
+ return this.postRawJson(path, rawBody, headers, signal, false, false, intent.guideMeasurement !== undefined);
492
+ }
458
493
  async postJson(path, body, extraHeaders, signal, keepalive = false, requireNoContent = false) {
494
+ return this.postRawJson(path, JSON.stringify(body), extraHeaders, signal, keepalive, requireNoContent);
495
+ }
496
+ async postRawJson(path, rawBody, extraHeaders, signal, keepalive = false, requireNoContent = false, rejectRedirect = false) {
459
497
  const response = await fetch(`${this.baseUrl}${path}`, {
460
498
  method: "POST",
461
499
  mode: "cors",
@@ -468,7 +506,8 @@ export class RuntimeClient {
468
506
  "X-Request-Id": requestId(),
469
507
  ...extraHeaders,
470
508
  },
471
- body: JSON.stringify(body),
509
+ body: rawBody,
510
+ ...(rejectRedirect ? { redirect: 'error' } : {}),
472
511
  ...(keepalive ? { keepalive: true } : {}),
473
512
  ...(signal ? { signal } : {}),
474
513
  });
@@ -0,0 +1,158 @@
1
+ import { type CommerceBootstrap, type CommerceContext, type CommerceMarket, type CommerceOption, type CommerceStore, type LiveCommerceDisplayed, type RealtimeCommerceDisplayed } from './contracts.js';
2
+ export declare const COMMERCE_CART_SMALL_MESSAGE_MAX_BYTES = 4096;
3
+ export declare const COMMERCE_CART_MESSAGE_MAX_BYTES = 12000;
4
+ export declare const COMMERCE_CART_CONFIRMATION_MAX_AGE_MS = 30000;
5
+ export declare const COMMERCE_CART_GRANT_MAX_AGE_MS = 8000;
6
+ export type CommerceCartProvider = {
7
+ kind: 'realtime';
8
+ generationDigest: string;
9
+ } | {
10
+ kind: 'live';
11
+ taskId: string;
12
+ inputEpoch: number;
13
+ };
14
+ export type CommerceCartScope = {
15
+ schemaVersion: 1;
16
+ requestId: string;
17
+ operationId: string;
18
+ proposalChecksum: string;
19
+ contextDigest: string;
20
+ contextRevision: number;
21
+ pageId: string;
22
+ provider: CommerceCartProvider;
23
+ };
24
+ export type CommerceCartItem = {
25
+ productRef: string;
26
+ variantRef: string;
27
+ shopifyVariantId: string;
28
+ title: string;
29
+ productUrl: string;
30
+ selectedOptions: CommerceOption[];
31
+ quantity: number;
32
+ unitPrice: {
33
+ amount: string;
34
+ currency: string;
35
+ };
36
+ quantityRule: {
37
+ minimum: number;
38
+ maximum: number | null;
39
+ increment: number;
40
+ };
41
+ requiresSellingPlan: false;
42
+ requiresComponents: false;
43
+ };
44
+ type CartRequestSelection = {
45
+ requestId: string;
46
+ productRef: string;
47
+ variantRef: string;
48
+ quantity: number;
49
+ selectionDigest: string;
50
+ };
51
+ export type CommerceCartRequest = (Omit<LiveCommerceDisplayed, 'products'> | Omit<RealtimeCommerceDisplayed, 'products'>) & CartRequestSelection;
52
+ export type CommerceCartConfirmation = CommerceCartScope & {
53
+ guideId: string;
54
+ store: CommerceStore;
55
+ market: CommerceMarket;
56
+ item: CommerceCartItem;
57
+ expiresAt: string;
58
+ };
59
+ export type CommerceCartConfirmationResult = {
60
+ schemaVersion: 1;
61
+ operationId: string;
62
+ proposalChecksum: string;
63
+ approved: boolean;
64
+ };
65
+ export type CommerceCartGrant = CommerceCartScope & {
66
+ grant: string;
67
+ action: 'add';
68
+ store: CommerceStore;
69
+ market: CommerceMarket;
70
+ item: CommerceCartItem;
71
+ operationMarker: string;
72
+ expiresAt: string;
73
+ };
74
+ export type CommerceCartExecutionBegin = {
75
+ schemaVersion: 1;
76
+ operationId: string;
77
+ grant: string;
78
+ executionId: string;
79
+ cartDigest: string;
80
+ };
81
+ export type CommerceCartExecutionReady = {
82
+ schemaVersion: 1;
83
+ operationId: string;
84
+ executionId: string;
85
+ cartDigest: string;
86
+ requestMessageId: string;
87
+ state: 'prepared' | 'already_started';
88
+ expiresAt: string;
89
+ };
90
+ export type CommerceCartRequestOutcome = {
91
+ outcome: 'response';
92
+ httpStatus: number;
93
+ } | {
94
+ outcome: 'timeout' | 'network_error' | 'aborted' | 'unknown';
95
+ };
96
+ export type CommerceCartObservation = {
97
+ source: 'browser_cart';
98
+ observedAt: string;
99
+ currency: string;
100
+ shopifyVariantId: string;
101
+ operationMarker: string;
102
+ quantity: number;
103
+ lineKeyDigest: string | null;
104
+ };
105
+ export type CommerceCartExecutionResult = CommerceCartScope & {
106
+ executionId: string;
107
+ cartDigest: string;
108
+ request: CommerceCartRequestOutcome;
109
+ observation: CommerceCartObservation | null;
110
+ };
111
+ export type CommerceCartRejectedCode = 'quote_unavailable' | 'quote_changed' | 'policy_denied' | 'unsupported_selection' | 'busy' | 'context_changed' | 'conflict';
112
+ export type CommerceCartResultCode = CommerceCartRejectedCode | 'expired' | 'declined' | 'unconfirmed' | 'observed' | 'partial';
113
+ type ResultBase = {
114
+ schemaVersion: 1;
115
+ requestId: string;
116
+ operationId: string | null;
117
+ executionId: string | null;
118
+ observation?: CommerceCartObservation;
119
+ };
120
+ export type CommerceCartResult = ResultBase & ({
121
+ status: 'rejected';
122
+ code: CommerceCartRejectedCode;
123
+ } | {
124
+ status: 'cancelled';
125
+ code: 'declined' | 'context_changed';
126
+ } | {
127
+ status: 'expired';
128
+ code: 'expired';
129
+ } | {
130
+ status: 'unconfirmed';
131
+ code: 'unconfirmed';
132
+ } | {
133
+ status: 'observed';
134
+ code: 'observed';
135
+ operationId: string;
136
+ executionId: string;
137
+ observation: CommerceCartObservation;
138
+ } | {
139
+ status: 'partial';
140
+ code: 'partial';
141
+ operationId: string;
142
+ executionId: string;
143
+ observation: CommerceCartObservation;
144
+ });
145
+ export type CommerceCartReadyExpectation = Partial<Pick<CommerceCartExecutionReady, 'operationId' | 'executionId' | 'cartDigest' | 'requestMessageId'>>;
146
+ export type CommerceCartResultExpectation = Partial<Pick<CommerceCartResult, 'requestId' | 'operationId' | 'executionId'>>;
147
+ /** A confirmation is a bounded quote, never permission to mutate the cart. */
148
+ export declare function parseCommerceCartConfirmation(value: unknown, bootstrap: CommerceBootstrap, context: CommerceContext | null, expected?: Partial<CommerceCartScope>, now?: number): CommerceCartConfirmation | null;
149
+ /** The session must additionally bind this grant to its approved quote and
150
+ * current control lease. operationMarker is an independent server-issued UUID. */
151
+ export declare function parseCommerceCartGrant(value: unknown, bootstrap: CommerceBootstrap, context: CommerceContext | null, expected?: Partial<CommerceCartScope>, now?: number): CommerceCartGrant | null;
152
+ /** already_started retains the original executionId/cartDigest exactly. The
153
+ * caller must correlate operation/requestMessageId and must never replay POST. */
154
+ export declare function parseCommerceCartExecutionReady(value: unknown, expected?: CommerceCartReadyExpectation, now?: number): CommerceCartExecutionReady | null;
155
+ /** observed/partial are correlated browser reports, not server-verified facts.
156
+ * observedAt remains the reported timestamp; no invented recency restriction. */
157
+ export declare function parseCommerceCartResult(value: unknown, expected?: CommerceCartResultExpectation, now?: number): CommerceCartResult | null;
158
+ export {};