@customer-agent/sdk 0.5.6-test.g260612164307

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 (103) hide show
  1. package/assets/emoji/en-emojibase-data.json +1 -0
  2. package/chunks/App-DTjTPofP.js +2 -0
  3. package/chunks/DockNavigation-CI9i1n3W.js +1 -0
  4. package/chunks/InterviewChatScreen-IQAQHn-E.js +2 -0
  5. package/chunks/InterviewInvitePrompt-DaJfNLz_.js +1 -0
  6. package/chunks/MarkdownText-CXKW_2Ol.js +29 -0
  7. package/chunks/MobileDockDrawer-ZIdezZML.js +1 -0
  8. package/chunks/Panel-Cfjcp7iD.js +7 -0
  9. package/chunks/WidgetComposer-CJtPQVbr.js +92 -0
  10. package/chunks/WidgetGlobalLoading-B_z-6_yk.js +1 -0
  11. package/chunks/classNames-3q0x02_x.js +1 -0
  12. package/chunks/client-duvjg9sB.js +9 -0
  13. package/chunks/constants-BVd2SKDq.js +1 -0
  14. package/chunks/controller-D2LKL4eu.js +1 -0
  15. package/chunks/conversationRegistry-Y5Ouo35n.js +1 -0
  16. package/chunks/createLucideIcon-B1BLVEeA.js +1 -0
  17. package/chunks/dist-dzGCY2H5.js +41 -0
  18. package/chunks/dist-gFPJclVl.js +1 -0
  19. package/chunks/emoji-picker-element-H87_ifwm.js +4 -0
  20. package/chunks/floating-ui.dom-Cs9alM6A.js +1 -0
  21. package/chunks/i18n-Q8u2wtW4.js +1 -0
  22. package/chunks/interviewTypes-Ch2NsXKB.js +1 -0
  23. package/chunks/jsx-runtime-S2ZBQkZm.js +1 -0
  24. package/chunks/launcherAnchorStore-JMTZZGKC.js +1 -0
  25. package/chunks/navigationState-LdqG_Osx.js +1 -0
  26. package/chunks/panel-DEg2n0VX.js +2 -0
  27. package/chunks/react-CKmEJ8Ba.js +1 -0
  28. package/chunks/routes-Dh46ka4-.js +1 -0
  29. package/chunks/useSmooth-CYGvfMVe.js +3 -0
  30. package/chunks/x-CcuT5rCV.js +1 -0
  31. package/index.js +1 -0
  32. package/messages/de.json +28 -0
  33. package/messages/en.json +28 -0
  34. package/messages/es.json +28 -0
  35. package/messages/fr.json +28 -0
  36. package/messages/it.json +28 -0
  37. package/messages/ja.json +28 -0
  38. package/messages/ko.json +28 -0
  39. package/messages/pt-BR.json +28 -0
  40. package/messages/zh-TW.json +28 -0
  41. package/messages/zh.json +28 -0
  42. package/package.json +36 -0
  43. package/react.js +1 -0
  44. package/runtime.es.js +1 -0
  45. package/sdk.js +1 -0
  46. package/types/main.d.ts +0 -0
  47. package/types/messages/en.json.d.ts +31 -0
  48. package/types/messages/index.d.ts +53 -0
  49. package/types/runtime/interview/interviewApiClient.d.ts +2 -0
  50. package/types/runtime/interview/interviewSessionCache.d.ts +5 -0
  51. package/types/runtime/interview/interviewSessionService.d.ts +93 -0
  52. package/types/runtime/interview/interviewTypes.d.ts +115 -0
  53. package/types/runtime/support/supportApiClient.d.ts +2 -0
  54. package/types/runtime/support/supportSessionCache.d.ts +4 -0
  55. package/types/runtime/support/supportSessionService.d.ts +43 -0
  56. package/types/runtime/support/supportTypes.d.ts +35 -0
  57. package/types/sdk/apiClient.d.ts +103 -0
  58. package/types/sdk/config.d.ts +4 -0
  59. package/types/sdk/constants.d.ts +28 -0
  60. package/types/sdk/controller.d.ts +36 -0
  61. package/types/sdk/conversation.d.ts +56 -0
  62. package/types/sdk/events.d.ts +106 -0
  63. package/types/sdk/hooks.d.ts +37 -0
  64. package/types/sdk/i18n.d.ts +9 -0
  65. package/types/sdk/index.d.ts +8 -0
  66. package/types/sdk/launcherAnchorStore.d.ts +7 -0
  67. package/types/sdk/launcherState.d.ts +21 -0
  68. package/types/sdk/navigationState.d.ts +25 -0
  69. package/types/sdk/public-types.d.ts +152 -0
  70. package/types/sdk/runtime.d.ts +37 -0
  71. package/types/sdk/script.d.ts +16 -0
  72. package/types/sdk/version.d.ts +7 -0
  73. package/types/sdk/viewport.d.ts +3 -0
  74. package/types/types.d.ts +64 -0
  75. package/types/ui/App.d.ts +55 -0
  76. package/types/ui/Iframe.d.ts +16 -0
  77. package/types/ui/Launcher.d.ts +12 -0
  78. package/types/ui/MarkdownText.d.ts +1 -0
  79. package/types/ui/Panel.d.ts +52 -0
  80. package/types/ui/WidgetComposer.d.ts +40 -0
  81. package/types/ui/WidgetGlobalLoading.d.ts +4 -0
  82. package/types/ui/WidgetPanelCloseButton.d.ts +4 -0
  83. package/types/ui/classNames.d.ts +1 -0
  84. package/types/ui/hostStyle.d.ts +7 -0
  85. package/types/ui/panel/DockNavigation.d.ts +14 -0
  86. package/types/ui/panel/MobileDockDrawer.d.ts +13 -0
  87. package/types/ui/panel/PanelShell.d.ts +26 -0
  88. package/types/ui/panel/RouteTransition.d.ts +7 -0
  89. package/types/ui/panel/agentSessionState.d.ts +21 -0
  90. package/types/ui/registry/conversationRegistry.d.ts +73 -0
  91. package/types/ui/router/reducer.d.ts +24 -0
  92. package/types/ui/router/routeNames.d.ts +9 -0
  93. package/types/ui/router/routeStorage.d.ts +6 -0
  94. package/types/ui/router/routes.d.ts +32 -0
  95. package/types/ui/router/targetRoute.d.ts +3 -0
  96. package/types/ui/screens/interview/InterviewChatScreen.d.ts +18 -0
  97. package/types/ui/screens/interview/InterviewInvitePrompt.d.ts +13 -0
  98. package/types/ui/screens/interview/interviewSessionCache.d.ts +10 -0
  99. package/types/ui/screens/interview/interviewSessionController.d.ts +89 -0
  100. package/types/ui/screens/interview/interviewUiAdapter.d.ts +3 -0
  101. package/types/ui/screens/interview/interviewWidgetClient.d.ts +2 -0
  102. package/types/ui/transcript.d.ts +17 -0
  103. package/types/ui/useWidgetEmojiPicker.d.ts +20 -0
@@ -0,0 +1,3 @@
1
+ import{r as e,t}from"../runtime.es.js";import{t as n}from"./react-CKmEJ8Ba.js";import{t as r}from"./jsx-runtime-S2ZBQkZm.js";import{t as i}from"./dist-gFPJclVl.js";var a=e(n(),1);function o(e){let t=[];for(let n of e.effectTasks)try{n()}catch(e){t.push(e)}if(t.length>0){if(t.length===1)throw t[0];for(let e of t)console.error(e);throw AggregateError(t,`Errors during commit`)}}function s(e){let t=[];for(let n of e.cells)if(n?.type===`effect`&&(n.deps=null,n.cleanup))try{n.cleanup?.()}catch(e){t.push(e)}finally{n.cleanup=void 0}if(t.length>0){if(t.length===1)throw t[0];for(let e of t)console.error(e);throw AggregateError(t,`Errors during cleanup`)}}var c=typeof process<`u`&&!1,l=null;function u(e,t){e.currentIndex=0;let n=l;l=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{l=n}}function d(){if(!l)throw Error(`No resource fiber available`);return l}function ee(e){return c?l?.devStrictMode?l.isFirstRender?`child`:`root`:e?`root`:null:null}function te(e,t){let n=e[ne];if(!n)throw Error(`ResourceElement.type is not a valid Resource`);return n(t)}var ne=Symbol(`fnSymbol`);function f(e,t,n=void 0,r=ee(!1)){return{type:e,root:t,markDirty:n,devStrictMode:r,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function p(e){if(!e.isMounted)throw Error(`Tried to unmount a fiber that is already unmounted`);e.isMounted=!1,s(e)}function m(e,t){let n={effectTasks:[],props:t,output:void 0};return u(e,()=>{e.renderContext=n;try{n.output=te(e.type,t)}finally{e.renderContext=void 0}}),n}function h(e,t){e.isMounted=!0,c&&e.isNeverMounted&&e.devStrictMode===`root`&&(e.isNeverMounted=!1,o(t),s(e)),e.isNeverMounted=!1,o(t)}var re=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],dirtyCells:[]}),g=e=>{for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.current=t.workInProgress;e.committedVersion=e.version,e.changelog.length=0,e.dirtyCells.length=0},_=(e,t)=>{let n=e.version>t;if(e.version=t,n){for(let t of e.dirtyCells)t.dirty=!1,t.queue.clear(),t.workInProgress=t.current;if(e.dirtyCells.length=0,t===e.committedVersion)e.changelog.length=0;else{if(e.committedVersion>t)throw Error(`Version is less than committed version`);for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop();e.changelog.forEach(e=>e()),g(e)}}},ie=(e,t)=>{t.dirty||(t.dirty=!0,e.markDirty?.(),e.root.dirtyCells.push(t))},ae=()=>{if(!c)return null;let e=(0,a.useRef)(0),t=e.current===0;return(0,a.useState)(()=>e.current++),e.current===2?t?`child`:`root`:null};function oe(e){let t=(0,a.useMemo)(()=>re(e=>r(e)),[]),[n,r]=(0,a.useReducer)((e,n)=>(_(t,e),e+ +!!n()),0);_(t,n);let i=ae(),o=(0,a.useMemo)(()=>(e.key,f(e.type,t,void 0,i)),[e.type,e.key,t,i]),s=m(o,e.props);return(0,a.useLayoutEffect)(()=>()=>p(o),[o]),(0,a.useLayoutEffect)(()=>{g(t),h(o,s)}),s.output}function v(e){let t=e=>({type:t,props:e});return t[ne]=e,t}function y(e,t){return{...t,key:e}}var se=(e,t)=>{let n=d(),r=n.currentIndex++;if(!n.isFirstRender&&r>=n.cells.length)throw Error(`Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.`);let i=n.cells[r];if(i||(i=t(),n.cells[r]=i),i.type!==e)throw Error(`Hook order changed between renders`);return i},ce=e=>{d().renderContext.effectTasks.push(e)},le=(e,t)=>{if(e.renderContext)throw Error(`Resource updated during render`);if(e.isNeverMounted)throw Error(`Resource updated before mount`);e.root.dispatchUpdate(()=>{let n=t();return n?(n(),e.root.changelog.push(n),!0):!1})};function ue(e,t,n,r){let i=se(`reducer`,()=>{let t=d(),a=r?r(n):n;return c&&t.devStrictMode&&r&&r(n),{type:`reducer`,queue:new Set,dirty:!1,workInProgress:a,current:a,reducer:e,dispatch:n=>{let r={action:n,hasEagerState:!1,eagerState:void 0};le(t,()=>t.root.dirtyCells.length===0&&!r.hasEagerState&&(r.eagerState=e(i.workInProgress,n),r.hasEagerState=!0,Object.is(i.current,r.eagerState))?null:()=>{ie(t,i),i.queue.add(r)})}}}),a=d(),o=e===i.reducer;i.reducer=e;for(let t of i.queue)(!t.hasEagerState||!o)&&(t.eagerState=e(i.workInProgress,t.action),t.hasEagerState=!0),c&&a.devStrictMode&&e(i.workInProgress,t.action),i.workInProgress=t.eagerState;if(i.queue.clear(),t){let e=t(i.workInProgress);Object.is(e,i.workInProgress)||(ie(a,i),i.workInProgress=e)}return[i.workInProgress,i.dispatch]}function de(e,t,n){return ue(e,void 0,t,n)}function fe(e,t,n,r){return ue(e,t,n,r)}var pe=(e,t)=>typeof t==`function`?t(e):t,me=e=>typeof e==`function`?e():e;function he(e){return de(pe,e,me)}var ge=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},_e=()=>({type:`effect`,cleanup:void 0,deps:null});function b(e,t){let n=se(`effect`,_e);if(!(t&&n.deps&&ge(n.deps,t))){if(n.deps!==null&&!!t!=!!n.deps)throw Error(`tapEffect called with and without dependencies across re-renders`);ce(()=>{let r=[];try{n.cleanup?.()}catch(e){r.push(e)}finally{n.cleanup=void 0}try{let t=e();if(t!==void 0&&typeof t!=`function`)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof t}`);n.cleanup=t}catch(e){r.push(e)}if(n.deps=t,r.length>0){if(r.length===1)throw r[0];for(let e of r)console.error(e);throw AggregateError(r,`Errors during commit`)}})}}function x(e){let[t]=he(()=>({current:e}));return t}function S(e,t){let[n]=he(e);return n}var ve=()=>{throw Error(`Memo reducer should not be called`)},C=(e,t)=>{let n=d(),[r]=fe(ve,r=>{if(r&&ge(r.deps,t))return r;let i=e();return c&&n.devStrictMode&&e(),{value:i,deps:t}},null);return r.value},ye=(e,t)=>C(()=>e,t);function w(e){let t=x(e);b(()=>{t.current=e});let n=d();return ye(((...e)=>{if(c&&n.renderContext)throw Error(`tapEffectEvent cannot be called during render`);return t.current(...e)}),[n])}function T(e,t){let n=d(),r=x(0),i=C(()=>(e.key,f(e.type,n.root,()=>{r.current++,n.markDirty?.()})),[e.type,e.key,n]),a=t?C(()=>m(i,e.props),[i,...t,r.current]):m(i,e.props);return b(()=>()=>p(i),[i]),b(()=>{h(i,a)},[i,a]),a.output}function E(e,t){let n=x(0),r=n.current,i=S(d,[]),a=S(()=>()=>{n.current++,i.markDirty?.()},[]),o=S(()=>new Map,[]),s=t?ye(e,t):e,c=C(()=>{let e=s(),t=new Set,n=[],r=0;for(let s=0;s<e.length;s++){let c=e[s],l=c.key;if(l===void 0)throw Error(`tapResources did not provide a key for array at index ${s}`);if(t.has(l))throw Error(`Duplicate key ${l} in tapResources`);t.add(l);let u=o.get(l);if(!u){let e=f(c.type,i.root,a),t=m(e,c.props);u={fiber:e,next:t},r++,o.set(l,u),n.push(t.output)}else if(u.fiber.type!==c.type){let e=f(c.type,i.root,a),t=m(e,c.props);u.next=[e,t],n.push(t.output)}else u.next=m(u.fiber,c.props),n.push(u.next.output)}if(o.size>n.length-r)for(let e of o.keys())t.has(e)||(o.get(e).next=`delete`);return n},[s,r]);return b(()=>()=>{for(let e of o.keys()){let t=o.get(e).fiber;p(t)}},[]),b(()=>{for(let[e,t]of o.entries())t.next===`delete`?(t.fiber.isMounted&&p(t.fiber),o.delete(e)):Array.isArray(t.next)?(p(t.fiber),t.fiber=t.next[0],h(t.fiber,t.next[1])):h(t.fiber,t.next)},[c]),c}var be=50,D={schedulers:new Set([]),isScheduled:!1},xe=class{_task;_isDirty=!1;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,D.schedulers.add(this),Se()}runTask(){this._isDirty=!1,this._task()}},Se=()=>{D.isScheduled||(D.isScheduled=!0,we())},Ce=()=>{try{let e=[],t=0;for(let n of D.schedulers)if(D.schedulers.delete(n),n.isDirty){if(t++,t>be)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.`);try{n.runTask()}catch(t){e.push(t)}}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,`Errors occurred during flushSync`)}}finally{D.schedulers.clear(),D.isScheduled=!1}},we=(()=>{if(typeof MessageChannel<`u`){let e=new MessageChannel;return e.port1.onmessage=Ce,()=>e.port2.postMessage(null)}return()=>setTimeout(Ce,0)})(),Te=e=>{let t=D;D={schedulers:new Set([]),isScheduled:!0};try{let t=e();return Ce(),t}finally{D=t}},Ee=e=>{let t=S(()=>new xe(()=>u(null)),[]),n=S(()=>[],[]),r=C(()=>(e.key,f(e.type,re(e=>{!t.isDirty&&!e()||(n.push(e),t.markDirty())}))),[e.type,e.key]);_(r.root,r.root.committedVersion);let i=m(r,e.props),a=x(!1),o=x(e.props),s=x(i.output),l=S(()=>new Set,[]),u=w(e=>{if(e===null&&(_(r.root,2),_(r.root,1),n.forEach(e=>{c&&r.devStrictMode&&e(),e()}),c&&r.devStrictMode&&m(r,o.current),e=m(r,o.current)),t.isDirty)throw Error(`Scheduler is dirty, this should never happen`);g(r.root),n.length=0,a.current&&h(r,e),!(t.isDirty||s.current===e.output)&&(s.current=e.output,l.forEach(e=>e()))});return b(()=>(a.current=!0,()=>{a.current=!1,p(r)}),[r]),b(()=>{o.current=i.props,g(r.root),h(r,i),!(t.isDirty||s.current===i.output)&&(s.current=i.output,l.forEach(e=>e()))}),C(()=>({getValue:()=>s.current,subscribe:e=>(l.add(e),()=>l.delete(e))}),[])},O=Symbol(`tap.Context`),De=e=>({[O]:e}),Oe=(e,t,n)=>{let r=e[O];e[O]=t;try{return n()}finally{e[O]=r}},ke=e=>e[O],k=r(),Ae=Symbol(`assistant-ui.store.clientIndex`),je=e=>e[Ae],Me=De([]),A=()=>ke(Me),Ne=(e,t)=>{let n=A();return Oe(Me,C(()=>[...n,e],[n,e]),t)},Pe=new Set([`$$typeof`,`nodeType`,`then`]),j=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!Pe.has(e))return!1}},M=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!1}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}},Fe=e=>{let t=v(e);return e=>{let n=t(e);return e.key===void 0?n:y(e.key,n)}},N=Symbol(`assistant-ui.store.getValue`),Ie=e=>{let t=e[N];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with tapClientResource(), not a plain resource.`);return t.getState?.()},Le=new Map;function Re(e){let t=Le.get(e);return t||(t=function(...t){if(!this||typeof this!=`object`)throw Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);let n=this[N];if(!n)throw Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let r=n[e];if(!r)throw Error(`Method "${String(e)}" is not implemented.`);if(typeof r!=`function`)throw Error(`"${String(e)}" is not a function.`);return r(...t)},Le.set(e,t)),t}var ze=class extends M{outputRef;index;boundFns;cachedReceiver;constructor(e,t){super(),this.outputRef=e,this.index=t}get(e,t,n){if(t===N)return this.outputRef.current;if(t===Ae)return this.index;let r=j(t,`ClientProxy`);if(r!==!1)return r;let i=this.outputRef.current[t];if(typeof i==`function`){this.cachedReceiver!==n&&(this.boundFns=new Map,this.cachedReceiver=n);let e=this.boundFns.get(t);return e||(e=Re(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===N||t===Ae?!0:t in this.outputRef.current}},Be=Fe(e=>{let t=x(null),n=A().length,r=C(()=>new Proxy({},new ze(t,n)),[n]),i=Ne(r,()=>T(e));return t.current||=i,b(()=>{t.current=i}),{methods:r,state:i.getState?.(),key:e.key}}),Ve=e=>T(Be(e)),P=Symbol(`assistant-ui.store.proxiedAssistantState`),F=e=>e===`on`||e===`subscribe`||typeof e==`symbol`,He=e=>{class t extends M{get(t,n){let r=j(n,`AssistantState`);if(r!==!1)return r;let i=n;if(!F(i))return Ie(e[i]())}ownKeys(){return Object.keys(e).filter(e=>!F(e))}has(t,n){return!F(n)&&n in e}}return new Proxy({},new t)},Ue=e=>e[P],We=()=>()=>{},Ge=e=>{let t=(()=>{throw Error(e)});return t.source=null,t.query=null,t},I=new Proxy({},new class extends M{get(e,t){if(t===`subscribe`||t===`on`)return We;if(t===P)return Ke;let n=j(t,`DefaultAssistantClient`);return n===!1?Ge(`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`):n}ownKeys(){return[`subscribe`,`on`,P]}has(e,t){return t===`subscribe`||t===`on`||t===P}}),Ke=He(I),qe=()=>new Proxy({},{get(e,t){let n=j(t,`AssistantClient`);return n===!1?Ge(`The current scope does not have a "${String(t)}" property.`):n}}),Je=(0,a.createContext)(I),Ye=()=>(0,a.useContext)(Je),Xe=({value:e,children:t})=>(0,k.jsx)(Je.Provider,{value:e,children:t}),L=v(e=>null),R=Symbol(`assistant-ui.transform-scopes`);function Ze(e,t){let n=e;if(n[R])throw Error(`transformScopes is already attached to this resource`);n[R]=t}function Qe(e){return e[R]}function $e(e,t){let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(e.type===L||r.has(e.type))continue;r.add(e.type);let a=Qe(e.type);if(a){a(n,t),i=!0;break}}}let a={},o={};for(let[e,t]of Object.entries(n))t.type===L?o[e]=t:a[e]=t;return{rootClients:a,derivedClients:o}}var et=e=>C(()=>e,[...Object.entries(e).flat()]),tt=(e,t)=>{let{rootClients:n,derivedClients:r}=$e(e,t);return{rootClients:et(n),derivedClients:et(r)}},nt=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},rt=v(()=>S(()=>{let e=new Map,t=new Set,n=new Set;return{on(n,r){let i=r;if(n===`*`)return t.add(i),()=>t.delete(i);let a=e.get(n);return a||(a=new Set,e.set(n,a)),a.add(i),()=>{a.delete(i),a.size===0&&e.delete(n)}},emit(n,r,i){let a=e.get(n);!a&&t.size===0||queueMicrotask(()=>{let e=[];if(a)for(let t of a)try{t(r,i)}catch(t){e.push(t)}if(t.size>0){let a={event:n,payload:r};for(let n of t)try{n(a,i)}catch(t){e.push(t)}}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,`Errors occurred during event emission`)}})},subscribe(e){return n.add(e),()=>n.delete(e)},notifySubscribers(){for(let e of n)try{e()}catch(e){console.error(`NotificationManager: subscriber callback error`,e)}}}},[])),it=De(null),at=(e,t)=>Oe(it,e,t),ot=()=>{let e=ke(it);if(!e)throw Error(`AssistantTapContext is not available`);return e},st=()=>ot().clientRef,ct=()=>{let{emit:e}=ot(),t=A();return w((n,r)=>{e(n,r,t)})},lt=e=>C(()=>e,e),ut=v(({element:e,emit:t,clientRef:n})=>{let{methods:r,state:i}=at({clientRef:n,emit:t},()=>Ve(e));return C(()=>({state:i,methods:r}),[r,i])}),dt=v(({element:e,notifications:t,clientRef:n,name:r})=>{let i=Ee(ut({element:e,emit:t.emit,clientRef:n}));return b(()=>i.subscribe(t.notifySubscribers),[i,t]),C(()=>{let e=()=>i.getValue().methods;return Object.defineProperties(e,{source:{value:`root`,writable:!1},query:{value:{},writable:!1},name:{value:r,configurable:!0}}),e},[i,r])}),ft=v(()=>C(()=>({clients:[],subscribe:void 0,on:void 0}),[])),pt=v(({clients:e,clientRef:t})=>{let n=T(rt());b(()=>t.parent.subscribe(n.notifySubscribers),[t,n]);let r=lt(E(()=>Object.keys(e).map(r=>y(r,dt({element:e[r],notifications:n,clientRef:t,name:r}))),[e,n,t]));return C(()=>({clients:r,subscribe:n.subscribe,on:function(e,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=nt(e);if(i!==`*`&&this[i].source===null)throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let o=n.on(a,(e,t)=>{if(i===`*`){r(e);return}let n=this[i]();n===t[je(n)]&&r(e)});if(i!==`*`&&t.parent[i].source===null)return o;let s=t.parent.on(e,r);return()=>{o(),s()}}}),[r,n,t])}),mt=(e,t,n)=>{if(`source`in e&&`query`in e)return e;if(n.dep===e)return n.meta;let r=e.getMeta(t.current);return n.meta=r,n.dep=e,r},ht=v(({element:e,clientRef:t,name:n})=>{let r=w(()=>e.props);return C(()=>{let e=()=>r().get(t.current),i={};return Object.defineProperties(e,{source:{get:()=>mt(r(),t,i).source},query:{get:()=>mt(r(),t,i).query},name:{value:n,configurable:!0}}),e},[t,n])}),gt=v(({clients:e,clientRef:t})=>lt(E(()=>Object.keys(e).map(n=>y(n,ht({element:e[n],clientRef:t,name:n}))),[e,t]))),_t=v(({parent:e,clients:t})=>{let{rootClients:n,derivedClients:r}=tt(t,e),i=x({parent:e,current:null}).current;b(()=>{i.current=s});let a=T(Object.keys(n).length>0?pt({clients:n,clientRef:i}):ft()),o=T(gt({clients:r,clientRef:i})),s=C(()=>{let t=e===I?qe():e,n=Object.create(t);Object.assign(n,{subscribe:a.subscribe??e.subscribe,on:a.on??e.on,[P]:He(n)});for(let e of a.clients)n[e.name]=e;for(let e of o)n[e.name]=e;return n},[e,a,o]);return i.current===null&&(i.current=s),s});function z(e,{parent:t}={parent:Ye()}){if(e)return oe(_t({parent:t??I,clients:e}));if(t===null)throw Error(`received null parent, this usage is not allowed`);return t}var B=e=>{let t=z(),n=Ue(t),r=(0,a.useSyncExternalStore)(t.subscribe,()=>e(n),()=>e(n));if(r===n)throw Error(`You tried to return the entire AssistantState. This is not supported due to technical limitations.`);return(0,a.useDebugValue)(r),r},vt=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},yt=(e=>e?vt(e):vt),bt=e=>e;function xt(e,t=bt){let n=a.useSyncExternalStore(e.subscribe,a.useCallback(()=>t(e.getState()),[e,t]),a.useCallback(()=>t(e.getInitialState()),[e,t]));return a.useDebugValue(n),n}var St=e=>{let t=yt(e),n=e=>xt(t,e);return Object.assign(n,t),n},Ct=(e=>e?St(e):St),wt=t(((e,t)=>{var n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),Tt=e(wt(),1);function Et(e){let t=[`ROOT`],n=-1,r=null,i=[],a;function o(){a!==void 0&&(i.push(JSON.parse(`"${a}"`)),a=void 0)}function s(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`),o();break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),o();break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),o();break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`),o();break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`),o();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop(),a=i.pop();break}}function l(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),a=(Number(a)+1).toString();break;case`]`:n=r,t.pop(),a=i.pop();break}}for(let o=0;o<e.length;o++){let u=e[o];switch(t[t.length-1]){case`ROOT`:s(u,o,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),a=``;break;case`}`:n=o,t.pop(),a=i.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),a=``;break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`),a+=u;break;default:a+=u;break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:s(u,o,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:c(u,o);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=o,a=i.pop();break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=o}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=o,t.pop(),a=i.pop();break;default:n=o,a=`0`,s(u,o,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),a=(Number(a)+1).toString();break;case`]`:n=o,t.pop(),a=i.pop();break;default:n=o;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:s(u,o,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),t[t.length-1]===`INSIDE_STRING`?n=o:t[t.length-1]===`INSIDE_OBJECT_KEY`&&(a+=u);break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=o;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&c(u,o);break;case`}`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&c(u,o);break;case`]`:t.pop(),a=i.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o);break;default:t.pop(),a=i.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,o+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?c(u,o):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&l(u,o)):n=o;break}}}let u=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:u+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:u+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:u+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?u+=`true`.slice(t.length):`false`.startsWith(t)?u+=`false`.slice(t.length):`null`.startsWith(t)&&(u+=`null`.slice(t.length))}}return[u,i]}var V=Symbol(`aui.parse-partial-json-object.meta`),Dt=e=>e?.[V],Ot=e=>{if(e.length===0)return{[V]:{state:`partial`,partialPath:[]}};try{let t=Tt.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[V]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=Et(e),r=Tt.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[V]={state:`partial`,partialPath:n},r}catch{return}}},kt=(e,t,n)=>{if(typeof e!=`object`||!e)return t.state;if(t.state===`complete`)return`complete`;if(n.length===0)return t.state;let[r,...i]=n;if(!Object.hasOwn(e,r))return`partial`;let[a,...o]=t.partialPath;if(r!==a)return`complete`;let s=e[r];return kt(s,{state:`partial`,partialPath:o},i)},At=(e,t)=>{let n=Dt(e);if(!n)throw Error(`unable to determine object state`);return kt(e,n,t.map(String))},jt=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r},Mt=e=>Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)).reduce((e,t)=>{if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[n,r]of Object.entries(t.tools)){let t=e.tools?.[n];if(t&&t!==r)throw Error(`You tried to define a tool with the name ${n}, but it already exists.`);e.tools||={},e.tools[n]=r}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),e},{}),Nt=class{_providers=new Set;getModelContext(){return Mt(this._providers)}registerModelContextProvider(e){this._providers.add(e);let t=e.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t?.(),this.notifySubscribers()}}_subscribers=new Set;notifySubscribers(){for(let e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},Pt=Symbol.for(`aui.tool-response`),Ft=class e{get[Pt](){return!0}artifact;result;isError;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact),this.result=e.result,this.isError=e.isError??!1,e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&Pt in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?`<no result>`:t})}},H=Symbol(`skip-update`);function It(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(let n of Object.keys(e)){let r=e[n],i=t[n];if(!Object.is(r,i))return!1}return!0}var Lt=class{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){let e=[];for(let t of this._subscribers)try{t()}catch(t){e.push(t)}if(e.length>0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e)}}},U=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e){for(let t of this._subscriptions)t(e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},W=class extends U{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e;let t=e.getState();if(t===H)throw Error(`Entry not available in the store`);this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return e===H||It(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){return this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()})}},Rt=class extends U{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==H&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw Error(`Entry not available in the store`);return this._previousState};_connect(){return this.binding.subscribe(()=>{this._previousStateDirty=!0,this.notifySubscribers()})}},G=class extends U{binding;get path(){return this.binding.path}constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),n=t?.subscribe(e),r=this.outerSubscribe(()=>{let r=this.binding.getState();r!==t&&(t=r,n?.(),n=r?.subscribe(e),e())});return()=>{r?.(),n?.()}}},zt=class extends U{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=e=>{this.notifySubscribers(e)},t=this.config.binding.getState(),n=t?.unstable_on(this.config.event,e),r=this.outerSubscribe(()=>{let r=this.config.binding.getState();r!==t&&(t=r,n?.(),n=r?.unstable_on(this.config.event,e))});return()=>{r?.(),n?.()}}},Bt=class{_contextProvider=new Nt;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},Vt=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+
3
+ `),K=jt(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),Ht=`__optimistic__`,Ut=()=>`${Ht}${K()}`,q=Symbol(`autoStatus`),Wt=Object.freeze(Object.assign({type:`running`},{[q]:!0})),Gt=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[q]:!0})),Kt=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[q]:!0})),qt=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[q]:!0})),Jt=e=>e[q]===!0,Yt=(e,t,n,r,i)=>e&&i?Object.assign({type:`incomplete`,reason:`error`,error:i},{[q]:!0}):e&&t?Wt:n?qt:r?Kt:Gt,Xt=(e,t)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t}},J=(e,t,n)=>{let{role:r,id:i,createdAt:a,attachments:o,status:s,metadata:c}=e,l={id:i??t,createdAt:a??new Date},u=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,d=({image:e,...t})=>e.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?{...t,image:e}:(console.warn(`Invalid image data format detected`),null);if(r!==`user`&&o?.length)throw Error(`attachments are only supported for user messages`);if(r!==`assistant`&&s)throw Error(`status is only supported for assistant messages`);if(r!==`assistant`&&c?.steps)throw Error(`metadata.steps is only supported for assistant messages`);switch(r){case`assistant`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`reasoning`:return e.text.trim().length===0?null:e;case`file`:case`source`:return e;case`image`:return d(e);case`data`:return e;case`tool-call`:{let{parentId:t,messages:n,...r}=e,i={...r,toolCallId:e.toolCallId??`tool-${K()}`,...t!==void 0&&{parentId:t},...n!==void 0&&{messages:n}};return e.args?{...i,args:e.args,argsText:e.argsText??JSON.stringify(e.args)}:{...i,args:Ot(e.argsText??``)??{},argsText:e.argsText??``}}default:{let n=Xt(t,e.data);if(n)return n;throw Error(`Unsupported assistant message part type: ${t}`)}}}).filter(e=>!!e),status:s??n,metadata:{unstable_state:c?.unstable_state??null,unstable_annotations:c?.unstable_annotations??[],unstable_data:c?.unstable_data??[],custom:c?.custom??{},steps:c?.steps??[],...c?.timing&&{timing:c.timing},...c?.submittedFeedback&&{submittedFeedback:c.submittedFeedback}}};case`user`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`image`:case`audio`:case`file`:case`data`:return e;default:{let n=Xt(t,e.data);if(n)return n;throw Error(`Unsupported user message part type: ${t}`)}}}),attachments:(o??[]).map(e=>({...e,content:e.content.map(e=>Xt(e.type,e.data)??e)})),metadata:{custom:c?.custom??{}}};case`system`:if(u.length!==1||u[0].type!==`text`)throw Error(`System messages must have exactly one text message part.`);return{...l,role:r,content:u,metadata:{custom:c?.custom??{}}};default:throw Error(`Unknown message role: ${r}`)}},Zt={fromArray:e=>{let t=e.map(e=>J(e,K(),Yt(!1,!1,!1,!1,void 0)));return{messages:t.map((e,n)=>({parentId:n>0?t[n-1].id:null,message:e}))}},fromBranchableArray:(e,t)=>{let n=Yt(!1,!1,!1,!1,void 0);return{...t?.headId===void 0?void 0:{headId:t.headId},messages:e.map(({message:e,parentId:t})=>{if(!e.id)throw Error(`ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.`);return{parentId:t,message:J(e,e.id,n)}})}}},Y=e=>e.next?Y(e.next):`current`in e?e:null,Qt=class{func;_value=null;constructor(e){this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},$t=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){e.level=t;for(let n of e.children){let e=this.messages.get(n);e&&this.updateLevels(e,t+1)}}performOp(e,t,n){let r=t.prev??this.root,i=e??this.root;if(!(n===`relink`&&r===i)){if(n!==`link`&&(r.children=r.children.filter(e=>e!==t.current.id),r.next===t)){let e=r.children.at(-1),t=e?this.messages.get(e):null;if(t===void 0)throw Error(`MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.`);r.next=t}if(n!==`cut`){for(let n=e;n;n=n.prev)if(n.current.id===t.current.id)throw Error(`MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.`);i.children=[...i.children,t.current.id],(Y(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;let n=e?e.level+1:0;this.updateLevels(t,n)}}}_messages=new Qt(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.`);let n=Array(t.level+1);for(let e=t;e;e=e.prev)n[e.level]=e.current;return n}addOrUpdateMessage(e,t){let n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw Error(`MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.`);if(n){n.current=t,this.performOp(r,n,`relink`),this._messages.dirty();return}let i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,`link`),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.`);return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let n;do n=Ut();while(this.messages.has(n));return this.addOrUpdateMessage(e,J(t,n,{type:`running`})),n}deleteMessage(e,t){let n=this.messages.get(e);if(!n)throw Error(`MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.`);let r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw Error(`MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.`);for(let e of n.children){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.`);this.performOp(r,t,`relink`)}this.performOp(null,n,`cut`),this.messages.delete(e),this.head===n&&(this.head=Y(r??this.root)),this._messages.dirty()}getBranches(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.`);let{children:n}=t.prev??this.root;return n}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.`);let n=t.prev??this.root;n.next=t,this.head=Y(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.`);if(t.children.length>0){let e=t=>{for(let n of t.children){let t=this.messages.get(n);t&&(e(t),this.messages.delete(n))}};e(t),t.children=[],t.next=null}this.head=t;for(let e=t;e;e=e.prev)e.prev?e.prev.next=e:this.root.next=e;this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[];for(let[,t]of this.messages)e.push({message:t.current,parentId:t.prev?.current.id??null});return{headId:this.head?.current.id??null,messages:e}}import({headId:e,messages:t}){for(let{message:e,parentId:n}of t)this.addOrUpdateMessage(n,e);this.resetHead(e??t.at(-1)?.message.id??null)}};function en(e,t){if(t===`*`)return!0;let n=t.split(`,`).map(e=>e.trim().toLowerCase()),r=`.${e.name.split(`.`).pop().toLowerCase()}`,i=e.type.toLowerCase();for(let e of n){if(e.startsWith(`.`)&&e===r||e.includes(`/`)&&e===i)return!0;if(e.endsWith(`/*`)){let t=e.split(`/`)[0];if(i.startsWith(`${t}/`))return!0}}return!1}function tn(e,t){return e.length===t.length?e.every((e,n)=>e.id===t[n].id):!1}function nn(e){let t=K();return e.type===`image`?{id:t,type:`image`,name:e.filename??`image`,content:[e],status:{type:`complete`}}:e.type===`file`?{id:t,type:`document`,name:e.filename??`document`,contentType:e.mimeType,content:[e],status:{type:`complete`}}:e.type===`audio`?{id:t,type:`audio`,name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:`complete`}}:{id:t,type:`data`,name:e.name,content:[e],status:{type:`complete`}}}function rn(e){let t=[];for(let n of e)n.type!==`text`&&t.push(nn(n));return t}var an=e=>e.status.type===`complete`,on=class extends Lt{isEditing=!0;get attachmentAccept(){return this.getAttachmentAdapter()?.accept??`*`}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text=``;get text(){return this._text}_role=`user`;get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){if(this._text!==e){if(this._text=e,this._dictation){this._dictationBaseText=e,this._currentInterimText=``;let{status:t,inputDisabled:n}=this._dictation;this._dictation=n?{status:t,inputDisabled:n}:{status:t}}this._notifySubscribers()}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text=``,this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();if(e){let t=this._attachments.filter(e=>!an(e));await Promise.all(t.map(t=>e.remove(t)))}}async reset(){if(this._attachments.length===0&&this._text===``&&this._role===`user`&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role=`user`,this._runConfig={},this._quote=void 0;let e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){let e=this._onClearAttachments();this.setAttachments([]),await e}async send(e){if(!this.canSend)return;this._dictationSession&&(this._dictationSession.cancel(),this._cleanupDictation());let t=this.getAttachmentAdapter(),n=this.attachments.length>0?Promise.all(this.attachments.map(async e=>{if(an(e))return e;if(!t)throw Error(`Attachments are not supported`);return await t.send(e)})):[],r=this.text,i=this._quote;this._quote=void 0,this._emptyTextAndAttachments();let a={createdAt:new Date,role:this.role,content:r?[{type:`text`,text:r}]:[],attachments:await n,runConfig:this.runConfig,metadata:{custom:{...i?{quote:i}:{}}}};this.handleSend(a,e),this._notifyEventSubscribers(`send`,{})}cancel(){this.handleCancel()}async addAttachment(e){if(!(e instanceof File)){let t=this.getAttachmentAdapter();if(t&&!en({name:e.name,type:e.contentType??``},t.accept)){let n=`File type ${e.contentType||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r),r}let n={id:e.id??K(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,n],this._notifySubscribers(),this._notifyEventSubscribers(`attachmentAdd`,{});return}let t=e=>{let t=this._attachments.findIndex(t=>t.id===e.id);t===-1?this._attachments=[...this._attachments,e]:this._attachments=[...this._attachments.slice(0,t),e,...this._attachments.slice(t+1)],this._notifySubscribers()},n=this.getAttachmentAdapter();if(!n){let e=`Attachments are not supported`,t=Error(e);throw this._safeEmitAttachmentAddError(`no-adapter`,e,void 0,t),t}if(!en({name:e.name,type:e.type},n.accept)){let t=`File type ${e.type||`unknown`} is not accepted. Accepted types: ${n.accept}`,r=Error(t);throw this._safeEmitAttachmentAddError(`not-accepted`,t,void 0,r),r}let r;try{let i=n.add({file:e});if(Symbol.asyncIterator in i)for await(let e of i)r=e,t(e);else r=await i,t(r)}catch(e){throw r&&t({...r,status:{type:`incomplete`,reason:`error`}}),this._safeEmitAttachmentAddError(`adapter-error`,e instanceof Error?e.message:String(e),r?.id,e instanceof Error?e:void 0),e}r?.status.type===`incomplete`&&r.status.reason===`error`?this._safeEmitAttachmentAddError(`adapter-error`,`Attachment upload did not complete successfully.`,r?.id):this._notifyEventSubscribers(`attachmentAdd`,{})}_safeEmitAttachmentAddError(e,t,n,r){try{this._notifyEventSubscribers(`attachmentAddError`,{reason:e,message:t,...n!==void 0&&{attachmentId:n},...r!==void 0&&{error:r}})}catch(e){console.error(`[assistant-ui] attachmentAddError subscriber threw:`,e)}}async removeAttachment(e){let t=this._attachments.findIndex(t=>t.id===e);if(t===-1)throw Error(`Attachment not found`);let n=this._attachments[t];if(!an(n)){let e=this.getAttachmentAdapter();if(!e)throw Error(`Attachments are not supported`);await e.remove(n)}this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText=``;_currentInterimText=``;_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error(`Dictation adapter not configured`);if(this._dictationSession){for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession.stop().catch(()=>{}),this._dictationSession=void 0}let t=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText=``;let n=e.listen();this._dictationSession=n;let r=++this._dictationSessionIdCounter;this._activeDictationSessionId=r,this._dictation={status:n.status,inputDisabled:t},this._notifySubscribers();let i=n.onSpeech(e=>{if(!this._isActiveSession(r,n))return;let t=e.isFinal!==!1,i=this._dictationBaseText&&!this._dictationBaseText.endsWith(` `)&&e.transcript?` `:``;if(t){if(this._dictationBaseText=this._dictationBaseText+i+e.transcript,this._currentInterimText=``,this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=i+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&={...this._dictation,transcript:e.transcript},this._notifySubscribers()});this._dictationUnsubscribes.push(i);let a=n.onSpeechStart(()=>{this._isActiveSession(r,n)&&(this._dictation={status:{type:`running`},inputDisabled:t,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(a);let o=n.onSpeechEnd(()=>{this._cleanupDictation({sessionId:r})});this._dictationUnsubscribes.push(o);let s=setInterval(()=>{this._isActiveSession(r,n)&&n.status.type===`ended`&&this._cleanupDictation({sessionId:r})},100);this._dictationUnsubscribes.push(()=>clearInterval(s))}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;e.stop().finally(()=>{this._cleanupDictation({sessionId:t})})}_cleanupDictation(e){if(!(e?.sessionId!==void 0&&e.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)){this._isCleaningDictation=!0;try{for(let e of this._dictationUnsubscribes)e();this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText=``,this._currentInterimText=``,this._notifySubscribers()}finally{this._isCleaningDictation=!1}}}_eventSubscribers=new Map;_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);if(n)for(let e of n)e(t)}unstable_on(e,t){let n=t,r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),()=>{this._eventSubscribers.get(e)?.delete(n)}}},sn=class extends on{runtime;_canCancel=!1;get canCancel(){return this._canCancel}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}constructor(e){super(),this.runtime=e,this.connect()}connect(){let e=this.runtime.isSendDisabled;return this.runtime.subscribe(()=>{let t=!1;this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,t=!0),e!==this.runtime.isSendDisabled&&(e=this.runtime.isSendDisabled,t=!0),t&&this._notifySubscribers()})}async handleSend(e,t){this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun})}async handleCancel(){this.runtime.cancelRun()}},X=class{_core;_threadListBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){let e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){let e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,o=i.id;n===a&&r===o||(n=a,r=o,!(e===`switchedTo`&&!a)&&(e===`switchedAway`&&a||t({})))})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}},Z=Symbol(`innerMessage`),cn=Symbol(`innerMessages`),ln=[],un=(e,t)=>{Z in e||(e[Z]=t)},dn=e=>{let t=`messages`in e?e.messages:e,n=t[cn]||t[Z];return n?Array.isArray(n)?n:(t[cn]=[n],t[cn]):ln},fn=class{_core;get path(){return this._core.path}constructor(e){this._core=e,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},pn=class extends fn{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error(`Composer is not available`);return e.removeAttachment(this.getState().id)}},mn=class extends pn{get source(){return`thread-composer`}},hn=class extends pn{get source(){return`edit-composer`}},gn=class extends fn{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},_n=Object.freeze([]),vn=Object.freeze({}),yn=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??_n,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??vn,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,value:e?.text??``}),bn=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??_n,runConfig:e?.runConfig??vn,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),xn=class{_core;get path(){return this._core.path}constructor(e){this._core=e}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.clearAttachments()}send(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.send(e)}cancel(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.cancel()}setRole(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new zt({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Sn=class extends xn{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new Rt({path:e.path,getState:()=>yn(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new mn(new W({path:{...this.path,attachmentSource:`thread-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`thread-composer`}:H},subscribe:e=>this._core.subscribe(e)}),this._core)}},Cn=class extends xn{_beginEdit;get path(){return this._core.path}get type(){return`edit`}_getState;constructor(e,t){let n=new Rt({path:e.path,getState:()=>bn(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>n.subscribe(e)}),this._beginEdit=t,this._getState=n.getState.bind(n),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new hn(new W({path:{...this.path,attachmentSource:`edit-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`edit-composer`}:H},subscribe:e=>this._core.subscribe(e)}),this._core)}},wn=class{contentBinding;messageApi;threadApi;get path(){return this.contentBinding.path}constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to add tool result to non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=t.toolName,i=t.toolCallId,a=Ft.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:a.result,artifact:a.artifact,isError:a.isError})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to resume tool call on non-tool message part`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Q=Object.freeze({type:`complete`}),Tn=(e,t,n)=>{if(e.role!==`assistant`)return Q;if(n.type===`tool-call`)return n.result?Q:e.status;let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?Q:r?e.status:Q},En=(e,t)=>{let n=e.content[t];if(!n)return H;let r=Tn(e,t,n);return Object.freeze({...n,[Z]:n[Z],status:r})},Dn=class{_core;_threadBinding;get path(){return this._core.path}constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new Cn(new G({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:`edit`},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}reload(e={}){let t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:i=r.runConfig}=e,a=this._core.getState();if(a.role!==`assistant`)throw Error(`Can only reload assistant messages`);this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error(`Message is not being spoken`)}submitFeedback({type:e}){let t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){let n=this._core.getState();if(t&&e)throw Error(`May not specify both branchId and position`);if(!t&&!e)throw Error(`Must specify either branchId or position`);let r=this._threadBinding.getState().getBranches(n.id),i=t;if(e===`previous`?i=r[n.branchNumber-2]:e===`next`&&(i=r[n.branchNumber]),!i)throw Error(`Branch not found`);this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Vt(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new wn(new W({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>En(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new wn(new W({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:`toolCallId`,toolCallId:e}},getState:()=>{let t=this._core.getState(),n=t.content.findIndex(t=>t.type===`tool-call`&&t.toolCallId===e);return n===-1?H:En(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new gn(new W({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:`message`,attachmentSelector:{type:`index`,index:e}},getState:()=>{let t=this.getState().attachments?.[e];return t?{...t,source:`message`}:H},subscribe:e=>this._core.subscribe(e)}))}},On=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),kn=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),An=(e,t)=>typeof t==`string`?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:`user`,content:[{type:`text`,text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??`user`,content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},jn=(e,t)=>{let n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:e.isRunning??(n?.role===`assistant`?n.status.type===`running`:!1),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice})},Mn=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(e,t){let n=new W({path:e.path,getState:()=>jn(e.getState(),t.getState()),subscribe:n=>{let r=e.subscribe(n),i=t.subscribe(n);return()=>{r(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new Sn(new G({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`thread`},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(An(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(kn(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(On(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw Error(`Message index must be >= 0`);return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:`index`,index:e}},()=>{let t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:`messageId`,messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new Dn(new W({path:e,getState:()=>{let{message:e,parentId:n,index:r}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||n===void 0||r===void 0)return H;let o=this._threadBinding.getState().getBranches(e.id);return{...e,[Z]:e[Z],index:r,isLast:i.at(-1)?.id===e.id,parentId:n,branchNumber:o.indexOf(e.id)+1,branchCount:o.length,speech:a?.messageId===e.id?a:void 0}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new zt({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Nn=Promise.resolve(),Pn=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),$=(e,t)=>{if(t===void 0)return H;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,custom:n.custom,isMain:n.id===e.mainThreadId}:H},Fn=class{_core;_runtimeFactory;_getState;constructor(e,t=Mn){this._core=e,this._runtimeFactory=t;let n=new Rt({path:{},getState:()=>Pn(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new X(new W({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>$(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new G({path:{ref:`threads.main`,threadSelector:{type:`main`}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??Nn}loadMore(){return this._core.loadMore?.()??Nn}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new G({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(e){return new X(new W({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>$(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new X(new W({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>$(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new X(new W({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>$(this._core,e),subscribe:e=>this._core.subscribe(e)}),this._core)}},In=class{_core;threads;_thread;constructor(e){this._core=e,this.threads=new Fn(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},Ln=(0,a.createContext)(null),Rn=()=>(0,a.useContext)(Ln);function zn(e,t){function n(n){let r=e(n);return r?r[t]:null}function r(e){let t=!1,r;typeof e==`function`?r=e:e&&typeof e==`object`&&(t=!!e.optional,r=e.selector);let i=n({optional:t});return i?r?i(r):i():null}return{[t]:r,[`${t}Store`]:n}}var Bn=e=>e,Vn=(0,a.createContext)(null),Hn=()=>(0,a.useContext)(Vn),Un=({children:e})=>{let t=(0,a.useRef)(new Map),n=(0,a.useRef)([]),r=(0,a.useCallback)(()=>{let e=Array.from(t.current.entries());e.sort((e,t)=>t[1]-e[1]),n.current=e.map(([e])=>e)},[]),i=(0,a.useCallback)((e,n)=>{let i=n?.priority??0;return t.current.set(e,i),r(),()=>{t.current.delete(e),r()}},[r]),o=(0,a.useCallback)(()=>n.current,[]),s=(0,a.useMemo)(()=>({register:i,getPlugins:o}),[i,o]);return(0,k.jsx)(Vn.Provider,{value:s,children:e})},Wn=()=>B(e=>{if(e.part.type!==`text`&&e.part.type!==`reasoning`)throw Error(`MessagePartText can only be used inside text or reasoning message parts.`);return e.part}),Gn=(0,a.createContext)(null),Kn=e=>({useSmoothStatus:Ct(()=>e)}),qn=({children:e})=>{let t=Yn({optional:!0}),n=z(),[r]=(0,a.useState)(()=>Kn(n.part().getState().status));return t?e:(0,k.jsx)(Gn.Provider,{value:r,children:e})},Jn=e=>{let t=(0,a.forwardRef)((t,n)=>(0,k.jsx)(qn,{children:(0,k.jsx)(e,{...t,ref:n})}));return t.displayName=e.displayName,t};function Yn(e){let t=(0,a.useContext)(Gn);if(!e?.optional&&!t)throw Error(`This component must be used within a SmoothContextProvider.`);return t}var{useSmoothStatus:Xn,useSmoothStatusStore:Zn}=zn(Yn,`useSmoothStatus`),Qn=class{currentText;setText;animationFrameId=null;lastUpdateTime=Date.now();targetText=``;constructor(e,t){this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{let e=Date.now(),t=e-this.lastUpdateTime,n=this.targetText.length-this.currentText.length,r=Math.min(5,250/n),i=0;for(;t>=r&&i<n;)i++,t-=r;i===n?this.animationFrameId=null:this.animationFrameId=requestAnimationFrame(this.animate),i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-t,this.setText(this.currentText))}},$n=Object.freeze({type:`running`}),er=(e,t=!1)=>{let{text:n}=e,r=B(e=>e.message.id),o=(0,a.useRef)(r),[s,c]=(0,a.useState)(e.status.type===`running`?``:n),l=Zn({optional:!0}),u=i(t=>{if(c(t),l){let n=s!==t||e.status.type===`running`?$n:e.status;Bn(l).setState(n,!0)}});(0,a.useEffect)(()=>{if(l){let r=t&&(s!==n||e.status.type===`running`)?$n:e.status;Bn(l).setState(r,!0)}},[l,t,n,s,e.status]);let[d]=(0,a.useState)(new Qn(s,u));return(0,a.useEffect)(()=>{if(!t){d.stop();return}if(o.current!==r||!n.startsWith(d.targetText)){o.current=r,e.status.type===`running`?(u(``),d.currentText=``,d.targetText=n,d.start()):(u(n),d.currentText=n,d.targetText=n,d.stop());return}d.targetText=n,d.start()},[u,d,r,t,n,e.status.type]),(0,a.useEffect)(()=>()=>{d.stop()},[d]),(0,a.useMemo)(()=>t?{type:`text`,text:s,status:n===s?e.status:$n}:e,[t,s,e,n])};export{Ot as A,Xe as B,K as C,Nt as D,Ft as E,st as F,E as G,Ve as H,ct as I,C as J,T as K,nt as L,Ct as M,B as N,jt as O,z as P,v as Q,Ze as R,Jt as S,Bt as T,Fe as U,Be as V,Te as W,he as X,b as Y,y as Z,rn as _,Un as a,J as b,zn as c,Mn as d,un as f,tn as g,on as h,Wn as i,wt as j,At as k,Rn as l,sn as m,Xn as n,Hn as o,dn as p,ye as q,Jn as r,Bn as s,er as t,In as u,Zt as v,Vt as w,Yt as x,$t as y,L as z};
@@ -0,0 +1 @@
1
+ import{t as e}from"./createLucideIcon-B1BLVEeA.js";var t=e(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]);export{t};
package/index.js ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunks/constants-BVd2SKDq.js";import{S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y,v as b,x,y as S}from"./chunks/controller-D2LKL4eu.js";import{n as C}from"./chunks/interviewTypes-Ch2NsXKB.js";var w=v;export{e as CUSTOMER_AGENT_EVENTS,v as CustomerAgent,C as INTERVIEW_INVITATION_ACTION,p as boot,g as chooseInvitation,w as default,u as ensureInvitation,r as getInterviewSession,m as getInterviewState,_ as getSession,a as getState,d as getSupportState,y as hide,o as identify,s as loadInterviewReward,h as on,f as openEntry,l as sendInterviewMessage,c as setContext,n as show,b as shutdown,S as startInterview,i as startInvitation,x as toggle,t as update};
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Emoji hinzufügen",
3
+ "assistant_author_ai": "Agent",
4
+ "assistant_author_human": "Support",
5
+ "attachment_label": "Bild, PDF oder MP4 anhängen",
6
+ "close_chat": "Chat schließen",
7
+ "collapse_window": "Fenster einklappen",
8
+ "download_transcript": "Transkript herunterladen",
9
+ "expand_window": "Fenster erweitern",
10
+ "input_placeholder": "Frage stellen...",
11
+ "interview_input_placeholder": "Antwort eingeben...",
12
+ "interview_session_description": "Teile deine Gedanken. Wir hören zu.",
13
+ "launcher_close": "{title} schließen",
14
+ "launcher_open": "{title} öffnen",
15
+ "message_aria_label": "Nachricht",
16
+ "more_options": "Weitere Optionen",
17
+ "relative_time_today": "Heute",
18
+ "relative_time_yesterday": "Gestern",
19
+ "relative_time_day": "vor {count} Tg.",
20
+ "relative_time_hour": "vor {count} Std.",
21
+ "relative_time_minute": "vor {count} Min.",
22
+ "relative_time_now": "jetzt",
23
+ "remove_attachment": "{name} entfernen",
24
+ "send_message": "Nachricht senden",
25
+ "status_reply_time": "Agent ist da. Wir bleiben dran.",
26
+ "support_chat_label": "{title} Support-Chat",
27
+ "welcome_message": "Hallo, ich bin dein Support-Assistent. Wie kann ich helfen?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Add emoji",
3
+ "assistant_author_ai": "Agent",
4
+ "assistant_author_human": "Support",
5
+ "attachment_label": "Attach image, PDF, or MP4",
6
+ "close_chat": "Close chat",
7
+ "collapse_window": "Collapse window",
8
+ "download_transcript": "Download transcript",
9
+ "expand_window": "Expand window",
10
+ "input_placeholder": "Ask a question...",
11
+ "interview_input_placeholder": "Your answer...",
12
+ "interview_session_description": "Insights start here. We’re listening.",
13
+ "launcher_close": "Close {title}",
14
+ "launcher_open": "Open {title}",
15
+ "message_aria_label": "Message",
16
+ "more_options": "More options",
17
+ "relative_time_today": "Today",
18
+ "relative_time_yesterday": "Yesterday",
19
+ "relative_time_day": "{count} days ago",
20
+ "relative_time_hour": "{count}h ago",
21
+ "relative_time_minute": "{count}m ago",
22
+ "relative_time_now": "now",
23
+ "remove_attachment": "Remove {name}",
24
+ "send_message": "Send message",
25
+ "status_reply_time": "Agent is here. Our team is nearby.",
26
+ "support_chat_label": "{title} support chat",
27
+ "welcome_message": "Hi, I’m your support assistant. How can I help?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Agregar emoji",
3
+ "assistant_author_ai": "Agente",
4
+ "assistant_author_human": "Soporte",
5
+ "attachment_label": "Adjuntar imagen, PDF o MP4",
6
+ "close_chat": "Cerrar chat",
7
+ "collapse_window": "Contraer ventana",
8
+ "download_transcript": "Descargar conversación",
9
+ "expand_window": "Ampliar ventana",
10
+ "input_placeholder": "Haz una pregunta...",
11
+ "interview_input_placeholder": "Escribe tu respuesta...",
12
+ "interview_session_description": "Comparte tus ideas. Te escuchamos.",
13
+ "launcher_close": "Cerrar {title}",
14
+ "launcher_open": "Abrir {title}",
15
+ "message_aria_label": "Mensaje",
16
+ "more_options": "Más opciones",
17
+ "relative_time_today": "Hoy",
18
+ "relative_time_yesterday": "Ayer",
19
+ "relative_time_day": "hace {count} d",
20
+ "relative_time_hour": "hace {count} h",
21
+ "relative_time_minute": "hace {count} min",
22
+ "relative_time_now": "ahora",
23
+ "remove_attachment": "Quitar {name}",
24
+ "send_message": "Enviar mensaje",
25
+ "status_reply_time": "El agente está listo. Te responderemos pronto.",
26
+ "support_chat_label": "Chat de soporte de {title}",
27
+ "welcome_message": "Hola, soy tu asistente de soporte. ¿En qué puedo ayudarte?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Ajouter un emoji",
3
+ "assistant_author_ai": "Agent",
4
+ "assistant_author_human": "Support",
5
+ "attachment_label": "Joindre une image, un PDF ou un MP4",
6
+ "close_chat": "Fermer le chat",
7
+ "collapse_window": "Réduire la fenêtre",
8
+ "download_transcript": "Télécharger la conversation",
9
+ "expand_window": "Agrandir la fenêtre",
10
+ "input_placeholder": "Posez une question...",
11
+ "interview_input_placeholder": "Votre réponse...",
12
+ "interview_session_description": "Partagez vos idées. On vous écoute.",
13
+ "launcher_close": "Fermer {title}",
14
+ "launcher_open": "Ouvrir {title}",
15
+ "message_aria_label": "Message",
16
+ "more_options": "Plus d'options",
17
+ "relative_time_today": "Aujourd'hui",
18
+ "relative_time_yesterday": "Hier",
19
+ "relative_time_day": "il y a {count} j",
20
+ "relative_time_hour": "il y a {count} h",
21
+ "relative_time_minute": "il y a {count} min",
22
+ "relative_time_now": "maintenant",
23
+ "remove_attachment": "Supprimer {name}",
24
+ "send_message": "Envoyer le message",
25
+ "status_reply_time": "L’agent est prêt. Réponse sous peu.",
26
+ "support_chat_label": "Chat d'assistance {title}",
27
+ "welcome_message": "Bonjour, je suis votre assistant support. Comment vous aider ?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Aggiungi emoji",
3
+ "assistant_author_ai": "Agente",
4
+ "assistant_author_human": "Supporto",
5
+ "attachment_label": "Allega immagine, PDF o MP4",
6
+ "close_chat": "Chiudi chat",
7
+ "collapse_window": "Comprimi finestra",
8
+ "download_transcript": "Scarica trascrizione",
9
+ "expand_window": "Espandi finestra",
10
+ "input_placeholder": "Fai una domanda...",
11
+ "interview_input_placeholder": "La tua risposta...",
12
+ "interview_session_description": "Condividi le tue idee. Ti ascoltiamo.",
13
+ "launcher_close": "Chiudi {title}",
14
+ "launcher_open": "Apri {title}",
15
+ "message_aria_label": "Messaggio",
16
+ "more_options": "Altre opzioni",
17
+ "relative_time_today": "Oggi",
18
+ "relative_time_yesterday": "Ieri",
19
+ "relative_time_day": "{count} g fa",
20
+ "relative_time_hour": "{count} h fa",
21
+ "relative_time_minute": "{count} min fa",
22
+ "relative_time_now": "ora",
23
+ "remove_attachment": "Rimuovi {name}",
24
+ "send_message": "Invia messaggio",
25
+ "status_reply_time": "L’agente è pronto. Risposta in arrivo.",
26
+ "support_chat_label": "Chat di supporto {title}",
27
+ "welcome_message": "Ciao, sono il tuo assistente di supporto. Come posso aiutarti?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "絵文字を追加",
3
+ "assistant_author_ai": "AI Assistant",
4
+ "assistant_author_human": "Support",
5
+ "attachment_label": "画像・PDF・MP4を添付",
6
+ "close_chat": "閉じる",
7
+ "collapse_window": "折りたたむ",
8
+ "download_transcript": "Transcriptを保存",
9
+ "expand_window": "拡大",
10
+ "input_placeholder": "ご質問を入力...",
11
+ "interview_input_placeholder": "回答を入力...",
12
+ "interview_session_description": "Insightはここから。ご意見をどうぞ。",
13
+ "launcher_close": "{title}を閉じる",
14
+ "launcher_open": "{title}を開く",
15
+ "message_aria_label": "メッセージ",
16
+ "more_options": "その他",
17
+ "relative_time_today": "今日",
18
+ "relative_time_yesterday": "昨日",
19
+ "relative_time_day": "{count}日前",
20
+ "relative_time_hour": "{count}時間前",
21
+ "relative_time_minute": "{count}分前",
22
+ "relative_time_now": "今",
23
+ "remove_attachment": "{name}を削除",
24
+ "send_message": "送信",
25
+ "status_reply_time": "Agentが対応中。まもなく返信します。",
26
+ "support_chat_label": "{title} Support Chat",
27
+ "welcome_message": "こんにちは。Support Assistantです。ご用件をどうぞ。"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "이모지 추가",
3
+ "assistant_author_ai": "AI 상담원",
4
+ "assistant_author_human": "지원팀",
5
+ "attachment_label": "이미지, PDF 또는 MP4 첨부",
6
+ "close_chat": "채팅 닫기",
7
+ "collapse_window": "창 접기",
8
+ "download_transcript": "대화 기록 다운로드",
9
+ "expand_window": "창 펼치기",
10
+ "input_placeholder": "질문을 입력하세요...",
11
+ "interview_input_placeholder": "답변을 입력하세요...",
12
+ "interview_session_description": "생각을 들려주세요. 귀 기울여 듣겠습니다.",
13
+ "launcher_close": "{title} 닫기",
14
+ "launcher_open": "{title} 열기",
15
+ "message_aria_label": "메시지",
16
+ "more_options": "추가 옵션",
17
+ "relative_time_today": "오늘",
18
+ "relative_time_yesterday": "어제",
19
+ "relative_time_day": "{count}일 전",
20
+ "relative_time_hour": "{count}시간 전",
21
+ "relative_time_minute": "{count}분 전",
22
+ "relative_time_now": "방금",
23
+ "remove_attachment": "{name} 제거",
24
+ "send_message": "메시지 보내기",
25
+ "status_reply_time": "상담원이 응답 중입니다. 곧 답변드릴게요.",
26
+ "support_chat_label": "{title} 지원 채팅",
27
+ "welcome_message": "안녕하세요, 지원 도우미입니다. 무엇을 도와드릴까요?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "Adicionar emoji",
3
+ "assistant_author_ai": "Agente",
4
+ "assistant_author_human": "Suporte",
5
+ "attachment_label": "Anexar imagem, PDF ou MP4",
6
+ "close_chat": "Fechar chat",
7
+ "collapse_window": "Recolher janela",
8
+ "download_transcript": "Baixar transcrição",
9
+ "expand_window": "Expandir janela",
10
+ "input_placeholder": "Faça uma pergunta...",
11
+ "interview_input_placeholder": "Digite sua resposta...",
12
+ "interview_session_description": "Compartilhe suas ideias. Estamos ouvindo.",
13
+ "launcher_close": "Fechar {title}",
14
+ "launcher_open": "Abrir {title}",
15
+ "message_aria_label": "Mensagem",
16
+ "more_options": "Mais opções",
17
+ "relative_time_today": "Hoje",
18
+ "relative_time_yesterday": "Ontem",
19
+ "relative_time_day": "há {count} d",
20
+ "relative_time_hour": "há {count} h",
21
+ "relative_time_minute": "há {count} min",
22
+ "relative_time_now": "agora",
23
+ "remove_attachment": "Remover {name}",
24
+ "send_message": "Enviar mensagem",
25
+ "status_reply_time": "O agente está pronto. Responderemos em breve.",
26
+ "support_chat_label": "Chat de suporte {title}",
27
+ "welcome_message": "Olá, sou seu assistente de suporte. Como posso ajudar?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "新增表情符號",
3
+ "assistant_author_ai": "Agent",
4
+ "assistant_author_human": "客服",
5
+ "attachment_label": "附加圖片、PDF 或 MP4",
6
+ "close_chat": "關閉聊天",
7
+ "collapse_window": "收合視窗",
8
+ "download_transcript": "下載對話紀錄",
9
+ "expand_window": "展開視窗",
10
+ "input_placeholder": "請輸入問題...",
11
+ "interview_input_placeholder": "請輸入回答...",
12
+ "interview_session_description": "聊出真知,我們在這裡傾聽。",
13
+ "launcher_close": "關閉{title}",
14
+ "launcher_open": "開啟{title}",
15
+ "message_aria_label": "訊息",
16
+ "more_options": "更多選項",
17
+ "relative_time_today": "今天",
18
+ "relative_time_yesterday": "昨天",
19
+ "relative_time_day": "{count}天前",
20
+ "relative_time_hour": "{count}小時前",
21
+ "relative_time_minute": "{count}分鐘前",
22
+ "relative_time_now": "剛剛",
23
+ "remove_attachment": "移除 {name}",
24
+ "send_message": "送出訊息",
25
+ "status_reply_time": "Agent 在線,我們就在旁邊。",
26
+ "support_chat_label": "{title} 客服聊天",
27
+ "welcome_message": "你好,我是你的客服助理。有什麼可以幫你?"
28
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "add_emoji": "添加表情",
3
+ "assistant_author_ai": "智能助理",
4
+ "assistant_author_human": "客服",
5
+ "attachment_label": "添加图片、PDF 或 MP4",
6
+ "close_chat": "关闭聊天",
7
+ "collapse_window": "缩小窗口",
8
+ "download_transcript": "下载对话记录",
9
+ "expand_window": "扩大窗口",
10
+ "input_placeholder": "请输入问题...",
11
+ "interview_input_placeholder": "请输入回答...",
12
+ "interview_session_description": "聊出真知,我们在这儿倾听。",
13
+ "launcher_close": "关闭{title}",
14
+ "launcher_open": "打开{title}",
15
+ "message_aria_label": "消息",
16
+ "more_options": "更多选项",
17
+ "relative_time_today": "今天",
18
+ "relative_time_yesterday": "昨天",
19
+ "relative_time_day": "{count}天前",
20
+ "relative_time_hour": "{count}小时前",
21
+ "relative_time_minute": "{count}分钟前",
22
+ "relative_time_now": "刚刚",
23
+ "remove_attachment": "移除 {name}",
24
+ "send_message": "发送消息",
25
+ "status_reply_time": "智能助理在线,我们就在旁边。",
26
+ "support_chat_label": "{title} 客服聊天",
27
+ "welcome_message": "你好,我是你的客服助手。有什么可以帮你?"
28
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@customer-agent/sdk",
3
+ "version": "0.5.6-test.g260612164307",
4
+ "type": "module",
5
+ "sideEffects": [
6
+ "./sdk.js"
7
+ ],
8
+ "main": "./index.js",
9
+ "module": "./index.js",
10
+ "types": "./types/sdk/index.d.ts",
11
+ "peerDependencies": {
12
+ "react": ">=18"
13
+ },
14
+ "peerDependenciesMeta": {
15
+ "react": {
16
+ "optional": true
17
+ }
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./types/sdk/index.d.ts",
22
+ "import": "./index.js"
23
+ },
24
+ "./react": {
25
+ "types": "./types/sdk/hooks.d.ts",
26
+ "import": "./react.js"
27
+ },
28
+ "./sdk.js": "./sdk.js",
29
+ "./runtime.es.js": "./runtime.es.js",
30
+ "./messages/*": "./messages/*"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "registry": "https://registry.npmjs.org/"
35
+ }
36
+ }
package/react.js ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./chunks/constants-BVd2SKDq.js";import{t}from"./chunks/controller-D2LKL4eu.js";import{a as n,n as r,r as i}from"./chunks/launcherAnchorStore-JMTZZGKC.js";import{useCallback as a,useEffect as o,useMemo as s,useRef as c,useSyncExternalStore as l}from"react";var u=[e.WIDGET_READY,e.WIDGET_OPENED,e.WIDGET_CLOSED,e.SUPPORT_STATE_CHANGED,e.INTERVIEW_STATE_CHANGED],d=null,f=null,p=new Set;function m(e,t){return JSON.stringify(e)===JSON.stringify(t)}function h(e,t){return e===t?!0:!e||!t?!1:e.appId===t.appId&&e.isOpen===t.isOpen&&e.isReady===t.isReady&&e.widgetId===t.widgetId&&e.activeEntryId===t.activeEntryId&&m(e.activeTarget,t.activeTarget)&&e.launcher.targetConfigured===t.launcher.targetConfigured&&e.launcher.targetConnected===t.launcher.targetConnected&&m(e.support,t.support)&&m(e.interview,t.interview)}function g(){let e=t.getState();return h(d,e)||(d=e),d}function _(){if(d!==g())for(let e of p)e()}function v(){_(),queueMicrotask(_),typeof window<`u`&&typeof window.requestAnimationFrame==`function`&&window.requestAnimationFrame(_)}function y(){f||=u.map(e=>t.on(e,v))}function b(e){return p.add(e),y(),()=>{p.delete(e),!(p.size>0)&&(f?.forEach(e=>e()),f=null)}}function x(){return null}function S(){return l(b,g,x)}function C(){return l(n,r,i)}function w(){let e=S(),n=C(),r=c(n);r.current=n;let i=a(e=>{let n=t.boot(e);return v(),n},[]),o=a(async(e,n)=>{await t.chooseInvitation(e,n),v()},[]),l=a(async()=>{let e=await t.ensureInvitation();return v(),e},[]),u=a(()=>{t.hide(),v()},[]),d=a(e=>{t.identify(e),v()},[]),f=a((e,n)=>{t.setContext(e,n),v()},[]),p=a(e=>{t.openEntry(e),v()},[]),m=a(async e=>{let n=await t.loadInterviewReward(e);return v(),n},[]),h=a(async e=>{await t.sendInterviewMessage(e),v()},[]),g=a(e=>{t.show(e),v()},[]),_=a(()=>{t.shutdown(),v()},[]),y=a(async e=>{let n=await t.startInvitation(e);return v(),n},[]),b=a(async()=>{let e=await t.startInterview();return v(),e},[]),x=a(e=>{t.toggle(e),v()},[]),w=a(e=>{t.update(e),v()},[]);return s(()=>({CustomerAgent:t,boot:i,chooseInvitation:o,ensureInvitation:l,getInterviewSession:t.getInterviewSession,getInterviewState:t.getInterviewState,getSession:t.getSession,getState:t.getState,getSupportState:t.getSupportState,hide:u,identify:d,isOpen:e?.isOpen??!1,isReady:e?.isReady??!1,launcher:e?.launcher??null,launcherAnchor:n,launcherAnchorRef:r,loadInterviewReward:m,on:t.on,openEntry:p,sendInterviewMessage:h,setContext:f,show:g,shutdown:_,startInterview:b,startInvitation:y,state:e,toggle:x,update:w}),[i,o,l,u,d,n,m,p,h,f,g,_,b,y,e,x,w])}function T(e,n){let r=c(n);o(()=>{r.current=n},[n]),o(()=>t(`on`,e,e=>{r.current(e)}),[e])}export{w as useCustomerAgent,T as useCustomerAgentEvent,S as useCustomerAgentState};
package/runtime.es.js ADDED
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./chunks/constants-BVd2SKDq.js";import{r as n,t as r}from"./chunks/interviewTypes-Ch2NsXKB.js";import{i,t as a}from"./chunks/launcherAnchorStore-JMTZZGKC.js";import{_ as o,b as s,f as c,g as l,m as u,n as d,p as f,u as p,v as m,y as h}from"./chunks/routes-Dh46ka4-.js";import{a as g,c as _,d as v,i as y,l as b,n as x,o as S,r as ee,u as te}from"./chunks/navigationState-LdqG_Osx.js";import{n as ne,r as re}from"./chunks/i18n-Q8u2wtW4.js";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,ie=Object.getOwnPropertyNames,E=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ie(t),a=0,o=i.length,s;a<o;a++)s=i[a],!D.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:C(E(e)),ae(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));function oe(){let e=s(m());return{async checkEligibility(t,n){let{data:r}=await e.request(`/interviews/eligibility`,{body:t,method:`POST`,signal:n?.signal});return r},async chooseInvitation(t,n){await e.request(`/interviews/invitations/${t}/choice`,{body:n,method:`PATCH`})},async createInvitation(t){let{data:n}=await e.request(`/interviews/invitations`,{body:t,method:`POST`});return n},async getReward(t){let{data:n}=await e.request(`/interviews/sessions/${t}/reward`);return n},async getSession(t,n){let{data:r}=await e.request(`/interviews/sessions/${t}`,{signal:n?.signal});return r},async sendMessage(t,n){let{data:r}=await e.request(`/interviews/sessions/${t}/messages`,{body:n,method:`POST`});return r},async startInvitation(t,n){let{data:r}=await e.request(`/interviews/invitations/${t}/start`,{body:n,method:`POST`});return r}}}function j(e){return typeof e==`string`&&e.trim()?e.trim():null}function M(e){return e.anonymous_id??e.user?.id}function N(e){return{...e.context,...e.user,userId:e.user?.id,visitorId:M(e)}}function P(e){return j(e.brand?.name)??`Customer Agent`}function F(e){return{appId:e.app_id,locale:e.locale,pageContext:e.context??{},userContext:N(e),visitorId:M(e)}}function se(e,t){return{appId:e.app_id,campaignId:t.campaignId,context:e.context??{},showRequestId:t.showRequestId,userContext:N(e),variantKey:t.variantKey,visitorId:M(e)}}function I(e){return e instanceof Error?e.message:`CustomerAgent interview request failed.`}function L(e,t){return JSON.stringify(e)===JSON.stringify(t)}function R(e,t){return e.status===n.ACTIVE?{entryId:`interview/session/${e.sessionId}`,sessionId:e.sessionId,status:r.ACTIVE,title:t}:{sessionId:e.sessionId,sessionStatus:e.status,status:r.TERMINAL}}function ce(e){return{conversationId:`interview/session/${e}`,conversationType:`interview`,entryId:`interview/session/${e}`,interviewSessionId:e}}function z(e){return typeof crypto<`u`&&`randomUUID`in crypto?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function le({api:e,buildContextPayload:t=p,cache:i,emitAvailable:a,emitConversationCreated:o,emitSessionStarted:s,emitStateChanged:c,getOptions:l}){let d=new Set,f={status:r.IDLE},m=0,h=null,g=null,_=null,v=null,y=null,b=null,x=null;function S(e){L(f,e)||(f=e,c(f))}function ee(e,t){y=t,b=null,x=null;let n={body:t.invitation.body,campaignId:t.campaignId,laterCta:t.invitation.laterCta,startCta:t.invitation.startCta,status:r.AVAILABLE,title:t.invitation.title};S(n),d.has(e)||(d.add(e),a(n))}function te(){y=null,b=null,x=null,S({status:r.IDLE})}function ne(){v?.abort(),v=null,g=null,_=null}async function re(t,n,i){let a=l(),o=await e.checkEligibility(F(a),{signal:i});if(!(n!==m||t!==u(l()))){if(h=t,!o.eligible||o.status&&o.status!==r.AVAILABLE||!o.campaignId||!o.showRequestId||!o.invitation){y=null,b=null,x=null,S({status:r.UNAVAILABLE});return}ee(t,o)}}async function C(){let t=l(),a=u(t);if(!a){m+=1,ne(),h=null,te();return}let o=g!==null&&_!==a;if(o&&ne(),!o&&h===a&&f.status!==r.ERROR)return;if(g&&_===a){await g;return}ne();let s=++m,c=new AbortController;v=c,_=a,g=(async()=>{S({status:r.CHECKING});try{let r=i.read(t);if(r)try{let t=await e.getSession(r.sessionId,{signal:c.signal});if(s!==m||a!==u(l()))return;if(t.status!==n.ACTIVE){x=null,i.clear(l()),await re(a,s,c.signal);return}x=t,S(R(t,r.title)),h=a;return}catch{if(s!==m||a!==u(l()))return;x=null,i.clear(l())}await re(a,s,c.signal)}catch(e){if(s!==m||a!==u(l()))return;x=null,S({error:{message:I(e)},status:r.ERROR})}finally{_===a&&(g=null,_=null),v===c&&(v=null)}})(),await g}return{async chooseInvitation(t,n){await e.chooseInvitation(t,{choice:n})},async ensureInvitation(){let t=u(l());if(!t)throw m+=1,ne(),h=null,te(),Error(`No interview invitation is available.`);if((!y||f.status!==r.AVAILABLE)&&await C(),!y||f.status!==r.AVAILABLE)throw Error(`No interview invitation is available.`);if(b)return b;let n=await e.createInvitation(se(l(),y));return t===u(l())&&(b=n.invitationId),n.invitationId},getState(){return f.status===r.ACTIVE?{...f,title:j(l().brand?.name)??f.title??P(l())}:f},getActiveSession(){return x},async loadReward(t=x?.sessionId){if(!t)throw Error(`Cannot load an interview reward before the session starts.`);return await e.getReward(t)},syncAvailability:C,async startInvitation(r){let a=l(),c=u(a),d=await e.startInvitation(r,t(a));if(!c||c!==u(l()))return{entryId:`interview/session/${d.sessionId}`,session:d,sessionId:d.sessionId};x=d,d.status===n.ACTIVE?i.write(a,{entryId:`interview/session/${d.sessionId}`,priority:20,sessionId:d.sessionId,title:P(a)}):i.clear(a),S(R(d,P(a)));let f=ce(d.sessionId);return o?.(f),s?.(f),{entryId:`interview/session/${d.sessionId}`,session:d,sessionId:d.sessionId}},async sendMessage(t){if(!x||f.status!==r.ACTIVE)throw Error(`Cannot send an interview message before the session starts.`);let a=u(l()),o=x.sessionId,s=await e.sendMessage(o,{clientMessageId:z(`interview-message`),content:t,locale:l().locale});a!==u(l())||f.status!==r.ACTIVE||(x={...x,messages:[...x.messages,{content:t,createdAt:new Date().toISOString(),id:z(`interview-user`),role:`user`},{content:s.assistantMessage,createdAt:new Date().toISOString(),id:z(`interview-assistant`),role:`assistant`}],status:s.sessionStatus},s.sessionStatus!==n.ACTIVE&&i.clear(l()),S(R(x,P(l()))))}}}function ue(e){let t=s(e);return{async startSession(e,n){let{data:r}=await t.request(`/session`,{body:{...e,conversationId:n??void 0},conversationId:n,method:`POST`});return{conversationId:r.conversationId,messages:r.messages}},async updateContext(e,n){let{data:r}=await t.request(`/context`,{body:e,conversationId:n,method:`PATCH`});return r}}}function B(e){return e instanceof Error?e.message:`CustomerAgent support session request failed.`}function de(e){return e instanceof h&&e.code===`NOT_FOUND`}function V(e,t){return JSON.stringify(e)===JSON.stringify(t)}function H(e){return Array.isArray(e)?`[${e.map(e=>H(e)).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${H(t)}`).join(`,`)}}`:JSON.stringify(e)}function fe({api:e,buildContextPayload:t=p,cache:n,emitConversationCreated:r,emitStateChanged:i,getOptions:a,onSessionReady:o}){let s={status:b.IDLE},c=0,l=null,u=null,d=null,f=null,m=null,h=null,g=null,_=null;function y(e){V(s,e)||(s=e,i(s))}async function x(n){let r=t(a());return await e.startSession(r,n)}async function S(n,r,i){if(!e.updateContext)return;let o={...t(n),conversationId:i},s=H({key:r,payload:o});_!==s&&await e.updateContext(o,i).then(()=>{r===v(a())&&(_=s)}).catch(()=>void 0)}return{async ensureSession(){let e=a(),t=v(e);if(s.status===b.READY&&u===t)return l??{conversationId:s.conversationId,messages:[]};if(m&&h===t){let e=await m;if(e)return e}if(d&&f===t)return await d;let i=n.read(e),p=++c;y({status:i?b.REFRESHING:b.STARTING}),f=t,d=(async()=>{try{return await x(i)}catch(t){if(!i||!de(t))throw t;return n.clear(e),await x(null)}})();try{let e=await d;return p!==c||t!==v(a())?e:(l=e,u=t,n.write(a(),e.conversationId),o?.(a(),e),(!i||i!==e.conversationId)&&r(e.conversationId),y({conversationId:e.conversationId,status:b.READY}),e)}catch(r){throw p!==c||t!==v(a())?r:(i&&n.clear(e),y({error:{message:B(r)},status:b.ERROR}),r)}finally{f===t&&(d=null,f=null)}},getState(){return s},getSessionSnapshot(){return u===v(a())?l:null},invalidateSession(){let e=a(),t=v(e);c+=1,n.clear(e),u===t&&(l=null,u=null),f===t&&(d=null,f=null),h===t&&(m=null,h=null),g=null,_=null,y({status:b.IDLE})},async syncCachedSession(){let r=a(),i=v(r);if(s.status===b.READY&&u===i){g=i,await S(r,i,s.conversationId);return}if(g===i&&s.status!==b.ERROR)return;if(m&&h===i){await m;return}if(d&&f===i)return;let p=n.read(r);if(!p){g=i,y({status:b.IDLE});return}let _=++c;h=i,m=(async()=>{y({status:b.REFRESHING});try{let s=await e.startSession(t(r),p);return _!==c||i!==v(a())?null:(l=s,u=i,n.write(a(),s.conversationId),o?.(a(),s),y({conversationId:s.conversationId,status:b.READY}),g=i,await S(a(),i,s.conversationId),s)}catch(e){return _!==c||i!==v(a())?null:(n.clear(a()),de(e)?(u===i&&(l=null,u=null),y({status:b.IDLE}),g=i,null):(y({error:{message:B(e)},status:b.ERROR}),null))}finally{h===i&&(m=null,h=null)}})(),await m}}}function pe(e){let t=new EventTarget;return{emit(...n){let[r,i={}]=n,a={...e(),...i,timestamp:new Date().toISOString(),type:r};t.dispatchEvent(new CustomEvent(r,{detail:a}))},on(e,n){let r=e=>n(e.detail);return t.addEventListener(e,r),()=>t.removeEventListener(e,r)}}}function U(e){let t=e.tagName.toLowerCase();return t===`button`||t===`input`||t===`select`||t===`textarea`||t===`summary`||t===`a`&&e.hasAttribute(`href`)}function me(e,t,n){if(n===void 0){delete e[t];return}e[t]=n}function he(e,t){let n=t.isOpen?`open`:`closed`;e.setAttribute(`aria-expanded`,t.isOpen?`true`:`false`),e.dataset.state=n,e.dataset.customerAgentState=n,me(e.dataset,`customerAgentActiveEntry`,t.activeEntryId),me(e.dataset,`customerAgentActiveKind`,t.activeKind),e.dataset.customerAgentHasInvitation=t.hasInvitation?`true`:`false`,e.dataset.customerAgentHasUnread=t.hasUnread?`true`:`false`,me(e.dataset,`customerAgentViewport`,t.viewport),delete e.dataset.customerAgentLauncher,U(e)||(e.setAttribute(`role`,`button`),e.hasAttribute(`tabindex`)||(e.tabIndex=0))}function ge(){let e=document.createElement(`div`);e.style.cssText=[`position: fixed`,`visibility: hidden`,`height: env(safe-area-inset-bottom)`,`pointer-events: none`].join(`;`),document.body.appendChild(e);let t=Number.parseFloat(getComputedStyle(e).height)||0;return e.remove(),t}function _e(e={}){let t=window.visualViewport,n=window.innerWidth,r=window.innerHeight,i=t?.height??r,a=e.mode!==`auto`&&e.mode!==void 0?!0:n<=640,o=a?e.mode===`bottom-sheet`?`bottom-sheet`:`fullscreen`:`desktop`,s=Math.max(0,t?.offsetTop??0);return{height:r,isMobile:a,keyboardInset:Math.max(0,r-i-s),mode:a?`mobile`:`desktop`,offsetTop:s,presentation:o,safeAreaBottom:ge(),visualHeight:i,width:n}}e();var W=null,G=null,K=null,ve=null,ye=`customer-agent-widget`,be=260,xe=[],Se=new WeakMap,Ce=0;async function we(){return K||(ve??=Promise.all([import(`./chunks/react-CKmEJ8Ba.js`).then(e=>A(e.t(),1)),import(`./chunks/client-duvjg9sB.js`).then(e=>A(e.t(),1)),import(`./chunks/App-DTjTPofP.js`)]).then(([e,t,n])=>(K={createElement:e.createElement,createRoot:t.createRoot,preloadWidgetPanelShell:n.preloadWidgetPanelShell,WidgetApp:n.WidgetApp},K)).catch(e=>{throw ve=null,e}),await ve)}function Te(e){let t=xe.splice(0);for(let n of t)n.active&&(n.unsubscribe=e.on(n.eventName,n.handler))}function Ee(){document.getElementById(ye)?.remove()}function De(e){return typeof e==`string`?document.querySelector(e)??document.body:e??document.body}function Oe(e){let t=Se.get(e);if(t)return t;let n=`element-${++Ce}`;return Se.set(e,n),n}function ke(e){return typeof e==`string`?document.querySelector(e):e??null}function Ae(e){return Object.prototype.toString.call(e)===`[object Object]`}function q(e){return Array.isArray(e)?`[${e.map(e=>q(e)).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${q(t)}`).join(`,`)}}`:JSON.stringify(e)}function je(e){return typeof e==`string`?`selector:${e}`:e?`element:${Oe(e)}`:null}function Me(e){let t=Oe(De(e.mount)),{launcher:n,mount:r,...i}=e;return{fingerprint:q({...i,launcher:n?{...n,target:je(n.target)}:void 0,mount:t}),key:q({appId:e.app_id,mount:t})}}function Ne(e,t){let n={...e};for(let[r,i]of Object.entries(t)){let t=e[r];n[r]=Ae(t)&&Ae(i)?Ne(t,i):i}return n}function J(e){return typeof e==`string`&&e.trim()?e.trim():null}function Pe(e,t){let n=t?.replace(`_`,`-`),r=n?.split(`-`)[0];return(n?e[n]:void 0)??(r?e[r]:void 0)??e.en??Object.values(e)[0]}function Fe(e,t){let n=J(t.branding.name)??J(t.branding.agentName)??J(t.branding.workspaceName),r=J(t.branding.primaryColor)??J(t.branding.primary_color),i=Pe(t.welcomeMessage,e.locale);return{...e,brand:{...e.brand,name:e.brand?.name??n??e.brand?.name},messages:{...i?{welcome_message:i}:{},...e.messages},theme:{...e.theme,primaryColor:e.theme?.primaryColor??r??e.theme?.primaryColor}}}function Ie(e,n=Me(e)){W?.shutdown(),Ee();let r=l(),u=document.createElement(`div`),p=pe(()=>({appId:b.app_id,widgetId:r})),v=De(e.mount),b=o(e,r),C=e.launcher?.target,w=!!b.open_on_init,T=y(b),ie=w,E=null,D=null,O=null,k=null,ae=null,A=null,j=null,M=null,N=re(b.locale,b.messages),P=_e(b.mobile),F=!1,se=0,I=null,L=`idle`,R=null,ce=!1,z=!1,B=!1,de=null,V=fe({api:ue(m()),cache:te(),emitConversationCreated(e){p.emit(t.CONVERSATION_CREATED,{...Ke(e)})},emitStateChanged(e){p.emit(t.SUPPORT_STATE_CHANGED,{support:e}),U(),J()},getOptions(){return b},onSessionReady(e,t){c.hydrateSession(e,t)}}),H=le({api:oe(),cache:f(),emitAvailable(e){p.emit(t.INTERVIEW_AVAILABLE,e)},emitConversationCreated(e){p.emit(t.CONVERSATION_CREATED,e)},emitSessionStarted(e){p.emit(t.INTERVIEW_SESSION_STARTED,e)},emitStateChanged(e){p.emit(t.INTERVIEW_STATE_CHANGED,{interview:e}),U(),J()},getOptions(){return b}});u.id=ye,u.className=`customer-agent-namespace`,u.dataset.customerAgent=`container`,v.appendChild(u);function U(){if(!E)return;let e=g(T.memoryRoute),t=T.requestedTarget?.type===`entry`?e?.split(`/`)[0]:T.requestedTarget?.type??e?.split(`/`)[0]??`support`;he(E,{activeEntryId:e,activeKind:t,hasInvitation:!1,hasUnread:!1,isOpen:w,targetConfigured:C!==void 0,targetConnected:!!E,viewport:P.mode})}function me(){!E||!D||(D.ariaExpanded===null?E.removeAttribute(`aria-expanded`):E.setAttribute(`aria-expanded`,D.ariaExpanded),D.role===null?E.removeAttribute(`role`):E.setAttribute(`role`,D.role),D.state===null?delete E.dataset.state:E.dataset.state=D.state,D.tabIndex===null?E.removeAttribute(`tabindex`):E.setAttribute(`tabindex`,D.tabIndex))}function ge(){ae?.(),ae=null,a(E),me(),E=null,D=null}function ve(){typeof C!=`string`||O!==null||(O=window.requestAnimationFrame(()=>{if(O=null,!(F||typeof C!=`string`)){if(ke(C)===E){U();return}J()}}))}function xe(){if(k?.disconnect(),k=null,typeof C!=`string`||typeof MutationObserver>`u`)return;let e=document.documentElement??document.body;e&&(k=new MutationObserver(ve),k.observe(e,{attributes:!0,childList:!0,subtree:!0}))}function Se(){let e=ke(C);if(e===E){U();return}if(ge(),!e)return;let t=e;E=t,i(t),D={ariaExpanded:t.getAttribute(`aria-expanded`),role:t.getAttribute(`role`),state:t.dataset.state??null,tabIndex:t.getAttribute(`tabindex`)};function n(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function r(e){n(e),Q(!w)}function a(e){e.key!==`Enter`&&e.key!==` `||(n(e),Q(!w))}t.addEventListener(`click`,r,{capture:!0}),t.addEventListener(`keydown`,a,{capture:!0}),ae=()=>{t.removeEventListener(`click`,r,{capture:!0}),t.removeEventListener(`keydown`,a,{capture:!0})},U()}function Ce(){L===`idle`&&(L=`queued`,queueMicrotask(()=>{F||(L=`emitted`,p.emit(t.WIDGET_READY))}))}function Oe(e){let n=!0;return queueMicrotask(()=>{F||!n||e({appId:b.app_id,timestamp:new Date().toISOString(),type:t.WIDGET_READY,widgetId:r})}),()=>{n=!1}}function Ae(e){let n=e instanceof Error?e.message:`CustomerAgent widget UI failed to load.`;console.error(`CustomerAgent widget UI failed to load.`,e),p.emit(t.ERROR,{message:n})}function q(){return R??=we().then(async e=>{F||(I??=e.createRoot(u),await e.preloadWidgetPanelShell())}).catch(e=>{throw R=null,e}),R}function je(){if(!F){if(!E||ie||w){J();return}if(!K||!I){J();return}I.render(K.createElement(K.WidgetApp,{activeTarget:T.requestedTarget,hasPanel:!1,hasCustomLauncher:!0,eventBus:p,interviewRuntime:{chooseInvitation:H.chooseInvitation,ensureInvitation:H.ensureInvitation,getActiveSession:H.getActiveSession,startInvitation:H.startInvitation},isOpen:!1,launcherTargetElement:E,memoryRoute:T.memoryRoute,onMemoryRouteChange:Ye,onOpenChange:Q,options:b,resolvedLocale:N,runtimeState:{interview:H.getState(),support:V.getState()},supportRuntime:{ensureSession:V.ensureSession,getSessionSnapshot:V.getSessionSnapshot,invalidateSession:V.invalidateSession},isViewportSettling:B,viewport:P,widgetId:r})),Ce()}}function J(){if(!F){if(Se(),E&&!ie&&!w){ce=!1,q().then(je).catch(Ae);return}if(!K||!I){ce=!0,we().then(e=>{F||(I??=e.createRoot(u),ce&&(ce=!1,J()))}).catch(e=>{Ae(e)});return}I.render(K.createElement(K.WidgetApp,{activeTarget:T.requestedTarget,hasPanel:ie,hasCustomLauncher:!!E,eventBus:p,interviewRuntime:{chooseInvitation:H.chooseInvitation,ensureInvitation:H.ensureInvitation,getActiveSession:H.getActiveSession,startInvitation:H.startInvitation},isOpen:w,launcherTargetElement:E,memoryRoute:T.memoryRoute,onMemoryRouteChange:Ye,onOpenChange:Q,options:b,resolvedLocale:N,runtimeState:{interview:H.getState(),support:V.getState()},supportRuntime:{ensureSession:V.ensureSession,getSessionSnapshot:V.getSessionSnapshot,invalidateSession:V.invalidateSession},isViewportSettling:B,viewport:P,widgetId:r})),q().then(Ce).catch(Ae)}}function Pe(){let e=++se;N=re(b.locale,b.messages),ne(b.locale,b.messages).then(t=>{F||e!==se||(N=t,J())}).catch(n=>{if(F||e!==se)return;let r=n instanceof Error?n.message:`CustomerAgent locale messages failed to load.`;console.error(`CustomerAgent locale messages failed to load.`,n),p.emit(t.ERROR,{message:r})})}function Ie(){N=re(b.locale,b.messages),P=_e(b.mobile),X()}function Le(e){S(e)!==S(b)&&(T=y(b))}function Y(){P=_e(b.mobile),X()}function Re(){return w&&!b.embedded&&P.presentation===`fullscreen`}function ze(){let e=window.navigator.platform,t=window.navigator.maxTouchPoints??0;return/iP(ad|hone|od)/.test(e)||e===`MacIntel`&&t>1}function Be(){if(de)return;let e=document.body,t=document.documentElement,n=window.scrollX,r=window.scrollY,i=ze()?`fixed`:`overflow`,a=Math.max(0,window.innerWidth-t.clientWidth),o=Number.parseFloat(window.getComputedStyle(e).paddingRight)||0;de={bodyLeft:e.style.left,bodyOverflow:e.style.overflow,bodyOverscrollBehavior:e.style.overscrollBehavior,bodyPaddingRight:e.style.paddingRight,bodyPosition:e.style.position,bodyRight:e.style.right,bodyTop:e.style.top,bodyWidth:e.style.width,htmlOverflow:t.style.overflow,htmlOverscrollBehavior:t.style.overscrollBehavior,htmlScrollbarGutter:t.style.scrollbarGutter,scrollX:n,scrollY:r,strategy:i},t.style.overflow=`hidden`,t.style.overscrollBehavior=`contain`,e.style.overflow=`hidden`,e.style.overscrollBehavior=`contain`,`scrollbarGutter`in t.style?t.style.scrollbarGutter=`stable`:a>0&&(e.style.paddingRight=`${o+a}px`),i===`fixed`&&(e.style.left=`-${n}px`,e.style.position=`fixed`,e.style.right=`0`,e.style.top=`-${r}px`,e.style.width=`100%`)}function Ve(){let e=de;if(!e)return;de=null;let t=document.body,n=document.documentElement;n.style.overflow=e.htmlOverflow,n.style.overscrollBehavior=e.htmlOverscrollBehavior,n.style.scrollbarGutter=e.htmlScrollbarGutter,t.style.left=e.bodyLeft,t.style.overflow=e.bodyOverflow,t.style.overscrollBehavior=e.bodyOverscrollBehavior,t.style.paddingRight=e.bodyPaddingRight,t.style.position=e.bodyPosition,t.style.right=e.bodyRight,t.style.top=e.bodyTop,t.style.width=e.bodyWidth,e.strategy===`fixed`&&window.scrollTo(e.scrollX,e.scrollY)}function X(){if(Re()){Be();return}Ve()}function He(e){return w&&!b.embedded&&e.presentation===`fullscreen`}function Ue(){j!==null&&(window.clearTimeout(j),j=null),B&&(B=!1,J())}function We(){j!==null&&window.clearTimeout(j),j=window.setTimeout(()=>{j=null,!F&&Ue()},be)}function Z(){A===null&&(A=window.requestAnimationFrame(()=>{if(A=null,F)return;let e=_e(b.mobile),t=He(e);P=e,X(),t?(B=!0,We()):(j!==null&&(window.clearTimeout(j),j=null),B=!1),J()}))}function Ge(){z||(z=!0,queueMicrotask(()=>{z=!1,!F&&(Je(),V.syncCachedSession(),H.syncAvailability())}))}function Ke(e){return{conversationId:e,conversationType:`support`,entryId:d(e),supportConversationId:e}}function qe(){return{activeEntryId:g(T.memoryRoute),activeTarget:T.requestedTarget,appId:b.app_id,isOpen:w,isReady:L===`emitted`,launcher:{targetConfigured:C!==void 0,targetConnected:!!E},support:V.getState(),interview:H.getState(),widgetId:r}}function Je(){let e=m(),n=`${e}::${b.app_id}`;M!==n&&(M=n,s(e).request(`/apps/${b.app_id}/public-config`).then(({data:e})=>{M===n&&(b=Fe(b,e),Pe(),Y(),J())}).catch(e=>{if(e instanceof h&&e.code===`NOT_FOUND`)return;let n=e instanceof Error?e.message:`CustomerAgent public config request failed.`;console.error(`CustomerAgent public config request failed.`,e),p.emit(t.ERROR,{message:n})}))}window.addEventListener(`resize`,Z),window.addEventListener(`orientationchange`,Z),window.visualViewport?.addEventListener(`resize`,Z),window.visualViewport?.addEventListener(`scroll`,Z);function Q(e){if(e?ie=!0:T=x(T),w===e){J();return}w=e,X(),U(),J(),p.emit(w?t.WIDGET_OPENED:t.WIDGET_CLOSED)}function $(e){T=_(b,T,e)}function Ye(e){T=ee(b,T,e),U()}let Xe={async chooseInvitation(e,t){await H.chooseInvitation(e,t)},async ensureInvitation(){return{invitationId:await H.ensureInvitation()}},hide(){Q(!1)},getInterviewState(){return H.getState()},getInterviewSession(){return H.getActiveSession()},async getSession(){return{conversationId:(await V.ensureSession()).conversationId}},getState:qe,getSupportState(){return V.getState()},identify(e){let t=b;b={...b,user:e},Le(t),Ie(),J(),Ge()},on(e,n){let r=p.on(e,n),i;return e===t.WIDGET_READY&&L===`emitted`&&(i=Oe(n)),()=>{i?.(),r()}},openEntry(e){$({entryId:e,type:`entry`}),Q(!0)},async loadInterviewReward(e){return await H.loadReward(e)},async sendInterviewMessage(e){await H.sendMessage(e)},setContext(e,t={}){b={...b,context:t.merge===!1?e:Ne(b.context,e),context_ready:t.ready??b.context_ready},Ie(),J(),Ge()},show(e){$(e),Q(!0)},shutdown(){F=!0,W===Xe&&(W=null,G=null),I?.unmount(),window.removeEventListener(`resize`,Z),window.removeEventListener(`orientationchange`,Z),window.visualViewport?.removeEventListener(`resize`,Z),window.visualViewport?.removeEventListener(`scroll`,Z),A!==null&&(window.cancelAnimationFrame(A),A=null),j!==null&&(window.clearTimeout(j),j=null),Ve(),k?.disconnect(),k=null,O!==null&&(window.cancelAnimationFrame(O),O=null),ge(),u.remove()},async startInvitation(e){let t=await H.startInvitation(e);return $({sessionId:t.sessionId,type:`interview`}),J(),{entryId:t.entryId,sessionId:t.sessionId}},async startInterview(){$({type:`interview`}),Q(!0);try{let e=await H.ensureInvitation(),t=await H.startInvitation(e);return $({sessionId:t.sessionId,type:`interview`}),J(),{entryId:t.entryId,sessionId:t.sessionId}}catch(e){throw $({type:`support`}),J(),e}},toggle(e){e&&$(e),Q(!w)},update(e){let t=b;Object.prototype.hasOwnProperty.call(e,`launcher`)&&(C=e.launcher?.target,xe()),b={...o({...b,...e,context:e.context??b.context},b.widgetId),embedded:b.embedded},Le(t),Pe(),Y(),J(),Ge()}};return W=Xe,G=n,Te(p),xe(),Pe(),X(),J(),Ge(),Xe}function Le(e){if(W&&e.app_id){let t=Me(e);return G?.key===t.key?(G.fingerprint!==t.fingerprint&&(W.update(e),G=t),e.open_on_init&&W.show(),W):Ie(e,t)}return Ie(e)}var Y={boot:Le,async chooseInvitation(e,t){await W?.chooseInvitation(e,t)},async ensureInvitation(){return W?await W.ensureInvitation():null},getInterviewState(){return W?.getInterviewState()??null},getInterviewSession(){return W?.getInterviewSession()??null},async getSession(){return W?await W.getSession():null},getState(){return W?.getState()??null},getSupportState(){return W?.getSupportState()??null},hide(){W?.hide()},identify(e){W?.identify(e)},on(e,t){if(W)return W.on(e,t);let n={active:!0,eventName:e,handler:t};return xe.push(n),()=>{n.active=!1,n.unsubscribe?.()}},setContext(e,t){W?.setContext(e,t)},openEntry(e){W?.openEntry(e)},async loadInterviewReward(e){return W?await W.loadInterviewReward(e):null},async sendInterviewMessage(e){await W?.sendInterviewMessage(e)},show(e){W?.show(e)},shutdown(){W?.shutdown(),W=null,G=null},async startInvitation(e){return W?await W.startInvitation(e):null},async startInterview(){return W?await W.startInterview():null},toggle(e){W?.toggle(e)},update(e){W?.update(e)}};function Re(e,...t){switch(e){case`boot`:return Y.boot(t[0]);case`chooseInvitation`:return Y.chooseInvitation(t[0],t[1]);case`ensureInvitation`:return Y.ensureInvitation();case`getSession`:return Y.getSession();case`getState`:return Y.getState();case`getSupportState`:return Y.getSupportState();case`getInterviewState`:return Y.getInterviewState();case`getInterviewSession`:return Y.getInterviewSession();case`hide`:return Y.hide();case`identify`:return Y.identify(t[0]);case`on`:return Y.on(t[0],t[1]);case`openEntry`:return Y.openEntry(t[0]);case`loadInterviewReward`:return Y.loadInterviewReward(t[0]);case`sendInterviewMessage`:return Y.sendInterviewMessage(t[0]);case`setContext`:return Y.setContext(t[0],t[1]);case`show`:return Y.show(t[0]);case`shutdown`:return Y.shutdown();case`startInvitation`:return Y.startInvitation(t[0]);case`startInterview`:return Y.startInterview();case`toggle`:return Y.toggle(t[0]);case`update`:return Y.update(t[0]);default:throw Error(`CustomerAgent received an unknown command: ${String(e)}.`)}}var ze=Object.assign(Re,Y),Be=Y.chooseInvitation,Ve=Y.ensureInvitation,X=Y.getInterviewState,He=Y.getInterviewSession,Ue=Y.getSession,We=Y.getState,Z=Y.getSupportState,Ge=Y.hide,Ke=Y.identify,qe=Y.on,Je=Y.openEntry,Q=Y.loadInterviewReward,$=Y.sendInterviewMessage,Ye=Y.setContext,Xe=Y.show,Ze=Y.shutdown,Qe=Y.startInvitation,$e=Y.startInterview,et=Y.toggle,tt=Y.update;export{ze as CustomerAgent,Le as boot,Be as chooseInvitation,Ve as ensureInvitation,He as getInterviewSession,X as getInterviewState,Ue as getSession,We as getState,Z as getSupportState,Ge as hide,Ke as identify,Q as loadInterviewReward,k as n,qe as on,Je as openEntry,A as r,$ as sendInterviewMessage,Ye as setContext,Xe as show,Ze as shutdown,$e as startInterview,Qe as startInvitation,O as t,et as toggle,tt as update};
package/sdk.js ADDED
@@ -0,0 +1 @@
1
+ (function(){var e=`0.5.6-test.g260612164307`;function t(){typeof window>`u`||(window.__customerAgentVersion=e)}var n=`__customerAgentRuntime`,r=`__customerAgentScript`,i=typeof document<`u`&&document.currentScript instanceof HTMLScriptElement?document.currentScript:null,a=[];t();var o=`idle`,s=null,c=null;function l(e){return typeof e==`object`&&!!e}function u(e){return Array.prototype.slice.call(e)}function d(){let e=i?.src??new URL(`sdk.js`,window.location.href).toString();return new URL(`runtime.es.js`,e).toString()}function f(e){let t=e.CustomerAgent??e.default;if(typeof t!=`function`)throw Error(`CustomerAgent widget runtime module did not export CustomerAgent.`);return Object.assign(t,{[n]:!0})}function p(){if(!s)return;let e=a.splice(0);for(let t of e)t(s)}async function m(){return o===`ready`&&s?s:o===`loading`&&c?await c:(o=`loading`,c=import(d()).then(e=>(s=f(e),window.CustomerAgent=s,o=`ready`,p(),s)).catch(e=>{throw o=`failed`,c=null,console.error(`CustomerAgent widget runtime failed to load.`,e),e}),await c)}function h(e){if(s){e(s);return}a.push(e),m().catch(()=>{})}function g(e,t){h(n=>{let r=n[e];typeof r==`function`&&r(...t)})}function _(e){return h(t=>{t(`boot`,e)}),R}async function v(){return await(await m()).ensureInvitation()}async function y(e){return await(await m()).startInvitation(e)}async function b(){return await(await m()).startInterview()}async function x(e,t){await(await m()).chooseInvitation(e,t)}async function S(e){await(await m()).sendInterviewMessage(e)}async function C(e){return await(await m()).loadInterviewReward(e)}function w(e){g(`update`,[e])}function T(e){g(`show`,[e])}function E(){g(`hide`,[])}function D(e){g(`toggle`,[e])}function O(e){g(`openEntry`,[e])}function k(){g(`shutdown`,[])}function A(e){g(`identify`,[e])}function j(e,t){g(`setContext`,[e,t])}async function M(){return await(await m()).getSession()}function N(){return s?.getSupportState()??null}function P(){return s?.getInterviewState()??null}function F(){return s?.getInterviewSession()??null}function I(){return s?.getState()??null}function L(e,t){let n=!0,r=()=>{};return h(i=>{n&&(r=i.on(e,t))}),()=>{n=!1,r()}}var R={chooseInvitation:x,async ensureInvitation(){let e=await v();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getInterviewState(){let e=P();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getInterviewSession(){return F()},async getSession(){let e=await M();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getState(){let e=I();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getSupportState(){let e=N();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},hide:E,identify:A,on:L,openEntry:O,loadInterviewReward:C,sendInterviewMessage:S,setContext:j,show:T,shutdown:k,async startInterview(){let e=await b();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},async startInvitation(e){let t=await y(e);if(!t)throw Error(`CustomerAgent widget is not initialized.`);return t},toggle:D,update:w};function z(e,...t){switch(e){case`boot`:return _(t[0]);case`chooseInvitation`:return x(t[0],t[1]);case`ensureInvitation`:return v();case`getSession`:return M();case`getState`:return I();case`getSupportState`:return N();case`getInterviewState`:return P();case`getInterviewSession`:return F();case`hide`:return E();case`identify`:return A(t[0]);case`on`:return L(t[0],t[1]);case`openEntry`:return O(t[0]);case`loadInterviewReward`:return C(t[0]);case`sendInterviewMessage`:return S(t[0]);case`setContext`:return j(t[0],t[1]);case`show`:return T(t[0]);case`shutdown`:return k();case`startInvitation`:return y(t[0]);case`startInterview`:return b();case`toggle`:return D(t[0]);case`update`:return w(t[0]);default:throw Error(`CustomerAgent received an unknown command: ${String(e)}.`)}}var B=Object.assign(z,{[r]:!0,boot:_,chooseInvitation:x,ensureInvitation:v,getInterviewState:P,getInterviewSession:F,getSession:M,getState:I,getSupportState:N,hide:E,identify:A,on:L,openEntry:O,loadInterviewReward:C,sendInterviewMessage:S,setContext:j,show:T,shutdown:k,startInterview:b,startInvitation:y,toggle:D,update:w});function V(e){if(!l(e))return!1;let t=e.q;if(!Array.isArray(t)||t.length===0)return!1;for(let e of t)z(...u(e));return!0}function H(){if(!i)return;let e=i.dataset.appId;e&&B(`boot`,{app_id:e,open_on_init:i.dataset.open===`true`,position:i.dataset.position===`bottom-left`?`bottom-left`:`bottom-right`})}if(typeof window<`u`){let e=window.CustomerAgent;window.CustomerAgent=B,V(e)||H()}})();
File without changes