@gengage/assistant-fe 0.6.18 → 0.6.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/account-config-D_EMuR0g.js +1479 -0
  2. package/dist/agentic/context/context-store.d.ts +2 -1
  3. package/dist/agentic/index.d.ts +0 -1
  4. package/dist/agentic/index.js +155 -181
  5. package/dist/agentic/types.d.ts +6 -1
  6. package/dist/agentic/worker.d.ts +0 -2
  7. package/dist/agentic/worker.js +117 -415
  8. package/dist/agentic.iife.js +6 -6
  9. package/dist/{api-paths-CEDR4rld.js → api-paths-DcKsQqb6.js} +1 -1
  10. package/dist/chat/components/InlineLauncher.d.ts +1 -1
  11. package/dist/chat/history-storage.d.ts +1 -0
  12. package/dist/chat/runtime.d.ts +1 -1
  13. package/dist/chat/types.d.ts +1 -0
  14. package/dist/chat-runtime.js +1 -1
  15. package/dist/chat.iife.js +10 -10
  16. package/dist/chat.js +1 -1
  17. package/dist/{common-BBgWfT-W.js → common-MpBmMLVk.js} +2 -2
  18. package/dist/common.js +8 -8
  19. package/dist/{connection-warning-B-doodzu.js → connection-warning-ClrMLgmZ.js} +1 -1
  20. package/dist/{context-heG8hv5l.js → context-UTzCGyR9.js} +19 -8
  21. package/dist/{fastIntent-CloHPZQh.js → fastIntent-Bl4xN0qL.js} +2 -2
  22. package/dist/index.js +13 -13
  23. package/dist/{native-webview-NWc9LrJh.js → native-webview-BcwGKkDe.js} +1 -1
  24. package/dist/native.iife.js +6 -6
  25. package/dist/native.js +1 -1
  26. package/dist/{overlay-COzFFq0-.js → overlay-cF2SjxYU.js} +1 -1
  27. package/dist/overlay.js +2 -2
  28. package/dist/qna-runtime.js +1 -1
  29. package/dist/qna.iife.js +1 -1
  30. package/dist/qna.js +1 -1
  31. package/dist/{runtime-BGCNkU1H.js → runtime-BlU1rKqc.js} +4 -4
  32. package/dist/{runtime-Ctqq0V6G.js → runtime-CS4mg3ra.js} +4 -4
  33. package/dist/{runtime-CbWCU424.js → runtime-_koZbJK_.js} +51 -48
  34. package/dist/{simbut-Dh4cJysK.js → simbut-BtL7zYIJ.js} +2 -2
  35. package/dist/simbut.iife.js +1 -1
  36. package/dist/simbut.js +1 -1
  37. package/dist/{simrel-B-sjHbL5.js → simrel-ekf3kUb_.js} +2 -2
  38. package/dist/simrel-runtime.js +1 -1
  39. package/dist/simrel.iife.js +2 -2
  40. package/dist/simrel.js +2 -2
  41. package/dist/{widget-base-CIJT5AiP.js → widget-base-p1EKDuiI.js} +2 -2
  42. package/package.json +4 -2
  43. package/dist/account-config-gj7_mF6Q.js +0 -1731
  44. package/dist/agentic/recipes/catalog-assistant-flow.d.ts +0 -50
  45. package/dist/agentic/recipes/input-text/actions.d.ts +0 -15
  46. package/dist/agentic/recipes/input-text/index.d.ts +0 -4
  47. package/dist/agentic/recipes/input-text/products.d.ts +0 -4
  48. package/dist/agentic/recipes/input-text/ranking.d.ts +0 -14
  49. package/dist/agentic/recipes/input-text/steps.d.ts +0 -31
@@ -1,7 +1,7 @@
1
- (function(s){Object.defineProperty(s,Symbol.toStringTag,{value:"Module"});function It(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function Rt({worker:e,tools:t={},beacon:r,memory:n=sessionStorage}){e.addEventListener("message",o=>{const i=o.data;It(i)&&Mt(e,i,{tools:t,beacon:r,memory:n})})}async function Mt(e,t,r){try{const n=await we(t.method,t.payload,r);e.postMessage({type:"rpc.result",rpcId:t.rpcId,ok:!0,value:n})}catch(n){e.postMessage({type:"rpc.result",rpcId:t.rpcId,ok:!1,error:{message:n instanceof Error?n.message:String(n)}})}}function Ut(e){if(e&&typeof e=="object"&&typeof e.name=="string")return e;throw new Error("tool.invoke requires { name, input }")}function Bt(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.get requires { key }")}function Lt(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}async function we(e,t,{tools:r,beacon:n,memory:o}){if(e==="tool.invoke"){const{name:i,input:a}=Ut(t),c=r[i];if(typeof c!="function")throw new Error(`Unknown tool: ${i}`);return c(a)}if(e==="beacon.send")return n?.(t),{sent:!0};if(e==="memory.get"){const{key:i}=Bt(t),a=o.getItem(String(i));return a?JSON.parse(a):null}if(e==="memory.set"){const{key:i,value:a}=Lt(t);return o.setItem(String(i),JSON.stringify(a??null)),{ok:!0}}throw new Error(`Unknown RPC method: ${e}`)}function be(){return new Date().toISOString()}function O(e){return Math.max(0,Math.round(performance.now()-e))}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nt(e){const{accountId:t,locale:r="en-GB",parentUrl:n="",threadId:o,incomingContext:i}=e,a=U(i)?i:{},c=U(a.thread)?a.thread:{},y=U(a.panel)?a.panel:{},m=U(a.meta)?a.meta:{},d=Se(a.messages),u={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||be()),extensions:U(c.extensions)?{...c.extensions}:{}},l=String(m.locale||r),f=String(m.parentUrl||n||typeof self<"u"&&self.location?.href||"");return{panel:{...y},messages:d,thread:u,meta:{locale:l,parentUrl:f,accountId:t}}}function Dt(e,t){const r=Se([t])[0];return r?{...e,messages:[...e.messages,r].slice(-50)}:e}function Se(e){return Array.isArray(e)?e.map(t=>{const r=t?.role;return{role:r==="model"?"assistant":typeof r=="string"?r:"",content:String(t?.content||"")}}).filter(t=>(t.role==="user"||t.role==="assistant")&&!!t.content).slice(-50):[]}var vt="gengage:agent:context:";async function $t({accountId:e,threadId:t,rpc:r}){const n=await r("memory.get",{tier:"session",key:Ae(e,t)});return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function Ft({accountId:e,threadId:t,extensions:r,panel:n,rpc:o}){await o("memory.set",{tier:"session",key:Ae(e,t),value:{thread:{extensions:r},...n&&Object.keys(n).length>0?{panel:n}:{}}})}function Ae(e,t){return`${vt}${e}:${t}`}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ke=class{#e=new Map;#t;#n;#o;#r;#i;constructor({accountId:e,locale:t,parentUrl:r,rpc:n,persistentPanelKeys:o=[]}){this.#t=e,this.#n=t,this.#o=r,this.#r=n,this.#i=[...new Set(o.filter(Boolean))]}async load(e){const t=e?.meta?.threadId||e?.session_id||e?.sessionId,r=String(t||"default"),n=this.#e.get(r);if(n)return n;const o=await $t({accountId:this.#t,threadId:r,rpc:this.#r}),i=Nt({accountId:this.#t,locale:e?.locale||this.#n,parentUrl:this.#o,threadId:r,incomingContext:zt(o,e?.context)});return this.#e.set(r,i),i}patch(e,t){const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=_e(n,typeof t=="function"?t(n):t);return this.#e.set(r,o),o}appendUserMessage(e,t){const r=String(e||"default");if(!t)return this.#e.get(r)??null;const n=this.#e.get(r);if(!n)return null;const o=Dt(n,{role:"user",content:t});return this.#e.set(r,o),o}async commit(e){const t=String(e||"default"),r=this.#e.get(t);return r?(await Ft({accountId:this.#t,threadId:t,extensions:r.thread.extensions,panel:qt(r.panel,this.#i),rpc:this.#r}),r):null}};function qt(e,t){if(!t.length||!b(e))return;const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function zt(e,t){return!b(e)&&!b(t)?{}:_e(b(e)?e:{},b(t)?t:{})}function _e(e,t){if(!b(t))return e;const r=e,n=t,o=b(r.panel)?r.panel:{},i=b(n.panel)?n.panel:{},a=b(r.thread)?r.thread:{},c=b(n.thread)?n.thread:{},y=b(a.extensions)?a.extensions:{},m=b(c.extensions)?c.extensions:{},d=b(r.meta)?r.meta:{},u=b(n.meta)?n.meta:{};return{...e,...t,panel:{...o,...i},thread:{...a,...c,extensions:{...y,...m}},meta:{...d,...u},messages:Array.isArray(n.messages)?n.messages.slice(-50):e.messages??[]}}function Ee(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function Te(e){return Ee(new TextEncoder().encode(JSON.stringify(e)))}async function Kt({accountId:e,devJwtSecret:t,ttlS:r=300}){if(!t)throw new Error("devJwtSecret is required for local agent mode.");const n=Math.floor(Date.now()/1e3),o=`${Te({alg:"HS256",typ:"JWT"})}.${Te({sub:e,iat:n,exp:n+r,scope:"invoke",jti:crypto.randomUUID?.()||`${n}-${Math.random()}`})}`,i=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",i,new TextEncoder().encode(o));return`${o}.${Ee(new Uint8Array(a))}`}function Y({accountId:e,devJwtSecret:t,tokenBrokerUrl:r,tokenBrokerAudience:n,refreshSkewS:o=30,fetchImpl:i=fetch}){let a=null;return async({signal:c,parentUrl:y}={})=>{if(t)return Kt({accountId:e,devJwtSecret:t});if(!r)throw new Error("tokenBrokerUrl is required for production agent mode.");const m=Math.floor(Date.now()/1e3);return a?.token&&a.expiresAtS-o>m||(a=await Jt({accountId:e,tokenBrokerUrl:r,tokenBrokerAudience:n,parentUrl:y,signal:c,fetchImpl:i})),a.token}}async function Jt({accountId:e,tokenBrokerUrl:t,tokenBrokerAudience:r,parentUrl:n,signal:o,fetchImpl:i}){const a=await i(t,{method:"POST",credentials:"include",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({accountId:e,scope:"invoke",audience:r||void 0,parentUrl:n||void 0}),...o?{signal:o}:{}});if(!a.ok)throw new Error(`Token broker request failed (${a.status}).`);const c=await a.json(),y=c?.token||c?.jwt||c?.access_token;if(!y||typeof y!="string")throw new Error("Token broker response did not include a JWT.");return{token:y,expiresAtS:Ht(c)||Gt(y)||Math.floor(Date.now()/1e3)+300}}function Ht(e){const t=e?.expiresAtS??e?.expires_at_s??e?.expiresInS??e?.expires_in_s;if(Number.isFinite(t))return Number(t);const r=e?.expiresIn??e?.expires_in;if(Number.isFinite(r))return Math.floor(Date.now()/1e3)+Number(r);const n=e?.expiresAt??e?.expires_at;if(typeof n=="string"){const o=Date.parse(n);if(Number.isFinite(o))return Math.floor(o/1e3)}return null}function Gt(e){try{const[,t]=e.split(".");if(!t)return null;const r=t.replace(/-/gu,"+").replace(/_/gu,"/"),n=atob(r.padEnd(Math.ceil(r.length/4)*4,"=")),o=JSON.parse(n);return Number.isFinite(o?.exp)?Number(o.exp):null}catch{return null}}var Pe={unauthorized:{code:"auth",message:"Assistant authentication failed. Please retry."},forbidden:{code:"auth",message:"Assistant authentication failed. Please retry."},unknown_op:{code:"op_unavailable",message:"This assistant action is not available yet."},invalid_input:{code:"invalid_request",message:"The assistant request was not valid."},account_config:{code:"account_config",message:"Assistant configuration is unavailable."},upstream_llm:{code:"op_failed",message:"The assistant could not complete that request."},upstream_timeout:{code:"op_timeout",message:"The assistant took too long to respond."},schema_mismatch:{code:"op_failed",message:"The assistant could not complete that request."},rate_limited:{code:"rate_limited",message:"The assistant is receiving too many requests. Please retry shortly."},internal:{code:"op_failed",message:"The assistant could not complete that request."},payload_too_large:{code:"invalid_request",message:"The assistant request was too large."}},F=class extends Error{constructor(e,t,r={}){super(t),this.name="AgentError",this.code=e,this.source=r.source||"agent",r.sourceCode&&(this.sourceCode=r.sourceCode),r.detail!==void 0&&(this.detail=r.detail)}};function X(e){const t=String(e?.code||"upstream_llm"),r=Pe[t]||Pe.upstream_llm;return new F(r.code,r.message,{source:"be",sourceCode:t,detail:e?.detail})}function je(e,t){const r=t?.error&&typeof t.error=="object"?t.error:{};return X({code:String(r.code||Wt(e)),detail:r.detail})}function xe(e){return e instanceof F?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function Wt(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var Qt=7200*1e3,Ce=200,Vt=5*1024*1024,Yt="gengage_request_response_cache",Xt=1,E="responses",Zt=new Set(["addToCart","like"]),T=new Map,Oe=null;async function er(e,t={},r={}){const n=tr(e,t);if(!n)return fetch(e,t);const o=Date.now(),i=await nr(n,o);if(i)return ar(i);const a=await fetch(e,t);return a.ok&&or(n,a.clone(),o,{ttlMs:r.ttlMs??Qt,maxEntries:r.maxEntries??Ce,maxBodyBytes:r.maxBodyBytes??Vt}),a}function tr(e,t={}){if(typeof Request<"u"&&e instanceof Request)return null;const r=String(t.method||"GET").toUpperCase();return r!=="POST"||typeof t.body!="string"||rr(t.body)?null:`rr:${mr(dr({url:String(e),method:r,headers:cr(t.headers),body:t.body}))}`}function rr(e){try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return!1;const r=t.type;return typeof r=="string"&&Zt.has(r)}catch{return!1}}async function nr(e,t){const r=T.get(e);if(r)if(r.expiresAt<=t)T.delete(e);else return r.lastAccessedAt=t,T.delete(e),T.set(e,r),Z(r),r;const n=await ur(e);return n?n.expiresAt<=t?(T.delete(e),lr(e),null):(n.lastAccessedAt=t,T.set(e,n),Z(n),Ie(Ce),n):null}async function or(e,t,r,n){try{const o=await t.text();if(yr(o)>n.maxBodyBytes||ir(o))return;const i={key:e,status:t.status,statusText:t.statusText,headers:sr(t.headers),body:o,createdAt:r,expiresAt:r+n.ttlMs,lastAccessedAt:r};T.set(e,i),Ie(n.maxEntries),await Z(i),await fr(n.maxEntries,r)}catch{}}function ir(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function ar(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function cr(e){const t=new Headers(e),r=[];return t.forEach((n,o)=>{const i=o.toLowerCase();i!=="authorization"&&i!=="cookie"&&r.push([i,n])}),r.sort(([n],[o])=>n.localeCompare(o))}function sr(e){const t=[];return e.forEach((r,n)=>{const o=n.toLowerCase();o!=="set-cookie"&&t.push([o,r])}),t.sort(([r],[n])=>r.localeCompare(n))}function Ie(e){for(;T.size>e;){const t=[...T.values()].sort((r,n)=>r.lastAccessedAt-n.lastAccessedAt)[0];if(!t)break;T.delete(t.key)}}async function q(){return typeof indexedDB>"u"?null:(Oe??=new Promise(e=>{const t=indexedDB.open(Yt,Xt);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(E)||r.createObjectStore(E,{keyPath:"key"}).createIndex("lastAccessedAt","lastAccessedAt",{unique:!1})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),Oe)}async function ur(e){const t=await q();return t?new Promise(r=>{const n=t.transaction(E,"readonly"),o=n.objectStore(E).get(e);o.onsuccess=()=>r(o.result??null),o.onerror=()=>r(null),n.onerror=()=>r(null)}):null}async function Z(e){const t=await q();t&&await new Promise(r=>{const n=t.transaction(E,"readwrite");n.objectStore(E).put(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function lr(e){const t=await q();t&&await new Promise(r=>{const n=t.transaction(E,"readwrite");n.objectStore(E).delete(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function fr(e,t){const r=await q();r&&await new Promise(n=>{const o=r.transaction(E,"readwrite"),i=o.objectStore(E),a=[],c=i.openCursor();c.onsuccess=()=>{const y=c.result;if(!y){const m=a.filter(u=>u.expiresAt<=t),d=a.filter(u=>u.expiresAt>t).sort((u,l)=>u.lastAccessedAt-l.lastAccessedAt).slice(0,Math.max(0,a.length-m.length-e));for(const u of[...m,...d])i.delete(u.key);return}a.push(y.value),y.continue()},c.onerror=()=>n(),o.oncomplete=()=>n(),o.onerror=()=>n(),o.onabort=()=>n()})}function dr(e){return JSON.stringify(ee(e))}function ee(e){return Array.isArray(e)?e.map(ee):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ee(r)]))}function mr(e){let t=14695981039346656037n;const r=1099511628211n;for(let n=0;n<e.length;n+=1)t^=BigInt(e.charCodeAt(n)),t=BigInt.asUintN(64,t*r);return t.toString(16).padStart(16,"0")}function yr(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function pr({beUrl:e,accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,jwtProvider:i,parentUrl:a,op:c,input:y,cacheTtlS:m,cacheKey:d,browserCache:u,signal:l}){const f=await(i||Y({accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o}))({...l?{signal:l}:{},...a?{parentUrl:a}:{}}),{opDomain:p,opName:g}=gr(c,t),h={method:"POST",headers:{authorization:`Bearer ${f}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:p,op_name:g,op_payload:y,...m!==void 0?{cache_ttl_s:m}:{},...d!==void 0?{cache_key:d}:{}}),...l?{signal:l}:{}},A=`${String(e).replace(/\/+$/u,"")}/v1/execute`,w=u===!1?await fetch(A,h):await er(A,h,typeof u=="object"?u:{});if(!w.ok)throw je(w.status,await wr(w));return br(w)}function gr(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:hr(t),opName:e}}function hr(e){return e.replace(/-agentic$/u,"")}async function wr(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function br(e){const t=e.body?.getReader();if(!t)throw new Error("BE response body is not readable.");const r=new TextDecoder;let n="";const o={};for(;;){const{value:a,done:c}=await t.read();if(c)break;n+=r.decode(a,{stream:!0});let y=n.indexOf(`
2
- `);for(;y>=0;){const m=n.slice(0,y).trim();n=n.slice(y+1),m&&Re(JSON.parse(m),o),y=n.indexOf(`
3
- `)}}const i=n.trim();return i&&Re(JSON.parse(i),o),o}function Re(e,t){if(e._error)throw X(e._error);if(!e._end)for(const[r,n]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,r))throw new F("op_failed",`BE streamed duplicate field "${r}".`,{source:"be",sourceCode:"schema_mismatch"});t[r]=n}}function Sr(e={}){return{type:"metadata",...e}}function te(e,t=!1,r={}){return{type:"text_chunk",content:e,final:t,...r}}function B(e){return{type:"ui_spec",...e}}function Ar(e){return{type:"action",action:e}}function Me(e,t){return{type:"error",code:e,message:t}}function re(){return{type:"done"}}function Ue(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}async function kr({request:e,accountModule:t,contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,signal:c}){const y=performance.now(),m=await r.load(e),d=m.thread.id,u=Br(e);r.appendUserMessage(d,u);const l=Ue(t.flows,e);if(!l)return i(Me("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(re()),{steps:0,productSkusEmitted:[]};const f={request:e,context:r.patch(d,{})||m,bag:{},accountConfig:t.accountConfig||{},threadId:d,steps:0,productSkusEmitted:new Set,committed:!1},p={contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...c?{signal:c}:{}};return await L(l,f,p),f.committed||await ne(f,p),await a("beacon.send",{type:"turnSummary",threadId:d,sessionId:e?.session_id||e?.sessionId||d,accountId:t.accountId||f.context.meta.accountId,steps:f.steps,totalLatencyMs:O(y),productSkusEmitted:[...f.productSkusEmitted]}),{steps:f.steps,productSkusEmitted:[...f.productSkusEmitted]}}async function L(e,t,r){for(const n of e){if(r.signal?.aborted)return;t.steps+=1,await _r(n,t,r),t.context=r.contextStore.patch(t.threadId,{})||t.context}}async function _r(e,t,r){const n=ie(t);if(e.kind==="be_op"){await Er(e,t,r,n);return}if(e.kind==="tool"){await Tr(e,t,r,n);return}if(e.kind==="adapter"){await Pr(e,t,r,n);return}if(e.kind==="emit"){jr(e,t,r);return}if(e.kind==="branch"){await xr(e,t,r,n);return}if(e.kind==="parallel"){await Cr(e,t,r);return}if(e.kind==="refusal"){await Or(e,t,r,n);return}e.kind==="commit"&&await Ir(e,t,r)}async function Er(e,t,r,n){const o=performance.now();let i;const a=x(e.cacheTtlS,n),c=x(e.cacheKey,n),y=x(e.browserCache,n);try{i=await r.beClient.invoke({op:e.op,input:x(e.input,n),...a!==void 0?{cacheTtlS:a}:{},...c!==void 0?{cacheKey:c}:{},...y!==void 0?{browserCache:y}:{},...r.signal?{signal:r.signal}:{}})}catch(d){const u=d,l=String(u?.sourceCode||u?.code||"unknown"),f={type:"agentOp",threadId:t.threadId,sessionId:t.request?.session_id||t.request?.sessionId||t.threadId,accountId:t.context.meta.accountId,op:e.op,status:"error",latencyMs:O(o),errorCode:l};if(await r.rpc("beacon.send",f),e.onError){e.errorOut&&(t.bag[e.errorOut]=d),await L(e.onError,t,r);return}throw d}e.out&&(t.bag[e.out]=i),oe(e,i,t,r.contextStore);const m={type:"agentOp",threadId:t.threadId,sessionId:t.request?.session_id||t.request?.sessionId||t.threadId,accountId:t.context.meta.accountId,op:e.op,status:"ok",latencyMs:O(o)};await r.rpc("beacon.send",m)}async function Tr(e,t,r,n){const o=performance.now();try{const i=await r.toolBridge.invoke(e.name,x(e.input,n));e.out&&(t.bag[e.out]=i),oe(e,i,t,r.contextStore),await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Be(t),accountId:t.context.meta.accountId,tool:e.name,status:"ok",latencyMs:O(o)})}catch(i){const a=i;if(await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Be(t),accountId:t.context.meta.accountId,tool:e.name,status:"error",latencyMs:O(o),errorCode:String(a?.code||a?.name||"unknown")}),e.onError){e.errorOut&&(t.bag[e.errorOut]=i),await L(e.onError,t,r);return}throw i}}async function Pr(e,t,r,n){const o=r.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);const i=await o(x(e.input,n),n);e.out&&(t.bag[e.out]=i),oe(e,i,t,r.contextStore)}function jr(e,t,r){const n=e.build(ie(t));Lr(n,t.productSkusEmitted),r.emit(n)}async function xr(e,t,r,n){const o=String(x(e.on,n)||"default");await L(e.cases[o]||e.cases.default||[],t,r)}async function Cr(e,t,r){const n=e.steps.map(a=>{const c={...t,context:Rr(t.context),bag:{...t.bag},productSkusEmitted:t.productSkusEmitted,committed:!1};return L(a,c,{...r,contextStore:Mr(c)}).then(()=>c)}),o=await Promise.all(n),i=e.merge||{};for(const a of o){for(const c of i.bag||[])Object.prototype.hasOwnProperty.call(a.bag,c)&&(t.bag[c]=a.bag[c]);if(i.panel?.length){const c=Le(a.context.panel,i.panel);Object.keys(c).length&&(t.context=r.contextStore.patch(t.threadId,{panel:c})||t.context)}if(i.threadExtensions?.length){const c=Le(a.context.thread.extensions,i.threadExtensions);Object.keys(c).length&&(t.context=r.contextStore.patch(t.threadId,{thread:{...t.context.thread,extensions:c}})||t.context)}}}async function Or(e,t,r,n){r.emit(te(x(e.message,n),!0)),await ne(t,r)}async function Ir(e,t,r){await ne(t,r)}async function ne(e,{contextStore:t,emit:r}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,r(re()))}function oe(e,t,r,n){if(typeof e.patch!="function")return;const o=e.patch(r.context,t,ie(r));o&&(r.context=n.patch(r.threadId,o)||r.context)}function ie(e){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig}}function Be(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function Rr(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Le(e,t){const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function Mr(e){return{async load(){return e.context},patch(t,r){return e.context=Ur(e.context,r),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function Ur(e,t){return!t||typeof t!="object"?e:{...e,...t,panel:{...e.panel||{},...t.panel||{}},thread:{...e.thread||{},...t.thread||{},extensions:{...e.thread?.extensions||{},...t.thread?.extensions||{}}},meta:{...e.meta||{},...t.meta||{}},messages:Array.isArray(t.messages)?t.messages.slice(-50):e.messages}}function x(e,t){return typeof e=="function"?e(t):e}function Br(e){const t=e?.payload;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"text"in t){const r=t.text;if(typeof r=="string")return r}return typeof e?.action?.payload=="string"?e.action.payload:typeof e?.action?.title=="string"?e.action.title:""}function Lr(e,t){const r=e,n=r.spec,o=Array.isArray(n?.items)?n.items:void 0,i=Array.isArray(r.items)?r.items:void 0,a=o||i;if(Array.isArray(a)){for(const c of a)if(c&&typeof c=="object"){const y=c.sku;typeof y=="string"&&t.add(y)}}}function Nr(e){return{invoke(t,r){return e("tool.invoke",{name:t,input:r})}}}var Dr=512,vr=.74;function Ne({accountId:e,worker:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:c={},beacon:y}){let m=1;const d=new Map;return Rt({worker:t,tools:c,beacon:u=>y?.({...u,accountId:u.accountId||e}),memory:sessionStorage}),t.addEventListener("message",u=>{const l=u.data||{},f=typeof l.id=="number"?l.id:null;if(f==null)return;const p=d.get(f);if(p){if(l.type==="event"&&l.event){ae(p,l.event);return}if(l.type==="error"){p.onError(new Error(l.message||"Agent worker failed")),d.delete(f);return}l.type==="end"&&d.delete(f)}}),(u,l,f,p)=>{const g=m++;d.set(g,l);const h=()=>{d.delete(g),t.postMessage({id:g,type:"abort"})},A=w=>{if(f.aborted){h();return}t.postMessage({id:g,type:"invoke",accountId:e,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,request:w,parentUrl:window.location.href})};if(f.aborted){h();return}if(f.addEventListener("abort",h,{once:!0}),p){ve(u,p).then(A).catch(w=>{d.delete(g),l.onError(w instanceof Error?w:new Error("Failed to read image attachment"))});return}A(u)}}function De({accountId:e,accountModule:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:c={},beacon:y}){let m=null;const d=$r({accountId:e,tools:c,beacon:y}),u=Nr(d),l=Y({accountId:e,...n?{devJwtSecret:n}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(f,p,g,h)=>{const A=await ve(f||{},h);m||=new ke({accountId:e,locale:A?.locale||a,parentUrl:window.location.href,rpc:d,persistentPanelKeys:t.contextPersistence?.panelKeys});try{await kr({request:A,accountModule:{...t,accountId:e},contextStore:m,beClient:{invoke({op:w,input:he,signal:Ot,cacheTtlS:$o,cacheKey:Fo,browserCache:qo}){return pr({beUrl:r,accountId:e,jwtProvider:l,parentUrl:window.location.href,op:w,input:he,cacheTtlS:$o,cacheKey:Fo,browserCache:qo,...Ot?{signal:Ot}:{}})}},toolBridge:u,emit:w=>ae(p,w),rpc:d,signal:g})}catch(w){g?.aborted||(ae(p,xe(w)),p.onDone())}}}function $r({accountId:e,tools:t,beacon:r}){const n=o=>r?.({...o,accountId:o.accountId||e});return((o,i)=>we(o,i,{tools:t,beacon:n,memory:sessionStorage}))}async function ve(e,t){if(!t||!t.type?.startsWith("image/"))return e;const r=await zr(t),n={...Fr(e.payload??e.action?.payload),image_data_url:r.dataUrl,image_mime:r.mime};return{...e,payload:n,...e.action?{action:{...e.action,payload:n}}:{}}}function Fr(e){return qr(e)?{...e}:typeof e=="string"?{text:e}:{}}function qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function zr(e){const t=await Kr(e);return t||{dataUrl:await $e(e),mime:e.type}}async function Kr(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const r=Math.min(1,Dr/Math.max(t.width,t.height)),n=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),i=document.createElement("canvas");i.width=n,i.height=o;const a=i.getContext("2d");if(!a)return null;a.drawImage(t,0,0,n,o);const c=await new Promise(y=>i.toBlob(y,"image/jpeg",vr));return c?{dataUrl:await $e(c),mime:c.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function $e(e){const t=new Uint8Array(await e.arrayBuffer());let r="";const n=32768;for(let o=0;o<t.length;o+=n)r+=String.fromCharCode(...t.subarray(o,o+n));return`data:${e.type};base64,${btoa(r)}`}function ae(e,t){switch(t?.type){case"text_chunk":{const r=t;e.onTextChunk(r.content||"",r.final===!0,r);break}case"ui_spec":{const r=t;e.onUISpec(r.spec,r.widget,r.panelHint,r.clearPanel===!0);break}case"action":e.onAction(t);break;case"metadata":e.onMetadata(t);break;case"error":e.onError(Jr(t));break;case"done":e.onDone();break;default:break}}function Jr(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}function Fe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function z(e){const t=Fe(e);if(!t)return null;const r=I(t.sku,t.SKU);if(!r)return null;const n={sku:r,name:I(t.name,t.title,t.short_name,r)||r,url:I(t.url)||""},o=Array.isArray(t.images)?t.images:void 0,i=I(t.imageUrl,t.image_url,t.image,o?.[0]);i&&(n.imageUrl=i),o&&o.length>1&&(n.images=o.filter(g=>!!g).map(String));const a=N(t.price_discounted),c=N(t.price),y=a||c;y>0&&(n.price=String(y));const m=a>0?c:0;m>0&&(n.originalPrice=String(m));const d=I(t.brand);d&&(n.brand=d);const u=N(t.rating);u>0&&(n.rating=u);const l=N(t.review_count)||N(t.reviewCount);l>0&&(n.reviewCount=l);const f=I(t.cart_code,t.cartCode);f&&(n.cartCode=f),typeof t.in_stock=="boolean"&&(n.inStock=t.in_stock),typeof t.inStock=="boolean"&&(n.inStock=t.inStock);const p=t.category_names;return Array.isArray(p)&&(n.categoryNames=p.map(String)),n}function K(e){const t=Fe(e);if(!t)return e;const r=t.category_names,n=Array.isArray(r)?r:void 0,o=t.images,i=Array.isArray(o)?o:void 0,a={sku:t.sku,name:t.name||t.title,url:t.url,price:t.price,currency:t.price_currency||t.currency,category:n?.[n.length-1]??void 0,category_names:n?n.slice(0,4):void 0,image:i?i[0]:t.image,in_stock:t.in_stock,rating:t.rating,review_count:t.review_count};for(const c of Object.keys(a))a[c]===void 0&&delete a[c];return a}function Hr(e){return Array.isArray(e)?e.map(K).filter(t=>!!t):[]}function I(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function N(e){const t=Number(e);return Number.isFinite(t)?t:0}function qe(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function Gr(e,t,r={}){return`${e}:${r.version||"v2"}:${R(t)}`}function Wr(e,t={}){return ze(e).map(r=>Ke(typeof r=="string"?r:r.sku,t.locale)).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n).sort((r,n)=>ce(r,n,t.locale)).slice(0,t.limit||16).join(",")}function Qr(e,t={}){return R(ze(e).map(r=>Yr(r,t)).filter(r=>!!r).sort((r,n)=>ce(String(r.sku||r.name||""),String(n.sku||n.name||""),t.locale)).slice(0,t.limit||16))}function Vr(e,t){return C(e,t)}function R(e){let t=2166136261;const r=Xr(e);for(let n=0;n<r.length;n+=1)t^=r.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Yr(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=t.mapProduct?.(r);if(n)return D(n);const o=K(r);return o&&typeof o=="object"&&!Array.isArray(o)?D(Zr(o,t)):null}function ze(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function Xr(e){return JSON.stringify(D(e))}function D(e){return Array.isArray(e)?e.map(D):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,D(r)]))}function Zr(e,t){return{sku:Ke(e.sku,t.locale),name:C(e.name,t.locale),url:C(e.url,t.locale),price:e.price,currency:C(e.currency,t.locale),category:C(e.category,t.locale),category_names:en(e.category_names,t.locale,16),image:C(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function Ke(e,t){return C(e,t).toUpperCase()}function C(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function ce(e,t,r){return e.localeCompare(t,r,{numeric:!0})}function en(e,t,r){return Array.isArray(e)?e.map(n=>C(n,t)).filter(Boolean).sort((n,o)=>ce(n,o,t)).slice(0,r):void 0}var tn="entries",rn=1,nn={volatile:"Hot per-page state and sensitive request context.",session:"Current-visit tool context without raw tokens or PII-heavy payloads.",local:"Small, non-sensitive capability facts or user preferences.",indexedDb:"Larger product/search payload caches with short TTLs."},Je=new Map;function se(){return Date.now()}function ue(e){return e?.expiresAt!=null&&e.expiresAt<=se()}function le(e,t){return{value:e,createdAt:se(),expiresAt:t?se()+t:null}}function on(e,t,r){try{const n=e.getItem(`${t}${r}`);if(!n)return null;const o=JSON.parse(n);return ue(o)?(e.removeItem(`${t}${r}`),null):o.value}catch{return null}}function an(e,t,r,n,o){try{return e.setItem(`${t}${r}`,JSON.stringify(le(n,o))),!0}catch{return!1}}function cn(e,t,r){try{e.removeItem(`${t}${r}`)}catch{}}function He(e){try{return window[e]}catch{return null}}function Ge(e,t){return e?{get:r=>on(e,t,r),set:(r,n,o={})=>an(e,t,r,n,o.ttlMs),remove:r=>cn(e,t,r)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function sn(e,t){const r=t.dbName||`gengage-${e}`,n=t.dbStore||tn,o=t.dbVersion||rn,i=new Map;let a=null;const c=()=>"indexedDB"in window?a||(a=new Promise(u=>{const l=indexedDB.open(r,o);l.onupgradeneeded=()=>{l.result.createObjectStore(n,{keyPath:"key"})},l.onsuccess=()=>u(l.result),l.onerror=()=>u(null),l.onblocked=()=>u(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async u=>{const l=await c();return l?new Promise(f=>{const p=l.transaction(n,"readwrite").objectStore(n),g=p.get(u);g.onsuccess=()=>{const h=g.result;if(!h||ue(h)){h&&p.delete(u),f(null);return}f(h.value)},g.onerror=()=>f(null)}):null},idbSet:async(u,l,f={})=>{const p=await c();return p?new Promise(g=>{const h=p.transaction(n,"readwrite");h.oncomplete=()=>g(!0),h.onerror=()=>g(!1),h.objectStore(n).put({key:u,...le(l,f.ttlMs)})}):!1},idbRemove:async u=>{const l=await c();l&&l.transaction(n,"readwrite").objectStore(n).delete(u)}}}function fe(e,t={}){const r=window,n=r.gengage||(r.gengage={}),o=n.memory||(n.memory={}),i=o[e];if(i)return i;const a=Je.get(e)||sn(e,t);Je.set(e,a);const c=t.sessionPrefix||`gengage:${e}:session:`,y=t.localPrefix||`gengage:${e}:local:`,d={get:f=>{const p=a.volatileEntries.get(f);return p?ue(p)?(a.volatileEntries.delete(f),null):p.value:null},set:(f,p,g={})=>(a.volatileEntries.set(f,le(p,g.ttlMs)),!0),remove:f=>{a.volatileEntries.delete(f)},clear:()=>a.volatileEntries.clear()},u={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},l={accountId:e,volatile:d,session:Ge(He("sessionStorage"),c),local:Ge(He("localStorage"),y),indexedDb:u,stableKey:R,policy:{...nn,...t.policy||{}}};o[e]=l;for(const f of t.aliases||[])o[f]=l;return l}var J="__gengageAgentFetchBridge",un=1e3*60*60*24*14;function ln({accountId:e,streamTransport:t,endpoints:r={},endpointCache:n}){if(!e)throw new Error("accountId is required.");if(typeof t!="function")throw new Error("streamTransport is required.");const o=fn(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,c=n?hn({accountId:e,endpointCache:n,fetchImpl:o.originalFetch}):void 0,y=m=>{const d=`${i}/chat/${m}`;a.add(d);const u=r[m],l={streamTransport:t,endpoint:m};u&&(l.endpointHandler=u),c&&(l.endpointCache=c),o.routes.set(d,l)};y("process_action");for(const m of Object.keys(r))m!=="process_action"&&y(m);return{middlewareUrl:i,stop(){for(const m of a)o.routes.delete(m);dn(o)}}}function fn(){const e=window,t=e[J];if(t)return t;const r=e.fetch.bind(e),n={routes:new Map,originalFetch:r,installedFetch:r};return n.installedFetch=(o,i)=>{const a=We(o),c=n.routes.get(a);return c?yn(c,o,i):r(o,i)},e.fetch=n.installedFetch,e[J]=n,n}function dn(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[J]===e&&delete t[J]}function We(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function Qe(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function Ve(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function mn(e,t){const r=Ve(e,t);if(r instanceof FormData){const o=r.get("request"),i=r.get("attachment");return{request:JSON.parse(String(o||"{}")),...i instanceof File?{attachment:i}:{}}}const n=await Promise.resolve(r);return typeof n=="string"?{request:JSON.parse(n||"{}")}:{request:{}}}async function yn(e,t,r){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const m=new AbortController,d=Qe(t,r);let u=null;if(d){const l=()=>m.abort();d.aborted&&l(),d.addEventListener("abort",l,{once:!0}),u=()=>d.removeEventListener("abort",l)}try{const l=await pn(t,r),f={accountId:gn(t),endpoint:e.endpoint,signal:m.signal},p=wn(e.endpointCache,e.endpoint,l,f.accountId);if(p){const h=await bn(e.endpointCache,p,m.signal);if(h)return Tn(h)}const g=await e.endpointHandler(l,f);return p&&g.ok&&await Sn(e.endpointCache,p,g.clone(),m.signal),g}finally{u?.()}}const n=new TextEncoder,o=new AbortController,i=Qe(t,r);let a=!1,c=null;const y=new ReadableStream({async start(m){const d=f=>{a||m.enqueue(n.encode(`${JSON.stringify(f)}
4
- `))},u=()=>{a||(a=!0,c?.(),m.close())},l=f=>{d({type:"error",code:f?.code||"agent_bridge_error",message:f instanceof Error?f.message:String(f)}),d({type:"done"}),u()};if(i){const f=()=>{o.abort(),a||(a=!0,c?.(),m.error(new DOMException("Aborted","AbortError")))};if(i.aborted){f();return}i.addEventListener("abort",f,{once:!0}),c=()=>i.removeEventListener("abort",f)}try{const{request:f,attachment:p}=await mn(t,r),g=e.streamTransport(f,{onTextChunk:(h,A,w={})=>d({type:"text_chunk",content:h,final:A===!0,...w}),onUISpec:(h,A,w,he)=>d({type:"ui_spec",spec:h,widget:A,...w?{panelHint:w}:{},...he?{clearPanel:!0}:{}}),onAction:h=>{d(h?.type==="action"?h:{type:"action",action:h})},onMetadata:h=>{d(h?.type==="metadata"?h:{type:"metadata",...h})},onError:l,onDone:()=>{d({type:"done"}),u()}},o.signal,p);Cn(g)&&(await g,o.signal.aborted||(d({type:"done"}),u()))}catch(f){o.signal.aborted||l(f)}},cancel(){o.abort(),c?.(),a=!0}});return new Response(y,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}async function pn(e,t){const r=await Promise.resolve(Ve(e,t));return typeof r!="string"||r.trim()===""?{}:JSON.parse(r)}function gn(e){try{const[t]=new URL(We(e)).pathname.split("/").filter(Boolean);return decodeURIComponent(t||"")}catch{return""}}function hn({accountId:e,endpointCache:t,fetchImpl:r}){return{accountId:e,beUrl:t.beUrl,...t.parentUrl?{parentUrl:t.parentUrl}:{},ttlMs:t.ttlMs??un,policies:t.policies,fetchImpl:r,jwtProvider:Y({accountId:e,...t.devJwtSecret?{devJwtSecret:t.devJwtSecret}:{},...t.tokenBrokerUrl?{tokenBrokerUrl:t.tokenBrokerUrl}:{},...t.tokenBrokerAudience?{tokenBrokerAudience:t.tokenBrokerAudience}:{},fetchImpl:r})}}function wn(e,t,r,n){if(!e)return null;const o=e.policies[t];if(!o)return null;const i=o(r,{accountId:n,endpoint:t});return!i?.partition||!i?.key?null:{partition:i.partition,key:i.key,ttlMs:i.ttlMs??e.ttlMs}}async function bn(e,t,r){const n=et(e.accountId,t),o=await Pn(e.accountId,n);if(Ze(o))return o;const i=await An(e,t,r);return i?(await tt(e.accountId,n,i,t.ttlMs),i):null}async function Sn(e,t,r,n){try{const o=await En(r);if(xn(o.body))return;const i=et(e.accountId,t);await tt(e.accountId,i,o,t.ttlMs),kn(e,t,o,n)}catch{}}async function An(e,t,r){try{const n=await e.fetchImpl(Xe(e.beUrl),{method:"POST",headers:await Ye(e,r),body:JSON.stringify({partition:t.partition,key:t.key}),signal:r});if(!n.ok)return null;const o=await n.json();return o.hit===!0&&Ze(o.payload)?o.payload:null}catch{return null}}async function kn(e,t,r,n){try{await e.fetchImpl(Xe(e.beUrl),{method:"POST",headers:await Ye(e,n),body:JSON.stringify({partition:t.partition,key:t.key,ttl_s:Math.max(1,Math.ceil(t.ttlMs/1e3)),payload:r}),signal:n})}catch{}}async function Ye(e,t){return{authorization:`Bearer ${await e.jwtProvider({signal:t,parentUrl:e.parentUrl||_n()})}`,"content-type":"application/json",accept:"application/json"}}function _n(){try{return window.location?.href||""}catch{return""}}function Xe(e){return`${String(e).replace(/\/+$/u,"")}/v1/cache`}async function En(e){return{status:e.status,statusText:e.statusText,headers:[...e.headers.entries()].filter(([t])=>jn(t)),body:await e.text()}}function Tn(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function Ze(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.body=="string"&&Array.isArray(t.headers)}function et(e,t){return`endpoint-response:${R({accountId:e,partition:t.partition,key:t.key})}`}async function Pn(e,t){const r=fe(e);return r.volatile.get(t)||await r.indexedDb.get(t)||r.local.get(t)}async function tt(e,t,r,n){const o=fe(e);o.volatile.set(t,r,{ttlMs:n}),await o.indexedDb.set(t,r,{ttlMs:n})||o.local.set(t,r,{ttlMs:n})}function jn(e){return["content-type","cache-control"].includes(e.toLowerCase())}function xn(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function Cn(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function On({accountId:e,beUrl:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,workerUrl:i,defaultLocale:a="en-GB",accountModule:c,tools:y={},beacon:m,allowBlobWorker:d=!1}){if(!e)throw new Error("accountId is required.");if(!t)throw new Error("beUrl is required. The injector owns backend URLs; the SDK has no default.");if(!i)throw new Error("workerUrl is required.");const u=window,l=u.GengageAssistantInjector||(u.GengageAssistantInjector={}),f=l[e]||(l[e]={});if(f.agentController)return f.agentController;const p=de(i)||d?rt(i,`gengage-${e}-agent`,{allowBlobWorker:d}):null;p||m?.({type:"agentRuntime",accountId:e,transport:"main-thread",reason:"cross-origin-worker-url",workerUrl:i}),f.streamTransport=p?Ne({accountId:e,worker:p.worker,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:y,...m?{beacon:m}:{}}):De({accountId:e,accountModule:c,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:y,...m?{beacon:m}:{}});const g={type:"agent",stop(){delete f.streamTransport,p?.worker.terminate(),p?.cleanup(),delete f.agentController},diagnostics(){return{accountId:e,beUrl:t,workerUrl:i,mounted:!0,transport:p?"worker":"main-thread",transportReason:p?"module-worker":"cross-origin-worker-url",flows:Object.keys(c?.flows||{})}}};return f.agentController=g,g}function de(e){const t=new URL(e,window.location.href);return t.origin===window.location.origin||t.protocol==="blob:"}function rt(e,t,r={}){const n=new URL(e,window.location.href);if(de(e))return{worker:new Worker(n.href,{type:"module",name:t}),cleanup(){}};if(!r.allowBlobWorker)throw new Error("Cross-origin agent workers require allowBlobWorker=true or a same-origin workerUrl.");const o=new Blob([`import ${JSON.stringify(n.href)};
5
- `],{type:"text/javascript"}),i=URL.createObjectURL(o);try{return{worker:new Worker(i,{type:"module",name:t}),cleanup(){URL.revokeObjectURL(i)}}}catch(a){throw URL.revokeObjectURL(i),a}}function In(e,t={}){if(!Array.isArray(e))return[];const r=t.maxItems??8,n=t.maxFeatures??8;return e.map(o=>Rn(o,t.defaultBrand,n)).filter(o=>!!o).slice(0,r)}function Rn(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,o=K(n);return o?Bn({sku:o.sku,name:o.name,url:o.url,image:o.image,price:o.price,currency:o.currency,category:o.category,category_names:o.category_names,brand:n.brand||t,features:Mn(n.features,r),specs:Un(n.specs,r),in_stock:o.in_stock}):null}function Mn(e,t){return Array.isArray(e)?e.filter(Boolean).slice(0,t):void 0}function Un(e,t){if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).filter(([,r])=>r!=null).slice(0,t))}function Bn(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function me(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,r=Array.isArray(t.rows)?t.rows:[];return{...t,rows:r.map(Nn).filter(Boolean)}}function nt(e,t){const r=Array.isArray(e)?e.filter(c=>!!(c&&typeof c=="object"&&!Array.isArray(c))):[],n=me(t),o=Array.isArray(n.columns)?n.columns.map(String):[];if(!o.length)return r;const i=new Map(r.map(c=>[String(c.sku||c.id||""),c])),a=o.map(c=>i.get(c)).filter(c=>!!c);return a.length?a:r}function Ln(e,t){const r=me(e?.table),n=nt(t,r);return{...e||{},table:r,products:n,multiple_product_details:n}}function Nn(e){return!e||typeof e!="object"||Array.isArray(e)?null:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ot(e=[]){const t={},r=[];return(Array.isArray(e)?e.map(z).filter(n=>!!n):[]).forEach((n,o)=>{const i=`product-${o.toString()}`;r.push(i);const a={sku:n.sku,product:n};t[i]={type:"ProductCard",props:{product:n,index:o,action:{title:n.name,type:"launchSingleProduct",payload:a}}}}),t.root={type:"ProductGrid",props:{layout:"grid"},children:r},{widget:"chat",panelHint:"panel",spec:{root:"root",elements:t}}}function it(e){return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:z(e)||e||{}}}}}}}function at(e={}){const t=(e.multiple_product_details||e.products||[]).map(z).filter(n=>!!n),r=e.table||{};return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:{products:t,recommended:t.find(n=>n.sku===e.recommended_choice_sku)||t[0],attributes:Object.entries(r).map(([n,o])=>({label:n,values:Array.isArray(o)?o.map(String):[String(o??"")]})),highlights:qe(e.key_differences),specialCases:qe(e.special_considerations),recommendedText:e.recommended_choice,productActions:Object.fromEntries(t.map(n=>[n.sku,{title:n.name,type:"launchSingleProduct",payload:{sku:n.sku,product:n}}]))}}}}}}function ct(e=[]){return{widget:"chat",panelHint:"inline",spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:(Array.isArray(e)?e:[]).map(t=>{const r=t.label||t.title||t.shortName||"",n=t.action||t.requestDetails||t.request_details;return!r||!n?.type?null:{label:r,action:{title:r,type:n.type,...n.payload!==void 0?{payload:n.payload}:{}}}}).filter(t=>!!t)}}}}}}function Dn(e){return Object.freeze([...e])}var st=new Set(["and","are","for","from","the","with"]),vn={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},$n=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function k(e){return String(e??"").normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function _(e,t=st){const r=t instanceof Set?t:new Set([...st,...t]),n=new Set,o=[];for(const i of k(e).split(/\s+/u))i.length<3||r.has(i)||n.has(i)||(n.add(i),o.push(i));return o}function v(e,t={}){if(Kn(e))return e;const r=t.facetKeys,n=S(e.category_names??e.category),o=S(e.category_ids),i=Jn(e.facet_hits),a=Object.entries(i).filter(([g])=>!r||r.some(h=>k(h)===k(g))).map(([,g])=>g),c=P(e.name,e.title),y=P(e.brand),m=t.sourceKeywords??[],d=[c,y,...n,...a,...S(e.promotions),P(e.description),...m].join(" "),u=_(d,t.stopWords),l=P(t.sourceProductType,Wn(n,c,u),u[0]),f=j([...Gn(d,$n),...Object.entries(i).filter(([g])=>/colou?r/iu.test(g)).flatMap(([,g])=>_(g,t.stopWords))]),p=j([...a.flatMap(g=>_(g,t.stopWords)),...S(e.promotions).flatMap(g=>_(g,t.stopWords))]).slice(0,24);return{sku:P(e.sku),title:c,brand:y,productType:l,categoryNames:n,categoryIds:o,facets:i,keywords:j([...m.flatMap(g=>_(g,t.stopWords)),...u]).slice(0,12),tokens:u,colors:f,attributes:p,price:Hn(e)}}function Fn(e,t={}){const r=P(e.product_type,e.productType),n=P(e.title,r,S(e.keywords).join(" ")),o=j([...S(e.keywords),...S(e.colors),...S(e.materials),...S(e.styles),...S(e.attributes)]);return v({sku:"__photo__",name:n,category_names:r?[r]:[],facet_hits:{colors:S(e.colors).join(", "),materials:S(e.materials).join(", "),styles:S(e.styles).join(", "),attributes:S(e.attributes).join(", ")},promotions:o},{...t,sourceProductType:r,sourceKeywords:o})}function qn(e,t={}){const r=v(e,t);return j([...t.sourceQueries??[],H([r.productType,...r.colors.slice(0,1),...r.attributes.slice(0,2)]),H([r.productType,...r.keywords.slice(0,3)]),H([r.categoryNames[r.categoryNames.length-1],...r.keywords.slice(0,2)]),H(r.title.split(/\s+/u).slice(0,6)),r.productType].map(n=>n.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function ut(e,t,r={}){const n={...vn,...r.weights},o=v(t,r),i=[],a=M(e.tokens,o.tokens),c=M(e.keywords,o.tokens),y=Qn(e.categoryNames,o.categoryNames)||M(lt(e.categoryNames),lt(o.categoryNames)),m=M(e.attributes,o.attributes),d=M(e.colors,o.colors),u=M(e.attributes,o.tokens),l=Vn(e.price,o.price),f=Yn(o.sku,r.hitCounts)>0?1:0,p=Xn(e,o),g=a*n.token+c*n.keyword+y*n.category+m*n.facet+d*n.color+u*n.attribute+l*n.price+f*n.retrieval,h=Zn(p?g:g*.35);return p&&e.productType&&e.productType===o.productType&&i.push("same product type"),y>.4&&i.push("similar category"),m>.2&&i.push("matching product attributes"),d>0&&i.push("matching colour"),l>.8&&i.push("similar price"),p||i.push("weaker product-type match"),{score:Number(h.toFixed(4)),reasons:i}}function zn(e,t,r={}){const n=v(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean));return t.filter(i=>{const a=P(i.sku);return a&&!o.has(a)}).map(i=>{const a=ut(n,i,r);return{...i,similarity_score:a.score,similarity_reasons:a.reasons}}).sort((i,a)=>a.similarity_score-i.similarity_score).slice(0,Math.max(1,Math.min(r.limit??12,100)))}function Kn(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function P(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function S(e){return Array.isArray(e)?e.map(t=>P(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function Jn(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,P(r)]).filter(([,t])=>t))}function Hn(e){const t=Number(e.price_discounted);if(Number.isFinite(t)&&t>0)return t;const r=Number(e.price);return Number.isFinite(r)&&r>0?r:0}function j(e){const t=new Set,r=[];for(const n of e){const o=k(n);!o||t.has(o)||(t.add(o),r.push(o))}return r}function Gn(e,t){const r=` ${k(e)} `;return t.filter(n=>r.includes(` ${k(n)} `))}function Wn(e,t,r){const n=k(e[e.length-1]??e[0]??"");if(n){const o=_(n),i=new Set(_(t));return o.find(a=>i.has(a))??o[0]??n}return r[0]??""}function H(e){return e.map(t=>k(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function lt(e){return e.flatMap(t=>_(t))}function M(e,t){const r=j(e),n=new Set(j(t));return r.length===0||n.size===0?0:r.filter(o=>n.has(o)).length/r.length}function Qn(e,t){const r=j(e),n=new Set(j(t));return r.length===0||n.size===0?0:r.filter(o=>n.has(o)).length/r.length}function Vn(e,t){return e<=0||t<=0?0:Math.min(e,t)/Math.max(e,t)}function Yn(e,t){return!e||!t?0:typeof t.get=="function"?t.get(e)??0:t[e]??0}function Xn(e,t){if(!e.productType||!t.productType||e.productType===t.productType)return!0;const r=new Set(_(e.productType)),n=new Set([..._(t.productType),...t.tokens]);return[...r].some(o=>n.has(o))}function Zn(e){return Math.max(0,Math.min(1,e))}function eo(e,t={}){if(!Array.isArray(e))return[];const r=e.filter(n=>!!(n&&typeof n=="object"&&!Array.isArray(n))).map((n,o)=>({product:n,index:o,score:ft(n,t)})).sort((n,o)=>o.score-n.score||n.index-o.index).map(({product:n})=>n);return typeof t.limit=="number"?r.slice(0,t.limit):r}function ft(e,t={}){const r=dt(t),n=ye(e);let o=0;for(const i of r)n.includes(i)&&(o+=i.length>3?3:1);return mt(e)&&(o+=2),yt(e)&&(o+=2),pt(e)&&(o+=1),e.in_stock===!1&&(o-=5),o}function dt(e={}){const t=[e.query,e.searchInput?.brands,e.searchInput?.categories,e.searchInput?.features,e.searchInput?.keywords,e.intent?.brands,e.intent?.categories,e.intent?.keywords];return[...new Set(t.flatMap(to))]}function mt(e){return e.price!=null||e.price_discounted!=null||e.priceText!=null}function yt(e){return!!(e.image||e.imageUrl||Array.isArray(e.images)&&e.images[0])}function pt(e){return!!(e.category||e.category_names||e.features||e.specs||e.facet_hits)}function ye(e){return k([e.name,e.title,e.brand,e.category,e.category_names,e.features,e.specs,e.facet_hits].flatMap(G).join(" "))}function gt(e){return k(typeof e=="string"?e:e==null?"":String(e))}function to(e){return G(e).join(" ").split(/\s+/u).map(gt).filter(t=>t.length>1)}function G(e){return Array.isArray(e)?e.flatMap(G):e&&typeof e=="object"?Object.values(e).flatMap(G):e==null?[]:[String(e)]}function W(e){if(!Array.isArray(e))return[];const t=new Set,r=[];for(const n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;const o=n,i=String(o.sku||o.url||o.name||"");!i||t.has(i)||(t.add(i),r.push(o))}return r}function ro(e,t){const r=W(e);if(!t||typeof t!="object"||Array.isArray(t))return r;const n=Object.values(t).flatMap(o=>Array.isArray(o)?o:[o]).map(o=>String(o||"").trim().toLocaleLowerCase()).filter(Boolean);return n.length?r.filter(o=>{const i=ye(o);return n.some(a=>i.includes(a))}):r}function no(e,t,r=8){const n=W(e),o=W(t),i=new Set(o.map(a=>String(a.sku||a.url||a.name||"")));return n.map((a,c)=>({product:a,index:c,score:ht(a,i)})).sort((a,c)=>c.score-a.score||a.index-c.index).map(({product:a})=>a).slice(0,r)}function ht(e,t){const r=String(e.sku||e.url||e.name||"");return t.has(r)?10:0}function wt(e,t={}){const r=e.sku,n=t.labels||{};return[t.includeCompare!==!1&&r?Q(n.compare||"Compare",{type:"compare",payload:{skus:[r]}}):null,t.includeSpecs!==!1&&r?Q(n.specs||"Specs",{type:"productQuestion",payload:{sku:r,text:n.specs||"Specs"}}):null,t.includeSimilar!==!1&&r?Q(n.similar||"Similar",{type:"findSimilar",payload:{sku:r}}):null].filter(o=>!!o)}function oo(e,t={}){return Array.isArray(e)?e.flatMap(r=>r&&typeof r=="object"&&!Array.isArray(r)?wt(r,t):[]):[]}function Q(e,t){return{label:pe(e),requestDetails:t}}function io(e,t=4){return Array.isArray(e)?e.map(r=>r&&typeof r=="object"&&!Array.isArray(r)?r:null).filter(r=>!!r).map(r=>({...r,label:pe(r.label)})).filter(r=>r.label).slice(0,t):[]}function pe(e,t=48){const r=typeof e=="string"?e.trim().replace(/\s+/gu," "):"";return r.length>t?`${r.slice(0,t-1).trim()}...`:r}function ao(e={}){return e.steps?[...e.steps]:V("intent","intent",e)}function co(e={}){return e.steps?[...e.steps]:[At("search","products",e),...e.emitProducts===!1?[]:[kt(e.out||"products")],...$(e)]}function bt(e={}){if(e.steps)return[...e.steps];const t=e.out||"answer";return[...V("product-answer","answer",e),...e.emitProductDetails?[po("product")]:[],...$(e,t)]}function so(e={}){return bt(e)}function uo(e={}){if(e.steps)return[...e.steps];const t=e.out||"comparison";return[...V("compare","comparison",e),...e.emitComparison===!1?[]:[_t(t)],...$(e,t)]}function lo(e={}){return e.steps?[...e.steps]:[At("search","products",e)]}function fo(e={}){return St(e)}function St(e={}){return e.steps?[...e.steps]:[_t(e.out||"comparison"),...$(e,"comparison")]}function mo(e={}){return e.steps?[...e.steps]:[kt(e.out||"products"),...$(e,"products")]}function yo(e={}){return e.steps?[...e.steps]:[...V("suggested-actions","suggestedActions",e),...e.emitActions===!1?[]:[go(e.out||"suggestedActions")]]}function V(e,t,r){return[{kind:"be_op",op:r.beOpName||e,input:r.input??(()=>({})),...r.cacheTtlS!==void 0?{cacheTtlS:r.cacheTtlS}:{},...r.cacheKey!==void 0?{cacheKey:r.cacheKey}:{},...r.browserCache!==void 0?{browserCache:r.browserCache}:{},...r.errorOut?{errorOut:r.errorOut}:{},...r.onError?{onError:r.onError}:{},...r.patch?{patch:r.patch}:{},out:r.out||t}]}function At(e,t,r){return{kind:"tool",name:r.toolName||e,input:r.input??(()=>({})),...r.errorOut?{errorOut:r.errorOut}:{},...r.onError?{onError:r.onError}:{},...r.patch?{patch:r.patch}:{},out:r.out||t}}function kt(e){return{kind:"emit",build:({bag:t})=>B(ot(wo(t[e])))}}function po(e){return{kind:"emit",build:({bag:t})=>B(it(t[e]))}}function _t(e){return{kind:"emit",build:({bag:t})=>B(at(t[e]))}}function go(e){return{kind:"emit",build:({bag:t})=>B(ct(bo(t[e])))}}function $(e,t){return!e.emitText&&!t?[]:[{kind:"emit",build:r=>te(ho(e.emitText,r,t),!0)}]}function ho(e,t,r){if(typeof e=="function")return e(t);if(typeof e=="string")return e;const n=r?t.bag[r]:void 0;return String(n?.answer_html||n?.plain_text||n?.summary||"")}function wo(e){return Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.products)?e.products:[]}function bo(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e;if(Array.isArray(t.actions))return t.actions;if(Array.isArray(t.buttons))return t.buttons}return[]}function Et(e,t,r="v1"){return`endpoint:${r}:${R({endpoint:e,request:t})}`}function So(e){const t=e.version||"v1",r=n=>o=>({partition:`${e.partitionPrefix}/${n}`,key:Et(n,o,t),...e.ttlMs?{ttlMs:e.ttlMs}:{}});return{launcher_action:r("launcher_action"),similar_products:r("similar_products"),product_groupings:r("product_groupings")}}function Ao(e){return{...e}}function ko(e,t={}){return new Response(e.map(r=>JSON.stringify(r)).join(`
1
+ (function(f){Object.defineProperty(f,Symbol.toStringTag,{value:"Module"});function at(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function ct({worker:e,tools:t={},beacon:n,memory:r=sessionStorage}){e.addEventListener("message",o=>{const i=o.data;at(i)&&st(e,i,{tools:t,beacon:n,memory:r})})}async function st(e,t,n){try{const r=await ue(t.method,t.payload,n);e.postMessage({type:"rpc.result",rpcId:t.rpcId,ok:!0,value:r})}catch(r){e.postMessage({type:"rpc.result",rpcId:t.rpcId,ok:!1,error:{message:r instanceof Error?r.message:String(r)}})}}function ut(e){if(e&&typeof e=="object"&&typeof e.name=="string")return e;throw new Error("tool.invoke requires { name, input }")}function lt(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.get requires { key }")}function dt(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}async function ue(e,t,{tools:n,beacon:r,memory:o}){if(e==="tool.invoke"){const{name:i,input:a}=ut(t),c=n[i];if(typeof c!="function")throw new Error(`Unknown tool: ${i}`);return c(a)}if(e==="beacon.send")return r?.(t),{sent:!0};if(e==="memory.get"){const{key:i}=lt(t),a=o.getItem(String(i));return a?JSON.parse(a):null}if(e==="memory.set"){const{key:i,value:a}=dt(t);return o.setItem(String(i),JSON.stringify(a??null)),{ok:!0}}throw new Error(`Unknown RPC method: ${e}`)}function le(){return new Date().toISOString()}function I(e){return Math.max(0,Math.round(performance.now()-e))}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e){const{accountId:t,locale:n="en-GB",parentUrl:r="",threadId:o,incomingContext:i}=e,a=M(i)?i:{},c=M(a.thread)?a.thread:{},y=M(a.panel)?a.panel:{},m=M(a.meta)?a.meta:{},d=de(a.messages),s={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||le()),extensions:M(c.extensions)?{...c.extensions}:{}},u=String(m.locale||n),l=String(m.parentUrl||r||typeof self<"u"&&self.location?.href||"");return{panel:{...y},messages:d,thread:s,meta:{locale:u,parentUrl:l,accountId:t}}}function mt(e,t){const n=de([t])[0];return n?{...e,messages:[...e.messages,n].slice(-50)}:e}function de(e){return Array.isArray(e)?e.map(t=>{const n=t?.role;return{role:n==="model"?"assistant":typeof n=="string"?n:"",content:String(t?.content||"")}}).filter(t=>(t.role==="user"||t.role==="assistant")&&!!t.content).slice(-50):[]}var yt="gengage:agent:context:";async function pt({accountId:e,threadId:t,rpc:n}){const r=await n("memory.get",{tier:"session",key:fe(e,t)});return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function gt({accountId:e,threadId:t,extensions:n,panel:r,rpc:o}){await o("memory.set",{tier:"session",key:fe(e,t),value:{thread:{extensions:n},...r&&Object.keys(r).length>0?{panel:r}:{}}})}function fe(e,t){return`${yt}${e}:${t}`}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var me=class{#e=new Map;#t;#r;#o;#n;#i;#a;constructor({accountId:e,locale:t,parentUrl:n,rpc:r,persistentPanelKeys:o=[],panelKeyLimits:i={}}){this.#t=e,this.#r=t,this.#o=n,this.#n=r,this.#i=[...new Set(o.filter(Boolean))],this.#a=wt(i)}async load(e){const t=e?.meta?.threadId||e?.session_id||e?.sessionId,n=String(t||"default"),r=this.#e.get(n);if(r)return r;const o=await pt({accountId:this.#t,threadId:n,rpc:this.#n}),i=ft({accountId:this.#t,locale:e?.locale||this.#r,parentUrl:this.#o,threadId:n,incomingContext:St(o,e?.context)});return this.#e.set(n,i),i}patch(e,t){const n=String(e||"default"),r=this.#e.get(n);if(!r)return null;const o=ye(r,typeof t=="function"?t(r):t);return this.#e.set(n,o),o}appendUserMessage(e,t){const n=String(e||"default");if(!t)return this.#e.get(n)??null;const r=this.#e.get(n);if(!r)return null;const o=mt(r,{role:"user",content:t});return this.#e.set(n,o),o}async commit(e){const t=String(e||"default"),n=this.#e.get(t);return n?(await gt({accountId:this.#t,threadId:t,extensions:n.thread.extensions,panel:ht(n.panel,this.#i,this.#a),rpc:this.#n}),n):null}};function ht(e,t,n){if(!t.length||!b(e))return;const r={};for(const o of t)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=bt(e[o],n[o]));return r}function wt(e){const t={};for(const[n,r]of Object.entries(e||{})){const o=Math.floor(Number(r));n&&Number.isFinite(o)&&o>0&&(t[n]=o)}return t}function bt(e,t){return!t||!Array.isArray(e)?e:e.slice(-t)}function St(e,t){return!b(e)&&!b(t)?{}:ye(b(e)?e:{},b(t)?t:{})}function ye(e,t){if(!b(t))return e;const n=e,r=t,o=b(n.panel)?n.panel:{},i=b(r.panel)?r.panel:{},a=b(n.thread)?n.thread:{},c=b(r.thread)?r.thread:{},y=b(a.extensions)?a.extensions:{},m=b(c.extensions)?c.extensions:{},d=b(n.meta)?n.meta:{},s=b(r.meta)?r.meta:{};return{...e,...t,panel:{...o,...i},thread:{...a,...c,extensions:{...y,...m}},meta:{...d,...s},messages:Array.isArray(r.messages)?r.messages.slice(-50):e.messages??[]}}function pe(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function ge(e){return pe(new TextEncoder().encode(JSON.stringify(e)))}async function At({accountId:e,devJwtSecret:t,ttlS:n=300}){if(!t)throw new Error("devJwtSecret is required for local agent mode.");const r=Math.floor(Date.now()/1e3),o=`${ge({alg:"HS256",typ:"JWT"})}.${ge({sub:e,iat:r,exp:r+n,scope:"invoke",jti:crypto.randomUUID?.()||`${r}-${Math.random()}`})}`,i=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",i,new TextEncoder().encode(o));return`${o}.${pe(new Uint8Array(a))}`}function H({accountId:e,devJwtSecret:t,tokenBrokerUrl:n,tokenBrokerAudience:r,refreshSkewS:o=30,fetchImpl:i=fetch}){let a=null;return async({signal:c,parentUrl:y}={})=>{if(t)return At({accountId:e,devJwtSecret:t});if(!n)throw new Error("tokenBrokerUrl is required for production agent mode.");const m=Math.floor(Date.now()/1e3);return a?.token&&a.expiresAtS-o>m||(a=await kt({accountId:e,tokenBrokerUrl:n,tokenBrokerAudience:r,parentUrl:y,signal:c,fetchImpl:i})),a.token}}async function kt({accountId:e,tokenBrokerUrl:t,tokenBrokerAudience:n,parentUrl:r,signal:o,fetchImpl:i}){const a=await i(t,{method:"POST",credentials:"include",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({accountId:e,scope:"invoke",audience:n||void 0,parentUrl:r||void 0}),...o?{signal:o}:{}});if(!a.ok)throw new Error(`Token broker request failed (${a.status}).`);const c=await a.json(),y=c?.token||c?.jwt||c?.access_token;if(!y||typeof y!="string")throw new Error("Token broker response did not include a JWT.");return{token:y,expiresAtS:_t(c)||Et(y)||Math.floor(Date.now()/1e3)+300}}function _t(e){const t=e?.expiresAtS??e?.expires_at_s??e?.expiresInS??e?.expires_in_s;if(Number.isFinite(t))return Number(t);const n=e?.expiresIn??e?.expires_in;if(Number.isFinite(n))return Math.floor(Date.now()/1e3)+Number(n);const r=e?.expiresAt??e?.expires_at;if(typeof r=="string"){const o=Date.parse(r);if(Number.isFinite(o))return Math.floor(o/1e3)}return null}function Et(e){try{const[,t]=e.split(".");if(!t)return null;const n=t.replace(/-/gu,"+").replace(/_/gu,"/"),r=atob(n.padEnd(Math.ceil(n.length/4)*4,"=")),o=JSON.parse(r);return Number.isFinite(o?.exp)?Number(o.exp):null}catch{return null}}var he={unauthorized:{code:"auth",message:"Assistant authentication failed. Please retry."},forbidden:{code:"auth",message:"Assistant authentication failed. Please retry."},unknown_op:{code:"op_unavailable",message:"This assistant action is not available yet."},invalid_input:{code:"invalid_request",message:"The assistant request was not valid."},account_config:{code:"account_config",message:"Assistant configuration is unavailable."},upstream_llm:{code:"op_failed",message:"The assistant could not complete that request."},upstream_timeout:{code:"op_timeout",message:"The assistant took too long to respond."},schema_mismatch:{code:"op_failed",message:"The assistant could not complete that request."},rate_limited:{code:"rate_limited",message:"The assistant is receiving too many requests. Please retry shortly."},internal:{code:"op_failed",message:"The assistant could not complete that request."},payload_too_large:{code:"invalid_request",message:"The assistant request was too large."}},D=class extends Error{constructor(e,t,n={}){super(t),this.name="AgentError",this.code=e,this.source=n.source||"agent",n.sourceCode&&(this.sourceCode=n.sourceCode),n.detail!==void 0&&(this.detail=n.detail)}};function G(e){const t=String(e?.code||"upstream_llm"),n=he[t]||he.upstream_llm;return new D(n.code,n.message,{source:"be",sourceCode:t,detail:e?.detail})}function we(e,t){const n=t?.error&&typeof t.error=="object"?t.error:{};return G({code:String(n.code||Tt(e)),detail:n.detail})}function be(e){return e instanceof D?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function Tt(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var xt=7200*1e3,Se=200,Pt=5*1024*1024,jt="gengage_request_response_cache",Ct=1,_="responses",It=new Set(["addToCart","like"]),E=new Map,Ae=null;async function Ot(e,t={},n={}){const r=Rt(e,t);if(!r)return fetch(e,t);const o=Date.now(),i=await Mt(r,o);if(i)return Lt(i);const a=await fetch(e,t);return a.ok&&Bt(r,a.clone(),o,{ttlMs:n.ttlMs??xt,maxEntries:n.maxEntries??Se,maxBodyBytes:n.maxBodyBytes??Pt}),a}function Rt(e,t={}){if(typeof Request<"u"&&e instanceof Request)return null;const n=String(t.method||"GET").toUpperCase();return n!=="POST"||typeof t.body!="string"||Ut(t.body)?null:`rr:${zt(Kt({url:String(e),method:n,headers:Nt(t.headers),body:t.body}))}`}function Ut(e){try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t.type;return typeof n=="string"&&It.has(n)}catch{return!1}}async function Mt(e,t){const n=E.get(e);if(n)if(n.expiresAt<=t)E.delete(e);else return n.lastAccessedAt=t,E.delete(e),E.set(e,n),W(n),n;const r=await $t(e);return r?r.expiresAt<=t?(E.delete(e),Ft(e),null):(r.lastAccessedAt=t,E.set(e,r),W(r),ke(Se),r):null}async function Bt(e,t,n,r){try{const o=await t.text();if(Jt(o)>r.maxBodyBytes||vt(o))return;const i={key:e,status:t.status,statusText:t.statusText,headers:Dt(t.headers),body:o,createdAt:n,expiresAt:n+r.ttlMs,lastAccessedAt:n};E.set(e,i),ke(r.maxEntries),await W(i),await qt(r.maxEntries,n)}catch{}}function vt(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function Lt(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function Nt(e){const t=new Headers(e),n=[];return t.forEach((r,o)=>{const i=o.toLowerCase();i!=="authorization"&&i!=="cookie"&&n.push([i,r])}),n.sort(([r],[o])=>r.localeCompare(o))}function Dt(e){const t=[];return e.forEach((n,r)=>{const o=r.toLowerCase();o!=="set-cookie"&&t.push([o,n])}),t.sort(([n],[r])=>n.localeCompare(r))}function ke(e){for(;E.size>e;){const t=[...E.values()].sort((n,r)=>n.lastAccessedAt-r.lastAccessedAt)[0];if(!t)break;E.delete(t.key)}}async function $(){return typeof indexedDB>"u"?null:(Ae??=new Promise(e=>{const t=indexedDB.open(jt,Ct);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(_)||n.createObjectStore(_,{keyPath:"key"}).createIndex("lastAccessedAt","lastAccessedAt",{unique:!1})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),Ae)}async function $t(e){const t=await $();return t?new Promise(n=>{const r=t.transaction(_,"readonly"),o=r.objectStore(_).get(e);o.onsuccess=()=>n(o.result??null),o.onerror=()=>n(null),r.onerror=()=>n(null)}):null}async function W(e){const t=await $();t&&await new Promise(n=>{const r=t.transaction(_,"readwrite");r.objectStore(_).put(e),r.oncomplete=()=>n(),r.onerror=()=>n(),r.onabort=()=>n()})}async function Ft(e){const t=await $();t&&await new Promise(n=>{const r=t.transaction(_,"readwrite");r.objectStore(_).delete(e),r.oncomplete=()=>n(),r.onerror=()=>n(),r.onabort=()=>n()})}async function qt(e,t){const n=await $();n&&await new Promise(r=>{const o=n.transaction(_,"readwrite"),i=o.objectStore(_),a=[],c=i.openCursor();c.onsuccess=()=>{const y=c.result;if(!y){const m=a.filter(s=>s.expiresAt<=t),d=a.filter(s=>s.expiresAt>t).sort((s,u)=>s.lastAccessedAt-u.lastAccessedAt).slice(0,Math.max(0,a.length-m.length-e));for(const s of[...m,...d])i.delete(s.key);return}a.push(y.value),y.continue()},c.onerror=()=>r(),o.oncomplete=()=>r(),o.onerror=()=>r(),o.onabort=()=>r()})}function Kt(e){return JSON.stringify(V(e))}function V(e){return Array.isArray(e)?e.map(V):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,V(n)]))}function zt(e){let t=14695981039346656037n;const n=1099511628211n;for(let r=0;r<e.length;r+=1)t^=BigInt(e.charCodeAt(r)),t=BigInt.asUintN(64,t*n);return t.toString(16).padStart(16,"0")}function Jt(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function Ht({beUrl:e,accountId:t,devJwtSecret:n,tokenBrokerUrl:r,tokenBrokerAudience:o,jwtProvider:i,parentUrl:a,op:c,input:y,cacheTtlS:m,cacheKey:d,browserCache:s,signal:u}){const l=await(i||H({accountId:t,devJwtSecret:n,tokenBrokerUrl:r,tokenBrokerAudience:o}))({...u?{signal:u}:{},...a?{parentUrl:a}:{}}),{opDomain:p,opName:g}=Gt(c,t),h={method:"POST",headers:{authorization:`Bearer ${l}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:p,op_name:g,op_payload:y,...m!==void 0?{cache_ttl_s:m}:{},...d!==void 0?{cache_key:d}:{}}),...u?{signal:u}:{}},A=`${String(e).replace(/\/+$/u,"")}/v1/execute`,w=s===!1?await fetch(A,h):await Ot(A,h,typeof s=="object"?s:{});if(!w.ok)throw we(w.status,await Vt(w));return Yt(w)}function Gt(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:Wt(t),opName:e}}function Wt(e){return e.replace(/-agentic$/u,"")}async function Vt(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function Yt(e){const t=e.body?.getReader();if(!t)throw new Error("BE response body is not readable.");const n=new TextDecoder;let r="";const o={};for(;;){const{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let y=r.indexOf(`
2
+ `);for(;y>=0;){const m=r.slice(0,y).trim();r=r.slice(y+1),m&&_e(JSON.parse(m),o),y=r.indexOf(`
3
+ `)}}const i=r.trim();return i&&_e(JSON.parse(i),o),o}function _e(e,t){if(e._error)throw G(e._error);if(!e._end)for(const[n,r]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,n))throw new D("op_failed",`BE streamed duplicate field "${n}".`,{source:"be",sourceCode:"schema_mismatch"});t[n]=r}}function Qt(e={}){return{type:"metadata",...e}}function Ee(e,t=!1,n={}){return{type:"text_chunk",content:e,final:t,...n}}function Xt(e){return{type:"ui_spec",...e}}function Zt(e){return{type:"action",action:e}}function Te(e,t){return{type:"error",code:e,message:t}}function Y(){return{type:"done"}}function xe(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}async function en({request:e,accountModule:t,contextStore:n,beClient:r,toolBridge:o,emit:i,rpc:a,signal:c}){const y=performance.now(),m=await n.load(e),d=m.thread.id,s=pn(e);n.appendUserMessage(d,s);const u=xe(t.flows,e);if(!u)return i(Te("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(Y()),{steps:0,productSkusEmitted:[]};const l={request:e,context:n.patch(d,{})||m,bag:{},accountConfig:t.accountConfig||{},threadId:d,steps:0,productSkusEmitted:new Set,committed:!1},p={contextStore:n,beClient:r,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...c?{signal:c}:{}};return await B(u,l,p),l.committed||await Q(l,p),await a("beacon.send",{type:"turnSummary",threadId:d,sessionId:e?.session_id||e?.sessionId||d,accountId:t.accountId||l.context.meta.accountId,steps:l.steps,totalLatencyMs:I(y),productSkusEmitted:[...l.productSkusEmitted]}),{steps:l.steps,productSkusEmitted:[...l.productSkusEmitted]}}async function B(e,t,n){for(const r of e){if(n.signal?.aborted||t.committed)return;t.steps+=1,await tn(r,t,n),t.context=n.contextStore.patch(t.threadId,{})||t.context}}async function tn(e,t,n){const r=X(t);if(e.kind==="be_op"){await nn(e,t,n,r);return}if(e.kind==="tool"){await rn(e,t,n,r);return}if(e.kind==="adapter"){await on(e,t,n,r);return}if(e.kind==="emit"){an(e,t,n);return}if(e.kind==="patch"){cn(e,t,n);return}if(e.kind==="branch"){await sn(e,t,n,r);return}if(e.kind==="parallel"){await un(e,t,n);return}if(e.kind==="refusal"){await ln(e,t,n,r);return}e.kind==="commit"&&await dn(e,t,n)}async function nn(e,t,n,r){const o=performance.now();let i;const a=j(e.cacheTtlS,r),c=j(e.cacheKey,r),y=j(e.browserCache,r);try{i=await n.beClient.invoke({op:e.op,input:j(e.input,r),...a!==void 0?{cacheTtlS:a}:{},...c!==void 0?{cacheKey:c}:{},...y!==void 0?{browserCache:y}:{},...n.signal?{signal:n.signal}:{}})}catch(d){const s=d,u=String(s?.sourceCode||s?.code||"unknown"),l={type:"agentOp",threadId:t.threadId,sessionId:t.request?.session_id||t.request?.sessionId||t.threadId,accountId:t.context.meta.accountId,op:e.op,status:"error",latencyMs:I(o),errorCode:u};if(await n.rpc("beacon.send",l),e.onError){e.errorOut&&(t.bag[e.errorOut]=d),await B(e.onError,t,n);return}throw d}e.out&&(t.bag[e.out]=i),F(e,i,t,n.contextStore);const m={type:"agentOp",threadId:t.threadId,sessionId:t.request?.session_id||t.request?.sessionId||t.threadId,accountId:t.context.meta.accountId,op:e.op,status:"ok",latencyMs:I(o)};await n.rpc("beacon.send",m)}async function rn(e,t,n,r){const o=performance.now();try{const i=await n.toolBridge.invoke(e.name,j(e.input,r));e.out&&(t.bag[e.out]=i),F(e,i,t,n.contextStore),await n.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Pe(t),accountId:t.context.meta.accountId,tool:e.name,status:"ok",latencyMs:I(o)})}catch(i){const a=i;if(await n.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Pe(t),accountId:t.context.meta.accountId,tool:e.name,status:"error",latencyMs:I(o),errorCode:String(a?.code||a?.name||"unknown")}),e.onError){e.errorOut&&(t.bag[e.errorOut]=i),await B(e.onError,t,n);return}throw i}}async function on(e,t,n,r){const o=n.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);const i=await o(j(e.input,r),r);e.out&&(t.bag[e.out]=i),F(e,i,t,n.contextStore)}function an(e,t,n){const r=e.build(X(t));gn(r,t.productSkusEmitted),n.emit(r)}function cn(e,t,n){F(e,void 0,t,n.contextStore)}async function sn(e,t,n,r){const o=String(j(e.on,r)||"default");await B(e.cases[o]||e.cases.default||[],t,n)}async function un(e,t,n){const r=e.steps.map(a=>{const c={...t,context:fn(t.context),bag:{...t.bag},productSkusEmitted:t.productSkusEmitted,committed:!1};return B(a,c,{...n,emit:y=>{y.type!=="done"&&n.emit(y)},contextStore:mn(c)}).then(()=>c)}),o=await Promise.all(r),i=e.merge||{};for(const a of o){for(const c of i.bag||[])Object.prototype.hasOwnProperty.call(a.bag,c)&&(t.bag[c]=a.bag[c]);if(i.panel?.length){const c=je(a.context.panel,i.panel);Object.keys(c).length&&(t.context=n.contextStore.patch(t.threadId,{panel:c})||t.context)}if(i.threadExtensions?.length){const c=je(a.context.thread.extensions,i.threadExtensions);Object.keys(c).length&&(t.context=n.contextStore.patch(t.threadId,{thread:{...t.context.thread,extensions:c}})||t.context)}}}async function ln(e,t,n,r){n.emit(Ee(j(e.message,r),!0)),await Q(t,n)}async function dn(e,t,n){await Q(t,n)}async function Q(e,{contextStore:t,emit:n}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,n(Y()))}function F(e,t,n,r){if(typeof e.patch!="function")return;const o=e.patch(n.context,t,X(n));o&&(n.context=r.patch(n.threadId,o)||n.context)}function X(e){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig}}function Pe(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function fn(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function je(e,t){const n={};for(const r of t)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function mn(e){return{async load(){return e.context},patch(t,n){return e.context=yn(e.context,n),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function yn(e,t){return!t||typeof t!="object"?e:{...e,...t,panel:{...e.panel||{},...t.panel||{}},thread:{...e.thread||{},...t.thread||{},extensions:{...e.thread?.extensions||{},...t.thread?.extensions||{}}},meta:{...e.meta||{},...t.meta||{}},messages:Array.isArray(t.messages)?t.messages.slice(-50):e.messages}}function j(e,t){return typeof e=="function"?e(t):e}function pn(e){const t=e?.payload;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"text"in t){const n=t.text;if(typeof n=="string")return n}return typeof e?.action?.payload=="string"?e.action.payload:typeof e?.action?.title=="string"?e.action.title:""}function gn(e,t){const n=e,r=n.spec,o=Array.isArray(r?.items)?r.items:void 0,i=Array.isArray(n.items)?n.items:void 0,a=o||i;if(Array.isArray(a)){for(const c of a)if(c&&typeof c=="object"){const y=c.sku;typeof y=="string"&&t.add(y)}}}function hn(e){return{invoke(t,n){return e("tool.invoke",{name:t,input:n})}}}var wn=512,bn=.74;function Ce({accountId:e,worker:t,beUrl:n,devJwtSecret:r,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:c={},beacon:y}){let m=1;const d=new Map;return ct({worker:t,tools:c,beacon:s=>y?.({...s,accountId:s.accountId||e}),memory:sessionStorage}),t.addEventListener("message",s=>{const u=s.data||{},l=typeof u.id=="number"?u.id:null;if(l==null)return;const p=d.get(l);if(p){if(u.type==="event"&&u.event){Z(p,u.event);return}if(u.type==="error"){p.onError(new Error(u.message||"Agent worker failed")),d.delete(l);return}u.type==="end"&&d.delete(l)}}),(s,u,l,p)=>{const g=m++;d.set(g,u);const h=()=>{d.delete(g),t.postMessage({id:g,type:"abort"})},A=w=>{if(l.aborted){h();return}t.postMessage({id:g,type:"invoke",accountId:e,beUrl:n,devJwtSecret:r,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,request:w,parentUrl:window.location.href})};if(l.aborted){h();return}if(l.addEventListener("abort",h,{once:!0}),p){Oe(s,p).then(A).catch(w=>{d.delete(g),u.onError(w instanceof Error?w:new Error("Failed to read image attachment"))});return}A(s)}}function Ie({accountId:e,accountModule:t,beUrl:n,devJwtSecret:r,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:c={},beacon:y}){let m=null;const d=Sn({accountId:e,tools:c,beacon:y}),s=hn(d),u=H({accountId:e,...r?{devJwtSecret:r}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(l,p,g,h)=>{const A=await Oe(l||{},h);m||=new me({accountId:e,locale:A?.locale||a,parentUrl:window.location.href,rpc:d,persistentPanelKeys:t.contextPersistence?.panelKeys,panelKeyLimits:t.contextPersistence?.panelKeyLimits});try{await en({request:A,accountModule:{...t,accountId:e},contextStore:m,beClient:{invoke({op:w,input:se,signal:it,cacheTtlS:ro,cacheKey:oo,browserCache:io}){return Ht({beUrl:n,accountId:e,jwtProvider:u,parentUrl:window.location.href,op:w,input:se,cacheTtlS:ro,cacheKey:oo,browserCache:io,...it?{signal:it}:{}})}},toolBridge:s,emit:w=>Z(p,w),rpc:d,signal:g})}catch(w){g?.aborted||(Z(p,be(w)),p.onDone())}}}function Sn({accountId:e,tools:t,beacon:n}){const r=o=>n?.({...o,accountId:o.accountId||e});return((o,i)=>ue(o,i,{tools:t,beacon:r,memory:sessionStorage}))}async function Oe(e,t){if(!t||!t.type?.startsWith("image/"))return e;const n=await _n(t),r={...An(e.payload??e.action?.payload),image_data_url:n.dataUrl,image_mime:n.mime};return{...e,payload:r,...e.action?{action:{...e.action,payload:r}}:{}}}function An(e){return kn(e)?{...e}:typeof e=="string"?{text:e}:{}}function kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function _n(e){const t=await En(e);return t||{dataUrl:await Re(e),mime:e.type}}async function En(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const n=Math.min(1,wn/Math.max(t.width,t.height)),r=Math.max(1,Math.round(t.width*n)),o=Math.max(1,Math.round(t.height*n)),i=document.createElement("canvas");i.width=r,i.height=o;const a=i.getContext("2d");if(!a)return null;a.drawImage(t,0,0,r,o);const c=await new Promise(y=>i.toBlob(y,"image/jpeg",bn));return c?{dataUrl:await Re(c),mime:c.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function Re(e){const t=new Uint8Array(await e.arrayBuffer());let n="";const r=32768;for(let o=0;o<t.length;o+=r)n+=String.fromCharCode(...t.subarray(o,o+r));return`data:${e.type};base64,${btoa(n)}`}function Z(e,t){switch(t?.type){case"text_chunk":{const n=t;e.onTextChunk(n.content||"",n.final===!0,n);break}case"ui_spec":{const n=t;e.onUISpec(n.spec,n.widget,n.panelHint,n.clearPanel===!0);break}case"action":e.onAction(t);break;case"metadata":e.onMetadata(t);break;case"error":e.onError(Tn(t));break;case"done":e.onDone();break;default:break}}function Tn(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}function Ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function q(e){const t=Ue(e);if(!t)return null;const n=O(t.sku,t.SKU);if(!n)return null;const r={sku:n,name:O(t.name,t.title,t.short_name,n)||n,url:O(t.url)||""},o=Array.isArray(t.images)?t.images:void 0,i=O(t.imageUrl,t.image_url,t.image,o?.[0]);i&&(r.imageUrl=i),o&&o.length>1&&(r.images=o.filter(g=>!!g).map(String));const a=v(t.price_discounted),c=v(t.price),y=a||c;y>0&&(r.price=String(y));const m=a>0?c:0;m>0&&(r.originalPrice=String(m));const d=O(t.brand);d&&(r.brand=d);const s=v(t.rating);s>0&&(r.rating=s);const u=v(t.review_count)||v(t.reviewCount);u>0&&(r.reviewCount=u);const l=O(t.cart_code,t.cartCode);l&&(r.cartCode=l),typeof t.in_stock=="boolean"&&(r.inStock=t.in_stock),typeof t.inStock=="boolean"&&(r.inStock=t.inStock);const p=t.category_names;return Array.isArray(p)&&(r.categoryNames=p.map(String)),r}function K(e){const t=Ue(e);if(!t)return e;const n=t.category_names,r=Array.isArray(n)?n:void 0,o=t.images,i=Array.isArray(o)?o:void 0,a={sku:t.sku,name:t.name||t.title,url:t.url,price:t.price,currency:t.price_currency||t.currency,category:r?.[r.length-1]??void 0,category_names:r?r.slice(0,4):void 0,image:i?i[0]:t.image,in_stock:t.in_stock,rating:t.rating,review_count:t.review_count};for(const c of Object.keys(a))a[c]===void 0&&delete a[c];return a}function xn(e){return Array.isArray(e)?e.map(K).filter(t=>!!t):[]}function O(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function v(e){const t=Number(e);return Number.isFinite(t)?t:0}function Me(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function Pn(e,t,n={}){return`${e}:${n.version||"v2"}:${R(t)}`}function jn(e,t={}){return Be(e).map(n=>ve(typeof n=="string"?n:n.sku,t.locale)).filter(Boolean).filter((n,r,o)=>o.indexOf(n)===r).sort((n,r)=>ee(n,r,t.locale)).slice(0,t.limit||16).join(",")}function Cn(e,t={}){return R(Be(e).map(n=>On(n,t)).filter(n=>!!n).sort((n,r)=>ee(String(n.sku||n.name||""),String(r.sku||r.name||""),t.locale)).slice(0,t.limit||16))}function In(e,t){return C(e,t)}function R(e){let t=2166136261;const n=Rn(e);for(let r=0;r<n.length;r+=1)t^=n.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function On(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,r=t.mapProduct?.(n);if(r)return L(r);const o=K(n);return o&&typeof o=="object"&&!Array.isArray(o)?L(Un(o,t)):null}function Be(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function Rn(e){return JSON.stringify(L(e))}function L(e){return Array.isArray(e)?e.map(L):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,L(n)]))}function Un(e,t){return{sku:ve(e.sku,t.locale),name:C(e.name,t.locale),url:C(e.url,t.locale),price:e.price,currency:C(e.currency,t.locale),category:C(e.category,t.locale),category_names:Mn(e.category_names,t.locale,16),image:C(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function ve(e,t){return C(e,t).toUpperCase()}function C(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function ee(e,t,n){return e.localeCompare(t,n,{numeric:!0})}function Mn(e,t,n){return Array.isArray(e)?e.map(r=>C(r,t)).filter(Boolean).sort((r,o)=>ee(r,o,t)).slice(0,n):void 0}var Bn="entries",vn=1,Ln={volatile:"Hot per-page state and sensitive request context.",session:"Current-visit tool context without raw tokens or PII-heavy payloads.",local:"Small, non-sensitive capability facts or user preferences.",indexedDb:"Larger product/search payload caches with short TTLs."},Le=new Map;function te(){return Date.now()}function ne(e){return e?.expiresAt!=null&&e.expiresAt<=te()}function re(e,t){return{value:e,createdAt:te(),expiresAt:t?te()+t:null}}function Nn(e,t,n){try{const r=e.getItem(`${t}${n}`);if(!r)return null;const o=JSON.parse(r);return ne(o)?(e.removeItem(`${t}${n}`),null):o.value}catch{return null}}function Dn(e,t,n,r,o){try{return e.setItem(`${t}${n}`,JSON.stringify(re(r,o))),!0}catch{return!1}}function $n(e,t,n){try{e.removeItem(`${t}${n}`)}catch{}}function Ne(e){try{return window[e]}catch{return null}}function De(e,t){return e?{get:n=>Nn(e,t,n),set:(n,r,o={})=>Dn(e,t,n,r,o.ttlMs),remove:n=>$n(e,t,n)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function Fn(e,t){const n=t.dbName||`gengage-${e}`,r=t.dbStore||Bn,o=t.dbVersion||vn,i=new Map;let a=null;const c=()=>"indexedDB"in window?a||(a=new Promise(s=>{const u=indexedDB.open(n,o);u.onupgradeneeded=()=>{u.result.createObjectStore(r,{keyPath:"key"})},u.onsuccess=()=>s(u.result),u.onerror=()=>s(null),u.onblocked=()=>s(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async s=>{const u=await c();return u?new Promise(l=>{const p=u.transaction(r,"readwrite").objectStore(r),g=p.get(s);g.onsuccess=()=>{const h=g.result;if(!h||ne(h)){h&&p.delete(s),l(null);return}l(h.value)},g.onerror=()=>l(null)}):null},idbSet:async(s,u,l={})=>{const p=await c();return p?new Promise(g=>{const h=p.transaction(r,"readwrite");h.oncomplete=()=>g(!0),h.onerror=()=>g(!1),h.objectStore(r).put({key:s,...re(u,l.ttlMs)})}):!1},idbRemove:async s=>{const u=await c();u&&u.transaction(r,"readwrite").objectStore(r).delete(s)}}}function oe(e,t={}){const n=window,r=n.gengage||(n.gengage={}),o=r.memory||(r.memory={}),i=o[e];if(i)return i;const a=Le.get(e)||Fn(e,t);Le.set(e,a);const c=t.sessionPrefix||`gengage:${e}:session:`,y=t.localPrefix||`gengage:${e}:local:`,d={get:l=>{const p=a.volatileEntries.get(l);return p?ne(p)?(a.volatileEntries.delete(l),null):p.value:null},set:(l,p,g={})=>(a.volatileEntries.set(l,re(p,g.ttlMs)),!0),remove:l=>{a.volatileEntries.delete(l)},clear:()=>a.volatileEntries.clear()},s={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},u={accountId:e,volatile:d,session:De(Ne("sessionStorage"),c),local:De(Ne("localStorage"),y),indexedDb:s,stableKey:R,policy:{...Ln,...t.policy||{}}};o[e]=u;for(const l of t.aliases||[])o[l]=u;return u}var z="__gengageAgentFetchBridge",qn=1e3*60*60*24*14;function Kn({accountId:e,streamTransport:t,endpoints:n={},endpointCache:r}){if(!e)throw new Error("accountId is required.");if(typeof t!="function")throw new Error("streamTransport is required.");const o=zn(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,c=r?Yn({accountId:e,endpointCache:r,fetchImpl:o.originalFetch}):void 0,y=m=>{const d=`${i}/chat/${m}`;a.add(d);const s=n[m],u={streamTransport:t,endpoint:m};s&&(u.endpointHandler=s),c&&(u.endpointCache=c),o.routes.set(d,u)};y("process_action");for(const m of Object.keys(n))m!=="process_action"&&y(m);return{middlewareUrl:i,stop(){for(const m of a)o.routes.delete(m);Jn(o)}}}function zn(){const e=window,t=e[z];if(t)return t;const n=e.fetch.bind(e),r={routes:new Map,originalFetch:n,installedFetch:n};return r.installedFetch=(o,i)=>{const a=$e(o),c=r.routes.get(a);return c?Gn(c,o,i):n(o,i)},e.fetch=r.installedFetch,e[z]=r,r}function Jn(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[z]===e&&delete t[z]}function $e(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function Fe(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function qe(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function Hn(e,t){const n=qe(e,t);if(n instanceof FormData){const o=n.get("request"),i=n.get("attachment");return{request:JSON.parse(String(o||"{}")),...i instanceof File?{attachment:i}:{}}}const r=await Promise.resolve(n);return typeof r=="string"?{request:JSON.parse(r||"{}")}:{request:{}}}async function Gn(e,t,n){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const m=new AbortController,d=Fe(t,n);let s=null;if(d){const u=()=>m.abort();d.aborted&&u(),d.addEventListener("abort",u,{once:!0}),s=()=>d.removeEventListener("abort",u)}try{const u=await Wn(t,n),l={accountId:Vn(t),endpoint:e.endpoint,signal:m.signal},p=Qn(e.endpointCache,e.endpoint,u,l.accountId);if(p){const h=await Xn(e.endpointCache,p,m.signal);if(h)return or(h)}const g=await e.endpointHandler(u,l);return p&&g.ok&&await Zn(e.endpointCache,p,g.clone(),m.signal),g}finally{s?.()}}const r=new TextEncoder,o=new AbortController,i=Fe(t,n);let a=!1,c=null;const y=new ReadableStream({async start(m){const d=l=>{a||m.enqueue(r.encode(`${JSON.stringify(l)}
4
+ `))},s=()=>{a||(a=!0,c?.(),m.close())},u=l=>{d({type:"error",code:l?.code||"agent_bridge_error",message:l instanceof Error?l.message:String(l)}),d({type:"done"}),s()};if(i){const l=()=>{o.abort(),a||(a=!0,c?.(),m.error(new DOMException("Aborted","AbortError")))};if(i.aborted){l();return}i.addEventListener("abort",l,{once:!0}),c=()=>i.removeEventListener("abort",l)}try{const{request:l,attachment:p}=await Hn(t,n),g=e.streamTransport(l,{onTextChunk:(h,A,w={})=>d({type:"text_chunk",content:h,final:A===!0,...w}),onUISpec:(h,A,w,se)=>d({type:"ui_spec",spec:h,widget:A,...w?{panelHint:w}:{},...se?{clearPanel:!0}:{}}),onAction:h=>{d(h?.type==="action"?h:{type:"action",action:h})},onMetadata:h=>{d(h?.type==="metadata"?h:{type:"metadata",...h})},onError:u,onDone:()=>{d({type:"done"}),s()}},o.signal,p);sr(g)&&(await g,o.signal.aborted||(d({type:"done"}),s()))}catch(l){o.signal.aborted||u(l)}},cancel(){o.abort(),c?.(),a=!0}});return new Response(y,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}async function Wn(e,t){const n=await Promise.resolve(qe(e,t));return typeof n!="string"||n.trim()===""?{}:JSON.parse(n)}function Vn(e){try{const[t]=new URL($e(e)).pathname.split("/").filter(Boolean);return decodeURIComponent(t||"")}catch{return""}}function Yn({accountId:e,endpointCache:t,fetchImpl:n}){return{accountId:e,beUrl:t.beUrl,...t.parentUrl?{parentUrl:t.parentUrl}:{},ttlMs:t.ttlMs??qn,policies:t.policies,fetchImpl:n,jwtProvider:H({accountId:e,...t.devJwtSecret?{devJwtSecret:t.devJwtSecret}:{},...t.tokenBrokerUrl?{tokenBrokerUrl:t.tokenBrokerUrl}:{},...t.tokenBrokerAudience?{tokenBrokerAudience:t.tokenBrokerAudience}:{},fetchImpl:n})}}function Qn(e,t,n,r){if(!e)return null;const o=e.policies[t];if(!o)return null;const i=o(n,{accountId:r,endpoint:t});return!i?.partition||!i?.key?null:{partition:i.partition,key:i.key,ttlMs:i.ttlMs??e.ttlMs}}async function Xn(e,t,n){const r=He(e.accountId,t),o=await ir(e.accountId,r);if(Je(o))return o;const i=await er(e,t,n);return i?(await Ge(e.accountId,r,i,t.ttlMs),i):null}async function Zn(e,t,n,r){try{const o=await rr(n);if(cr(o.body))return;const i=He(e.accountId,t);await Ge(e.accountId,i,o,t.ttlMs),tr(e,t,o,r)}catch{}}async function er(e,t,n){try{const r=await e.fetchImpl(ze(e.beUrl),{method:"POST",headers:await Ke(e,n),body:JSON.stringify({partition:t.partition,key:t.key}),signal:n});if(!r.ok)return null;const o=await r.json();return o.hit===!0&&Je(o.payload)?o.payload:null}catch{return null}}async function tr(e,t,n,r){try{await e.fetchImpl(ze(e.beUrl),{method:"POST",headers:await Ke(e,r),body:JSON.stringify({partition:t.partition,key:t.key,ttl_s:Math.max(1,Math.ceil(t.ttlMs/1e3)),payload:n}),signal:r})}catch{}}async function Ke(e,t){return{authorization:`Bearer ${await e.jwtProvider({signal:t,parentUrl:e.parentUrl||nr()})}`,"content-type":"application/json",accept:"application/json"}}function nr(){try{return window.location?.href||""}catch{return""}}function ze(e){return`${String(e).replace(/\/+$/u,"")}/v1/cache`}async function rr(e){return{status:e.status,statusText:e.statusText,headers:[...e.headers.entries()].filter(([t])=>ar(t)),body:await e.text()}}function or(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function Je(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.body=="string"&&Array.isArray(t.headers)}function He(e,t){return`endpoint-response:${R({accountId:e,partition:t.partition,key:t.key})}`}async function ir(e,t){const n=oe(e);return n.volatile.get(t)||await n.indexedDb.get(t)||n.local.get(t)}async function Ge(e,t,n,r){const o=oe(e);o.volatile.set(t,n,{ttlMs:r}),await o.indexedDb.set(t,n,{ttlMs:r})||o.local.set(t,n,{ttlMs:r})}function ar(e){return["content-type","cache-control"].includes(e.toLowerCase())}function cr(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function sr(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function ur({accountId:e,beUrl:t,devJwtSecret:n,tokenBrokerUrl:r,tokenBrokerAudience:o,workerUrl:i,defaultLocale:a="en-GB",accountModule:c,tools:y={},beacon:m,allowBlobWorker:d=!1}){if(!e)throw new Error("accountId is required.");if(!t)throw new Error("beUrl is required. The injector owns backend URLs; the SDK has no default.");if(!i)throw new Error("workerUrl is required.");const s=window,u=s.GengageAssistantInjector||(s.GengageAssistantInjector={}),l=u[e]||(u[e]={});if(l.agentController)return l.agentController;const p=ie(i)||d?We(i,`gengage-${e}-agent`,{allowBlobWorker:d}):null;p||m?.({type:"agentRuntime",accountId:e,transport:"main-thread",reason:"cross-origin-worker-url",workerUrl:i}),l.streamTransport=p?Ce({accountId:e,worker:p.worker,beUrl:t,...n?{devJwtSecret:n}:{},...r?{tokenBrokerUrl:r}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:y,...m?{beacon:m}:{}}):Ie({accountId:e,accountModule:c,beUrl:t,...n?{devJwtSecret:n}:{},...r?{tokenBrokerUrl:r}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:y,...m?{beacon:m}:{}});const g={type:"agent",stop(){delete l.streamTransport,p?.worker.terminate(),p?.cleanup(),delete l.agentController},diagnostics(){return{accountId:e,beUrl:t,workerUrl:i,mounted:!0,transport:p?"worker":"main-thread",transportReason:p?"module-worker":"cross-origin-worker-url",flows:Object.keys(c?.flows||{})}}};return l.agentController=g,g}function ie(e){const t=new URL(e,window.location.href);return t.origin===window.location.origin||t.protocol==="blob:"}function We(e,t,n={}){const r=new URL(e,window.location.href);if(ie(e))return{worker:new Worker(r.href,{type:"module",name:t}),cleanup(){}};if(!n.allowBlobWorker)throw new Error("Cross-origin agent workers require allowBlobWorker=true or a same-origin workerUrl.");const o=new Blob([`import ${JSON.stringify(r.href)};
5
+ `],{type:"text/javascript"}),i=URL.createObjectURL(o);try{return{worker:new Worker(i,{type:"module",name:t}),cleanup(){URL.revokeObjectURL(i)}}}catch(a){throw URL.revokeObjectURL(i),a}}function lr(e,t={}){if(!Array.isArray(e))return[];const n=t.maxItems??8,r=t.maxFeatures??8;return e.map(o=>dr(o,t.defaultBrand,r)).filter(o=>!!o).slice(0,n)}function dr(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,o=K(r);return o?yr({sku:o.sku,name:o.name,url:o.url,image:o.image,price:o.price,currency:o.currency,category:o.category,category_names:o.category_names,brand:r.brand||t,features:fr(r.features,n),specs:mr(r.specs,n),in_stock:o.in_stock}):null}function fr(e,t){return Array.isArray(e)?e.filter(Boolean).slice(0,t):void 0}function mr(e,t){if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).filter(([,n])=>n!=null).slice(0,t))}function yr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function ae(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n=Array.isArray(t.rows)?t.rows:[];return{...t,rows:n.map(gr).filter(Boolean)}}function Ve(e,t){const n=Array.isArray(e)?e.filter(c=>!!(c&&typeof c=="object"&&!Array.isArray(c))):[],r=ae(t),o=Array.isArray(r.columns)?r.columns.map(String):[];if(!o.length)return n;const i=new Map(n.map(c=>[String(c.sku||c.id||""),c])),a=o.map(c=>i.get(c)).filter(c=>!!c);return a.length?a:n}function pr(e,t){const n=ae(e?.table),r=Ve(t,n);return{...e||{},table:n,products:r,multiple_product_details:r}}function gr(e){return!e||typeof e!="object"||Array.isArray(e)?null:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function hr(e=[]){const t={},n=[];return(Array.isArray(e)?e.map(q).filter(r=>!!r):[]).forEach((r,o)=>{const i=`product-${o.toString()}`;n.push(i);const a={sku:r.sku,product:r};t[i]={type:"ProductCard",props:{product:r,index:o,action:{title:r.name,type:"launchSingleProduct",payload:a}}}}),t.root={type:"ProductGrid",props:{layout:"grid"},children:n},{widget:"chat",panelHint:"panel",spec:{root:"root",elements:t}}}function wr(e){return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:q(e)||e||{}}}}}}}function br(e={}){const t=(e.multiple_product_details||e.products||[]).map(q).filter(r=>!!r),n=e.table||{};return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:{products:t,recommended:t.find(r=>r.sku===e.recommended_choice_sku)||t[0],attributes:Object.entries(n).map(([r,o])=>({label:r,values:Array.isArray(o)?o.map(String):[String(o??"")]})),highlights:Me(e.key_differences),specialCases:Me(e.special_considerations),recommendedText:e.recommended_choice,productActions:Object.fromEntries(t.map(r=>[r.sku,{title:r.name,type:"launchSingleProduct",payload:{sku:r.sku,product:r}}]))}}}}}}function Sr(e=[]){return{widget:"chat",panelHint:"inline",spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:(Array.isArray(e)?e:[]).map(t=>{const n=t.label||t.title||t.shortName||"",r=t.action||t.requestDetails||t.request_details;return!n||!r?.type?null:{label:n,action:{title:n,type:r.type,...r.payload!==void 0?{payload:r.payload}:{}}}}).filter(t=>!!t)}}}}}}function Ar(e){return Object.freeze([...e])}function Ye(e,t,n="v1"){return`endpoint:${n}:${R({endpoint:e,request:t})}`}function kr(e){const t=e.version||"v1",n=r=>o=>({partition:`${e.partitionPrefix}/${r}`,key:Ye(r,o,t),...e.ttlMs?{ttlMs:e.ttlMs}:{}});return{launcher_action:n("launcher_action"),similar_products:n("similar_products"),product_groupings:n("product_groupings")}}function _r(e){return{...e}}function Er(e,t={}){return new Response(e.map(n=>JSON.stringify(n)).join(`
6
6
  `)+`
7
- `,{...t,headers:{"content-type":"application/x-ndjson",...t.headers||{}}})}function _o(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}function Eo(e){const t=(e?.chat||e?._chat)?.root||e?._chat?.root;return t?t.getRootNode?.()?.host||t:Array.from(document.querySelectorAll("*")).find(r=>r.shadowRoot?.querySelector?.(".gengage-chat-root, .gengage-chat-launcher-container"))}function To(e,t){const r=Eo(e);r?.style&&(t?r.style.removeProperty("display"):r.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var Po="nd_be_url";function jo(e,t){const r=xo()||e.beUrl||t;if(!r)throw new Error("resolveBeUrl: backend URL is required. The injector must supply a fallback URL; the SDK has no default.");return r}function xo(){try{const e=new URLSearchParams(window.location.search).get(Po)?.trim();if(!e)return null;const t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString().replace(/\/+$/u,"")}catch{return null}}function Tt(e){const t=e?.payload;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"text"in t){const n=t.text;if(typeof n=="string")return n}const r=e?.action;return r&&typeof r.payload=="string"?r.payload:r&&typeof r.title=="string"?r.title:""}var Pt=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:Oo},{pattern:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu,replacement:"[email]"},{pattern:/\b(?:\+?\d[\d\s().-]{7,}\d)\b/gu,replacement:"[phone]"},{pattern:/\b(?:token|secret|csrf|cookie|bearer|session|sid|cart(?:[_-]?id)?)\s*[:=]\s*[^\s,;&]+/giu,replacement:"[secret]"},{pattern:/\b(?:order|cart|session)[_-]?(?:id|no|number)?\s*[:#=]?\s*[A-Z0-9-]{6,}\b/giu,replacement:"[secret]"}],ge={patterns:Pt};function jt(e,t=ge){let r=typeof e=="string"?e:e==null?"":String(e);for(const n of t.patterns||[]){const o=n.replacement;r=typeof o=="function"?r.replace(n.pattern,i=>o(i)):r.replace(n.pattern,o)}return r}function Co(e,t=ge){return jt(Tt(e),t)}function Oo(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var Io=["assistantName","homeDomain","categories","policyTopics"],Ro={intent:["searchContract","competitorBrands"]};function Mo(e,t,r,n={}){const o=xt(t,r,n);return Object.keys(o).length?{...e,account_config:o}:e}function xt(e,t,r={}){if(!e)return{};const n={},o=r.baseKeys||Io;for(const c of o)Ct(n,e,c);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(n,Uo(i));const a=r.opAllowlist||Ro;for(const c of a[t]||[])Ct(n,e,c);return n}function Ct(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Uo(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Bo=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Lo(e,t,r={}){const n=window,o=n.gengage||(n.gengage={}),i=o.tools||(o.tools={});i[e]=t;for(const a of r.accountAliases||[])i[a]=t;if(r.exposeStandardAliases!==!1)for(const a of r.standardAliases||Bo){const c=t[a];typeof c=="function"&&(i[a]=i[a]||c)}return t}function No({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function Do({accountId:e,getPageType:t,getProduct:r,getToolNames:n,getSearchCapabilities:o,getMemory:i}){return async()=>({accountId:e,url:window.location.href,pageType:t(),productSku:r()?.sku??null,toolNames:n(),...o?{searchCapabilities:o()}:{},...i?{memoryPolicy:i().policy}:{},timestamp:new Date().toISOString()})}function vo({accountId:e,runtimeFile:t="runtime.js",startExport:r="start",globalBaseUrlKey:n,errorLabel:o}={}){if(!e)throw new Error("accountId is required.");const i=o||e,a=window,c=()=>{const u=a.GengageInjectorConfig||{},l=u[e]||{};return{...u,...l}},y=()=>{const u=c();if(u.runtimeUrl)return u.runtimeUrl;const l=u.assetBaseUrl||u.baseUrl||document.currentScript?.getAttribute("src")||(n?a[n]:null);if(!l)throw new Error(`${i} runtime URL cannot be resolved.`);return new URL(t,l).href},m=a.GengageAssistantInjector||(a.GengageAssistantInjector={}),d=m[e]||(m[e]={});return d.loaderPromise||(d.loaderPromise=import(y()).then(u=>{const l=u[r];if(typeof l!="function")throw new Error(`${i} runtime export ${r} is unavailable.`);return l()}).catch(u=>{throw delete d.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,u),u})),d.loaderPromise}s.AgentError=F,s.ContextStore=ke,s.action=Ar,s.actionButtonsUiSpec=ct,s.actionCandidatePayload=Q,s.alignProductsToTable=nt,s.anonymousRequestText=Co,s.beErrorToAgentError=X,s.buildPhotoSimilarityProfile=Fn,s.buildProductSimilarityProfile=v,s.buildSimilarityQueries=qn,s.canUseModuleWorker=de,s.caughtToStreamError=xe,s.compactAccountConfig=xt,s.compactContextProducts=In,s.compareCachedResultSteps=fo,s.compareResultSteps=St,s.compareSearchSteps=lo,s.compareSteps=uo,s.comparisonResultForUi=Ln,s.comparisonUiSpec=at,s.createBrowserMemory=fe,s.createDiagnosticsTool=Do,s.createEndpointCachePolicies=So,s.createEndpointHandlers=Ao,s.createFlow=Dn,s.createInjectorAdapter=Ne,s.createMainThreadInjectorAdapter=De,s.createModuleWorker=rt,s.createReadPageTool=No,s.defaultPiiPatternPack=ge,s.defaultPiiPatterns=Pt,s.done=re,s.elapsedMs=O,s.endpointStableKey=Et,s.error=Me,s.hasProductImage=yt,s.hasUsablePrice=mt,s.hasVisibleShoppingFacts=pt,s.httpErrorToAgentError=je,s.installBrowserTools=Lo,s.installFetchTransportBridge=ln,s.intentQuestionSteps=ao,s.jsonResponse=_o,s.llmCacheKey=Gr,s.metadata=Sr,s.mountAccount=On,s.ndjsonResponse=ko,s.normalizeActionLabel=pe,s.normalizeComparisonTable=me,s.normalizeProduct=z,s.normalizeQueryText=gt,s.normalizeSimilarityText=k,s.normalizeSuggestedActions=io,s.nowIso=be,s.panelProductScore=ht,s.panelQuestionSteps=so,s.prioritizePanelProducts=no,s.productActions=wt,s.productDetailsUiSpec=it,s.productFactsKey=Qr,s.productPanelActions=oo,s.productQuestionSteps=bt,s.productRankScore=ft,s.productSearchText=ye,s.productSkuKey=Wr,s.productsMatchingParams=ro,s.productsUiSpec=ot,s.rankSimilarProducts=zn,s.rankedSearchProducts=eo,s.rankingTokens=dt,s.redactPii=jt,s.requestText=Tt,s.resolveBeUrl=jo,s.resolveFlow=Ue,s.scoreSimilarityCandidate=ut,s.searchResultSteps=mo,s.searchSteps=co,s.setAssistantHostVisible=To,s.stableKey=R,s.startLazyRuntimeLoader=vo,s.suggestedActionSteps=yo,s.textChunk=te,s.textKey=Vr,s.tokenizeSimilarityText=_,s.trimProductFactsCore=K,s.trimProductFactsListCore=Hr,s.uiSpec=B,s.uniqueProducts=W,s.withAccountConfig=Mo})(this.Gengage=this.Gengage||{});
7
+ `,{...t,headers:{"content-type":"application/x-ndjson",...t.headers||{}}})}function Tr(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}var Qe=new Set(["and","are","for","from","the","with"]),xr={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},Pr=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function x(e){return String(e??"").normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function k(e,t=Qe){const n=t instanceof Set?t:new Set([...Qe,...t]),r=new Set,o=[];for(const i of x(e).split(/\s+/u))i.length<3||n.has(i)||r.has(i)||(r.add(i),o.push(i));return o}function N(e,t={}){if(Or(e))return e;const n=t.facetKeys,r=S(e.category_names??e.category),o=S(e.category_ids),i=Rr(e.facet_hits),a=Object.entries(i).filter(([g])=>!n||n.some(h=>x(h)===x(g))).map(([,g])=>g),c=T(e.name,e.title),y=T(e.brand),m=t.sourceKeywords??[],d=[c,y,...r,...a,...S(e.promotions),T(e.description),...m].join(" "),s=k(d,t.stopWords),u=T(t.sourceProductType,Br(r,c,s),s[0]),l=P([...Mr(d,Pr),...Object.entries(i).filter(([g])=>/colou?r/iu.test(g)).flatMap(([,g])=>k(g,t.stopWords))]),p=P([...a.flatMap(g=>k(g,t.stopWords)),...S(e.promotions).flatMap(g=>k(g,t.stopWords))]).slice(0,24);return{sku:T(e.sku),title:c,brand:y,productType:u,categoryNames:r,categoryIds:o,facets:i,keywords:P([...m.flatMap(g=>k(g,t.stopWords)),...s]).slice(0,12),tokens:s,colors:l,attributes:p,price:Ur(e)}}function jr(e,t={}){const n=T(e.product_type,e.productType),r=T(e.title,n,S(e.keywords).join(" ")),o=P([...S(e.keywords),...S(e.colors),...S(e.materials),...S(e.styles),...S(e.attributes)]);return N({sku:"__photo__",name:r,category_names:n?[n]:[],facet_hits:{colors:S(e.colors).join(", "),materials:S(e.materials).join(", "),styles:S(e.styles).join(", "),attributes:S(e.attributes).join(", ")},promotions:o},{...t,sourceProductType:n,sourceKeywords:o})}function Cr(e,t={}){const n=N(e,t);return P([...t.sourceQueries??[],J([n.productType,...n.colors.slice(0,1),...n.attributes.slice(0,2)]),J([n.productType,...n.keywords.slice(0,3)]),J([n.categoryNames[n.categoryNames.length-1],...n.keywords.slice(0,2)]),J(n.title.split(/\s+/u).slice(0,6)),n.productType].map(r=>r.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function Xe(e,t,n={}){const r={...xr,...n.weights},o=N(t,n),i=[],a=U(e.tokens,o.tokens),c=U(e.keywords,o.tokens),y=vr(e.categoryNames,o.categoryNames)||U(Ze(e.categoryNames),Ze(o.categoryNames)),m=U(e.attributes,o.attributes),d=U(e.colors,o.colors),s=U(e.attributes,o.tokens),u=Lr(e.price,o.price),l=Nr(o.sku,n.hitCounts)>0?1:0,p=Dr(e,o),g=a*r.token+c*r.keyword+y*r.category+m*r.facet+d*r.color+s*r.attribute+u*r.price+l*r.retrieval,h=$r(p?g:g*.35);return p&&e.productType&&e.productType===o.productType&&i.push("same product type"),y>.4&&i.push("similar category"),m>.2&&i.push("matching product attributes"),d>0&&i.push("matching colour"),u>.8&&i.push("similar price"),p||i.push("weaker product-type match"),{score:Number(h.toFixed(4)),reasons:i}}function Ir(e,t,n={}){const r=N(e,n),o=new Set([r.sku,...n.ignoreSkus??[]].filter(Boolean));return t.filter(i=>{const a=T(i.sku);return a&&!o.has(a)}).map(i=>{const a=Xe(r,i,n);return{...i,similarity_score:a.score,similarity_reasons:a.reasons}}).sort((i,a)=>a.similarity_score-i.similarity_score).slice(0,Math.max(1,Math.min(n.limit??12,100)))}function Or(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function T(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function S(e){return Array.isArray(e)?e.map(t=>T(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function Rr(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,T(n)]).filter(([,t])=>t))}function Ur(e){const t=Number(e.price_discounted);if(Number.isFinite(t)&&t>0)return t;const n=Number(e.price);return Number.isFinite(n)&&n>0?n:0}function P(e){const t=new Set,n=[];for(const r of e){const o=x(r);!o||t.has(o)||(t.add(o),n.push(o))}return n}function Mr(e,t){const n=` ${x(e)} `;return t.filter(r=>n.includes(` ${x(r)} `))}function Br(e,t,n){const r=x(e[e.length-1]??e[0]??"");if(r){const o=k(r),i=new Set(k(t));return o.find(a=>i.has(a))??o[0]??r}return n[0]??""}function J(e){return e.map(t=>x(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function Ze(e){return e.flatMap(t=>k(t))}function U(e,t){const n=P(e),r=new Set(P(t));return n.length===0||r.size===0?0:n.filter(o=>r.has(o)).length/n.length}function vr(e,t){const n=P(e),r=new Set(P(t));return n.length===0||r.size===0?0:n.filter(o=>r.has(o)).length/n.length}function Lr(e,t){return e<=0||t<=0?0:Math.min(e,t)/Math.max(e,t)}function Nr(e,t){return!e||!t?0:typeof t.get=="function"?t.get(e)??0:t[e]??0}function Dr(e,t){if(!e.productType||!t.productType||e.productType===t.productType)return!0;const n=new Set(k(e.productType)),r=new Set([...k(t.productType),...t.tokens]);return[...n].some(o=>r.has(o))}function $r(e){return Math.max(0,Math.min(1,e))}function Fr(e){const t=(e?.chat||e?._chat)?.root||e?._chat?.root;return t?t.getRootNode?.()?.host||t:Array.from(document.querySelectorAll("*")).find(n=>n.shadowRoot?.querySelector?.(".gengage-chat-root, .gengage-chat-launcher-container"))}function qr(e,t){const n=Fr(e);n?.style&&(t?n.style.removeProperty("display"):n.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var Kr="nd_be_url";function zr(e,t){const n=Jr()||e.beUrl||t;if(!n)throw new Error("resolveBeUrl: backend URL is required. The injector must supply a fallback URL; the SDK has no default.");return n}function Jr(){try{const e=new URLSearchParams(window.location.search).get(Kr)?.trim();if(!e)return null;const t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString().replace(/\/+$/u,"")}catch{return null}}function et(e){const t=e?.payload;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"text"in t){const r=t.text;if(typeof r=="string")return r}const n=e?.action;return n&&typeof n.payload=="string"?n.payload:n&&typeof n.title=="string"?n.title:""}var tt=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:Gr},{pattern:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu,replacement:"[email]"},{pattern:/\b(?:\+?\d[\d\s().-]{7,}\d)\b/gu,replacement:"[phone]"},{pattern:/\b(?:token|secret|csrf|cookie|bearer|session|sid|cart(?:[_-]?id)?)\s*[:=]\s*[^\s,;&]+/giu,replacement:"[secret]"},{pattern:/\b(?:order|cart|session)[_-]?(?:id|no|number)?\s*[:#=]?\s*[A-Z0-9-]{6,}\b/giu,replacement:"[secret]"}],ce={patterns:tt};function nt(e,t=ce){let n=typeof e=="string"?e:e==null?"":String(e);for(const r of t.patterns||[]){const o=r.replacement;n=typeof o=="function"?n.replace(r.pattern,i=>o(i)):n.replace(r.pattern,o)}return n}function Hr(e,t=ce){return nt(et(e),t)}function Gr(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var Wr=["assistantName","homeDomain","categories","policyTopics"],Vr={intent:["searchContract","competitorBrands"]};function Yr(e,t,n,r={}){const o=rt(t,n,r);return Object.keys(o).length?{...e,account_config:o}:e}function rt(e,t,n={}){if(!e)return{};const r={},o=n.baseKeys||Wr;for(const c of o)ot(r,e,c);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(r,Qr(i));const a=n.opAllowlist||Vr;for(const c of a[t]||[])ot(r,e,c);return r}function ot(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Qr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Xr=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Zr(e,t,n={}){const r=window,o=r.gengage||(r.gengage={}),i=o.tools||(o.tools={});i[e]=t;for(const a of n.accountAliases||[])i[a]=t;if(n.exposeStandardAliases!==!1)for(const a of n.standardAliases||Xr){const c=t[a];typeof c=="function"&&(i[a]=i[a]||c)}return t}function eo({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function to({accountId:e,getPageType:t,getProduct:n,getToolNames:r,getSearchCapabilities:o,getMemory:i}){return async()=>({accountId:e,url:window.location.href,pageType:t(),productSku:n()?.sku??null,toolNames:r(),...o?{searchCapabilities:o()}:{},...i?{memoryPolicy:i().policy}:{},timestamp:new Date().toISOString()})}function no({accountId:e,runtimeFile:t="runtime.js",startExport:n="start",globalBaseUrlKey:r,errorLabel:o}={}){if(!e)throw new Error("accountId is required.");const i=o||e,a=window,c=()=>{const s=a.GengageInjectorConfig||{},u=s[e]||{};return{...s,...u}},y=()=>{const s=c();if(s.runtimeUrl)return s.runtimeUrl;const u=s.assetBaseUrl||s.baseUrl||document.currentScript?.getAttribute("src")||(r?a[r]:null);if(!u)throw new Error(`${i} runtime URL cannot be resolved.`);return new URL(t,u).href},m=a.GengageAssistantInjector||(a.GengageAssistantInjector={}),d=m[e]||(m[e]={});return d.loaderPromise||(d.loaderPromise=import(y()).then(s=>{const u=s[n];if(typeof u!="function")throw new Error(`${i} runtime export ${n} is unavailable.`);return u()}).catch(s=>{throw delete d.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,s),s})),d.loaderPromise}f.AgentError=D,f.ContextStore=me,f.action=Zt,f.actionButtonsUiSpec=Sr,f.alignProductsToTable=Ve,f.anonymousRequestText=Hr,f.beErrorToAgentError=G,f.buildPhotoSimilarityProfile=jr,f.buildProductSimilarityProfile=N,f.buildSimilarityQueries=Cr,f.canUseModuleWorker=ie,f.caughtToStreamError=be,f.compactAccountConfig=rt,f.compactContextProducts=lr,f.comparisonResultForUi=pr,f.comparisonUiSpec=br,f.createBrowserMemory=oe,f.createDiagnosticsTool=to,f.createEndpointCachePolicies=kr,f.createEndpointHandlers=_r,f.createFlow=Ar,f.createInjectorAdapter=Ce,f.createMainThreadInjectorAdapter=Ie,f.createModuleWorker=We,f.createReadPageTool=eo,f.defaultPiiPatternPack=ce,f.defaultPiiPatterns=tt,f.done=Y,f.elapsedMs=I,f.endpointStableKey=Ye,f.error=Te,f.httpErrorToAgentError=we,f.installBrowserTools=Zr,f.installFetchTransportBridge=Kn,f.jsonResponse=Tr,f.llmCacheKey=Pn,f.metadata=Qt,f.mountAccount=ur,f.ndjsonResponse=Er,f.normalizeComparisonTable=ae,f.normalizeProduct=q,f.normalizeSimilarityText=x,f.nowIso=le,f.productDetailsUiSpec=wr,f.productFactsKey=Cn,f.productSkuKey=jn,f.productsUiSpec=hr,f.rankSimilarProducts=Ir,f.redactPii=nt,f.requestText=et,f.resolveBeUrl=zr,f.resolveFlow=xe,f.scoreSimilarityCandidate=Xe,f.setAssistantHostVisible=qr,f.stableKey=R,f.startLazyRuntimeLoader=no,f.textChunk=Ee,f.textKey=In,f.tokenizeSimilarityText=k,f.trimProductFactsCore=K,f.trimProductFactsListCore=xn,f.uiSpec=Xt,f.withAccountConfig=Yr})(this.Gengage=this.Gengage||{});
@@ -1,4 +1,4 @@
1
- import { i as U } from "./widget-base-CIJT5AiP.js";
1
+ import { i as U } from "./widget-base-p1EKDuiI.js";
2
2
  var z = ({ element: e, renderElement: t }) => {
3
3
  if (!e.children || e.children.length === 0) return null;
4
4
  const r = document.createElement("div");
@@ -61,7 +61,7 @@ export interface InlineLauncherOptions {
61
61
  siblingPlacement?: 'before' | 'after';
62
62
  /**
63
63
  * Where the flex row is inserted inside the host when first created.
64
- * `'start'` keeps dropdown/sibling overlays below the search row (idefix-style headers).
64
+ * `'start'` keeps dropdown/sibling overlays below the search row in compact header layouts.
65
65
  * Default: `'end'`.
66
66
  */
67
67
  rowPlacement?: 'start' | 'end';
@@ -67,6 +67,7 @@ export interface SaveHistorySessionParams {
67
67
  lastBackendContext: BackendContext | null;
68
68
  pageType?: string | undefined;
69
69
  sku?: string | undefined;
70
+ attachmentPlaceholder?: string | undefined;
70
71
  }
71
72
  export declare class ChatHistoryStorage {
72
73
  private readonly _appId;
@@ -240,7 +240,7 @@ export declare class GengageChat extends BaseWidget<ChatWidgetConfig> {
240
240
  * - floating: drawer open and side panel visible (split / “maximized” layout)
241
241
  */
242
242
  private _isMaximizedForHostChrome;
243
- /** Host page scroll blocked whenever MainPane is shown (including collapsed split). */
243
+ /** Host page scroll blocked when host chrome is maximized (overlay/mobile sheet, or expanded desktop MainPane). */
244
244
  private _shouldLockHostDocumentScroll;
245
245
  private _applyOpenStateClasses;
246
246
  /** MainPane = assistant left panel; mobile counts full overlay panel as expanded. */
@@ -329,6 +329,7 @@ export interface ChatI18n {
329
329
  favoritesAriaLabel: string;
330
330
  historyAriaLabel: string;
331
331
  historyPageTitle: string;
332
+ historyImageAttachmentLabel: string;
332
333
  emptyHistoryMessage: string;
333
334
  historyDeleteLabel: string;
334
335
  historyDeleteConfirmMessage: string;
@@ -1,4 +1,4 @@
1
- import { c as e, d as t, f as r, i as s, l as n, n as i, r as l, s as C, t as c, u as d } from "./runtime-CbWCU424.js";
1
+ import { c as e, d as t, f as r, i as s, l as n, n as i, r as l, s as C, t as c, u as d } from "./runtime-_koZbJK_.js";
2
2
  export {
3
3
  d as CHAT_SCROLL_ELEMENT_ID,
4
4
  s as ChatPresentationState,