@gengage/assistant-fe 0.6.30 → 0.6.31
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.
- package/dist/{agent-ui-steps-WKbTVOS4.js → agent-ui-steps-DIWmTMuV.js} +297 -295
- package/dist/agentic/index.js +1 -1
- package/dist/agentic/types.d.ts +2 -0
- package/dist/agentic/worker/be-client.d.ts +1 -0
- package/dist/agentic/worker.js +108 -106
- package/dist/agentic.iife.js +5 -5
- package/dist/{api-paths-Bu9ctkKv.js → api-paths-D101rmWG.js} +1 -1
- package/dist/chat-runtime.js +1 -1
- package/dist/chat.iife.js +1 -1
- package/dist/chat.js +1 -1
- package/dist/{common-Cz-AVJ2C.js → common-50FH3QV2.js} +1 -1
- package/dist/common.js +5 -5
- package/dist/{connection-warning-ByISkfmd.js → connection-warning-Cc3xz5jy.js} +1 -1
- package/dist/{fastIntent-CVFoeCkX.js → fastIntent-TxOduVED.js} +1 -1
- package/dist/index.js +10 -10
- package/dist/native.iife.js +1 -1
- package/dist/qna-runtime.js +1 -1
- package/dist/qna.iife.js +1 -1
- package/dist/qna.js +1 -1
- package/dist/{runtime-fbyf-Q1_.js → runtime-BeO54n4j.js} +3 -3
- package/dist/{runtime-C_igcdtR.js → runtime-D9TnX-6x.js} +3 -3
- package/dist/{runtime-B3wxv8V8.js → runtime-D9W63PrT.js} +3 -3
- package/dist/{simbut-CfqbQIVL.js → simbut-bLkp0vVZ.js} +1 -1
- package/dist/simbut.iife.js +1 -1
- package/dist/simbut.js +1 -1
- package/dist/{simrel-vCmhTjw0.js → simrel-CP3g-Sm0.js} +1 -1
- package/dist/simrel-runtime.js +1 -1
- package/dist/simrel.iife.js +1 -1
- package/dist/simrel.js +2 -2
- package/dist/{widget-base-DgQV6knT.js → widget-base-8IG9xvDd.js} +1 -1
- package/package.json +1 -1
package/dist/agentic.iife.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(d){Object.defineProperty(d,Symbol.toStringTag,{value:"Module"});var Co=120*1e3,Po="gengage-agentic-ref";function pr({namespace:e=Po,ttlMs:t=Co,maxEntries:r=100}={}){const n=new Map;async function o(u,l={}){c();const f=Ro(),m=l.kind||"pageRef",p={kind:m,value:u,expiresAt:Date.now()+(l.ttlMs||t)};for(n.set(f,p);n.size>r;)n.delete(n.keys().next().value);return await jo(e,f,p),{kind:m,id:f}}async function i(u){const l=typeof u=="string"?u:u?.id;if(!l)return;const f=n.get(l)||await Io(e,l);if(f){if(f.expiresAt<=Date.now()){n.delete(l),await gr(e,l);return}return n.set(l,f),f.value}}async function a(u){const l=typeof u=="string"?u:u?.id;l&&(n.delete(l),await gr(e,l))}async function s(u){if(mr(u))return i(u);if(Array.isArray(u))return Promise.all(u.map(f=>s(f)));if(!u||typeof u!="object")return u;const l=await Promise.all(Object.entries(u).map(async([f,m])=>[f,await s(m)]));return Object.fromEntries(l)}function c(){const u=Date.now();for(const[l,f]of n.entries())f.expiresAt<=u&&n.delete(l)}return{put:o,get:i,delete:a,materialize:s,cleanup:c}}function mr(e){return!!(e&&typeof e=="object"&&typeof e.kind=="string"&&typeof e.id=="string")}function Ro(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function jo(e,t,r){const n=await nt(e);n&&(await Oe(n.transaction("refs","readwrite").objectStore("refs").put(r,t)),n.close())}async function Io(e,t){const r=await nt(e);if(!r)return;const n=await Oe(r.transaction("refs","readonly").objectStore("refs").get(t));return r.close(),n}async function gr(e,t){const r=await nt(e);r&&(await Oe(r.transaction("refs","readwrite").objectStore("refs").delete(t)),r.close())}async function nt(e){if(!globalThis.indexedDB)return null;try{const t=globalThis.indexedDB.open(e,1);return t.onupgradeneeded=()=>{t.result.createObjectStore("refs")},await Oe(t)}catch{return null}}function Oe(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function Lo(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function Oo({worker:e,tools:t={},beacon:r,confirmation:n,memory:o=it(),refStore:i}){e.addEventListener("message",a=>{const s=a.data;Lo(s)&&Bo(e,s,{tools:t,beacon:r,confirmation:n,memory:o,refStore:i})})}async function Bo(e,t,r){try{const n=await hr(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)}})}}var ot=new Map,yr=null;function it(){try{if(typeof sessionStorage<"u")return sessionStorage}catch{}return{getItem:e=>ot.get(e)??null,setItem:(e,t)=>{ot.set(e,t)},removeItem:e=>{ot.delete(e)}}}function Mo(){return yr||=pr(),yr}function No(e){if(e&&typeof e=="object"&&typeof e.name=="string")return e;throw new Error("tool.invoke requires { name, input }")}function $o(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.get requires { key }")}function Fo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}function qo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.remove requires { key }")}function Uo(e){return!e||typeof e!="object"?{value:e}:e}function Do(e){const t=typeof e.kind=="string"&&e.kind.trim()?e.kind.trim():void 0,r=typeof e.ttlMs=="number"&&Number.isFinite(e.ttlMs)&&e.ttlMs>0?e.ttlMs:void 0;return t||r?{...t?{kind:t}:{},...r?{ttlMs:r}:{}}:void 0}function at(e){if(e==null)return"session";if(e==="volatile"||e==="session"||e==="local"||e==="indexedDb")return e;if(typeof e=="string"){const t=e.toLowerCase();if(t==="indexeddb"||t==="idb")return"indexedDb"}throw new Error(`Unsupported memory tier: ${String(e)}`)}function st(e){return typeof e.getItem=="function"&&typeof e.setItem=="function"}function ct(e){return typeof e.get=="function"&&typeof e.set=="function"}function ut(e){return typeof e.accountId=="string"&&!!e.session&&!!e.indexedDb}function zo(e){const t=e.options?.ttlMs??e.ttlMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?{ttlMs:t}:void 0}async function Go(e,t,r){if(st(e)){const n=e.getItem(r);if(!n)return null;try{return JSON.parse(n)}catch{return e.removeItem?.(r),null}}return ct(e)&&!ut(e)?await e.get(t,r)??null:await e[t].get(r)??null}async function Ho(e,t,r,n,o){return st(e)?(e.setItem(r,JSON.stringify(n??null)),!0):ct(e)&&!ut(e)?await e.set(t,r,n??null,o)!==!1:await e[t].set(r,n??null,o)!==!1}async function Vo(e,t,r){return st(e)?(e.removeItem?.(r),!0):ct(e)&&!ut(e)?e.remove?(await e.remove(t,r),!0):!1:(await e[t].remove(r),!0)}async function hr(e,t,{tools:r,beacon:n,confirmation:o,memory:i,refStore:a}){if(e==="tool.invoke"){const{name:s,input:c}=No(t),u=r[s];if(typeof u!="function")throw new Error(`Unknown tool: ${s}`);return u(c)}if(e==="beacon.send")return n?.(t),{sent:!0};if(e==="confirmation.request"){if(typeof o!="function")throw new Error("No confirmation handler is configured.");const s=await o(t);return typeof s=="boolean"?{confirmed:s}:s}if(e==="memory.get"){const{key:s,tier:c}=$o(t);return Go(i,at(c),String(s))}if(e==="memory.set"){const s=Fo(t);return{ok:await Ho(i,at(s.tier),String(s.key),s.value,zo(s))}}if(e==="memory.remove"){const{key:s,tier:c}=qo(t);return{ok:await Vo(i,at(c),String(s))}}if(e==="ref.put"){const s=Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}),c=Uo(t);return s.put(c.value,Do(c))}if(e==="ref.get")return Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).get(t);if(e==="ref.materialize")return Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).materialize(t);if(e==="ref.remove")return await Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).delete(t),{ok:!0};throw new Error(`Unknown RPC method: ${e}`)}function Be(e){const t=e.refStore||Mo();if(!t||typeof t.put!="function"||typeof t.get!="function")throw new Error("No ref store is configured.");return t}function br(){return new Date().toISOString()}function q(e){return Math.max(0,Math.round(performance.now()-e))}function we(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ko(e){const{accountId:t,locale:r="en-GB",parentUrl:n="",threadId:o,incomingContext:i,messageLimit:a}=e,s=we(i)?i:{},c=we(s.thread)?s.thread:{},u=we(s.panel)?s.panel:{},l=we(s.meta)?s.meta:{},f=kr(s.messages,a),m={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||br()),extensions:we(c.extensions)?{...c.extensions}:{}},p=String(l.locale||r),g=String(l.parentUrl||n||typeof self<"u"&&self.location?.href||"");return{panel:{...u},messages:f,thread:m,meta:{locale:p,parentUrl:g,accountId:t}}}function wr(e,t,r){const n=kr([t],r)[0];return n?{...e,messages:Me([...e.messages,n],r)}:e}function Me(e,t){const r=Wo(t);return r===1/0?[...e]:e.slice(-r)}function kr(e,t){return Array.isArray(e)?Me(e.map(r=>{const n=r?.role;return{role:n==="model"?"assistant":typeof n=="string"?n:"",content:String(r?.content||"")}}).filter(r=>(r.role==="user"||r.role==="assistant"||r.role==="tool_result")&&(r.role==="tool_result"||!!r.content)),t):[]}function Wo(e){if(e===void 0)return 50;if(!Number.isFinite(e))return 1/0;const t=Math.floor(e);return t>0?t:50}var Jo="gengage:agent:context:";async function Zo({accountId:e,threadId:t,rpc:r}){const n=await r("memory.get",{tier:"session",key:lt(e,t)});return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function Yo({accountId:e,threadId:t,extensions:r,panel:n,rpc:o}){await o("memory.set",{tier:"session",key:lt(e,t),value:{thread:{extensions:r},...n&&Object.keys(n).length>0?{panel:n}:{}}})}function lt(e,t){return`${Jo}${e}:${t}`}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qo="gengage_agentic_savepoints",Ne="savepoints",_r=3600*1e3,Xo=1,Sr=class{#e=new Map;#i=new Map;#t;#u;#l;#a;#d;#f;#o;#s;#c;#r=new Map;constructor({accountId:e,locale:t,parentUrl:r,rpc:n,persistentPanelKeys:o=[],panelKeyLimits:i={},messageLimit:a,maxThreads:s,threadTtlMs:c}){this.#t=e,this.#u=t,this.#l=r,this.#a=n,this.#d=[...new Set(o.filter(Boolean))],this.#f=ri(i),this.#o=pt(a),this.#s=pt(s),this.#c=pt(c)}get size(){return this.pruneExpired(),this.#e.size}get(e="default"){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#n(t,r),r):null}getPanel(e="default"){return this.get(e)?.panel??null}getRecentProducts(e="default",t="last_search_products"){const r=this.getPanel(e)?.[t];return Array.isArray(r)?r:[]}async load(e){this.pruneExpired();const t=e?.session_id||e?.meta?.threadId||e?.sessionId,r=String(t||"default"),n=this.#e.get(r);if(n){const a=ii(n,e?.context,this.#o);return this.#n(r,a),a}const o=await Zo({accountId:this.#t,threadId:r,rpc:this.#a}),i=Ko({accountId:this.#t,locale:e?.locale||this.#u,parentUrl:this.#l,threadId:r,incomingContext:oi(o,e?.context),messageLimit:this.#o});return this.#n(r,i),this.#m(),i}patch(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=mt(n,typeof t=="function"?t(n):t,this.#o);return this.#n(r,o),o}appendUserMessage(e,t){this.pruneExpired();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=wr(n,{role:"user",content:t},this.#o);return this.#n(r,o),o}appendToolResult(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=wr(n,{role:"tool_result",content:String(t?.content||""),...t?.name?{name:String(t.name)}:{},...t?.details!==void 0?{details:t.details}:{}},this.#o);return this.#n(r,o),o}async commit(e){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#n(t,r),await Yo({accountId:this.#t,threadId:t,extensions:r.thread.extensions,panel:ti(r.panel,this.#d,this.#f),rpc:this.#a}),r):null}delete(e){const t=String(e||"default");return this.#i.delete(t),this.#r.delete(t),this.#e.delete(t)}clear(){this.#e.clear(),this.#i.clear(),this.#r.clear()}enqueueSteer(e,t,r="all"){this.#p(e,"steer",t,r)}enqueueFollowUp(e,t,r="all"){this.#p(e,"follow_up",t,r)}drainPending(e,t){const r=String(e||"default"),n=this.#r.get(r);if(!n||!n.length)return null;const o=n.findIndex(a=>a.kind===t);if(o<0)return null;const[i]=n.splice(o,1);return n.length||this.#r.delete(r),i||null}peekPending(e="default"){const t=String(e||"default"),r=this.#r.get(t);return r?[...r]:[]}#p(e,t,r,n){const o=String(r||"").trim();if(!o)return;const i=String(e||"default"),a=this.#r.get(i)||[];if(n==="one-at-a-time")for(let s=a.length-1;s>=0;s-=1)a[s].kind===t&&a.splice(s,1);a.push({kind:t,text:o,enqueuedAt:Date.now()}),this.#r.set(i,a)}async savepoint(e,t,r){if(!e||typeof t!="number"||!Number.isFinite(t))return;const n={threadId:e,turnIndex:t,payload:r,createdAt:Date.now()};try{await ft(this.#t,"readwrite",o=>{o.put(n,dt(e,t))})}catch{}}async restoreSavepoint(e,t){if(!e)return null;try{let r=null;return await ft(this.#t,"readonly",n=>{const o=typeof t=="number"?dt(e,t):null;if(o!==null){const i=n.get(o);i.onsuccess=()=>{const a=i.result;a&&Date.now()-a.createdAt<_r&&(r=a)}}else{const i=n.openCursor(null,"prev");i.onsuccess=()=>{const a=i.result;if(!a||r)return;const s=a.value;if(s.threadId!==e){a.continue();return}Date.now()-s.createdAt<_r&&(r=s)}}}),r}catch{return null}}async clearSavepoint(e,t){if(e)try{await ft(this.#t,"readwrite",r=>{if(typeof t=="number"){r.delete(dt(e,t));return}const n=r.openCursor();n.onsuccess=()=>{const o=n.result;o&&(o.value.threadId===e&&o.delete(),o.continue())}})}catch{}}pruneExpired(e=Date.now()){if(!this.#c)return 0;let t=0;for(const[r,n]of this.#i)e-n<=this.#c||(this.#i.delete(r),this.#e.delete(r)&&(t+=1));return t}#n(e,t){this.#e.delete(e),this.#e.set(e,t),this.#i.set(e,Date.now())}#m(){if(this.#s)for(;this.#e.size>this.#s;){const e=this.#e.keys().next().value;if(!e)return;this.delete(e)}}};function dt(e,t){return`${e}|${t}`}function ei(){return(typeof self<"u"?self:globalThis)?.indexedDB||null}async function ft(e,t,r){const n=ei();if(!n)return;const o=`${Qo}_${e}`;await new Promise((i,a)=>{const s=n.open(o,Xo);s.onupgradeneeded=()=>{const c=s.result;c.objectStoreNames.contains(Ne)||c.createObjectStore(Ne)},s.onerror=()=>a(s.error||new Error("savepoint:open_failed")),s.onsuccess=()=>{const c=s.result;try{const u=c.transaction(Ne,t);r(u.objectStore(Ne)),u.oncomplete=()=>{c.close(),i()},u.onerror=()=>{c.close(),a(u.error||new Error("savepoint:tx_failed"))},u.onabort=()=>{c.close(),a(u.error||new Error("savepoint:tx_aborted"))}}catch(u){c.close(),a(u instanceof Error?u:new Error(String(u)))}}})}function ti(e,t,r){if(!t.length||!C(e))return;const n={};for(const o of t)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=ni(e[o],r[o]));return n}function ri(e){const t={};for(const[r,n]of Object.entries(e||{})){const o=Math.floor(Number(n));r&&Number.isFinite(o)&&o>0&&(t[r]=o)}return t}function pt(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function ni(e,t){return!t||!Array.isArray(e)?e:e.slice(-t)}function oi(e,t){if(!C(e)&&!C(t))return{};const r=C(e)?e:{},n=mt(r,C(t)?t:{});return C(r.panel)&&(n.panel=r.panel),n}function ii(e,t,r){if(!C(t))return e;const n=mt(e,t,r);return{...n,panel:e.panel,thread:{...n.thread,id:e.thread.id,started_at:e.thread.started_at},meta:{...n.meta,accountId:e.meta.accountId}}}function mt(e,t,r){if(!C(t))return e;const n=e,o=t,i=C(n.panel)?n.panel:{},a=C(o.panel)?o.panel:{},s=C(n.thread)?n.thread:{},c=C(o.thread)?o.thread:{},u=C(s.extensions)?s.extensions:{},l=C(c.extensions)?c.extensions:{},f=C(n.meta)?n.meta:{},m=C(o.meta)?o.meta:{};return{...e,...t,panel:{...i,...a},thread:{...s,...c,extensions:{...u,...l}},meta:{...f,...m},messages:Array.isArray(o.messages)?Me(o.messages,r):e.messages??[]}}function Ar(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function vr(e){return Ar(new TextEncoder().encode(JSON.stringify(e)))}async function ai({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=`${vr({alg:"HS256",typ:"JWT"})}.${vr({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}.${Ar(new Uint8Array(a))}`}function gt({accountId:e,devJwtSecret:t,tokenBrokerUrl:r,tokenBrokerAudience:n,refreshSkewS:o=30,fetchImpl:i=fetch}){let a=null;return async({signal:s,parentUrl:c}={})=>{if(t)return ai({accountId:e,devJwtSecret:t});if(!r)throw new Error("tokenBrokerUrl is required for production agent mode.");const u=Math.floor(Date.now()/1e3);return a?.token&&a.expiresAtS-o>u||(a=await si({accountId:e,tokenBrokerUrl:r,tokenBrokerAudience:n,parentUrl:c,signal:s,fetchImpl:i})),a.token}}async function si({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 s=await a.json(),c=s?.token||s?.jwt||s?.access_token;if(!c||typeof c!="string")throw new Error("Token broker response did not include a JWT.");return{token:c,expiresAtS:ci(s)||ui(c)||Math.floor(Date.now()/1e3)+300}}function ci(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 ui(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 Tr={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."}},B=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 yt(e){const t=String(e?.code||"upstream_llm"),r=Tr[t]||Tr.upstream_llm;return new B(r.code,r.message,{source:"be",sourceCode:t,detail:e?.detail})}function xr(e,t){const r=t?.error&&typeof t.error=="object"?t.error:{};return yt({code:String(r.code||li(e)),detail:r.detail})}function Er(e){return e instanceof B?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function li(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var di=7200*1e3,Cr=200,fi=5*1024*1024,pi="gengage_request_response_cache",mi=1,U="responses",gi=new Set(["addToCart","like"]),D=new Map,Pr=null;async function yi(e,t={},r={}){const n=hi(e,t);if(!n)return fetch(e,t);const o=Date.now(),i=await wi(n,o);if(i)return Si(i);const a=await fetch(e,t);return a.ok&&ki(n,a.clone(),o,{ttlMs:r.ttlMs??di,maxEntries:r.maxEntries??Cr,maxBodyBytes:r.maxBodyBytes??fi}),a}function hi(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"||bi(t.body)?null:`rr:${Pi(Ci({url:String(e),method:r,headers:Ai(t.headers),body:t.body}))}`}function bi(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"&&gi.has(r)}catch{return!1}}async function wi(e,t){const r=D.get(e);if(r)if(r.expiresAt<=t)D.delete(e);else return r.lastAccessedAt=t,D.delete(e),D.set(e,r),ht(r),r;const n=await Ti(e);return n?n.expiresAt<=t?(D.delete(e),xi(e),null):(n.lastAccessedAt=t,D.set(e,n),ht(n),Rr(Cr),n):null}async function ki(e,t,r,n){try{const o=await t.text();if(Ri(o)>n.maxBodyBytes||_i(o))return;const i={key:e,status:t.status,statusText:t.statusText,headers:vi(t.headers),body:o,createdAt:r,expiresAt:r+n.ttlMs,lastAccessedAt:r};D.set(e,i),Rr(n.maxEntries),await ht(i),await Ei(n.maxEntries,r)}catch{}}function _i(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function Si(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function Ai(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 vi(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 Rr(e){for(;D.size>e;){const t=[...D.values()].sort((r,n)=>r.lastAccessedAt-n.lastAccessedAt)[0];if(!t)break;D.delete(t.key)}}async function $e(){return typeof indexedDB>"u"?null:(Pr??=new Promise(e=>{const t=indexedDB.open(pi,mi);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(U)||r.createObjectStore(U,{keyPath:"key"}).createIndex("lastAccessedAt","lastAccessedAt",{unique:!1})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),Pr)}async function Ti(e){const t=await $e();return t?new Promise(r=>{const n=t.transaction(U,"readonly"),o=n.objectStore(U).get(e);o.onsuccess=()=>r(o.result??null),o.onerror=()=>r(null),n.onerror=()=>r(null)}):null}async function ht(e){const t=await $e();t&&await new Promise(r=>{const n=t.transaction(U,"readwrite");n.objectStore(U).put(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function xi(e){const t=await $e();t&&await new Promise(r=>{const n=t.transaction(U,"readwrite");n.objectStore(U).delete(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function Ei(e,t){const r=await $e();r&&await new Promise(n=>{const o=r.transaction(U,"readwrite"),i=o.objectStore(U),a=[],s=i.openCursor();s.onsuccess=()=>{const c=s.result;if(!c){const u=a.filter(f=>f.expiresAt<=t),l=a.filter(f=>f.expiresAt>t).sort((f,m)=>f.lastAccessedAt-m.lastAccessedAt).slice(0,Math.max(0,a.length-u.length-e));for(const f of[...u,...l])i.delete(f.key);return}a.push(c.value),c.continue()},s.onerror=()=>n(),o.oncomplete=()=>n(),o.onerror=()=>n(),o.onabort=()=>n()})}function Ci(e){return JSON.stringify(bt(e))}function bt(e){return Array.isArray(e)?e.map(bt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,bt(r)]))}function Pi(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 Ri(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function ji(e){const{beUrl:t,accountId:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,jwtProvider:a,parentUrl:s,op:c,input:u,cacheTtlS:l,cacheKey:f,browserCache:m,signal:p,interceptors:g}=e,h=await(a||gt({accountId:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i}))({...p?{signal:p}:{},...s?{parentUrl:s}:{}}),{opDomain:y,opName:b}=Ii(c,r);let w={method:"POST",headers:{authorization:`Bearer ${h}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:y,op_name:b,op_payload:u,...l!==void 0?{cache_ttl_s:l}:{},...f!==void 0?{cache_key:f}:{}}),...p?{signal:p}:{}};const v=`${String(t).replace(/\/+$/u,"")}/v1/execute`;if(g?.beforeRequest){const k=await g.beforeRequest(e,{url:v,init:w});if(k&&"cached"in k&&k.cached!==void 0)return k.cached;k?.init&&(w=k.init)}const S=m===!1?await fetch(v,w):await yi(v,w,typeof m=="object"?m:{});if(!S.ok)throw xr(S.status,await Oi(S));let E=await Bi(S);if(g?.afterResponse){const k=await g.afterResponse(e,E);k&&"result"in k&&k.result!==void 0&&(E=k.result)}return E}function Ii(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:Li(t),opName:e}}function Li(e){return e.replace(/-agentic$/u,"")}async function Oi(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function Bi(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:s}=await t.read();if(s)break;n+=r.decode(a,{stream:!0});let c=n.indexOf(`
|
|
1
|
+
(function(d){Object.defineProperty(d,Symbol.toStringTag,{value:"Module"});var Co=120*1e3,Po="gengage-agentic-ref";function pr({namespace:e=Po,ttlMs:t=Co,maxEntries:r=100}={}){const n=new Map;async function o(u,l={}){c();const f=Ro(),m=l.kind||"pageRef",p={kind:m,value:u,expiresAt:Date.now()+(l.ttlMs||t)};for(n.set(f,p);n.size>r;)n.delete(n.keys().next().value);return await jo(e,f,p),{kind:m,id:f}}async function i(u){const l=typeof u=="string"?u:u?.id;if(!l)return;const f=n.get(l)||await Io(e,l);if(f){if(f.expiresAt<=Date.now()){n.delete(l),await gr(e,l);return}return n.set(l,f),f.value}}async function a(u){const l=typeof u=="string"?u:u?.id;l&&(n.delete(l),await gr(e,l))}async function s(u){if(mr(u))return i(u);if(Array.isArray(u))return Promise.all(u.map(f=>s(f)));if(!u||typeof u!="object")return u;const l=await Promise.all(Object.entries(u).map(async([f,m])=>[f,await s(m)]));return Object.fromEntries(l)}function c(){const u=Date.now();for(const[l,f]of n.entries())f.expiresAt<=u&&n.delete(l)}return{put:o,get:i,delete:a,materialize:s,cleanup:c}}function mr(e){return!!(e&&typeof e=="object"&&typeof e.kind=="string"&&typeof e.id=="string")}function Ro(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function jo(e,t,r){const n=await nt(e);n&&(await Oe(n.transaction("refs","readwrite").objectStore("refs").put(r,t)),n.close())}async function Io(e,t){const r=await nt(e);if(!r)return;const n=await Oe(r.transaction("refs","readonly").objectStore("refs").get(t));return r.close(),n}async function gr(e,t){const r=await nt(e);r&&(await Oe(r.transaction("refs","readwrite").objectStore("refs").delete(t)),r.close())}async function nt(e){if(!globalThis.indexedDB)return null;try{const t=globalThis.indexedDB.open(e,1);return t.onupgradeneeded=()=>{t.result.createObjectStore("refs")},await Oe(t)}catch{return null}}function Oe(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function Lo(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function Oo({worker:e,tools:t={},beacon:r,confirmation:n,memory:o=it(),refStore:i}){e.addEventListener("message",a=>{const s=a.data;Lo(s)&&Bo(e,s,{tools:t,beacon:r,confirmation:n,memory:o,refStore:i})})}async function Bo(e,t,r){try{const n=await hr(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)}})}}var ot=new Map,yr=null;function it(){try{if(typeof sessionStorage<"u")return sessionStorage}catch{}return{getItem:e=>ot.get(e)??null,setItem:(e,t)=>{ot.set(e,t)},removeItem:e=>{ot.delete(e)}}}function Mo(){return yr||=pr(),yr}function No(e){if(e&&typeof e=="object"&&typeof e.name=="string")return e;throw new Error("tool.invoke requires { name, input }")}function $o(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.get requires { key }")}function Fo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}function qo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.remove requires { key }")}function Uo(e){return!e||typeof e!="object"?{value:e}:e}function Do(e){const t=typeof e.kind=="string"&&e.kind.trim()?e.kind.trim():void 0,r=typeof e.ttlMs=="number"&&Number.isFinite(e.ttlMs)&&e.ttlMs>0?e.ttlMs:void 0;return t||r?{...t?{kind:t}:{},...r?{ttlMs:r}:{}}:void 0}function at(e){if(e==null)return"session";if(e==="volatile"||e==="session"||e==="local"||e==="indexedDb")return e;if(typeof e=="string"){const t=e.toLowerCase();if(t==="indexeddb"||t==="idb")return"indexedDb"}throw new Error(`Unsupported memory tier: ${String(e)}`)}function st(e){return typeof e.getItem=="function"&&typeof e.setItem=="function"}function ct(e){return typeof e.get=="function"&&typeof e.set=="function"}function ut(e){return typeof e.accountId=="string"&&!!e.session&&!!e.indexedDb}function zo(e){const t=e.options?.ttlMs??e.ttlMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?{ttlMs:t}:void 0}async function Go(e,t,r){if(st(e)){const n=e.getItem(r);if(!n)return null;try{return JSON.parse(n)}catch{return e.removeItem?.(r),null}}return ct(e)&&!ut(e)?await e.get(t,r)??null:await e[t].get(r)??null}async function Ho(e,t,r,n,o){return st(e)?(e.setItem(r,JSON.stringify(n??null)),!0):ct(e)&&!ut(e)?await e.set(t,r,n??null,o)!==!1:await e[t].set(r,n??null,o)!==!1}async function Vo(e,t,r){return st(e)?(e.removeItem?.(r),!0):ct(e)&&!ut(e)?e.remove?(await e.remove(t,r),!0):!1:(await e[t].remove(r),!0)}async function hr(e,t,{tools:r,beacon:n,confirmation:o,memory:i,refStore:a}){if(e==="tool.invoke"){const{name:s,input:c}=No(t),u=r[s];if(typeof u!="function")throw new Error(`Unknown tool: ${s}`);return u(c)}if(e==="beacon.send")return n?.(t),{sent:!0};if(e==="confirmation.request"){if(typeof o!="function")throw new Error("No confirmation handler is configured.");const s=await o(t);return typeof s=="boolean"?{confirmed:s}:s}if(e==="memory.get"){const{key:s,tier:c}=$o(t);return Go(i,at(c),String(s))}if(e==="memory.set"){const s=Fo(t);return{ok:await Ho(i,at(s.tier),String(s.key),s.value,zo(s))}}if(e==="memory.remove"){const{key:s,tier:c}=qo(t);return{ok:await Vo(i,at(c),String(s))}}if(e==="ref.put"){const s=Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}),c=Uo(t);return s.put(c.value,Do(c))}if(e==="ref.get")return Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).get(t);if(e==="ref.materialize")return Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).materialize(t);if(e==="ref.remove")return await Be({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).delete(t),{ok:!0};throw new Error(`Unknown RPC method: ${e}`)}function Be(e){const t=e.refStore||Mo();if(!t||typeof t.put!="function"||typeof t.get!="function")throw new Error("No ref store is configured.");return t}function br(){return new Date().toISOString()}function q(e){return Math.max(0,Math.round(performance.now()-e))}function we(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ko(e){const{accountId:t,locale:r="en-GB",parentUrl:n="",threadId:o,incomingContext:i,messageLimit:a}=e,s=we(i)?i:{},c=we(s.thread)?s.thread:{},u=we(s.panel)?s.panel:{},l=we(s.meta)?s.meta:{},f=kr(s.messages,a),m={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||br()),extensions:we(c.extensions)?{...c.extensions}:{}},p=String(l.locale||r),g=String(l.parentUrl||n||typeof self<"u"&&self.location?.href||"");return{panel:{...u},messages:f,thread:m,meta:{locale:p,parentUrl:g,accountId:t}}}function wr(e,t,r){const n=kr([t],r)[0];return n?{...e,messages:Me([...e.messages,n],r)}:e}function Me(e,t){const r=Wo(t);return r===1/0?[...e]:e.slice(-r)}function kr(e,t){return Array.isArray(e)?Me(e.map(r=>{const n=r?.role;return{role:n==="model"?"assistant":typeof n=="string"?n:"",content:String(r?.content||"")}}).filter(r=>(r.role==="user"||r.role==="assistant"||r.role==="tool_result")&&(r.role==="tool_result"||!!r.content)),t):[]}function Wo(e){if(e===void 0)return 50;if(!Number.isFinite(e))return 1/0;const t=Math.floor(e);return t>0?t:50}var Jo="gengage:agent:context:";async function Zo({accountId:e,threadId:t,rpc:r}){const n=await r("memory.get",{tier:"session",key:lt(e,t)});return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function Yo({accountId:e,threadId:t,extensions:r,panel:n,rpc:o}){await o("memory.set",{tier:"session",key:lt(e,t),value:{thread:{extensions:r},...n&&Object.keys(n).length>0?{panel:n}:{}}})}function lt(e,t){return`${Jo}${e}:${t}`}function P(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qo="gengage_agentic_savepoints",Ne="savepoints",_r=3600*1e3,Xo=1,Sr=class{#e=new Map;#i=new Map;#t;#u;#l;#a;#d;#f;#o;#s;#c;#r=new Map;constructor({accountId:e,locale:t,parentUrl:r,rpc:n,persistentPanelKeys:o=[],panelKeyLimits:i={},messageLimit:a,maxThreads:s,threadTtlMs:c}){this.#t=e,this.#u=t,this.#l=r,this.#a=n,this.#d=[...new Set(o.filter(Boolean))],this.#f=ri(i),this.#o=pt(a),this.#s=pt(s),this.#c=pt(c)}get size(){return this.pruneExpired(),this.#e.size}get(e="default"){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#n(t,r),r):null}getPanel(e="default"){return this.get(e)?.panel??null}getRecentProducts(e="default",t="last_search_products"){const r=this.getPanel(e)?.[t];return Array.isArray(r)?r:[]}async load(e){this.pruneExpired();const t=e?.session_id||e?.meta?.threadId||e?.sessionId,r=String(t||"default"),n=this.#e.get(r);if(n){const a=ii(n,e?.context,this.#o);return this.#n(r,a),a}const o=await Zo({accountId:this.#t,threadId:r,rpc:this.#a}),i=Ko({accountId:this.#t,locale:e?.locale||this.#u,parentUrl:this.#l,threadId:r,incomingContext:oi(o,e?.context),messageLimit:this.#o});return this.#n(r,i),this.#m(),i}patch(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=mt(n,typeof t=="function"?t(n):t,this.#o);return this.#n(r,o),o}appendUserMessage(e,t){this.pruneExpired();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=wr(n,{role:"user",content:t},this.#o);return this.#n(r,o),o}appendToolResult(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=wr(n,{role:"tool_result",content:String(t?.content||""),...t?.name?{name:String(t.name)}:{},...t?.details!==void 0?{details:t.details}:{}},this.#o);return this.#n(r,o),o}async commit(e){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#n(t,r),await Yo({accountId:this.#t,threadId:t,extensions:r.thread.extensions,panel:ti(r.panel,this.#d,this.#f),rpc:this.#a}),r):null}delete(e){const t=String(e||"default");return this.#i.delete(t),this.#r.delete(t),this.#e.delete(t)}clear(){this.#e.clear(),this.#i.clear(),this.#r.clear()}enqueueSteer(e,t,r="all"){this.#p(e,"steer",t,r)}enqueueFollowUp(e,t,r="all"){this.#p(e,"follow_up",t,r)}drainPending(e,t){const r=String(e||"default"),n=this.#r.get(r);if(!n||!n.length)return null;const o=n.findIndex(a=>a.kind===t);if(o<0)return null;const[i]=n.splice(o,1);return n.length||this.#r.delete(r),i||null}peekPending(e="default"){const t=String(e||"default"),r=this.#r.get(t);return r?[...r]:[]}#p(e,t,r,n){const o=String(r||"").trim();if(!o)return;const i=String(e||"default"),a=this.#r.get(i)||[];if(n==="one-at-a-time")for(let s=a.length-1;s>=0;s-=1)a[s].kind===t&&a.splice(s,1);a.push({kind:t,text:o,enqueuedAt:Date.now()}),this.#r.set(i,a)}async savepoint(e,t,r){if(!e||typeof t!="number"||!Number.isFinite(t))return;const n={threadId:e,turnIndex:t,payload:r,createdAt:Date.now()};try{await ft(this.#t,"readwrite",o=>{o.put(n,dt(e,t))})}catch{}}async restoreSavepoint(e,t){if(!e)return null;try{let r=null;return await ft(this.#t,"readonly",n=>{const o=typeof t=="number"?dt(e,t):null;if(o!==null){const i=n.get(o);i.onsuccess=()=>{const a=i.result;a&&Date.now()-a.createdAt<_r&&(r=a)}}else{const i=n.openCursor(null,"prev");i.onsuccess=()=>{const a=i.result;if(!a||r)return;const s=a.value;if(s.threadId!==e){a.continue();return}Date.now()-s.createdAt<_r&&(r=s)}}}),r}catch{return null}}async clearSavepoint(e,t){if(e)try{await ft(this.#t,"readwrite",r=>{if(typeof t=="number"){r.delete(dt(e,t));return}const n=r.openCursor();n.onsuccess=()=>{const o=n.result;o&&(o.value.threadId===e&&o.delete(),o.continue())}})}catch{}}pruneExpired(e=Date.now()){if(!this.#c)return 0;let t=0;for(const[r,n]of this.#i)e-n<=this.#c||(this.#i.delete(r),this.#e.delete(r)&&(t+=1));return t}#n(e,t){this.#e.delete(e),this.#e.set(e,t),this.#i.set(e,Date.now())}#m(){if(this.#s)for(;this.#e.size>this.#s;){const e=this.#e.keys().next().value;if(!e)return;this.delete(e)}}};function dt(e,t){return`${e}|${t}`}function ei(){return(typeof self<"u"?self:globalThis)?.indexedDB||null}async function ft(e,t,r){const n=ei();if(!n)return;const o=`${Qo}_${e}`;await new Promise((i,a)=>{const s=n.open(o,Xo);s.onupgradeneeded=()=>{const c=s.result;c.objectStoreNames.contains(Ne)||c.createObjectStore(Ne)},s.onerror=()=>a(s.error||new Error("savepoint:open_failed")),s.onsuccess=()=>{const c=s.result;try{const u=c.transaction(Ne,t);r(u.objectStore(Ne)),u.oncomplete=()=>{c.close(),i()},u.onerror=()=>{c.close(),a(u.error||new Error("savepoint:tx_failed"))},u.onabort=()=>{c.close(),a(u.error||new Error("savepoint:tx_aborted"))}}catch(u){c.close(),a(u instanceof Error?u:new Error(String(u)))}}})}function ti(e,t,r){if(!t.length||!P(e))return;const n={};for(const o of t)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=ni(e[o],r[o]));return n}function ri(e){const t={};for(const[r,n]of Object.entries(e||{})){const o=Math.floor(Number(n));r&&Number.isFinite(o)&&o>0&&(t[r]=o)}return t}function pt(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function ni(e,t){return!t||!Array.isArray(e)?e:e.slice(-t)}function oi(e,t){if(!P(e)&&!P(t))return{};const r=P(e)?e:{},n=mt(r,P(t)?t:{});return P(r.panel)&&(n.panel=r.panel),n}function ii(e,t,r){if(!P(t))return e;const n=mt(e,t,r);return{...n,panel:e.panel,thread:{...n.thread,id:e.thread.id,started_at:e.thread.started_at},meta:{...n.meta,accountId:e.meta.accountId}}}function mt(e,t,r){if(!P(t))return e;const n=e,o=t,i=P(n.panel)?n.panel:{},a=P(o.panel)?o.panel:{},s=P(n.thread)?n.thread:{},c=P(o.thread)?o.thread:{},u=P(s.extensions)?s.extensions:{},l=P(c.extensions)?c.extensions:{},f=P(n.meta)?n.meta:{},m=P(o.meta)?o.meta:{};return{...e,...t,panel:{...i,...a},thread:{...s,...c,extensions:{...u,...l}},meta:{...f,...m},messages:Array.isArray(o.messages)?Me(o.messages,r):e.messages??[]}}function vr(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function Ar(e){return vr(new TextEncoder().encode(JSON.stringify(e)))}async function ai({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=`${Ar({alg:"HS256",typ:"JWT"})}.${Ar({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}.${vr(new Uint8Array(a))}`}function gt({accountId:e,devJwtSecret:t,tokenBrokerUrl:r,tokenBrokerAudience:n,refreshSkewS:o=30,fetchImpl:i=fetch}){let a=null;return async({signal:s,parentUrl:c}={})=>{if(t)return ai({accountId:e,devJwtSecret:t});if(!r)throw new Error("tokenBrokerUrl is required for production agent mode.");const u=Math.floor(Date.now()/1e3);return a?.token&&a.expiresAtS-o>u||(a=await si({accountId:e,tokenBrokerUrl:r,tokenBrokerAudience:n,parentUrl:c,signal:s,fetchImpl:i})),a.token}}async function si({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 s=await a.json(),c=s?.token||s?.jwt||s?.access_token;if(!c||typeof c!="string")throw new Error("Token broker response did not include a JWT.");return{token:c,expiresAtS:ci(s)||ui(c)||Math.floor(Date.now()/1e3)+300}}function ci(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 ui(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 Tr={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."}},M=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 yt(e){const t=String(e?.code||"upstream_llm"),r=Tr[t]||Tr.upstream_llm;return new M(r.code,r.message,{source:"be",sourceCode:t,detail:e?.detail})}function xr(e,t){const r=t?.error&&typeof t.error=="object"?t.error:{};return yt({code:String(r.code||li(e)),detail:r.detail})}function Er(e){return e instanceof M?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function li(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var di=7200*1e3,Cr=200,fi=5*1024*1024,pi="gengage_request_response_cache",mi=1,U="responses",gi=new Set(["addToCart","like"]),D=new Map,Pr=null;async function yi(e,t={},r={}){const n=hi(e,t);if(!n)return fetch(e,t);const o=Date.now(),i=await wi(n,o);if(i)return Si(i);const a=await fetch(e,t);return a.ok&&ki(n,a.clone(),o,{ttlMs:r.ttlMs??di,maxEntries:r.maxEntries??Cr,maxBodyBytes:r.maxBodyBytes??fi}),a}function hi(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"||bi(t.body)?null:`rr:${Pi(Ci({url:String(e),method:r,headers:vi(t.headers),body:t.body}))}`}function bi(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"&&gi.has(r)}catch{return!1}}async function wi(e,t){const r=D.get(e);if(r)if(r.expiresAt<=t)D.delete(e);else return r.lastAccessedAt=t,D.delete(e),D.set(e,r),ht(r),r;const n=await Ti(e);return n?n.expiresAt<=t?(D.delete(e),xi(e),null):(n.lastAccessedAt=t,D.set(e,n),ht(n),Rr(Cr),n):null}async function ki(e,t,r,n){try{const o=await t.text();if(Ri(o)>n.maxBodyBytes||_i(o))return;const i={key:e,status:t.status,statusText:t.statusText,headers:Ai(t.headers),body:o,createdAt:r,expiresAt:r+n.ttlMs,lastAccessedAt:r};D.set(e,i),Rr(n.maxEntries),await ht(i),await Ei(n.maxEntries,r)}catch{}}function _i(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function Si(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function vi(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 Ai(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 Rr(e){for(;D.size>e;){const t=[...D.values()].sort((r,n)=>r.lastAccessedAt-n.lastAccessedAt)[0];if(!t)break;D.delete(t.key)}}async function $e(){return typeof indexedDB>"u"?null:(Pr??=new Promise(e=>{const t=indexedDB.open(pi,mi);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(U)||r.createObjectStore(U,{keyPath:"key"}).createIndex("lastAccessedAt","lastAccessedAt",{unique:!1})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),Pr)}async function Ti(e){const t=await $e();return t?new Promise(r=>{const n=t.transaction(U,"readonly"),o=n.objectStore(U).get(e);o.onsuccess=()=>r(o.result??null),o.onerror=()=>r(null),n.onerror=()=>r(null)}):null}async function ht(e){const t=await $e();t&&await new Promise(r=>{const n=t.transaction(U,"readwrite");n.objectStore(U).put(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function xi(e){const t=await $e();t&&await new Promise(r=>{const n=t.transaction(U,"readwrite");n.objectStore(U).delete(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function Ei(e,t){const r=await $e();r&&await new Promise(n=>{const o=r.transaction(U,"readwrite"),i=o.objectStore(U),a=[],s=i.openCursor();s.onsuccess=()=>{const c=s.result;if(!c){const u=a.filter(f=>f.expiresAt<=t),l=a.filter(f=>f.expiresAt>t).sort((f,m)=>f.lastAccessedAt-m.lastAccessedAt).slice(0,Math.max(0,a.length-u.length-e));for(const f of[...u,...l])i.delete(f.key);return}a.push(c.value),c.continue()},s.onerror=()=>n(),o.oncomplete=()=>n(),o.onerror=()=>n(),o.onabort=()=>n()})}function Ci(e){return JSON.stringify(bt(e))}function bt(e){return Array.isArray(e)?e.map(bt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,bt(r)]))}function Pi(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 Ri(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function ji(e){const{beUrl:t,accountId:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,jwtProvider:a,parentUrl:s,op:c,input:u,cacheTtlS:l,cacheKey:f,cacheFreshness:m,browserCache:p,signal:g,interceptors:h}=e,y=await(a||gt({accountId:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i}))({...g?{signal:g}:{},...s?{parentUrl:s}:{}}),{opDomain:b,opName:w}=Ii(c,r);let v={method:"POST",headers:{authorization:`Bearer ${y}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:b,op_name:w,op_payload:u,...l!==void 0?{cache_ttl_s:l}:{},...f!==void 0?{cache_key:f}:{},...m!==void 0?{cache_freshness:m}:{}}),...g?{signal:g}:{}};const _=`${String(t).replace(/\/+$/u,"")}/v1/execute`;if(h?.beforeRequest){const T=await h.beforeRequest(e,{url:_,init:v});if(T&&"cached"in T&&T.cached!==void 0)return T.cached;T?.init&&(v=T.init)}const C=p===!1?await fetch(_,v):await yi(_,v,typeof p=="object"?p:{});if(!C.ok)throw xr(C.status,await Oi(C));let A=await Bi(C);if(h?.afterResponse){const T=await h.afterResponse(e,A);T&&"result"in T&&T.result!==void 0&&(A=T.result)}return A}function Ii(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:Li(t),opName:e}}function Li(e){return e.replace(/-agentic$/u,"")}async function Oi(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function Bi(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:s}=await t.read();if(s)break;n+=r.decode(a,{stream:!0});let c=n.indexOf(`
|
|
2
2
|
`);for(;c>=0;){const u=n.slice(0,c).trim();n=n.slice(c+1),u&&jr(JSON.parse(u),o),c=n.indexOf(`
|
|
3
|
-
`)}}const i=n.trim();return i&&jr(JSON.parse(i),o),o}function jr(e,t){if(e._error)throw yt(e._error);if(!e._end)for(const[r,n]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,r))throw new B("op_failed",`BE streamed duplicate field "${r}".`,{source:"be",sourceCode:"schema_mismatch"});t[r]=n}}function Mi(e={}){return{type:"metadata",...e}}function Ir(e,t=!1,r={}){return{type:"text_chunk",content:e,final:t,...r}}function Ni(e){return{type:"ui_spec",...e}}function $i(e){return{type:"action",action:e}}function Lr(e,t){return{type:"error",code:e,message:t}}function wt(){return{type:"done"}}function Or(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}function Br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fe(e,t={}){const r=Br(e);if(!r)return null;const n=t.catalogMapper?.(r);if(n)return n;const o=oe(r.sku,r.SKU);if(!o)return null;const i={sku:o,name:oe(r.name,r.title,r.short_name,o)||o,url:oe(r.url)||""},a=Array.isArray(r.images)?r.images:void 0,s=oe(r.imageUrl,r.image_url,r.image,a?.[0]);s&&(i.imageUrl=s),a&&a.length>1&&(i.images=a.filter(b=>!!b).map(String));const c=ke(r.price_discounted),u=ke(r.price),l=c||u;l>0&&(i.price=String(l));const f=c>0?u:0;f>0&&(i.originalPrice=String(f));const m=oe(r.brand);m&&(i.brand=m);const p=ke(r.rating);p>0&&(i.rating=p);const g=ke(r.review_count)||ke(r.reviewCount);g>0&&(i.reviewCount=g);const h=oe(r.cart_code,r.cartCode);h&&(i.cartCode=h),typeof r.in_stock=="boolean"&&(i.inStock=r.in_stock),typeof r.inStock=="boolean"&&(i.inStock=r.inStock);const y=r.category_names;return Array.isArray(y)&&(i.categoryNames=y.map(String)),i}function qe(e){const t=Br(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 s of Object.keys(a))a[s]===void 0&&delete a[s];return a}function Fi(e){return Array.isArray(e)?e.map(qe).filter(t=>!!t):[]}function oe(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function ke(e){const t=Number(e);return Number.isFinite(t)?t:0}function Mr(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function kt(e,t,r={}){return`${e}:${r.version||"v2"}:${ie(t)}`}function qi(e,t={}){return Nr(e).map(r=>$r(typeof r=="string"?r:r.sku,t.locale)).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n).sort((r,n)=>_t(r,n,t.locale)).slice(0,t.limit||16).join(",")}function Ui(e,t={}){return ie(Nr(e).map(r=>zi(r,t)).filter(r=>!!r).sort((r,n)=>_t(String(r.sku||r.name||""),String(n.sku||n.name||""),t.locale)).slice(0,t.limit||16))}function Di(e,t){return Q(e,t)}function ie(e){let t=2166136261;const r=Gi(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 zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=t.mapProduct?.(r);if(n)return _e(n);const o=qe(r);return o&&typeof o=="object"&&!Array.isArray(o)?_e(Hi(o,t)):null}function Nr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function Gi(e){return JSON.stringify(_e(e))}function _e(e){return Array.isArray(e)?e.map(_e):!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,_e(r)]))}function Hi(e,t){return{sku:$r(e.sku,t.locale),name:Q(e.name,t.locale),url:Q(e.url,t.locale),price:e.price,currency:Q(e.currency,t.locale),category:Q(e.category,t.locale),category_names:Vi(e.category_names,t.locale,16),image:Q(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function $r(e,t){return Q(e,t).toUpperCase()}function Q(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function _t(e,t,r){return e.localeCompare(t,r,{numeric:!0})}function Vi(e,t,r){return Array.isArray(e)?e.map(n=>Q(n,t)).filter(Boolean).sort((n,o)=>_t(n,o,t)).slice(0,r):void 0}function Fr(e,t){if(!e)return{ok:!0};const r=[];return St(e,t,"",r),r.length?{ok:!1,error:r[0]||"invalid"}:{ok:!0}}function St(e,t,r,n){if(e){if(Array.isArray(e.enum)&&!e.enum.includes(t)){n.push(`${r||"value"} must be one of [${e.enum.join(", ")}]`);return}switch(e.type){case"string":if(typeof t!="string"){n.push(`${r||"value"} must be a string`);return}e.minLength&&t.length<e.minLength&&n.push(`${r||"value"} must be at least ${e.minLength} chars`);return;case"number":if(typeof t!="number"||!Number.isFinite(t)){n.push(`${r||"value"} must be a number`);return}e.minimum!=null&&t<e.minimum&&n.push(`${r||"value"} must be >= ${e.minimum}`),e.maximum!=null&&t>e.maximum&&n.push(`${r||"value"} must be <= ${e.maximum}`);return;case"boolean":typeof t!="boolean"&&n.push(`${r||"value"} must be a boolean`);return;case"array":if(!Array.isArray(t)){n.push(`${r||"value"} must be an array`);return}if(e.minItems!=null&&t.length<e.minItems&&n.push(`${r||"value"} must have >= ${e.minItems} items`),e.maxItems!=null&&t.length>e.maxItems&&n.push(`${r||"value"} must have <= ${e.maxItems} items`),e.items){for(let o=0;o<t.length;o+=1)if(St(e.items,t[o],`${r}[${o}]`,n),n.length)return}return;case"object":if(!t||typeof t!="object"||Array.isArray(t)){n.push(`${r||"value"} must be an object`);return}if(Array.isArray(e.required))for(const o of e.required){const i=t[o];if(i==null||i===""){n.push(`${r?`${r}.`:""}${o} is required`);return}}if(e.properties)for(const[o,i]of Object.entries(e.properties)){const a=t[o];if(a!==void 0&&(St(i,a,r?`${r}.${o}`:o,n),n.length))return}return;default:return}}}var Ki=12e4;async function Wi({request:e,accountModule:t,contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,signal:s}){const c=performance.now(),u=await r.load(e),l=u.thread.id,f=ha(e);ca(u,f)&&r.appendUserMessage(l,f);const m=Or(t.flows,e);if(!m)return i(Lr("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(wt()),{steps:0,productSkusEmitted:[]};const p={request:e,context:r.patch(l,{})||u,bag:{},accountConfig:t.accountConfig||{},threadId:l,steps:0,productSkusEmitted:new Set,committed:!1,messageLimit:ya(t.contextPersistence?.messageLimit),catalogMapper:t.catalogMapper,similarityMapper:t.similarityMapper},g={contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...s?{signal:s}:{},...t.trace?{trace:t.trace}:{},...t.hooks?{hooks:t.hooks}:{}};await z(g,ce("turn:start",p));try{await ae(m,p,g),p.committed||await At(p,g)}catch(h){throw await z(g,{...ce("turn:error",p),latencyMs:q(c),errorCode:xe(h)}),h}return await a("beacon.send",{type:"turnSummary",threadId:l,sessionId:e?.session_id||e?.sessionId||l,accountId:t.accountId||p.context.meta.accountId,steps:p.steps,totalLatencyMs:q(c),productSkusEmitted:[...p.productSkusEmitted]}),await z(g,{...ce("turn:end",p),latencyMs:q(c)}),{steps:p.steps,productSkusEmitted:[...p.productSkusEmitted]}}async function ae(e,t,r){for(const n of e){if(r.signal?.aborted||t.committed)return;t.steps+=1;const o=t.steps,i=performance.now();await z(r,xt("step:start",t,n,o));try{await Ji(n,t,r),await z(r,{...xt("step:end",t,n,o),latencyMs:q(i)})}catch(a){throw await z(r,{...xt("step:error",t,n,o),latencyMs:q(i),errorCode:xe(a)}),a}t.context=r.contextStore.patch(t.threadId,{})||t.context}}async function Ji(e,t,r){if(r.hooks?.transformContext){const o=await Te(r,t,"transformContext",()=>r.hooks.transformContext(t.context));o&&(t.context=o)}const n=se(t,r);if(e.kind==="be_op"){await Zi(e,t,r,n);return}if(e.kind==="tool"){await Xi(e,t,r,n);return}if(e.kind==="adapter"){await ea(e,t,r,n);return}if(e.kind==="emit"){await ta(e,t,r);return}if(e.kind==="patch"){await ra(e,t,r);return}if(e.kind==="branch"){await na(e,t,r,n);return}if(e.kind==="agent_loop"){await oa(e,t,r,n);return}if(e.kind==="parallel"){await ia(e,t,r);return}if(e.kind==="refusal"){await aa(e,t,r,n);return}e.kind==="commit"&&await sa(e,t,r)}async function Zi(e,t,r,n){const o=performance.now();let i;try{let s=await R(e.input,n);if(r.hooks?.beforeBeOp){const c=await Te(r,t,"beforeBeOp",()=>r.hooks.beforeBeOp(e.op,s,n));c&&"cached"in c&&c.cached!==void 0?i=c.cached:c&&"input"in c&&c.input!==void 0&&(s=c.input)}if(i===void 0){const c=await R(e.cache,n),u=Yi(e,t,s,c),l=await R(e.cacheTtlS,n)??u.cacheTtlS,f=await R(e.cacheKey,n)??u.cacheKey,m=await R(e.browserCache,n),p=Ae(await R(e.timeoutMs,n));await Tt(e,t,r,n);const g=p?new AbortController:null,h=Dr(r.signal,g?.signal);i=await ve(r.beClient.invoke({op:e.op,input:s,...l!==void 0?{cacheTtlS:l}:{},...f!==void 0?{cacheKey:f}:{},...m!==void 0?{browserCache:m}:{},...h?{signal:h}:{}}),p,()=>new B("op_timeout","The assistant took too long to respond.",{source:"be",sourceCode:"timeout"}),()=>g?.abort())}if(r.hooks?.afterBeOp){const c=await Te(r,t,"afterBeOp",()=>r.hooks.afterBeOp(e.op,i,n));c&&"result"in c&&c.result!==void 0&&(i=c.result)}}catch(s){const c=s,u=String(c?.sourceCode||c?.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:q(o),errorCode:u};if(await r.rpc("beacon.send",l),e.onError){e.errorOut&&(t.bag[e.errorOut]=s),await ae(e.onError,t,r);return}throw s}e.out&&(t.bag[e.out]=i),await Ue(e,i,t,r.contextStore);const a={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:q(o)};await r.rpc("beacon.send",a)}function Yi(e,t,r,n){if(!n||n.strategy!=="input-hash")return{};const o=Ae(n.ttlS);if(!o)return{};const i=t.context.meta.locale,a=n.promptVersion||Qi(r)||"current";return{cacheTtlS:o,cacheKey:kt(e.op,{account:t.context.meta.accountId,locale:i,promptVersion:a,payload:r},{version:"input-hash"})}}function Qi(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=t.prompt_version||t.promptVersion;return typeof r=="string"&&r.trim()?r.trim():void 0}async function Xi(e,t,r,n){const o=performance.now();try{await Tt(e,t,r,n);const i=Ae(await R(e.timeoutMs,n));let a=await R(e.input,n);if(r.hooks?.beforeToolCall){const c=await Te(r,t,"beforeToolCall",()=>r.hooks.beforeToolCall(e.name,a,n));if(c?.block)throw new B("tool_blocked",c.reason||`Tool '${e.name}' blocked by hook.`,{source:"tool",sourceCode:"blocked"});c&&"args"in c&&c.args!==void 0&&(a=c.args)}if(e.parameters){const c=Fr(e.parameters,a);if(!c.ok)throw new B("tool_invalid_args",`Invalid args for tool '${e.name}': ${c.error}`,{source:"tool",sourceCode:"invalid_args"})}let s=await ve(r.toolBridge.invoke(e.name,a),i,()=>new B("tool_timeout","The assistant tool took too long to respond.",{source:"tool",sourceCode:"timeout"}));if(r.hooks?.afterToolCall){const c=await Te(r,t,"afterToolCall",()=>r.hooks.afterToolCall(e.name,s,n));c&&"result"in c&&c.result!==void 0&&(s=c.result),c?.terminate&&(t.committed=!0)}e.out&&(t.bag[e.out]=s),await Ue(e,s,t,r.contextStore),await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,tool:e.name,status:"ok",latencyMs:q(o)})}catch(i){const a=i;if(await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,tool:e.name,status:"error",latencyMs:q(o),errorCode:String(a?.code||a?.name||"unknown")}),e.onError){e.errorOut&&(t.bag[e.errorOut]=i),await ae(e.onError,t,r);return}throw i}}async function ea(e,t,r,n){const o=r.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);await Tt(e,t,r,n);const i=Ae(await R(e.timeoutMs,n)),a=await ve(o(await R(e.input,n),n),i,()=>new B("adapter_timeout","The assistant adapter took too long to respond.",{source:"adapter",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Ue(e,a,t,r.contextStore)}async function ta(e,t,r){const n=await e.build(se(t,r));ba(n,t.productSkusEmitted),r.emit(n)}async function ra(e,t,r){await Ue(e,void 0,t,r.contextStore)}async function na(e,t,r,n){const o=String(await R(e.on,n)||"default");await ae(e.cases[o]||e.cases.default||[],t,r)}async function oa(e,t,r,n){if(!await e.shouldContinue(t.bag,n))return;const o=Math.max(0,Math.floor(Number(e.maxIterations)||0));let i=0;for(;!r.signal?.aborted&&!t.committed;){if(await ae(e.body,t,r),r.signal?.aborted||t.committed||!await e.shouldContinue(t.bag,se(t,r))||i>=o)return;const a=await e.onIterate?.(t.bag,se(t,r));a&&typeof a=="object"&&Object.assign(t.bag,a),i+=1}}async function ia(e,t,r){const n=Ae(await R(e.timeoutMs,se(t,r))),o=n?new AbortController:null,i=Dr(r.signal,o?.signal),a=e.steps.map(u=>{const l={...t,context:ua(t.context),bag:vt(t.bag),productSkusEmitted:new Set(t.productSkusEmitted),committed:!1},f=[];return ae(u,l,{...r,emit:m=>{!i?.aborted&&m.type!=="done"&&f.push(m)},contextStore:la(l),...i?{signal:i}:{}}).then(()=>({state:l,events:f}))}),s=await ve(Promise.all(a),n,()=>new B("parallel_timeout","The assistant parallel step took too long to respond.",{source:"agent",sourceCode:"timeout"}),()=>o?.abort()),c=e.merge||{};for(const{state:u,events:l}of s){for(const f of l)r.emit(f);for(const f of u.productSkusEmitted)t.productSkusEmitted.add(f);for(const f of c.bag||[])Object.prototype.hasOwnProperty.call(u.bag,f)&&(t.bag[f]=u.bag[f]);if(c.panel?.length){const f=qr(u.context.panel,c.panel);Object.keys(f).length&&(t.context=r.contextStore.patch(t.threadId,{panel:f})||t.context)}if(c.threadExtensions?.length){const f=qr(u.context.thread.extensions,c.threadExtensions);Object.keys(f).length&&(t.context=r.contextStore.patch(t.threadId,{thread:{...t.context.thread,extensions:f}})||t.context)}}}async function aa(e,t,r,n){r.emit(Ir(await R(e.message,n),!0)),await At(t,r)}async function sa(e,t,r){await At(t,r)}async function At(e,{contextStore:t,emit:r}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,r(wt()))}async function Ue(e,t,r,n){if(typeof e.patch!="function")return;const o=await e.patch(r.context,t,se(r));o&&(r.context=n.patch(r.threadId,o)||r.context)}function se(e,t){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig,catalogMapper:e.catalogMapper,similarityMapper:e.similarityMapper,...t?{beClient:t.beClient,toolBridge:t.toolBridge}:{},...t?.signal?{signal:t.signal}:{}}}function Se(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function ca(e,t){if(!t)return!1;const r=e.messages[e.messages.length-1];return r?.role!=="user"||r.content!==t}function qr(e,t){const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function ua(e){return{...e,panel:vt(e.panel||{}),thread:{...e.thread,extensions:vt(e.thread?.extensions||{})},meta:e.meta,messages:e.messages}}function la(e){return{async load(){return e.context},patch(t,r){return e.context=da(e.context,r,e.messageLimit),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function da(e,t,r){if(!t||typeof t!="object")return e;const n=Ur(e.panel,t.panel),o=Ur(e.thread?.extensions||{},t.thread?.extensions);return{...e,...t,panel:n,thread:{...e.thread||{},...t.thread||{},extensions:o},meta:{...e.meta||{},...t.meta||{}},messages:Array.isArray(t.messages)?Me(t.messages,r):e.messages}}function Ur(e,t){if(!t||typeof t!="object"||Array.isArray(t))return e;const r={};for(const n of Object.keys(e))r[n]=e[n];for(const[n,o]of Object.entries(t))r[n]=o;return r}function vt(e){return new Proxy({},{get(t,r,n){if(typeof r!="string")return Reflect.get(t,r,n);if(Object.prototype.hasOwnProperty.call(t,r))return t[r];const o=e[r];if(fa(o)){const i=pa(o);return t[r]=i,i}return o},has(t,r){return Reflect.has(t,r)||Reflect.has(e,r)},ownKeys(t){return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,r){return Object.getOwnPropertyDescriptor(t,r)}})}function fa(e){return!!(e&&typeof e=="object")}function pa(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}async function R(e,t){return typeof e=="function"?await e(t):e}function Ae(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}async function ve(e,t,r,n){if(!t)return e;let o,i=!1;return new Promise((a,s)=>{o=setTimeout(()=>{i||(i=!0,n?.(),s(r()))},t),Promise.resolve(e).then(c=>{i||(i=!0,o&&clearTimeout(o),a(c))},c=>{i||(i=!0,o&&clearTimeout(o),s(c))})})}function Dr(e,t){if(!e)return t;if(!t||e.aborted)return e;if(t.aborted)return t;const r=new AbortController,n=()=>r.abort();return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",n,{once:!0}),r.signal}async function Tt(e,t,r,n){if(!e.confirm)return;const o=await R(e.confirm,n);if(!o)return;const i=ma(o,e,t);await z(r,Et("confirmation:start",t,e));try{const a=await ve(r.rpc("confirmation.request",i),Ki,()=>new B("confirmation_timeout","The confirmation prompt timed out without a response.",{source:e.kind==="be_op"?"be":e.kind,sourceCode:"confirmation_timeout"})),s=typeof a=="boolean"?a:a?.confirmed===!0;if(await z(r,Et("confirmation:end",t,e)),s)return;throw new B("confirmation_declined","The requested action was not confirmed.",{source:e.kind==="be_op"?"be":e.kind,sourceCode:"confirmation_declined",detail:a})}catch(a){throw await z(r,{...Et("confirmation:error",t,e),errorCode:xe(a)}),a}}function ma(e,t,r){return{...ga(e),accountId:r.context.meta.accountId,threadId:r.threadId,sessionId:Se(r),stepKind:t.kind,...t.kind==="be_op"?{stepName:t.op}:{stepName:t.name}}}function ga(e){return typeof e=="string"?{message:e}:e===!0?{}:e&&typeof e=="object"?{...typeof e.title=="string"?{title:e.title}:{},...typeof e.message=="string"?{message:e.message}:{},...typeof e.action=="string"?{action:e.action}:{},...Object.prototype.hasOwnProperty.call(e,"payload")?{payload:e.payload}:{}}:{}}async function z(e,t){try{await e.trace?.(t)}catch{}}async function Te(e,t,r,n){try{return await n()}catch(o){await z(e,{...ce("step:error",t),stepName:`hook:${r}`,errorCode:xe(o)});try{await e.rpc("beacon.send",{type:"agentHookError",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,hook:r,errorCode:xe(o),message:o instanceof Error?o.message:String(o)})}catch{}return}}function ce(e,t){return{type:e,accountId:t.context.meta.accountId,threadId:t.threadId,sessionId:Se(t)}}function xt(e,t,r,n){const o=zr(r);return{...ce(e,t),stepIndex:n,stepKind:r.kind,...o?{stepName:o}:{}}}function Et(e,t,r){const n=zr(r);return{...ce(e,t),stepKind:r.kind,...n?{stepName:n}:{}}}function zr(e){if(e.kind==="be_op")return e.op;if(e.kind==="tool"||e.kind==="adapter")return e.name}function xe(e){if(e&&typeof e=="object"){const t=e;return String(t.sourceCode||t.code||t.name||"unknown")}return"unknown"}function ya(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function ha(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 ba(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 s of a)if(s&&typeof s=="object"){const c=s.sku;typeof c=="string"&&t.add(c)}}}function wa(e){return{invoke(t,r){return e("tool.invoke",{name:t,input:r})}}}var ka=512,_a=.74;function Gr({accountId:e,worker:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l=it()}){let f=1;const m=new Map;return Oo({worker:t,tools:s,beacon:p=>c?.({...p,accountId:p.accountId||e}),...u?{confirmation:u}:{},memory:l}),t.addEventListener("message",p=>{const g=p.data||{};if(g.type==="activity"&&g.entry){Hr(g.entry);return}const h=typeof g.id=="number"?g.id:null;if(h==null)return;const y=m.get(h);if(y){if(g.type==="event"&&g.event){Ct(y,g.event);return}if(g.type==="error"){y.onError(new Error(g.message||"Agent worker failed")),m.delete(h);return}g.type==="end"&&m.delete(h)}}),(p,g,h,y)=>{const b=f++;m.set(b,g);const w=()=>{m.delete(b),t.postMessage({id:b,type:"abort"})},v=S=>{if(h.aborted){w();return}t.postMessage({id:b,type:"invoke",accountId:e,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,request:S,parentUrl:window.location.href,debugActivity:Sa()})};if(h.aborted){w();return}if(h.addEventListener("abort",w,{once:!0}),y){Kr(p,y).then(v).catch(S=>{m.delete(b),g.onError(S instanceof Error?S:new Error("Failed to read image attachment"))});return}v(p)}}function Hr(e){const t=window;(t.__GENGAGE_AGENTIC_DEBUG_RECORD__||t.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)?.(e)}function Sa(){const e=window;return typeof(e.__GENGAGE_AGENTIC_DEBUG_RECORD__||e.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)=="function"}function Vr({accountId:e,accountModule:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l}){let f=null;const m=Aa({accountId:e,tools:s,beacon:c,confirmation:u,memory:l??it()}),p=wa(m),g=gt({accountId:e,...n?{devJwtSecret:n}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(h,y,b,w)=>{const v=await Kr(h||{},w);f||=new Sr({accountId:e,locale:v?.locale||a,parentUrl:window.location.href,rpc:m,persistentPanelKeys:t.contextPersistence?.panelKeys,panelKeyLimits:t.contextPersistence?.panelKeyLimits,messageLimit:t.contextPersistence?.messageLimit,maxThreads:t.contextPersistence?.maxThreads,threadTtlMs:t.contextPersistence?.threadTtlMs});try{await Wi({request:v,accountModule:{...t,accountId:e,trace:async S=>{Hr({kind:"flow/trace",event:S}),await t.trace?.(S)}},contextStore:f,beClient:{invoke({op:S,input:E,signal:k,cacheTtlS:N,cacheKey:Z,browserCache:rt}){return ji({beUrl:r,accountId:e,jwtProvider:g,parentUrl:window.location.href,op:S,input:E,cacheTtlS:N,cacheKey:Z,browserCache:rt,...k?{signal:k}:{}})}},toolBridge:p,emit:S=>Ct(y,S),rpc:m,signal:b})}catch(S){b?.aborted||(Ct(y,Er(S)),y.onDone())}}}function Aa({accountId:e,tools:t,beacon:r,confirmation:n,memory:o}){const i=a=>r?.({...a,accountId:a.accountId||e});return((a,s)=>hr(a,s,{tools:t,beacon:i,confirmation:n,memory:o}))}async function Kr(e,t){if(!t||!t.type?.startsWith("image/"))return e;const r=await xa(t),n={...va(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 va(e){return Ta(e)?{...e}:typeof e=="string"?{text:e}:{}}function Ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function xa(e){const t=await Ea(e);return t||{dataUrl:await Wr(e),mime:e.type}}async function Ea(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const r=Math.min(1,ka/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 s=await new Promise(c=>i.toBlob(c,"image/jpeg",_a));return s?{dataUrl:await Wr(s),mime:s.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function Wr(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 Ct(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(Ca(t));break;case"done":e.onDone();break;default:break}}function Ca(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}var Pa="entries",Ra=1,ja={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."},Jr=new Map;function Pt(){return Date.now()}function ue(e){return e?.expiresAt!=null&&e.expiresAt<=Pt()}function Rt(e,t){return{value:e,createdAt:Pt(),expiresAt:t?Pt()+t:null}}function Ia(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 La(e,t,r,n,o){try{return e.setItem(`${t}${r}`,JSON.stringify(Rt(n,o))),!0}catch{return!1}}function Oa(e,t,r){try{e.removeItem(`${t}${r}`)}catch{}}function Zr(e,t){if(!e)return 0;let r=0;try{const n=[];for(let o=0;o<e.length;o+=1){const i=e.key(o);i?.startsWith(t)&&n.push(i)}for(const o of n)try{const i=JSON.parse(e.getItem(o)||"null");(!i||ue(i))&&(e.removeItem(o),r+=1)}catch{e.removeItem(o),r+=1}}catch{return r}return r}function Yr(e){try{return window[e]}catch{return null}}function Qr(e,t){return e?{get:r=>Ia(e,t,r),set:(r,n,o={})=>La(e,t,r,n,o.ttlMs),remove:r=>Oa(e,t,r)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function Ba(e,t){const r=t.dbName||`gengage-${e}`,n=t.dbStore||Pa,o=t.dbVersion||Ra,i=new Map;let a=null;const s=()=>"indexedDB"in window?a||(a=new Promise(m=>{const p=indexedDB.open(r,o);p.onupgradeneeded=()=>{p.result.createObjectStore(n,{keyPath:"key"})},p.onsuccess=()=>m(p.result),p.onerror=()=>m(null),p.onblocked=()=>m(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async m=>{const p=await s();return p?new Promise(g=>{const h=p.transaction(n,"readwrite").objectStore(n),y=h.get(m);y.onsuccess=()=>{const b=y.result;if(!b||ue(b)){b&&h.delete(m),g(null);return}g(b.value)},y.onerror=()=>g(null)}):null},idbSet:async(m,p,g={})=>{const h=await s();return h?new Promise(y=>{const b=h.transaction(n,"readwrite");b.oncomplete=()=>y(!0),b.onerror=()=>y(!1),b.objectStore(n).put({key:m,...Rt(p,g.ttlMs)})}):!1},idbRemove:async m=>{const p=await s();p&&p.transaction(n,"readwrite").objectStore(n).delete(m)},idbGc:async()=>{const m=await s();return m?new Promise(p=>{let g=0;const h=m.transaction(n,"readwrite"),y=h.objectStore(n).openCursor();y.onsuccess=()=>{const b=y.result;if(!b)return;const w=b.value;(!w||ue(w))&&(b.delete(),g+=1),b.continue()},h.oncomplete=()=>p(g),h.onerror=()=>p(g),y.onerror=()=>p(g)}):0}}}function jt(e,t={}){const r=window,n=r.gengage||(r.gengage={}),o=n.memory||(n.memory={}),i=o[e];if(i)return i;const a=Jr.get(e)||Ba(e,t);Jr.set(e,a);const s=t.sessionPrefix||`gengage:${e}:session:`,c=t.localPrefix||`gengage:${e}:local:`,u=Yr("sessionStorage"),l=Yr("localStorage"),m={get:y=>{const b=a.volatileEntries.get(y);return b?ue(b)?(a.volatileEntries.delete(y),null):b.value:null},set:(y,b,w={})=>(a.volatileEntries.set(y,Rt(b,w.ttlMs)),!0),remove:y=>{a.volatileEntries.delete(y)},clear:()=>a.volatileEntries.clear()},p={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},g=async()=>{let y=0;for(const[S,E]of a.volatileEntries)ue(E)&&(a.volatileEntries.delete(S),y+=1);const b=Zr(u,s),w=Zr(l,c),v=await a.idbGc();return{volatile:y,session:b,local:w,indexedDb:v}},h={accountId:e,volatile:m,session:Qr(u,s),local:Qr(l,c),indexedDb:p,gc:g,stableKey:ie,policy:{...ja,...t.policy||{}}};o[e]=h;for(const y of t.aliases||[])o[y]=h;return Ma(h),h}function Ma(e){const t=window,r=()=>{e.gc().catch(()=>{})};if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(r);return}setTimeout(r,5e3)}var De="__gengageAgentFetchBridge",Na=1e3*60*60*24*14;function $a({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=Fa(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,s=n?Ha({accountId:e,endpointCache:n,fetchImpl:o.originalFetch}):void 0,c=u=>{const l=`${i}/chat/${u}`;a.add(l);const f=r[u],m={streamTransport:t,endpoint:u};f&&(m.endpointHandler=f),s&&(m.endpointCache=s),o.routes.set(l,m)};c("process_action");for(const u of Object.keys(r))u!=="process_action"&&c(u);return{middlewareUrl:i,stop(){for(const u of a)o.routes.delete(u);qa(o)}}}function Fa(){const e=window,t=e[De];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=Xr(o),s=n.routes.get(a);return s?Da(s,o,i):r(o,i)},e.fetch=n.installedFetch,e[De]=n,n}function qa(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[De]===e&&delete t[De]}function Xr(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function en(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function tn(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function Ua(e,t){const r=tn(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 Da(e,t,r){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const u=new AbortController,l=en(t,r);let f=null;if(l){const m=()=>u.abort();l.aborted&&m(),l.addEventListener("abort",m,{once:!0}),f=()=>l.removeEventListener("abort",m)}try{const m=await za(t,r),p={accountId:Ga(t),endpoint:e.endpoint,signal:u.signal},g=Va(e.endpointCache,e.endpoint,m,p.accountId);if(g){const y=await Ka(e.endpointCache,g,u.signal);if(y)return Xa(y)}const h=await e.endpointHandler(m,p);return g&&h.ok&&await Wa(e.endpointCache,g,h.clone(),u.signal),h}finally{f?.()}}const n=new TextEncoder,o=new AbortController,i=en(t,r);let a=!1,s=null;const c=new ReadableStream({async start(u){const l=p=>{a||u.enqueue(n.encode(`${JSON.stringify(p)}
|
|
4
|
-
`))},f=()=>{a||(a=!0,s?.(),u.close())},m=p=>{l({type:"error",code:p?.code||"agent_bridge_error",message:p instanceof Error?p.message:String(p)}),l({type:"done"}),f()};if(i){const p=()=>{o.abort(),a||(a=!0,s?.(),u.error(new DOMException("Aborted","AbortError")))};if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0}),s=()=>i.removeEventListener("abort",p)}try{const{request:p,attachment:g}=await Ua(t,r),h=e.streamTransport(p,{onTextChunk:(y,b,w={})=>l({type:"text_chunk",content:y,final:b===!0,...w}),onUISpec:(y,b,w,v)=>l({type:"ui_spec",spec:y,widget:b,...w?{panelHint:w}:{},...v?{clearPanel:!0}:{}}),onAction:y=>{l(y?.type==="action"?y:{type:"action",action:y})},onMetadata:y=>{l(y?.type==="metadata"?y:{type:"metadata",...y})},onError:m,onDone:()=>{l({type:"done"}),f()}},o.signal,g);ns(h)&&(await h,o.signal.aborted||(l({type:"done"}),f()))}catch(p){o.signal.aborted||m(p)}},cancel(){o.abort(),s?.(),a=!0}});return new Response(c,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}async function za(e,t){const r=await Promise.resolve(tn(e,t));return typeof r!="string"||r.trim()===""?{}:JSON.parse(r)}function Ga(e){try{const[t]=new URL(Xr(e)).pathname.split("/").filter(Boolean);return decodeURIComponent(t||"")}catch{return""}}function Ha({accountId:e,endpointCache:t,fetchImpl:r}){return{accountId:e,beUrl:t.beUrl,...t.parentUrl?{parentUrl:t.parentUrl}:{},ttlMs:t.ttlMs??Na,policies:t.policies,fetchImpl:r,jwtProvider:gt({accountId:e,...t.devJwtSecret?{devJwtSecret:t.devJwtSecret}:{},...t.tokenBrokerUrl?{tokenBrokerUrl:t.tokenBrokerUrl}:{},...t.tokenBrokerAudience?{tokenBrokerAudience:t.tokenBrokerAudience}:{},fetchImpl:r})}}function Va(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 Ka(e,t,r){const n=an(e.accountId,t),o=await es(e.accountId,n);if(on(o))return o;const i=await Ja(e,t,r);return i?(await sn(e.accountId,n,i,t.ttlMs),i):null}async function Wa(e,t,r,n){try{const o=await Qa(r);if(rs(o.body))return;const i=an(e.accountId,t);await sn(e.accountId,i,o,t.ttlMs),Za(e,t,o,n)}catch{}}async function Ja(e,t,r){try{const n=await e.fetchImpl(nn(e.beUrl),{method:"POST",headers:await rn(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&&on(o.payload)?o.payload:null}catch{return null}}async function Za(e,t,r,n){try{await e.fetchImpl(nn(e.beUrl),{method:"POST",headers:await rn(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 rn(e,t){return{authorization:`Bearer ${await e.jwtProvider({signal:t,parentUrl:e.parentUrl||Ya()})}`,"content-type":"application/json",accept:"application/json"}}function Ya(){try{return window.location?.href||""}catch{return""}}function nn(e){return`${String(e).replace(/\/+$/u,"")}/v1/cache`}async function Qa(e){return{status:e.status,statusText:e.statusText,headers:[...e.headers.entries()].filter(([t])=>ts(t)),body:await e.text()}}function Xa(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function on(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 an(e,t){return`endpoint-response:${ie({accountId:e,partition:t.partition,key:t.key})}`}async function es(e,t){const r=jt(e);return r.volatile.get(t)||await r.indexedDb.get(t)||r.local.get(t)}async function sn(e,t,r,n){const o=jt(e);o.volatile.set(t,r,{ttlMs:n}),await o.indexedDb.set(t,r,{ttlMs:n})||o.local.set(t,r,{ttlMs:n})}function ts(e){return["content-type","cache-control"].includes(e.toLowerCase())}function rs(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function ns(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function os({accountId:e,beUrl:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,workerUrl:i,defaultLocale:a="en-GB",accountModule:s,tools:c={},beacon:u,confirmation:l,memory:f,allowBlobWorker:m=!1,signal:p}){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 g=window,h=g.GengageAssistantInjector||(g.GengageAssistantInjector={}),y=h[e]||(h[e]={});if(y.agentController)return y.agentController;const b=It(i)||m?cn(i,`gengage-${e}-agent`,{allowBlobWorker:m}):null;b||u?.({type:"agentRuntime",accountId:e,transport:"main-thread",reason:"cross-origin-worker-url",workerUrl:i}),y.streamTransport=b?Gr({accountId:e,worker:b.worker,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:c,...u?{beacon:u}:{},...l?{confirmation:l}:{},...f?{memory:f}:{}}):Vr({accountId:e,accountModule:s,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:c,...u?{beacon:u}:{},...l?{confirmation:l}:{},...f?{memory:f}:{}});const w=new AbortController,v=[],
|
|
3
|
+
`)}}const i=n.trim();return i&&jr(JSON.parse(i),o),o}function jr(e,t){if(e._error)throw yt(e._error);if(!e._end)for(const[r,n]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,r))throw new M("op_failed",`BE streamed duplicate field "${r}".`,{source:"be",sourceCode:"schema_mismatch"});t[r]=n}}function Mi(e={}){return{type:"metadata",...e}}function Ir(e,t=!1,r={}){return{type:"text_chunk",content:e,final:t,...r}}function Ni(e){return{type:"ui_spec",...e}}function $i(e){return{type:"action",action:e}}function Lr(e,t){return{type:"error",code:e,message:t}}function wt(){return{type:"done"}}function Or(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}function Br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fe(e,t={}){const r=Br(e);if(!r)return null;const n=t.catalogMapper?.(r);if(n)return n;const o=oe(r.sku,r.SKU);if(!o)return null;const i={sku:o,name:oe(r.name,r.title,r.short_name,o)||o,url:oe(r.url)||""},a=Array.isArray(r.images)?r.images:void 0,s=oe(r.imageUrl,r.image_url,r.image,a?.[0]);s&&(i.imageUrl=s),a&&a.length>1&&(i.images=a.filter(b=>!!b).map(String));const c=ke(r.price_discounted),u=ke(r.price),l=c||u;l>0&&(i.price=String(l));const f=c>0?u:0;f>0&&(i.originalPrice=String(f));const m=oe(r.brand);m&&(i.brand=m);const p=ke(r.rating);p>0&&(i.rating=p);const g=ke(r.review_count)||ke(r.reviewCount);g>0&&(i.reviewCount=g);const h=oe(r.cart_code,r.cartCode);h&&(i.cartCode=h),typeof r.in_stock=="boolean"&&(i.inStock=r.in_stock),typeof r.inStock=="boolean"&&(i.inStock=r.inStock);const y=r.category_names;return Array.isArray(y)&&(i.categoryNames=y.map(String)),i}function qe(e){const t=Br(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 s of Object.keys(a))a[s]===void 0&&delete a[s];return a}function Fi(e){return Array.isArray(e)?e.map(qe).filter(t=>!!t):[]}function oe(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function ke(e){const t=Number(e);return Number.isFinite(t)?t:0}function Mr(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function kt(e,t,r={}){return`${e}:${r.version||"v2"}:${ie(t)}`}function qi(e,t={}){return Nr(e).map(r=>$r(typeof r=="string"?r:r.sku,t.locale)).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n).sort((r,n)=>_t(r,n,t.locale)).slice(0,t.limit||16).join(",")}function Ui(e,t={}){return ie(Nr(e).map(r=>zi(r,t)).filter(r=>!!r).sort((r,n)=>_t(String(r.sku||r.name||""),String(n.sku||n.name||""),t.locale)).slice(0,t.limit||16))}function Di(e,t){return Q(e,t)}function ie(e){let t=2166136261;const r=Gi(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 zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=t.mapProduct?.(r);if(n)return _e(n);const o=qe(r);return o&&typeof o=="object"&&!Array.isArray(o)?_e(Hi(o,t)):null}function Nr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function Gi(e){return JSON.stringify(_e(e))}function _e(e){return Array.isArray(e)?e.map(_e):!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,_e(r)]))}function Hi(e,t){return{sku:$r(e.sku,t.locale),name:Q(e.name,t.locale),url:Q(e.url,t.locale),price:e.price,currency:Q(e.currency,t.locale),category:Q(e.category,t.locale),category_names:Vi(e.category_names,t.locale,16),image:Q(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function $r(e,t){return Q(e,t).toUpperCase()}function Q(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function _t(e,t,r){return e.localeCompare(t,r,{numeric:!0})}function Vi(e,t,r){return Array.isArray(e)?e.map(n=>Q(n,t)).filter(Boolean).sort((n,o)=>_t(n,o,t)).slice(0,r):void 0}function Fr(e,t){if(!e)return{ok:!0};const r=[];return St(e,t,"",r),r.length?{ok:!1,error:r[0]||"invalid"}:{ok:!0}}function St(e,t,r,n){if(e){if(Array.isArray(e.enum)&&!e.enum.includes(t)){n.push(`${r||"value"} must be one of [${e.enum.join(", ")}]`);return}switch(e.type){case"string":if(typeof t!="string"){n.push(`${r||"value"} must be a string`);return}e.minLength&&t.length<e.minLength&&n.push(`${r||"value"} must be at least ${e.minLength} chars`);return;case"number":if(typeof t!="number"||!Number.isFinite(t)){n.push(`${r||"value"} must be a number`);return}e.minimum!=null&&t<e.minimum&&n.push(`${r||"value"} must be >= ${e.minimum}`),e.maximum!=null&&t>e.maximum&&n.push(`${r||"value"} must be <= ${e.maximum}`);return;case"boolean":typeof t!="boolean"&&n.push(`${r||"value"} must be a boolean`);return;case"array":if(!Array.isArray(t)){n.push(`${r||"value"} must be an array`);return}if(e.minItems!=null&&t.length<e.minItems&&n.push(`${r||"value"} must have >= ${e.minItems} items`),e.maxItems!=null&&t.length>e.maxItems&&n.push(`${r||"value"} must have <= ${e.maxItems} items`),e.items){for(let o=0;o<t.length;o+=1)if(St(e.items,t[o],`${r}[${o}]`,n),n.length)return}return;case"object":if(!t||typeof t!="object"||Array.isArray(t)){n.push(`${r||"value"} must be an object`);return}if(Array.isArray(e.required))for(const o of e.required){const i=t[o];if(i==null||i===""){n.push(`${r?`${r}.`:""}${o} is required`);return}}if(e.properties)for(const[o,i]of Object.entries(e.properties)){const a=t[o];if(a!==void 0&&(St(i,a,r?`${r}.${o}`:o,n),n.length))return}return;default:return}}}var Ki=12e4;async function Wi({request:e,accountModule:t,contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,signal:s}){const c=performance.now(),u=await r.load(e),l=u.thread.id,f=ha(e);ca(u,f)&&r.appendUserMessage(l,f);const m=Or(t.flows,e);if(!m)return i(Lr("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(wt()),{steps:0,productSkusEmitted:[]};const p={request:e,context:r.patch(l,{})||u,bag:{},accountConfig:t.accountConfig||{},threadId:l,steps:0,productSkusEmitted:new Set,committed:!1,messageLimit:ya(t.contextPersistence?.messageLimit),catalogMapper:t.catalogMapper,similarityMapper:t.similarityMapper},g={contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...s?{signal:s}:{},...t.trace?{trace:t.trace}:{},...t.hooks?{hooks:t.hooks}:{}};await z(g,ce("turn:start",p));try{await ae(m,p,g),p.committed||await vt(p,g)}catch(h){throw await z(g,{...ce("turn:error",p),latencyMs:q(c),errorCode:xe(h)}),h}return await a("beacon.send",{type:"turnSummary",threadId:l,sessionId:e?.session_id||e?.sessionId||l,accountId:t.accountId||p.context.meta.accountId,steps:p.steps,totalLatencyMs:q(c),productSkusEmitted:[...p.productSkusEmitted]}),await z(g,{...ce("turn:end",p),latencyMs:q(c)}),{steps:p.steps,productSkusEmitted:[...p.productSkusEmitted]}}async function ae(e,t,r){for(const n of e){if(r.signal?.aborted||t.committed)return;t.steps+=1;const o=t.steps,i=performance.now();await z(r,xt("step:start",t,n,o));try{await Ji(n,t,r),await z(r,{...xt("step:end",t,n,o),latencyMs:q(i)})}catch(a){throw await z(r,{...xt("step:error",t,n,o),latencyMs:q(i),errorCode:xe(a)}),a}t.context=r.contextStore.patch(t.threadId,{})||t.context}}async function Ji(e,t,r){if(r.hooks?.transformContext){const o=await Te(r,t,"transformContext",()=>r.hooks.transformContext(t.context));o&&(t.context=o)}const n=se(t,r);if(e.kind==="be_op"){await Zi(e,t,r,n);return}if(e.kind==="tool"){await Xi(e,t,r,n);return}if(e.kind==="adapter"){await ea(e,t,r,n);return}if(e.kind==="emit"){await ta(e,t,r);return}if(e.kind==="patch"){await ra(e,t,r);return}if(e.kind==="branch"){await na(e,t,r,n);return}if(e.kind==="agent_loop"){await oa(e,t,r,n);return}if(e.kind==="parallel"){await ia(e,t,r);return}if(e.kind==="refusal"){await aa(e,t,r,n);return}e.kind==="commit"&&await sa(e,t,r)}async function Zi(e,t,r,n){const o=performance.now();let i;try{let s=await R(e.input,n);if(r.hooks?.beforeBeOp){const c=await Te(r,t,"beforeBeOp",()=>r.hooks.beforeBeOp(e.op,s,n));c&&"cached"in c&&c.cached!==void 0?i=c.cached:c&&"input"in c&&c.input!==void 0&&(s=c.input)}if(i===void 0){const c=await R(e.cache,n),u=Yi(e,t,s,c),l=await R(e.cacheTtlS,n)??u.cacheTtlS,f=await R(e.cacheKey,n)??u.cacheKey,m=await R(e.cacheFreshness,n),p=await R(e.browserCache,n),g=ve(await R(e.timeoutMs,n));await Tt(e,t,r,n);const h=g?new AbortController:null,y=Dr(r.signal,h?.signal);i=await Ae(r.beClient.invoke({op:e.op,input:s,...l!==void 0?{cacheTtlS:l}:{},...f!==void 0?{cacheKey:f}:{},...m!==void 0?{cacheFreshness:m}:{},...p!==void 0?{browserCache:p}:{},...y?{signal:y}:{}}),g,()=>new M("op_timeout","The assistant took too long to respond.",{source:"be",sourceCode:"timeout"}),()=>h?.abort())}if(r.hooks?.afterBeOp){const c=await Te(r,t,"afterBeOp",()=>r.hooks.afterBeOp(e.op,i,n));c&&"result"in c&&c.result!==void 0&&(i=c.result)}}catch(s){const c=s,u=String(c?.sourceCode||c?.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:q(o),errorCode:u};if(await r.rpc("beacon.send",l),e.onError){e.errorOut&&(t.bag[e.errorOut]=s),await ae(e.onError,t,r);return}throw s}e.out&&(t.bag[e.out]=i),await Ue(e,i,t,r.contextStore);const a={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:q(o)};await r.rpc("beacon.send",a)}function Yi(e,t,r,n){if(!n||n.strategy!=="input-hash")return{};const o=ve(n.ttlS);if(!o)return{};const i=t.context.meta.locale,a=n.promptVersion||Qi(r)||"current";return{cacheTtlS:o,cacheKey:kt(e.op,{account:t.context.meta.accountId,locale:i,promptVersion:a,payload:r},{version:"input-hash"})}}function Qi(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=t.prompt_version||t.promptVersion;return typeof r=="string"&&r.trim()?r.trim():void 0}async function Xi(e,t,r,n){const o=performance.now();try{await Tt(e,t,r,n);const i=ve(await R(e.timeoutMs,n));let a=await R(e.input,n);if(r.hooks?.beforeToolCall){const c=await Te(r,t,"beforeToolCall",()=>r.hooks.beforeToolCall(e.name,a,n));if(c?.block)throw new M("tool_blocked",c.reason||`Tool '${e.name}' blocked by hook.`,{source:"tool",sourceCode:"blocked"});c&&"args"in c&&c.args!==void 0&&(a=c.args)}if(e.parameters){const c=Fr(e.parameters,a);if(!c.ok)throw new M("tool_invalid_args",`Invalid args for tool '${e.name}': ${c.error}`,{source:"tool",sourceCode:"invalid_args"})}let s=await Ae(r.toolBridge.invoke(e.name,a),i,()=>new M("tool_timeout","The assistant tool took too long to respond.",{source:"tool",sourceCode:"timeout"}));if(r.hooks?.afterToolCall){const c=await Te(r,t,"afterToolCall",()=>r.hooks.afterToolCall(e.name,s,n));c&&"result"in c&&c.result!==void 0&&(s=c.result),c?.terminate&&(t.committed=!0)}e.out&&(t.bag[e.out]=s),await Ue(e,s,t,r.contextStore),await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,tool:e.name,status:"ok",latencyMs:q(o)})}catch(i){const a=i;if(await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,tool:e.name,status:"error",latencyMs:q(o),errorCode:String(a?.code||a?.name||"unknown")}),e.onError){e.errorOut&&(t.bag[e.errorOut]=i),await ae(e.onError,t,r);return}throw i}}async function ea(e,t,r,n){const o=r.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);await Tt(e,t,r,n);const i=ve(await R(e.timeoutMs,n)),a=await Ae(o(await R(e.input,n),n),i,()=>new M("adapter_timeout","The assistant adapter took too long to respond.",{source:"adapter",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Ue(e,a,t,r.contextStore)}async function ta(e,t,r){const n=await e.build(se(t,r));ba(n,t.productSkusEmitted),r.emit(n)}async function ra(e,t,r){await Ue(e,void 0,t,r.contextStore)}async function na(e,t,r,n){const o=String(await R(e.on,n)||"default");await ae(e.cases[o]||e.cases.default||[],t,r)}async function oa(e,t,r,n){if(!await e.shouldContinue(t.bag,n))return;const o=Math.max(0,Math.floor(Number(e.maxIterations)||0));let i=0;for(;!r.signal?.aborted&&!t.committed;){if(await ae(e.body,t,r),r.signal?.aborted||t.committed||!await e.shouldContinue(t.bag,se(t,r))||i>=o)return;const a=await e.onIterate?.(t.bag,se(t,r));a&&typeof a=="object"&&Object.assign(t.bag,a),i+=1}}async function ia(e,t,r){const n=ve(await R(e.timeoutMs,se(t,r))),o=n?new AbortController:null,i=Dr(r.signal,o?.signal),a=e.steps.map(u=>{const l={...t,context:ua(t.context),bag:At(t.bag),productSkusEmitted:new Set(t.productSkusEmitted),committed:!1},f=[];return ae(u,l,{...r,emit:m=>{!i?.aborted&&m.type!=="done"&&f.push(m)},contextStore:la(l),...i?{signal:i}:{}}).then(()=>({state:l,events:f}))}),s=await Ae(Promise.all(a),n,()=>new M("parallel_timeout","The assistant parallel step took too long to respond.",{source:"agent",sourceCode:"timeout"}),()=>o?.abort()),c=e.merge||{};for(const{state:u,events:l}of s){for(const f of l)r.emit(f);for(const f of u.productSkusEmitted)t.productSkusEmitted.add(f);for(const f of c.bag||[])Object.prototype.hasOwnProperty.call(u.bag,f)&&(t.bag[f]=u.bag[f]);if(c.panel?.length){const f=qr(u.context.panel,c.panel);Object.keys(f).length&&(t.context=r.contextStore.patch(t.threadId,{panel:f})||t.context)}if(c.threadExtensions?.length){const f=qr(u.context.thread.extensions,c.threadExtensions);Object.keys(f).length&&(t.context=r.contextStore.patch(t.threadId,{thread:{...t.context.thread,extensions:f}})||t.context)}}}async function aa(e,t,r,n){r.emit(Ir(await R(e.message,n),!0)),await vt(t,r)}async function sa(e,t,r){await vt(t,r)}async function vt(e,{contextStore:t,emit:r}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,r(wt()))}async function Ue(e,t,r,n){if(typeof e.patch!="function")return;const o=await e.patch(r.context,t,se(r));o&&(r.context=n.patch(r.threadId,o)||r.context)}function se(e,t){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig,catalogMapper:e.catalogMapper,similarityMapper:e.similarityMapper,...t?{beClient:t.beClient,toolBridge:t.toolBridge}:{},...t?.signal?{signal:t.signal}:{}}}function Se(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function ca(e,t){if(!t)return!1;const r=e.messages[e.messages.length-1];return r?.role!=="user"||r.content!==t}function qr(e,t){const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function ua(e){return{...e,panel:At(e.panel||{}),thread:{...e.thread,extensions:At(e.thread?.extensions||{})},meta:e.meta,messages:e.messages}}function la(e){return{async load(){return e.context},patch(t,r){return e.context=da(e.context,r,e.messageLimit),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function da(e,t,r){if(!t||typeof t!="object")return e;const n=Ur(e.panel,t.panel),o=Ur(e.thread?.extensions||{},t.thread?.extensions);return{...e,...t,panel:n,thread:{...e.thread||{},...t.thread||{},extensions:o},meta:{...e.meta||{},...t.meta||{}},messages:Array.isArray(t.messages)?Me(t.messages,r):e.messages}}function Ur(e,t){if(!t||typeof t!="object"||Array.isArray(t))return e;const r={};for(const n of Object.keys(e))r[n]=e[n];for(const[n,o]of Object.entries(t))r[n]=o;return r}function At(e){return new Proxy({},{get(t,r,n){if(typeof r!="string")return Reflect.get(t,r,n);if(Object.prototype.hasOwnProperty.call(t,r))return t[r];const o=e[r];if(fa(o)){const i=pa(o);return t[r]=i,i}return o},has(t,r){return Reflect.has(t,r)||Reflect.has(e,r)},ownKeys(t){return Reflect.ownKeys(t)},getOwnPropertyDescriptor(t,r){return Object.getOwnPropertyDescriptor(t,r)}})}function fa(e){return!!(e&&typeof e=="object")}function pa(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}async function R(e,t){return typeof e=="function"?await e(t):e}function ve(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}async function Ae(e,t,r,n){if(!t)return e;let o,i=!1;return new Promise((a,s)=>{o=setTimeout(()=>{i||(i=!0,n?.(),s(r()))},t),Promise.resolve(e).then(c=>{i||(i=!0,o&&clearTimeout(o),a(c))},c=>{i||(i=!0,o&&clearTimeout(o),s(c))})})}function Dr(e,t){if(!e)return t;if(!t||e.aborted)return e;if(t.aborted)return t;const r=new AbortController,n=()=>r.abort();return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",n,{once:!0}),r.signal}async function Tt(e,t,r,n){if(!e.confirm)return;const o=await R(e.confirm,n);if(!o)return;const i=ma(o,e,t);await z(r,Et("confirmation:start",t,e));try{const a=await Ae(r.rpc("confirmation.request",i),Ki,()=>new M("confirmation_timeout","The confirmation prompt timed out without a response.",{source:e.kind==="be_op"?"be":e.kind,sourceCode:"confirmation_timeout"})),s=typeof a=="boolean"?a:a?.confirmed===!0;if(await z(r,Et("confirmation:end",t,e)),s)return;throw new M("confirmation_declined","The requested action was not confirmed.",{source:e.kind==="be_op"?"be":e.kind,sourceCode:"confirmation_declined",detail:a})}catch(a){throw await z(r,{...Et("confirmation:error",t,e),errorCode:xe(a)}),a}}function ma(e,t,r){return{...ga(e),accountId:r.context.meta.accountId,threadId:r.threadId,sessionId:Se(r),stepKind:t.kind,...t.kind==="be_op"?{stepName:t.op}:{stepName:t.name}}}function ga(e){return typeof e=="string"?{message:e}:e===!0?{}:e&&typeof e=="object"?{...typeof e.title=="string"?{title:e.title}:{},...typeof e.message=="string"?{message:e.message}:{},...typeof e.action=="string"?{action:e.action}:{},...Object.prototype.hasOwnProperty.call(e,"payload")?{payload:e.payload}:{}}:{}}async function z(e,t){try{await e.trace?.(t)}catch{}}async function Te(e,t,r,n){try{return await n()}catch(o){await z(e,{...ce("step:error",t),stepName:`hook:${r}`,errorCode:xe(o)});try{await e.rpc("beacon.send",{type:"agentHookError",threadId:t.threadId,sessionId:Se(t),accountId:t.context.meta.accountId,hook:r,errorCode:xe(o),message:o instanceof Error?o.message:String(o)})}catch{}return}}function ce(e,t){return{type:e,accountId:t.context.meta.accountId,threadId:t.threadId,sessionId:Se(t)}}function xt(e,t,r,n){const o=zr(r);return{...ce(e,t),stepIndex:n,stepKind:r.kind,...o?{stepName:o}:{}}}function Et(e,t,r){const n=zr(r);return{...ce(e,t),stepKind:r.kind,...n?{stepName:n}:{}}}function zr(e){if(e.kind==="be_op")return e.op;if(e.kind==="tool"||e.kind==="adapter")return e.name}function xe(e){if(e&&typeof e=="object"){const t=e;return String(t.sourceCode||t.code||t.name||"unknown")}return"unknown"}function ya(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function ha(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 ba(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 s of a)if(s&&typeof s=="object"){const c=s.sku;typeof c=="string"&&t.add(c)}}}function wa(e){return{invoke(t,r){return e("tool.invoke",{name:t,input:r})}}}var ka=512,_a=.74;function Gr({accountId:e,worker:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l=it()}){let f=1;const m=new Map;return Oo({worker:t,tools:s,beacon:p=>c?.({...p,accountId:p.accountId||e}),...u?{confirmation:u}:{},memory:l}),t.addEventListener("message",p=>{const g=p.data||{};if(g.type==="activity"&&g.entry){Hr(g.entry);return}const h=typeof g.id=="number"?g.id:null;if(h==null)return;const y=m.get(h);if(y){if(g.type==="event"&&g.event){Ct(y,g.event);return}if(g.type==="error"){y.onError(new Error(g.message||"Agent worker failed")),m.delete(h);return}g.type==="end"&&m.delete(h)}}),(p,g,h,y)=>{const b=f++;m.set(b,g);const w=()=>{m.delete(b),t.postMessage({id:b,type:"abort"})},v=_=>{if(h.aborted){w();return}t.postMessage({id:b,type:"invoke",accountId:e,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,request:_,parentUrl:window.location.href,debugActivity:Sa()})};if(h.aborted){w();return}if(h.addEventListener("abort",w,{once:!0}),y){Kr(p,y).then(v).catch(_=>{m.delete(b),g.onError(_ instanceof Error?_:new Error("Failed to read image attachment"))});return}v(p)}}function Hr(e){const t=window;(t.__GENGAGE_AGENTIC_DEBUG_RECORD__||t.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)?.(e)}function Sa(){const e=window;return typeof(e.__GENGAGE_AGENTIC_DEBUG_RECORD__||e.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)=="function"}function Vr({accountId:e,accountModule:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l}){let f=null;const m=va({accountId:e,tools:s,beacon:c,confirmation:u,memory:l??it()}),p=wa(m),g=gt({accountId:e,...n?{devJwtSecret:n}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(h,y,b,w)=>{const v=await Kr(h||{},w);f||=new Sr({accountId:e,locale:v?.locale||a,parentUrl:window.location.href,rpc:m,persistentPanelKeys:t.contextPersistence?.panelKeys,panelKeyLimits:t.contextPersistence?.panelKeyLimits,messageLimit:t.contextPersistence?.messageLimit,maxThreads:t.contextPersistence?.maxThreads,threadTtlMs:t.contextPersistence?.threadTtlMs});try{await Wi({request:v,accountModule:{...t,accountId:e,trace:async _=>{Hr({kind:"flow/trace",event:_}),await t.trace?.(_)}},contextStore:f,beClient:{invoke({op:_,input:C,signal:A,cacheTtlS:T,cacheKey:Z,browserCache:rt}){return ji({beUrl:r,accountId:e,jwtProvider:g,parentUrl:window.location.href,op:_,input:C,cacheTtlS:T,cacheKey:Z,browserCache:rt,...A?{signal:A}:{}})}},toolBridge:p,emit:_=>Ct(y,_),rpc:m,signal:b})}catch(_){b?.aborted||(Ct(y,Er(_)),y.onDone())}}}function va({accountId:e,tools:t,beacon:r,confirmation:n,memory:o}){const i=a=>r?.({...a,accountId:a.accountId||e});return((a,s)=>hr(a,s,{tools:t,beacon:i,confirmation:n,memory:o}))}async function Kr(e,t){if(!t||!t.type?.startsWith("image/"))return e;const r=await xa(t),n={...Aa(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 Aa(e){return Ta(e)?{...e}:typeof e=="string"?{text:e}:{}}function Ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function xa(e){const t=await Ea(e);return t||{dataUrl:await Wr(e),mime:e.type}}async function Ea(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const r=Math.min(1,ka/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 s=await new Promise(c=>i.toBlob(c,"image/jpeg",_a));return s?{dataUrl:await Wr(s),mime:s.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function Wr(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 Ct(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(Ca(t));break;case"done":e.onDone();break;default:break}}function Ca(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}var Pa="entries",Ra=1,ja={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."},Jr=new Map;function Pt(){return Date.now()}function ue(e){return e?.expiresAt!=null&&e.expiresAt<=Pt()}function Rt(e,t){return{value:e,createdAt:Pt(),expiresAt:t?Pt()+t:null}}function Ia(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 La(e,t,r,n,o){try{return e.setItem(`${t}${r}`,JSON.stringify(Rt(n,o))),!0}catch{return!1}}function Oa(e,t,r){try{e.removeItem(`${t}${r}`)}catch{}}function Zr(e,t){if(!e)return 0;let r=0;try{const n=[];for(let o=0;o<e.length;o+=1){const i=e.key(o);i?.startsWith(t)&&n.push(i)}for(const o of n)try{const i=JSON.parse(e.getItem(o)||"null");(!i||ue(i))&&(e.removeItem(o),r+=1)}catch{e.removeItem(o),r+=1}}catch{return r}return r}function Yr(e){try{return window[e]}catch{return null}}function Qr(e,t){return e?{get:r=>Ia(e,t,r),set:(r,n,o={})=>La(e,t,r,n,o.ttlMs),remove:r=>Oa(e,t,r)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function Ba(e,t){const r=t.dbName||`gengage-${e}`,n=t.dbStore||Pa,o=t.dbVersion||Ra,i=new Map;let a=null;const s=()=>"indexedDB"in window?a||(a=new Promise(m=>{const p=indexedDB.open(r,o);p.onupgradeneeded=()=>{p.result.createObjectStore(n,{keyPath:"key"})},p.onsuccess=()=>m(p.result),p.onerror=()=>m(null),p.onblocked=()=>m(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async m=>{const p=await s();return p?new Promise(g=>{const h=p.transaction(n,"readwrite").objectStore(n),y=h.get(m);y.onsuccess=()=>{const b=y.result;if(!b||ue(b)){b&&h.delete(m),g(null);return}g(b.value)},y.onerror=()=>g(null)}):null},idbSet:async(m,p,g={})=>{const h=await s();return h?new Promise(y=>{const b=h.transaction(n,"readwrite");b.oncomplete=()=>y(!0),b.onerror=()=>y(!1),b.objectStore(n).put({key:m,...Rt(p,g.ttlMs)})}):!1},idbRemove:async m=>{const p=await s();p&&p.transaction(n,"readwrite").objectStore(n).delete(m)},idbGc:async()=>{const m=await s();return m?new Promise(p=>{let g=0;const h=m.transaction(n,"readwrite"),y=h.objectStore(n).openCursor();y.onsuccess=()=>{const b=y.result;if(!b)return;const w=b.value;(!w||ue(w))&&(b.delete(),g+=1),b.continue()},h.oncomplete=()=>p(g),h.onerror=()=>p(g),y.onerror=()=>p(g)}):0}}}function jt(e,t={}){const r=window,n=r.gengage||(r.gengage={}),o=n.memory||(n.memory={}),i=o[e];if(i)return i;const a=Jr.get(e)||Ba(e,t);Jr.set(e,a);const s=t.sessionPrefix||`gengage:${e}:session:`,c=t.localPrefix||`gengage:${e}:local:`,u=Yr("sessionStorage"),l=Yr("localStorage"),m={get:y=>{const b=a.volatileEntries.get(y);return b?ue(b)?(a.volatileEntries.delete(y),null):b.value:null},set:(y,b,w={})=>(a.volatileEntries.set(y,Rt(b,w.ttlMs)),!0),remove:y=>{a.volatileEntries.delete(y)},clear:()=>a.volatileEntries.clear()},p={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},g=async()=>{let y=0;for(const[_,C]of a.volatileEntries)ue(C)&&(a.volatileEntries.delete(_),y+=1);const b=Zr(u,s),w=Zr(l,c),v=await a.idbGc();return{volatile:y,session:b,local:w,indexedDb:v}},h={accountId:e,volatile:m,session:Qr(u,s),local:Qr(l,c),indexedDb:p,gc:g,stableKey:ie,policy:{...ja,...t.policy||{}}};o[e]=h;for(const y of t.aliases||[])o[y]=h;return Ma(h),h}function Ma(e){const t=window,r=()=>{e.gc().catch(()=>{})};if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(r);return}setTimeout(r,5e3)}var De="__gengageAgentFetchBridge",Na=1e3*60*60*24*14;function $a({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=Fa(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,s=n?Ha({accountId:e,endpointCache:n,fetchImpl:o.originalFetch}):void 0,c=u=>{const l=`${i}/chat/${u}`;a.add(l);const f=r[u],m={streamTransport:t,endpoint:u};f&&(m.endpointHandler=f),s&&(m.endpointCache=s),o.routes.set(l,m)};c("process_action");for(const u of Object.keys(r))u!=="process_action"&&c(u);return{middlewareUrl:i,stop(){for(const u of a)o.routes.delete(u);qa(o)}}}function Fa(){const e=window,t=e[De];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=Xr(o),s=n.routes.get(a);return s?Da(s,o,i):r(o,i)},e.fetch=n.installedFetch,e[De]=n,n}function qa(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[De]===e&&delete t[De]}function Xr(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function en(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function tn(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function Ua(e,t){const r=tn(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 Da(e,t,r){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const u=new AbortController,l=en(t,r);let f=null;if(l){const m=()=>u.abort();l.aborted&&m(),l.addEventListener("abort",m,{once:!0}),f=()=>l.removeEventListener("abort",m)}try{const m=await za(t,r),p={accountId:Ga(t),endpoint:e.endpoint,signal:u.signal},g=Va(e.endpointCache,e.endpoint,m,p.accountId);if(g){const y=await Ka(e.endpointCache,g,u.signal);if(y)return Xa(y)}const h=await e.endpointHandler(m,p);return g&&h.ok&&await Wa(e.endpointCache,g,h.clone(),u.signal),h}finally{f?.()}}const n=new TextEncoder,o=new AbortController,i=en(t,r);let a=!1,s=null;const c=new ReadableStream({async start(u){const l=p=>{a||u.enqueue(n.encode(`${JSON.stringify(p)}
|
|
4
|
+
`))},f=()=>{a||(a=!0,s?.(),u.close())},m=p=>{l({type:"error",code:p?.code||"agent_bridge_error",message:p instanceof Error?p.message:String(p)}),l({type:"done"}),f()};if(i){const p=()=>{o.abort(),a||(a=!0,s?.(),u.error(new DOMException("Aborted","AbortError")))};if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0}),s=()=>i.removeEventListener("abort",p)}try{const{request:p,attachment:g}=await Ua(t,r),h=e.streamTransport(p,{onTextChunk:(y,b,w={})=>l({type:"text_chunk",content:y,final:b===!0,...w}),onUISpec:(y,b,w,v)=>l({type:"ui_spec",spec:y,widget:b,...w?{panelHint:w}:{},...v?{clearPanel:!0}:{}}),onAction:y=>{l(y?.type==="action"?y:{type:"action",action:y})},onMetadata:y=>{l(y?.type==="metadata"?y:{type:"metadata",...y})},onError:m,onDone:()=>{l({type:"done"}),f()}},o.signal,g);ns(h)&&(await h,o.signal.aborted||(l({type:"done"}),f()))}catch(p){o.signal.aborted||m(p)}},cancel(){o.abort(),s?.(),a=!0}});return new Response(c,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}async function za(e,t){const r=await Promise.resolve(tn(e,t));return typeof r!="string"||r.trim()===""?{}:JSON.parse(r)}function Ga(e){try{const[t]=new URL(Xr(e)).pathname.split("/").filter(Boolean);return decodeURIComponent(t||"")}catch{return""}}function Ha({accountId:e,endpointCache:t,fetchImpl:r}){return{accountId:e,beUrl:t.beUrl,...t.parentUrl?{parentUrl:t.parentUrl}:{},ttlMs:t.ttlMs??Na,policies:t.policies,fetchImpl:r,jwtProvider:gt({accountId:e,...t.devJwtSecret?{devJwtSecret:t.devJwtSecret}:{},...t.tokenBrokerUrl?{tokenBrokerUrl:t.tokenBrokerUrl}:{},...t.tokenBrokerAudience?{tokenBrokerAudience:t.tokenBrokerAudience}:{},fetchImpl:r})}}function Va(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 Ka(e,t,r){const n=an(e.accountId,t),o=await es(e.accountId,n);if(on(o))return o;const i=await Ja(e,t,r);return i?(await sn(e.accountId,n,i,t.ttlMs),i):null}async function Wa(e,t,r,n){try{const o=await Qa(r);if(rs(o.body))return;const i=an(e.accountId,t);await sn(e.accountId,i,o,t.ttlMs),Za(e,t,o,n)}catch{}}async function Ja(e,t,r){try{const n=await e.fetchImpl(nn(e.beUrl),{method:"POST",headers:await rn(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&&on(o.payload)?o.payload:null}catch{return null}}async function Za(e,t,r,n){try{await e.fetchImpl(nn(e.beUrl),{method:"POST",headers:await rn(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 rn(e,t){return{authorization:`Bearer ${await e.jwtProvider({signal:t,parentUrl:e.parentUrl||Ya()})}`,"content-type":"application/json",accept:"application/json"}}function Ya(){try{return window.location?.href||""}catch{return""}}function nn(e){return`${String(e).replace(/\/+$/u,"")}/v1/cache`}async function Qa(e){return{status:e.status,statusText:e.statusText,headers:[...e.headers.entries()].filter(([t])=>ts(t)),body:await e.text()}}function Xa(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function on(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 an(e,t){return`endpoint-response:${ie({accountId:e,partition:t.partition,key:t.key})}`}async function es(e,t){const r=jt(e);return r.volatile.get(t)||await r.indexedDb.get(t)||r.local.get(t)}async function sn(e,t,r,n){const o=jt(e);o.volatile.set(t,r,{ttlMs:n}),await o.indexedDb.set(t,r,{ttlMs:n})||o.local.set(t,r,{ttlMs:n})}function ts(e){return["content-type","cache-control"].includes(e.toLowerCase())}function rs(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function ns(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function os({accountId:e,beUrl:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,workerUrl:i,defaultLocale:a="en-GB",accountModule:s,tools:c={},beacon:u,confirmation:l,memory:f,allowBlobWorker:m=!1,signal:p}){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 g=window,h=g.GengageAssistantInjector||(g.GengageAssistantInjector={}),y=h[e]||(h[e]={});if(y.agentController)return y.agentController;const b=It(i)||m?cn(i,`gengage-${e}-agent`,{allowBlobWorker:m}):null;b||u?.({type:"agentRuntime",accountId:e,transport:"main-thread",reason:"cross-origin-worker-url",workerUrl:i}),y.streamTransport=b?Gr({accountId:e,worker:b.worker,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:c,...u?{beacon:u}:{},...l?{confirmation:l}:{},...f?{memory:f}:{}}):Vr({accountId:e,accountModule:s,beUrl:t,...r?{devJwtSecret:r}:{},...n?{tokenBrokerUrl:n}:{},...o?{tokenBrokerAudience:o}:{},defaultLocale:a,tools:c,...u?{beacon:u}:{},...l?{confirmation:l}:{},...f?{memory:f}:{}});const w=new AbortController,v=[],_=()=>{for(;v.length;){const T=v.pop();try{T?.()}catch{}}},C=()=>{w.signal.aborted||(w.abort(),p?.removeEventListener("abort",C),delete y.streamTransport,b?.worker.terminate(),b?.cleanup(),_(),delete y.agentController)};p?.addEventListener("abort",C,{once:!0});const A={type:"agent",signal:w.signal,addCleanup(T){if(typeof T=="function"){if(w.signal.aborted){T();return}v.push(T)}},stop:C,diagnostics(){return{accountId:e,beUrl:t,workerUrl:i,mounted:!0,transport:b?"worker":"main-thread",transportReason:b?"module-worker":"cross-origin-worker-url",flows:Object.keys(s?.flows||{})}}};return y.agentController=A,A}function It(e){const t=new URL(e,window.location.href);return t.origin===window.location.origin||t.protocol==="blob:"}function cn(e,t,r={}){const n=new URL(e,window.location.href);if(It(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
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 is(e,t={}){if(!Array.isArray(e))return[];const r=t.maxItems??8,n=t.maxFeatures??8;return e.map(o=>as(o,t.defaultBrand,n)).filter(o=>!!o).slice(0,r)}function as(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,o=qe(n);return o?us({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:ss(n.features,r),specs:cs(n.specs,r),in_stock:o.in_stock}):null}function ss(e,t){return Array.isArray(e)?e.filter(Boolean).slice(0,t):void 0}function cs(e,t){if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).filter(([,r])=>r!=null).slice(0,t))}function us(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function Lt(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(ds).filter(Boolean)}}function un(e,t){const r=Array.isArray(e)?e.filter(s=>!!(s&&typeof s=="object"&&!Array.isArray(s))):[],n=Lt(t),o=Array.isArray(n.columns)?n.columns.map(String):[];if(!o.length)return r;const i=new Map(r.map(s=>[String(s.sku||s.id||""),s])),a=o.map(s=>i.get(s)).filter(s=>!!s);return a.length?a:r}function ls(e,t){const r=Lt(e?.table),n=un(t,r);return{...e||{},table:r,products:n,multiple_product_details:n}}function ds(e){return!e||typeof e!="object"||Array.isArray(e)?null:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function fs(e=[],t={}){const r={},n=[];return(Array.isArray(e)?e.map(o=>Fe(o,t)).filter(o=>!!o):[]).forEach((o,i)=>{const a=`product-${i.toString()}`;n.push(a);const s={sku:o.sku,product:o};r[a]={type:"ProductCard",props:{product:o,index:i,action:{title:o.name,type:"launchSingleProduct",payload:s}}}}),r.root={type:"ProductGrid",props:{layout:"grid"},children:n},{widget:"chat",panelHint:"panel",spec:{root:"root",elements:r}}}function ps(e,t={}){return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:Fe(e,t)||e||{}}}}}}}function ms(e={},t={}){const r=(e.multiple_product_details||e.products||[]).map(o=>Fe(o,t)).filter(o=>!!o),n=e.table||gs(e.comparison_table);return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:{products:r,recommended:r.find(o=>o.sku===e.recommended_choice_sku)||r[0],attributes:Object.entries(n).map(([o,i])=>({label:o,values:Array.isArray(i)?i.map(String):[String(i??"")]})),highlights:Mr(e.key_differences),specialCases:Mr(e.special_considerations),recommendedText:e.recommended_choice,productActions:Object.fromEntries(r.map(o=>[o.sku,{title:o.name,type:"launchSingleProduct",payload:{sku:o.sku,product:o}}]))}}}}}}function gs(e){return Array.isArray(e)?Object.fromEntries(e.map(t=>{const r=typeof t?.label=="string"?t.label.trim():"";return r?[r,t.values]:null}).filter(t=>!!t)):{}}function ys(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 hs(e){return Object.freeze([...e])}function ln(e,t,r="v1"){return`endpoint:${r}:${ie({endpoint:e,request:t})}`}function bs(e){const t=e.version||"v1",r=n=>o=>({partition:`${e.partitionPrefix}/${n}`,key:ln(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 ws(e){return{...e}}function ks(e,t={}){return new Response(e.map(r=>JSON.stringify(r)).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`,{...t,headers:{"content-type":"application/x-ndjson",...t.headers||{}}})}function _s(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}var Ee=new Set(["and","are","for","from","the","with"]),Ss={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},As=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function H(e,t){return String(e??"").toLocaleLowerCase(t||void 0).normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),"").replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function $(e,t=Ee,r){const n=t instanceof Set?t:new Set([...Ee,...t]),o=new Set,i=[];for(const a of H(e,r).split(/\s+/u))a.length<3||n.has(a)||o.has(a)||(o.add(a),i.push(a));return i}function le(e,t={}){if(Ps(e))return e;const r=t.similarityMapper?.(e);if(r)return r;const n=t.facetKeys,o=j(e.category_names??e.category),i=j(e.category_ids),a=Rs(e.facet_hits),s=Object.entries(a).filter(([y])=>!n||n.some(b=>H(b,t.locale)===H(y,t.locale))).map(([,y])=>y),c=F(e.name,e.title),u=F(e.brand),l=t.sourceKeywords??[],f=[c,u,...o,...s,...j(e.promotions),F(e.description),...l].join(" "),m=$(f,t.stopWords,t.locale),p=F(t.sourceProductType,Ls(o,c,m,t.locale),m[0]),g=V([...Is(f,As,t.locale),...Object.entries(a).filter(([y])=>/colou?r/iu.test(y)).flatMap(([,y])=>$(y,t.stopWords,t.locale))],t.locale),h=V([...s.flatMap(y=>$(y,t.stopWords,t.locale)),...j(e.promotions).flatMap(y=>$(y,t.stopWords,t.locale))],t.locale).slice(0,24);return{sku:F(e.sku),title:c,brand:u,productType:p,categoryNames:o,categoryIds:i,facets:a,keywords:V([...l.flatMap(y=>$(y,t.stopWords,t.locale)),...m],t.locale).slice(0,12),tokens:m,colors:g,attributes:h,price:js(e)}}function vs(e,t={}){const r=F(e.product_type,e.productType),n=F(e.title,r,j(e.keywords).join(" ")),o=V([...j(e.keywords),...j(e.colors),...j(e.materials),...j(e.styles),...j(e.attributes)]);return le({sku:"__photo__",name:n,category_names:r?[r]:[],facet_hits:{colors:j(e.colors).join(", "),materials:j(e.materials).join(", "),styles:j(e.styles).join(", "),attributes:j(e.attributes).join(", ")},promotions:o},{...t,sourceProductType:r,sourceKeywords:o})}function Ts(e,t={}){const r=le(e,t);return V([...t.sourceQueries??[],ze([r.productType,...r.colors.slice(0,1),...r.attributes.slice(0,2)]),ze([r.productType,...r.keywords.slice(0,3)]),ze([r.categoryNames[r.categoryNames.length-1],...r.keywords.slice(0,2)]),ze(r.title.split(/\s+/u).slice(0,6)),r.productType].map(n=>n.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function Ot(e,t,r={}){const n={...Ss,...r.weights},o=le(t,r),i=[],a=de(e.tokens,o.tokens,r.locale),s=de(e.keywords,o.tokens,r.locale),c=Os(e.categoryNames,o.categoryNames,r.locale)||de(pn(e.categoryNames,r.locale),pn(o.categoryNames,r.locale),r.locale),u=de(e.attributes,o.attributes,r.locale),l=de(e.colors,o.colors,r.locale),f=de(e.attributes,o.tokens,r.locale),m=Bs(e.price,o.price),p=Ms(o.sku,r.hitCounts)>0?1:0,g=Ns(e,o),h=a*n.token+s*n.keyword+c*n.category+u*n.facet+l*n.color+f*n.attribute+m*n.price+p*n.retrieval,y=$s(g?h:h*.35);return g&&e.productType&&e.productType===o.productType&&i.push("same product type"),c>.4&&i.push("similar category"),u>.2&&i.push("matching product attributes"),l>0&&i.push("matching colour"),m>.8&&i.push("similar price"),g||i.push("weaker product-type match"),{score:Number(y.toFixed(4)),reasons:i}}function xs(e,t,r={}){const n=le(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean));return dn(t.filter(i=>{const a=F(i.sku);return a&&!o.has(a)}),r.maxCandidates).map(i=>{const a=Ot(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)))}async function Es(e,t,r={}){const n=le(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean)),i=dn(t.filter(c=>{const u=F(c.sku);return u&&!o.has(u)}),r.maxCandidates),a=Math.max(1,Math.floor(r.batchSize??50)),s=[];for(let c=0;c<i.length;c+=1){fn(r.signal);const u=i[c],l=Ot(n,u,r);s.push({...u,similarity_score:l.score,similarity_reasons:l.reasons}),(c+1)%a===0&&await Cs(r.yield)}return fn(r.signal),s.sort((c,u)=>u.similarity_score-c.similarity_score).slice(0,Math.max(1,Math.min(r.limit??12,100)))}function dn(e,t){if(t===void 0)return e;const r=Math.floor(Number(t));return Number.isFinite(r)&&r>0?e.slice(0,r):e}async function Cs(e){if(e){await e();return}await new Promise(t=>{const r=globalThis;if(typeof r.scheduler?.yield=="function"){r.scheduler.yield().then(t,t);return}if(typeof setTimeout=="function"){setTimeout(t,0);return}t()})}function fn(e){if(e?.aborted)throw new DOMException("Similarity ranking aborted.","AbortError")}function Ps(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function F(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function j(e){return Array.isArray(e)?e.map(t=>F(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function Rs(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,F(r)]).filter(([,t])=>t))}function js(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 V(e,t){const r=new Set,n=[];for(const o of e){const i=H(o,t);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Is(e,t,r){const n=` ${H(e,r)} `;return t.filter(o=>n.includes(` ${H(o,r)} `))}function Ls(e,t,r,n){const o=H(e[e.length-1]??e[0]??"",n);if(o){const i=$(o,Ee,n),a=new Set($(t,Ee,n));return i.find(s=>a.has(s))??i[0]??o}return r[0]??""}function ze(e){return e.map(t=>H(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function pn(e,t){return e.flatMap(r=>$(r,Ee,t))}function de(e,t,r){const n=V(e,r),o=new Set(V(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function Os(e,t,r){const n=V(e,r),o=new Set(V(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function Bs(e,t){return e<=0||t<=0?0:Math.min(e,t)/Math.max(e,t)}function Ms(e,t){return!e||!t?0:typeof t.get=="function"?t.get(e)??0:t[e]??0}function Ns(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 $s(e){return Math.max(0,Math.min(1,e))}function Fs(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 qs(e,t){const r=Fs(e);r?.style&&(t?r.style.removeProperty("display"):r.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var Us="nd_be_url";function Ds(e,t){const r=zs()||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 zs(){try{const e=new URLSearchParams(window.location.search).get(Us)?.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 mn(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 Bt=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:Gs},{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]"}],Mt={patterns:Bt};function Nt(e,t=Mt){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 gn(e,t=Mt){return Nt(mn(e),t)}function Gs(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var Hs=["assistantName","homeDomain","categories","policyTopics"],Vs={intent:["searchContract","competitorBrands"]};function Ks(e,t,r,n={}){const o=yn(t,r,n);return Object.keys(o).length?{...e,account_config:o}:e}function yn(e,t,r={}){if(!e)return{};const n={},o=r.baseKeys||Hs;for(const s of o)hn(n,e,s);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(n,Ws(i));const a=r.opAllowlist||Vs;for(const s of a[t]||[])hn(n,e,s);return n}function hn(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ws(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Js=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Zs(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||Js){const s=t[a];typeof s=="function"&&(i[a]=i[a]||s)}return t}function Ys({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function Qs({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 Xs({accountId:e,runtimeFile:t="runtime.js",startExport:r="start",globalBaseUrlKey:n,errorLabel:o,trustedRuntimeOrigins:i}={}){if(!e)throw new Error("accountId is required.");const a=o||e,s=window,c=()=>{const p=s.GengageInjectorConfig||{},g=p[e]||{};return{...p,...g}},u=()=>{const p=c();if(p.runtimeUrl)return p.runtimeUrl;const g=p.assetBaseUrl||p.baseUrl||document.currentScript?.getAttribute("src")||(n?s[n]:null);if(!g)throw new Error(`${a} runtime URL cannot be resolved.`);return new URL(t,g).href},l=p=>{if(i===!0)return p;const g=new URL(p,window.location.href).origin,h=new Set([window.location.origin]),y=c();Ce(h,document.currentScript?.getAttribute("src")),Ce(h,y.assetBaseUrl),Ce(h,y.baseUrl),Ce(h,n?s[n]:void 0);for(const b of i||[])Ce(h,b);if(!h.has(g))throw new Error(`${a} runtime origin ${g} is not trusted.`);return p},f=s.GengageAssistantInjector||(s.GengageAssistantInjector={}),m=f[e]||(f[e]={});return m.loaderPromise||(m.loaderPromise=import(l(u())).then(p=>{const g=p[r];if(typeof g!="function")throw new Error(`${a} runtime export ${r} is unavailable.`);return g()}).catch(p=>{throw delete m.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,p),p})),m.loaderPromise}function Ce(e,t){if(t)try{const r=new URL(t,window.location.href);e.add(r.origin)}catch{e.add(t)}}var ec=500,bn="__GENGAGE_AGENTIC_ACTIVITY__";function wn({accountId:e,clock:t=()=>Date.now()}={}){const r=new Set;let n=1;const o={accountId:e,entries:[]};function i(a){const s=_n({id:n++,at:t(),accountId:e,...a});o.entries.push(s),o.entries.length>ec&&(o.entries=o.entries.slice(-500));for(const c of r)c(s,o.entries);return s}return{accountId:e,get entries(){return o.entries.slice()},clear(){o.entries=[];for(const a of r)a(null,o.entries)},record:i,subscribe(a){return typeof a!="function"?()=>{}:(r.add(a),a(null,o.entries),()=>r.delete(a))}}}function kn(e){const t=window[bn];if(t?.accountId===e&&typeof t.record=="function")return t;const r=wn({accountId:e});return window[bn]=r,r}function _n(e){const t=String(e.kind||e.type||"activity"),r=Sn(t),n=e.severity||An({...e,kind:t});return{...e,kind:t,section:r,severity:n,group:e.group||vn({...e,kind:t,section:r}),noise:e.noise===!0||n==="info"&&tc({...e,kind:t})}}function tc(e){const t=String(e?.kind||"");if(t==="flow/trace"){const r=String(e?.event?.type||"");if(r==="step:start"||r==="step:end")return!0}if(t==="flow/metadata"){const r=String(e?.event?.phase||e?.event?.type||e?.event?.name||"").toLowerCase();if(r==="panelloading"||r==="heartbeat"||r==="tick")return!0}return!!t.startsWith("runtime/")}function Sn(e){return e.startsWith("flow/")?"Flow":e.startsWith("intent/")?"Intent":e.startsWith("be/")?"Backend":e.startsWith("tool/")?"Tools":e==="beacon"?"Telemetry":"Runtime"}function An(e){const t=String(e?.kind||"");return/\/(?:error|rejected|thrown)$/u.test(t)||e?.error||t==="be/response"&&Number(e?.status)>=400?"error":t==="flow/metadata"&&/fallback|retry|missing|empty/iu.test(String(e?.event?.phase||e?.event?.type||""))||t==="be/response"&&Number(e?.status)>=300?"warn":"info"}function vn(e){const t=String(e?.kind||"");if(t.startsWith("tool/"))return e?.tool?`Tool: ${e.tool}`:"Tools";if(t.startsWith("be/"))return e?.op?`BE: ${e.op}`:"Backend";if(t==="flow/request"){const r=e?.request?.type||e?.request?.action?.type;return r?`Flow: ${r}`:"Flow request"}if(t==="flow/action"){const r=e?.event?.name||e?.event?.action||e?.event?.type;return r?`Action: ${r}`:"Flow action"}return t==="flow/ui"?e?.widget?`UI: ${e.widget}`:"UI":t.startsWith("flow/")?"Flow lifecycle":t.startsWith("intent/")?e?.intent?.kind?`Intent: ${e.intent.kind}`:"Intent":t==="beacon"?e?.payload?.type?`Beacon: ${e.payload.type}`:"Beacon":e?.section||"Runtime"}var rc=8,$t=120;function Tn(e=[]){const t=Array.isArray(e)?e:[],r={status:"idle",sessionId:"",requestType:"",actionType:"",model:"",current:"Waiting for activity",errors:0,warnings:0,startedAt:null,lastAt:null,tools:[],beOps:[],uiSurfaces:[],timeline:[]},n={intent:null,route:null,panel:null,threadExtensions:{},pageProduct:null,products:null,ui:null,lastText:""};for(const o of t)nc(r,n,o);return r.tools=Ut(r.tools).slice(-8),r.beOps=Ut(r.beOps).slice(-8),r.uiSurfaces=Ut(r.uiSurfaces).slice(-8),r.timeline=r.timeline.slice(-36),!r.lastAt&&t.length&&(r.lastAt=t.at(-1)?.at||null),{flow:r,context:n}}function Pe(e,t=""){if(!e||typeof e!="object")return null;const r=L({source:t,panel:Ge(e.panel||e.panel_state),threadExtensions:fc(e.thread?.extensions||e.threadExtensions||e.extensions),pageProduct:hc(e.product||e.page?.product),products:fe(e.products||e.last_search_products||e.items),ui:Ft(e.spec),intent:qt(e.intent),route:Ve({searchParams:e.searchParams||e.search_params,flowParams:e.flowParams||e.flow_params})});return Object.keys(r).some(n=>n!=="source")?r:null}function Ge(e){if(!e||typeof e!="object")return null;const t=fe(e.last_search_products||e.current_panel_products),r=pe(e.screen_sku_list||e.search_suggestions_skus);return L({source:e.list_source||e.source,screenType:_(e.screen_type||e.screen),screenSummary:_(e.screen_summary||e.ai_plist_summary),screenSkus:r,chatMentionedSkus:pe(e.chat_mentioned_skus),lastSearch:pc(e.last_search),productCount:t?.count??Dt(e.current_panel_product_count),productSkus:t?.skus})}function Ft(e,t="",r=""){if(!e||typeof e!="object")return null;const n=bc(e);if(!n)return null;const o=n.props||{},i=mc(e,n,o),a=Array.isArray(o.buttons)?o.buttons:Array.isArray(o.actions)?o.actions:[],s=Array.isArray(o.rows)?o.rows.length:Array.isArray(o.comparison_table)?o.comparison_table.length:void 0;return L({widget:t,panelHint:r,rootType:n.type,productCount:i?.count,productSkus:i?.skus,buttonCount:a.length||void 0,buttonLabels:a.length?pe(a.map(c=>c.label||c.title)):void 0,comparisonRows:s})}function nc(e,t,r={}){if(!(!r||typeof r!="object"))switch(e.lastAt=r.at||e.lastAt,r.severity==="error"&&(e.errors+=1),r.severity==="warn"&&(e.warnings+=1),r.state&&He(t,r.state),r.kind){case"flow/request":oc(e,t,r);break;case"flow/metadata":ic(e,t,r);break;case"flow/trace":sc(e,r);break;case"flow/ui":ac(e,t,r);break;case"flow/text-final":t.lastText=_(r.content,$t),I(e,r,"Text",t.lastText,"done");break;case"flow/done":e.status=e.status==="error"?"error":"done",e.current="Done",I(e,r,"Done","Flow completed","done");break;case"flow/error":case"flow/rejected":case"flow/thrown":e.status="error",e.current="Flow error",I(e,r,"Error",_(r.error||r.kind),"error");break;case"tool/start":e.status=e.status==="idle"?"running":e.status,e.current=`Tool: ${r.tool||"tool"}`,e.tools.push(r.tool||"tool"),I(e,r,"Tool",r.tool||"tool","running");break;case"tool/done":e.tools.push(r.tool||"tool"),I(e,r,"Tool",r.tool||"tool","done");break;case"tool/error":e.status="error",e.current=`Tool error: ${r.tool||"tool"}`,e.tools.push(r.tool||"tool"),I(e,r,"Tool",r.tool||"tool","error");break;case"be/request":e.status=e.status==="idle"?"running":e.status,e.current=`BE: ${r.op||"request"}`,e.beOps.push(r.op||"unknown"),cc(t,r),I(e,r,"BE",r.op||"request","running");break;case"be/response":e.beOps.push(r.op||r.result?.op||"unknown"),uc(t,r.result),I(e,r,"BE",r.op||r.result?.intent?.kind||"response",r.severity||"done");break;case"intent/selected":t.intent=qt(r.intent),t.route=Ve({searchParams:r.searchParams,flowParams:r.flowParams}),e.current=`Intent: ${t.intent?.kind||"selected"}`,I(e,r,"Intent",t.intent?.kind||"selected","done");break;default:r.kind?.startsWith?.("runtime/")&&I(e,r,"Runtime",r.title||r.kind,"done");break}}function oc(e,t,r){const n=r.request||{};e.status="running",e.startedAt=r.at||e.startedAt,e.sessionId=_(n.session_id||n.sessionId||e.sessionId),e.requestType=_(n.type||e.requestType),e.actionType=_(n.action?.type||n.payload?.type||e.actionType),e.current=e.actionType||e.requestType||"Flow request",He(t,Pe(n.context||{},"request.context")),I(e,r,"Request",[e.requestType,e.actionType].filter(Boolean).join(" / ")||"request","running")}function ic(e,t,r){const n=r.event||{};e.sessionId=_(n.sessionId||n.session_id||e.sessionId),e.model=_(n.model||e.model),n.panelLoading===!0&&(e.current="Panel loading"),He(t,Pe(n,"flow.metadata")),I(e,r,"Metadata",_(n.name||n.phase||n.type||"metadata"),r.severity)}function ac(e,t,r){const n=Ft(r.spec,r.widget,r.panelHint);n&&(t.ui=n,typeof n.productCount=="number"&&(t.products={count:n.productCount,skus:n.productSkus||[]}),e.uiSurfaces.push(n.rootType),e.current=`UI: ${n.rootType}`,I(e,r,"UI",n.rootType||"ui","done"))}function sc(e,t){const r=t.event||{},n=_(r.type||"trace"),o=_(r.stepName||r.stepKind||"");e.sessionId=_(r.sessionId||e.sessionId),e.current=o?`${n}: ${o}`:n,I(e,t,"Trace",[n,o].filter(Boolean).join(" / ")||"trace",wc(n))}function cc(e,t){const r=t.params||{};He(e,Pe(r,"be.params")),r.panel_state&&(e.panel=Ge(r.panel_state)),r.structured_context&&(e.panel=xn(e.panel,Ge(r.structured_context)));const n=Ve({searchParams:r.search_params,flowParams:r.flow_params});n&&(e.route=n)}function uc(e,t){if(!t||typeof t!="object")return;t.intent&&(e.intent=qt(t.intent));const r=Ve({searchParams:t.search_params,flowParams:t.flow_params});r&&(e.route=r)}function He(e,t){!t||typeof t!="object"||(t.panel&&(e.panel=xn(e.panel,t.panel)),t.threadExtensions&&(e.threadExtensions={...e.threadExtensions,...t.threadExtensions}),t.pageProduct&&(e.pageProduct=t.pageProduct),t.products&&(e.products=t.products),t.ui&&(e.ui=t.ui),t.intent&&(e.intent=t.intent),t.route&&(e.route=t.route))}function xn(e,t){return e?t?L({...e,...t}):e:t||null}function I(e,t,r,n,o="done"){e.timeline.push(L({id:t.id,at:t.at,label:r,detail:_(n,$t),status:o==="info"?"done":o,kind:t.kind}))}function qt(e){return!e||typeof e!="object"?null:L({kind:_(e.kind||e.intent||e.type),target:_(e.target),confidence:typeof e.confidence=="number"?Math.round(e.confidence*100)/100:void 0})}function Ve({searchParams:e,flowParams:t}={}){const r=L({search:lc(e),flow:dc(t)});return Object.keys(r).length?r:null}function lc(e){return!e||typeof e!="object"?null:L({query:_(e.query||e.search_query),category:_(e.category||e.category_name||e.categoryName),categoryId:_(e.categoryId||e.category_id),limit:Dt(e.limit),facets:Array.isArray(e.facets)?e.facets.length:void 0})}function dc(e){return!e||typeof e!="object"?null:L({target:_(e.target),sku:_(e.sku||e.product_sku),skus:pe(e.skus||e.sku_list),action:_(e.action||e.action_type)})}function fc(e){if(!e||typeof e!="object")return{};const t={};for(const[r,n]of Object.entries(e))n!=null&&(t[r]=n&&typeof n=="object"?L({keys:Object.keys(n).slice(0,8),summary:_(n.summary||n.occasion||n.target_date_iso||n.type)}):_(n));return t}function pc(e){return!e||typeof e!="object"?null:L({query:_(e.query),source:_(e.source),category:_(e.category||e.category_name),count:Dt(e.count)})}function fe(e){if(!Array.isArray(e))return null;const t=e.filter(Boolean);return L({count:t.length,skus:pe(t.map(r=>r?.sku||r?.code||r?.id)),names:pe(t.map(r=>r?.name||r?.title),4)})}function mc(e,t,r){if(t.type==="ProductDetailsPanel")return fe([r.product||r.item].filter(Boolean));if(t.type==="ProductGrid"){const n=gc(r.products,r.items,r.cards);return fe(n||yc(e,t))}return fe(r.products||r.items||r.cards)}function gc(...e){return e.find(t=>Array.isArray(t))||null}function yc(e,t){const r=e.elements||{};return(Array.isArray(t.children)?t.children:[]).map(n=>r[n]).filter(n=>n?.type==="ProductCard").map(n=>n.props?.product||n.props?.item||n.props).filter(Boolean)}function hc(e){return!e||typeof e!="object"?null:L({sku:_(e.sku||e.code||e.id),name:_(e.name||e.title),category:_(e.category),url:_(e.url)})}function bc(e){const t=e.elements||{};return t[e.root||"root"]||t.root||e.rootElement||null}function pe(e,t=rc){if(!Array.isArray(e))return;const r=e.map(n=>_(n)).filter(Boolean);return r.length?r.slice(0,t):void 0}function Ut(e){return[...new Set(e.map(t=>_(t)).filter(Boolean))]}function Dt(e){return Number.isFinite(Number(e))?Number(e):void 0}function wc(e){return/error$/u.test(e)?"error":/start$/u.test(e)?"running":"done"}function _(e,t=$t){const r=String(e??"").replace(/\s+/gu," ").trim();return r.length>t?`${r.slice(0,t-1)}...`:r}function L(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t==null||t===""?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0))}function En(e,t){if(!e||typeof e!="object"||!t)return e;const r={...e};for(const[n,o]of Object.entries(e))typeof o!="function"||o.__gengageActivityWrapped||(r[n]=async function(a,...s){t.record({kind:"tool/start",tool:n,params:a});try{const c=await o.call(this,a,...s);return t.record({kind:"tool/done",tool:n,params:a,result:Pc(c),state:Pe(c,`tool:${n}`)}),c}catch(c){throw t.record({kind:"tool/error",tool:n,params:a,error:me(c)}),c}},Object.defineProperty(r[n],"__gengageActivityWrapped",{value:!0}));return r}function Cn(e,t){return t?r=>(t.record({kind:"beacon",payload:r}),e?.(r)):e}function Pn(e,t){if(!t)return!1;const r=window.GengageAssistantInjector?.[e],n=r?.streamTransport;if(typeof n!="function"||n.__gengageActivityWrapped)return!1;const o=function(a,s,c,u){t.record({kind:"flow/request",request:a});try{const l=n.call(this,a,kc(s,t),c,u);return l&&typeof l.then=="function"?l.catch(f=>{throw t.record({kind:"flow/rejected",requestType:a?.type,error:me(f)}),f}):l}catch(l){throw t.record({kind:"flow/thrown",requestType:a?.type,error:me(l)}),l}};return Object.defineProperty(o,"__gengageActivityWrapped",{value:!0}),r.streamTransport=o,t.record({kind:"runtime/transport-wrapped",title:"streamTransport wrapped"}),!0}function Rn({accountId:e,collector:t,promptBaseUrl:r}={}){if(!t||window.__GENGAGE_ACTIVITY_FETCH_PATCHED__)return;window.__GENGAGE_ACTIVITY_FETCH_PATCHED__=!0;const n=window.fetch?.bind(window);typeof n=="function"&&(window.fetch=async(o,i)=>{const a=Tc(o,i),s=Ec(a.url);let c="";s&&(c=a.body?.op_name||a.body?.op||"unknown",t.record({kind:"be/request",source:"main-thread-fetch",url:a.url,op:c,opDomain:a.body?.op_domain||"",prompt:await _c({accountId:e,opName:c,promptBaseUrl:r}),params:a.body?.op_payload||{},rawBody:a.body}));const u=await n(o,i);return s&&u.clone().text().then(l=>{const f=Cc(l);t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,result:f,rawText:l}),jn(t,f)}).catch(l=>{t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,error:me(l)})}),u})}function kc(e,t){if(!e||e.__gengageActivityWrapped)return e;const r={...e};Object.defineProperty(r,"__gengageActivityWrapped",{value:!0});for(const n of["onAction","onMetadata","onUISpec","onTextChunk","onError","onDone"])typeof e[n]=="function"&&(r[n]=(...o)=>(n==="onAction"?t.record({kind:"flow/action",event:o[0]}):n==="onMetadata"?t.record({kind:"flow/metadata",event:o[0]}):n==="onUISpec"?t.record({kind:"flow/ui",widget:o[1],panelHint:o[2],clearPanel:o[3]===!0,spec:o[0]}):n==="onTextChunk"&&o[1]===!0?t.record({kind:"flow/text-final",content:o[0],extra:o[2]}):n==="onError"?t.record({kind:"flow/error",error:me(o[0])}):n==="onDone"&&t.record({kind:"flow/done"}),e[n](...o)));return r}function zt(e,t){!e||!t||(e.record(t),t.kind==="be/response"&&jn(e,t.result))}async function _c({accountId:e,opName:t,promptBaseUrl:r}){if(!e||!t)return null;const n=Sc({accountId:e,baseId:String(e).replace(/-agentic$/u,""),promptBaseUrl:r});if(!n)return{error:"Configure agenticActivityPromptBaseUrl to inspect prompt source in this build."};try{const o=new URL(`${t}.yaml`,n).href,i=await fetch(o,{cache:"no-store"});return i.ok?{url:o,yaml:await i.text()}:{url:o,error:`HTTP ${i.status}`}}catch(o){return{error:me(o)}}}function Sc({accountId:e,baseId:t,promptBaseUrl:r}){if(typeof r=="string"&&r.trim())return r;const n=Ac(e,t);return n||vc(t)}function Ac(e,t){const r=window.__GENGAGE_AGENTIC_PROMPT_BASE_URL__;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){const o=r[e]||r[t];if(typeof o=="string"&&o.trim())return o}const n=(window.GengageInjectorConfig?.[e]||window.GengageInjectorConfig?.[t])?.agenticActivityPromptBaseUrl;return typeof n=="string"&&n.trim()?n:null}function vc(e){const t=Array.from(document.scripts||[]);for(const r of t){const n=r?.src||"";if(n.includes("/agentic/index.js"))return new URL(`../prompts/${e}/`,n).href;if(n.includes("/agentic.iife.js"))return new URL(`prompts/${e}/`,n).href}return null}function jn(e,t){const r=t?.intent;r&&e.record({kind:"intent/selected",intent:r,searchParams:t?.search_params,flowParams:t?.flow_params})}function Tc(e,t){const r=typeof e=="string"?e:e?.url||"",n=t?.body||(typeof e!="string"?e?.body:null);return{url:String(r||""),body:xc(n)}}function xc(e){if(!e||typeof e!="string")return{};try{return JSON.parse(e)}catch{return{raw:e}}}function Ec(e){try{const t=new URL(e,window.location.href);return t.pathname==="/v1/execute"&&/agentic\.gengage\.ai$/u.test(t.hostname)}catch{return!1}}function Cc(e){const t={};for(const r of String(e||"").split(/\r?\n/u)){const n=r.trim();if(n)try{Object.assign(t,JSON.parse(n))}catch{t._raw=[t._raw,n].filter(Boolean).join(`
|
|
7
|
+
`,{...t,headers:{"content-type":"application/x-ndjson",...t.headers||{}}})}function _s(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}var Ee=new Set(["and","are","for","from","the","with"]),Ss={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},vs=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function H(e,t){return String(e??"").toLocaleLowerCase(t||void 0).normalize("NFKD").replace(new RegExp("\\p{Diacritic}","gu"),"").replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function $(e,t=Ee,r){const n=t instanceof Set?t:new Set([...Ee,...t]),o=new Set,i=[];for(const a of H(e,r).split(/\s+/u))a.length<3||n.has(a)||o.has(a)||(o.add(a),i.push(a));return i}function le(e,t={}){if(Ps(e))return e;const r=t.similarityMapper?.(e);if(r)return r;const n=t.facetKeys,o=I(e.category_names??e.category),i=I(e.category_ids),a=Rs(e.facet_hits),s=Object.entries(a).filter(([y])=>!n||n.some(b=>H(b,t.locale)===H(y,t.locale))).map(([,y])=>y),c=F(e.name,e.title),u=F(e.brand),l=t.sourceKeywords??[],f=[c,u,...o,...s,...I(e.promotions),F(e.description),...l].join(" "),m=$(f,t.stopWords,t.locale),p=F(t.sourceProductType,Ls(o,c,m,t.locale),m[0]),g=V([...Is(f,vs,t.locale),...Object.entries(a).filter(([y])=>/colou?r/iu.test(y)).flatMap(([,y])=>$(y,t.stopWords,t.locale))],t.locale),h=V([...s.flatMap(y=>$(y,t.stopWords,t.locale)),...I(e.promotions).flatMap(y=>$(y,t.stopWords,t.locale))],t.locale).slice(0,24);return{sku:F(e.sku),title:c,brand:u,productType:p,categoryNames:o,categoryIds:i,facets:a,keywords:V([...l.flatMap(y=>$(y,t.stopWords,t.locale)),...m],t.locale).slice(0,12),tokens:m,colors:g,attributes:h,price:js(e)}}function As(e,t={}){const r=F(e.product_type,e.productType),n=F(e.title,r,I(e.keywords).join(" ")),o=V([...I(e.keywords),...I(e.colors),...I(e.materials),...I(e.styles),...I(e.attributes)]);return le({sku:"__photo__",name:n,category_names:r?[r]:[],facet_hits:{colors:I(e.colors).join(", "),materials:I(e.materials).join(", "),styles:I(e.styles).join(", "),attributes:I(e.attributes).join(", ")},promotions:o},{...t,sourceProductType:r,sourceKeywords:o})}function Ts(e,t={}){const r=le(e,t);return V([...t.sourceQueries??[],ze([r.productType,...r.colors.slice(0,1),...r.attributes.slice(0,2)]),ze([r.productType,...r.keywords.slice(0,3)]),ze([r.categoryNames[r.categoryNames.length-1],...r.keywords.slice(0,2)]),ze(r.title.split(/\s+/u).slice(0,6)),r.productType].map(n=>n.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function Ot(e,t,r={}){const n={...Ss,...r.weights},o=le(t,r),i=[],a=de(e.tokens,o.tokens,r.locale),s=de(e.keywords,o.tokens,r.locale),c=Os(e.categoryNames,o.categoryNames,r.locale)||de(pn(e.categoryNames,r.locale),pn(o.categoryNames,r.locale),r.locale),u=de(e.attributes,o.attributes,r.locale),l=de(e.colors,o.colors,r.locale),f=de(e.attributes,o.tokens,r.locale),m=Bs(e.price,o.price),p=Ms(o.sku,r.hitCounts)>0?1:0,g=Ns(e,o),h=a*n.token+s*n.keyword+c*n.category+u*n.facet+l*n.color+f*n.attribute+m*n.price+p*n.retrieval,y=$s(g?h:h*.35);return g&&e.productType&&e.productType===o.productType&&i.push("same product type"),c>.4&&i.push("similar category"),u>.2&&i.push("matching product attributes"),l>0&&i.push("matching colour"),m>.8&&i.push("similar price"),g||i.push("weaker product-type match"),{score:Number(y.toFixed(4)),reasons:i}}function xs(e,t,r={}){const n=le(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean));return dn(t.filter(i=>{const a=F(i.sku);return a&&!o.has(a)}),r.maxCandidates).map(i=>{const a=Ot(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)))}async function Es(e,t,r={}){const n=le(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean)),i=dn(t.filter(c=>{const u=F(c.sku);return u&&!o.has(u)}),r.maxCandidates),a=Math.max(1,Math.floor(r.batchSize??50)),s=[];for(let c=0;c<i.length;c+=1){fn(r.signal);const u=i[c],l=Ot(n,u,r);s.push({...u,similarity_score:l.score,similarity_reasons:l.reasons}),(c+1)%a===0&&await Cs(r.yield)}return fn(r.signal),s.sort((c,u)=>u.similarity_score-c.similarity_score).slice(0,Math.max(1,Math.min(r.limit??12,100)))}function dn(e,t){if(t===void 0)return e;const r=Math.floor(Number(t));return Number.isFinite(r)&&r>0?e.slice(0,r):e}async function Cs(e){if(e){await e();return}await new Promise(t=>{const r=globalThis;if(typeof r.scheduler?.yield=="function"){r.scheduler.yield().then(t,t);return}if(typeof setTimeout=="function"){setTimeout(t,0);return}t()})}function fn(e){if(e?.aborted)throw new DOMException("Similarity ranking aborted.","AbortError")}function Ps(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function F(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function I(e){return Array.isArray(e)?e.map(t=>F(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function Rs(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,F(r)]).filter(([,t])=>t))}function js(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 V(e,t){const r=new Set,n=[];for(const o of e){const i=H(o,t);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Is(e,t,r){const n=` ${H(e,r)} `;return t.filter(o=>n.includes(` ${H(o,r)} `))}function Ls(e,t,r,n){const o=H(e[e.length-1]??e[0]??"",n);if(o){const i=$(o,Ee,n),a=new Set($(t,Ee,n));return i.find(s=>a.has(s))??i[0]??o}return r[0]??""}function ze(e){return e.map(t=>H(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function pn(e,t){return e.flatMap(r=>$(r,Ee,t))}function de(e,t,r){const n=V(e,r),o=new Set(V(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function Os(e,t,r){const n=V(e,r),o=new Set(V(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function Bs(e,t){return e<=0||t<=0?0:Math.min(e,t)/Math.max(e,t)}function Ms(e,t){return!e||!t?0:typeof t.get=="function"?t.get(e)??0:t[e]??0}function Ns(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 $s(e){return Math.max(0,Math.min(1,e))}function Fs(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 qs(e,t){const r=Fs(e);r?.style&&(t?r.style.removeProperty("display"):r.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var Us="nd_be_url";function Ds(e,t){const r=zs()||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 zs(){try{const e=new URLSearchParams(window.location.search).get(Us)?.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 mn(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 Bt=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:Gs},{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]"}],Mt={patterns:Bt};function Nt(e,t=Mt){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 gn(e,t=Mt){return Nt(mn(e),t)}function Gs(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var Hs=["assistantName","homeDomain","categories","policyTopics"],Vs={intent:["searchContract","competitorBrands"]};function Ks(e,t,r,n={}){const o=yn(t,r,n);return Object.keys(o).length?{...e,account_config:o}:e}function yn(e,t,r={}){if(!e)return{};const n={},o=r.baseKeys||Hs;for(const s of o)hn(n,e,s);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(n,Ws(i));const a=r.opAllowlist||Vs;for(const s of a[t]||[])hn(n,e,s);return n}function hn(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ws(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Js=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Zs(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||Js){const s=t[a];typeof s=="function"&&(i[a]=i[a]||s)}return t}function Ys({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function Qs({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 Xs({accountId:e,runtimeFile:t="runtime.js",startExport:r="start",globalBaseUrlKey:n,errorLabel:o,trustedRuntimeOrigins:i}={}){if(!e)throw new Error("accountId is required.");const a=o||e,s=window,c=()=>{const p=s.GengageInjectorConfig||{},g=p[e]||{};return{...p,...g}},u=()=>{const p=c();if(p.runtimeUrl)return p.runtimeUrl;const g=p.assetBaseUrl||p.baseUrl||document.currentScript?.getAttribute("src")||(n?s[n]:null);if(!g)throw new Error(`${a} runtime URL cannot be resolved.`);return new URL(t,g).href},l=p=>{if(i===!0)return p;const g=new URL(p,window.location.href).origin,h=new Set([window.location.origin]),y=c();Ce(h,document.currentScript?.getAttribute("src")),Ce(h,y.assetBaseUrl),Ce(h,y.baseUrl),Ce(h,n?s[n]:void 0);for(const b of i||[])Ce(h,b);if(!h.has(g))throw new Error(`${a} runtime origin ${g} is not trusted.`);return p},f=s.GengageAssistantInjector||(s.GengageAssistantInjector={}),m=f[e]||(f[e]={});return m.loaderPromise||(m.loaderPromise=import(l(u())).then(p=>{const g=p[r];if(typeof g!="function")throw new Error(`${a} runtime export ${r} is unavailable.`);return g()}).catch(p=>{throw delete m.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,p),p})),m.loaderPromise}function Ce(e,t){if(t)try{const r=new URL(t,window.location.href);e.add(r.origin)}catch{e.add(t)}}var ec=500,bn="__GENGAGE_AGENTIC_ACTIVITY__";function wn({accountId:e,clock:t=()=>Date.now()}={}){const r=new Set;let n=1;const o={accountId:e,entries:[]};function i(a){const s=_n({id:n++,at:t(),accountId:e,...a});o.entries.push(s),o.entries.length>ec&&(o.entries=o.entries.slice(-500));for(const c of r)c(s,o.entries);return s}return{accountId:e,get entries(){return o.entries.slice()},clear(){o.entries=[];for(const a of r)a(null,o.entries)},record:i,subscribe(a){return typeof a!="function"?()=>{}:(r.add(a),a(null,o.entries),()=>r.delete(a))}}}function kn(e){const t=window[bn];if(t?.accountId===e&&typeof t.record=="function")return t;const r=wn({accountId:e});return window[bn]=r,r}function _n(e){const t=String(e.kind||e.type||"activity"),r=Sn(t),n=e.severity||vn({...e,kind:t});return{...e,kind:t,section:r,severity:n,group:e.group||An({...e,kind:t,section:r}),noise:e.noise===!0||n==="info"&&tc({...e,kind:t})}}function tc(e){const t=String(e?.kind||"");if(t==="flow/trace"){const r=String(e?.event?.type||"");if(r==="step:start"||r==="step:end")return!0}if(t==="flow/metadata"){const r=String(e?.event?.phase||e?.event?.type||e?.event?.name||"").toLowerCase();if(r==="panelloading"||r==="heartbeat"||r==="tick")return!0}return!!t.startsWith("runtime/")}function Sn(e){return e.startsWith("flow/")?"Flow":e.startsWith("intent/")?"Intent":e.startsWith("be/")?"Backend":e.startsWith("tool/")?"Tools":e==="beacon"?"Telemetry":"Runtime"}function vn(e){const t=String(e?.kind||"");return/\/(?:error|rejected|thrown)$/u.test(t)||e?.error||t==="be/response"&&Number(e?.status)>=400?"error":t==="flow/metadata"&&/fallback|retry|missing|empty/iu.test(String(e?.event?.phase||e?.event?.type||""))||t==="be/response"&&Number(e?.status)>=300?"warn":"info"}function An(e){const t=String(e?.kind||"");if(t.startsWith("tool/"))return e?.tool?`Tool: ${e.tool}`:"Tools";if(t.startsWith("be/"))return e?.op?`BE: ${e.op}`:"Backend";if(t==="flow/request"){const r=e?.request?.type||e?.request?.action?.type;return r?`Flow: ${r}`:"Flow request"}if(t==="flow/action"){const r=e?.event?.name||e?.event?.action||e?.event?.type;return r?`Action: ${r}`:"Flow action"}return t==="flow/ui"?e?.widget?`UI: ${e.widget}`:"UI":t.startsWith("flow/")?"Flow lifecycle":t.startsWith("intent/")?e?.intent?.kind?`Intent: ${e.intent.kind}`:"Intent":t==="beacon"?e?.payload?.type?`Beacon: ${e.payload.type}`:"Beacon":e?.section||"Runtime"}var rc=8,$t=120;function Tn(e=[]){const t=Array.isArray(e)?e:[],r={status:"idle",sessionId:"",requestType:"",actionType:"",model:"",current:"Waiting for activity",errors:0,warnings:0,startedAt:null,lastAt:null,tools:[],beOps:[],uiSurfaces:[],timeline:[]},n={intent:null,route:null,panel:null,threadExtensions:{},pageProduct:null,products:null,ui:null,lastText:""};for(const o of t)nc(r,n,o);return r.tools=Ut(r.tools).slice(-8),r.beOps=Ut(r.beOps).slice(-8),r.uiSurfaces=Ut(r.uiSurfaces).slice(-8),r.timeline=r.timeline.slice(-36),!r.lastAt&&t.length&&(r.lastAt=t.at(-1)?.at||null),{flow:r,context:n}}function Pe(e,t=""){if(!e||typeof e!="object")return null;const r=O({source:t,panel:Ge(e.panel||e.panel_state),threadExtensions:fc(e.thread?.extensions||e.threadExtensions||e.extensions),pageProduct:hc(e.product||e.page?.product),products:fe(e.products||e.last_search_products||e.items),ui:Ft(e.spec),intent:qt(e.intent),route:Ve({searchParams:e.searchParams||e.search_params,flowParams:e.flowParams||e.flow_params})});return Object.keys(r).some(n=>n!=="source")?r:null}function Ge(e){if(!e||typeof e!="object")return null;const t=fe(e.last_search_products||e.current_panel_products),r=pe(e.screen_sku_list||e.search_suggestions_skus);return O({source:e.list_source||e.source,screenType:k(e.screen_type||e.screen),screenSummary:k(e.screen_summary||e.ai_plist_summary),screenSkus:r,chatMentionedSkus:pe(e.chat_mentioned_skus),lastSearch:pc(e.last_search),productCount:t?.count??Dt(e.current_panel_product_count),productSkus:t?.skus})}function Ft(e,t="",r=""){if(!e||typeof e!="object")return null;const n=bc(e);if(!n)return null;const o=n.props||{},i=mc(e,n,o),a=Array.isArray(o.buttons)?o.buttons:Array.isArray(o.actions)?o.actions:[],s=Array.isArray(o.rows)?o.rows.length:Array.isArray(o.comparison_table)?o.comparison_table.length:void 0;return O({widget:t,panelHint:r,rootType:n.type,productCount:i?.count,productSkus:i?.skus,buttonCount:a.length||void 0,buttonLabels:a.length?pe(a.map(c=>c.label||c.title)):void 0,comparisonRows:s})}function nc(e,t,r={}){if(!(!r||typeof r!="object"))switch(e.lastAt=r.at||e.lastAt,r.severity==="error"&&(e.errors+=1),r.severity==="warn"&&(e.warnings+=1),r.state&&He(t,r.state),r.kind){case"flow/request":oc(e,t,r);break;case"flow/metadata":ic(e,t,r);break;case"flow/trace":sc(e,r);break;case"flow/ui":ac(e,t,r);break;case"flow/text-final":t.lastText=k(r.content,$t),L(e,r,"Text",t.lastText,"done");break;case"flow/done":e.status=e.status==="error"?"error":"done",e.current="Done",L(e,r,"Done","Flow completed","done");break;case"flow/error":case"flow/rejected":case"flow/thrown":e.status="error",e.current="Flow error",L(e,r,"Error",k(r.error||r.kind),"error");break;case"tool/start":e.status=e.status==="idle"?"running":e.status,e.current=`Tool: ${r.tool||"tool"}`,e.tools.push(r.tool||"tool"),L(e,r,"Tool",r.tool||"tool","running");break;case"tool/done":e.tools.push(r.tool||"tool"),L(e,r,"Tool",r.tool||"tool","done");break;case"tool/error":e.status="error",e.current=`Tool error: ${r.tool||"tool"}`,e.tools.push(r.tool||"tool"),L(e,r,"Tool",r.tool||"tool","error");break;case"be/request":e.status=e.status==="idle"?"running":e.status,e.current=`BE: ${r.op||"request"}`,e.beOps.push(r.op||"unknown"),cc(t,r),L(e,r,"BE",r.op||"request","running");break;case"be/response":e.beOps.push(r.op||r.result?.op||"unknown"),uc(t,r.result),L(e,r,"BE",r.op||r.result?.intent?.kind||"response",r.severity||"done");break;case"intent/selected":t.intent=qt(r.intent),t.route=Ve({searchParams:r.searchParams,flowParams:r.flowParams}),e.current=`Intent: ${t.intent?.kind||"selected"}`,L(e,r,"Intent",t.intent?.kind||"selected","done");break;default:r.kind?.startsWith?.("runtime/")&&L(e,r,"Runtime",r.title||r.kind,"done");break}}function oc(e,t,r){const n=r.request||{};e.status="running",e.startedAt=r.at||e.startedAt,e.sessionId=k(n.session_id||n.sessionId||e.sessionId),e.requestType=k(n.type||e.requestType),e.actionType=k(n.action?.type||n.payload?.type||e.actionType),e.current=e.actionType||e.requestType||"Flow request",He(t,Pe(n.context||{},"request.context")),L(e,r,"Request",[e.requestType,e.actionType].filter(Boolean).join(" / ")||"request","running")}function ic(e,t,r){const n=r.event||{};e.sessionId=k(n.sessionId||n.session_id||e.sessionId),e.model=k(n.model||e.model),n.panelLoading===!0&&(e.current="Panel loading"),He(t,Pe(n,"flow.metadata")),L(e,r,"Metadata",k(n.name||n.phase||n.type||"metadata"),r.severity)}function ac(e,t,r){const n=Ft(r.spec,r.widget,r.panelHint);n&&(t.ui=n,typeof n.productCount=="number"&&(t.products={count:n.productCount,skus:n.productSkus||[]}),e.uiSurfaces.push(n.rootType),e.current=`UI: ${n.rootType}`,L(e,r,"UI",n.rootType||"ui","done"))}function sc(e,t){const r=t.event||{},n=k(r.type||"trace"),o=k(r.stepName||r.stepKind||"");e.sessionId=k(r.sessionId||e.sessionId),e.current=o?`${n}: ${o}`:n,L(e,t,"Trace",[n,o].filter(Boolean).join(" / ")||"trace",wc(n))}function cc(e,t){const r=t.params||{};He(e,Pe(r,"be.params")),r.panel_state&&(e.panel=Ge(r.panel_state)),r.structured_context&&(e.panel=xn(e.panel,Ge(r.structured_context)));const n=Ve({searchParams:r.search_params,flowParams:r.flow_params});n&&(e.route=n)}function uc(e,t){if(!t||typeof t!="object")return;t.intent&&(e.intent=qt(t.intent));const r=Ve({searchParams:t.search_params,flowParams:t.flow_params});r&&(e.route=r)}function He(e,t){!t||typeof t!="object"||(t.panel&&(e.panel=xn(e.panel,t.panel)),t.threadExtensions&&(e.threadExtensions={...e.threadExtensions,...t.threadExtensions}),t.pageProduct&&(e.pageProduct=t.pageProduct),t.products&&(e.products=t.products),t.ui&&(e.ui=t.ui),t.intent&&(e.intent=t.intent),t.route&&(e.route=t.route))}function xn(e,t){return e?t?O({...e,...t}):e:t||null}function L(e,t,r,n,o="done"){e.timeline.push(O({id:t.id,at:t.at,label:r,detail:k(n,$t),status:o==="info"?"done":o,kind:t.kind}))}function qt(e){return!e||typeof e!="object"?null:O({kind:k(e.kind||e.intent||e.type),target:k(e.target),confidence:typeof e.confidence=="number"?Math.round(e.confidence*100)/100:void 0})}function Ve({searchParams:e,flowParams:t}={}){const r=O({search:lc(e),flow:dc(t)});return Object.keys(r).length?r:null}function lc(e){return!e||typeof e!="object"?null:O({query:k(e.query||e.search_query),category:k(e.category||e.category_name||e.categoryName),categoryId:k(e.categoryId||e.category_id),limit:Dt(e.limit),facets:Array.isArray(e.facets)?e.facets.length:void 0})}function dc(e){return!e||typeof e!="object"?null:O({target:k(e.target),sku:k(e.sku||e.product_sku),skus:pe(e.skus||e.sku_list),action:k(e.action||e.action_type)})}function fc(e){if(!e||typeof e!="object")return{};const t={};for(const[r,n]of Object.entries(e))n!=null&&(t[r]=n&&typeof n=="object"?O({keys:Object.keys(n).slice(0,8),summary:k(n.summary||n.occasion||n.target_date_iso||n.type)}):k(n));return t}function pc(e){return!e||typeof e!="object"?null:O({query:k(e.query),source:k(e.source),category:k(e.category||e.category_name),count:Dt(e.count)})}function fe(e){if(!Array.isArray(e))return null;const t=e.filter(Boolean);return O({count:t.length,skus:pe(t.map(r=>r?.sku||r?.code||r?.id)),names:pe(t.map(r=>r?.name||r?.title),4)})}function mc(e,t,r){if(t.type==="ProductDetailsPanel")return fe([r.product||r.item].filter(Boolean));if(t.type==="ProductGrid"){const n=gc(r.products,r.items,r.cards);return fe(n||yc(e,t))}return fe(r.products||r.items||r.cards)}function gc(...e){return e.find(t=>Array.isArray(t))||null}function yc(e,t){const r=e.elements||{};return(Array.isArray(t.children)?t.children:[]).map(n=>r[n]).filter(n=>n?.type==="ProductCard").map(n=>n.props?.product||n.props?.item||n.props).filter(Boolean)}function hc(e){return!e||typeof e!="object"?null:O({sku:k(e.sku||e.code||e.id),name:k(e.name||e.title),category:k(e.category),url:k(e.url)})}function bc(e){const t=e.elements||{};return t[e.root||"root"]||t.root||e.rootElement||null}function pe(e,t=rc){if(!Array.isArray(e))return;const r=e.map(n=>k(n)).filter(Boolean);return r.length?r.slice(0,t):void 0}function Ut(e){return[...new Set(e.map(t=>k(t)).filter(Boolean))]}function Dt(e){return Number.isFinite(Number(e))?Number(e):void 0}function wc(e){return/error$/u.test(e)?"error":/start$/u.test(e)?"running":"done"}function k(e,t=$t){const r=String(e??"").replace(/\s+/gu," ").trim();return r.length>t?`${r.slice(0,t-1)}...`:r}function O(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t==null||t===""?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0))}function En(e,t){if(!e||typeof e!="object"||!t)return e;const r={...e};for(const[n,o]of Object.entries(e))typeof o!="function"||o.__gengageActivityWrapped||(r[n]=async function(a,...s){t.record({kind:"tool/start",tool:n,params:a});try{const c=await o.call(this,a,...s);return t.record({kind:"tool/done",tool:n,params:a,result:Pc(c),state:Pe(c,`tool:${n}`)}),c}catch(c){throw t.record({kind:"tool/error",tool:n,params:a,error:me(c)}),c}},Object.defineProperty(r[n],"__gengageActivityWrapped",{value:!0}));return r}function Cn(e,t){return t?r=>(t.record({kind:"beacon",payload:r}),e?.(r)):e}function Pn(e,t){if(!t)return!1;const r=window.GengageAssistantInjector?.[e],n=r?.streamTransport;if(typeof n!="function"||n.__gengageActivityWrapped)return!1;const o=function(a,s,c,u){t.record({kind:"flow/request",request:a});try{const l=n.call(this,a,kc(s,t),c,u);return l&&typeof l.then=="function"?l.catch(f=>{throw t.record({kind:"flow/rejected",requestType:a?.type,error:me(f)}),f}):l}catch(l){throw t.record({kind:"flow/thrown",requestType:a?.type,error:me(l)}),l}};return Object.defineProperty(o,"__gengageActivityWrapped",{value:!0}),r.streamTransport=o,t.record({kind:"runtime/transport-wrapped",title:"streamTransport wrapped"}),!0}function Rn({accountId:e,collector:t,promptBaseUrl:r}={}){if(!t||window.__GENGAGE_ACTIVITY_FETCH_PATCHED__)return;window.__GENGAGE_ACTIVITY_FETCH_PATCHED__=!0;const n=window.fetch?.bind(window);typeof n=="function"&&(window.fetch=async(o,i)=>{const a=Tc(o,i),s=Ec(a.url);let c="";s&&(c=a.body?.op_name||a.body?.op||"unknown",t.record({kind:"be/request",source:"main-thread-fetch",url:a.url,op:c,opDomain:a.body?.op_domain||"",prompt:await _c({accountId:e,opName:c,promptBaseUrl:r}),params:a.body?.op_payload||{},rawBody:a.body}));const u=await n(o,i);return s&&u.clone().text().then(l=>{const f=Cc(l);t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,result:f,rawText:l}),jn(t,f)}).catch(l=>{t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,error:me(l)})}),u})}function kc(e,t){if(!e||e.__gengageActivityWrapped)return e;const r={...e};Object.defineProperty(r,"__gengageActivityWrapped",{value:!0});for(const n of["onAction","onMetadata","onUISpec","onTextChunk","onError","onDone"])typeof e[n]=="function"&&(r[n]=(...o)=>(n==="onAction"?t.record({kind:"flow/action",event:o[0]}):n==="onMetadata"?t.record({kind:"flow/metadata",event:o[0]}):n==="onUISpec"?t.record({kind:"flow/ui",widget:o[1],panelHint:o[2],clearPanel:o[3]===!0,spec:o[0]}):n==="onTextChunk"&&o[1]===!0?t.record({kind:"flow/text-final",content:o[0],extra:o[2]}):n==="onError"?t.record({kind:"flow/error",error:me(o[0])}):n==="onDone"&&t.record({kind:"flow/done"}),e[n](...o)));return r}function zt(e,t){!e||!t||(e.record(t),t.kind==="be/response"&&jn(e,t.result))}async function _c({accountId:e,opName:t,promptBaseUrl:r}){if(!e||!t)return null;const n=Sc({accountId:e,baseId:String(e).replace(/-agentic$/u,""),promptBaseUrl:r});if(!n)return{error:"Configure agenticActivityPromptBaseUrl to inspect prompt source in this build."};try{const o=new URL(`${t}.yaml`,n).href,i=await fetch(o,{cache:"no-store"});return i.ok?{url:o,yaml:await i.text()}:{url:o,error:`HTTP ${i.status}`}}catch(o){return{error:me(o)}}}function Sc({accountId:e,baseId:t,promptBaseUrl:r}){if(typeof r=="string"&&r.trim())return r;const n=vc(e,t);return n||Ac(t)}function vc(e,t){const r=window.__GENGAGE_AGENTIC_PROMPT_BASE_URL__;if(typeof r=="string"&&r.trim())return r;if(r&&typeof r=="object"){const o=r[e]||r[t];if(typeof o=="string"&&o.trim())return o}const n=(window.GengageInjectorConfig?.[e]||window.GengageInjectorConfig?.[t])?.agenticActivityPromptBaseUrl;return typeof n=="string"&&n.trim()?n:null}function Ac(e){const t=Array.from(document.scripts||[]);for(const r of t){const n=r?.src||"";if(n.includes("/agentic/index.js"))return new URL(`../prompts/${e}/`,n).href;if(n.includes("/agentic.iife.js"))return new URL(`prompts/${e}/`,n).href}return null}function jn(e,t){const r=t?.intent;r&&e.record({kind:"intent/selected",intent:r,searchParams:t?.search_params,flowParams:t?.flow_params})}function Tc(e,t){const r=typeof e=="string"?e:e?.url||"",n=t?.body||(typeof e!="string"?e?.body:null);return{url:String(r||""),body:xc(n)}}function xc(e){if(!e||typeof e!="string")return{};try{return JSON.parse(e)}catch{return{raw:e}}}function Ec(e){try{const t=new URL(e,window.location.href);return t.pathname==="/v1/execute"&&/agentic\.gengage\.ai$/u.test(t.hostname)}catch{return!1}}function Cc(e){const t={};for(const r of String(e||"").split(/\r?\n/u)){const n=r.trim();if(n)try{Object.assign(t,JSON.parse(n))}catch{t._raw=[t._raw,n].filter(Boolean).join(`
|
|
8
8
|
`)}}return t}function Pc(e){if(Array.isArray(e))return{type:"array",length:e.length,preview:e.slice(0,5)};if(!e||typeof e!="object")return e;const t={};for(const[r,n]of Object.entries(e))Array.isArray(n)?t[r]={type:"array",length:n.length,preview:n.slice(0,5)}:n&&typeof n=="object"?t[r]={type:"object",keys:Object.keys(n).slice(0,20)}:t[r]=n;return t}function me(e){return e?.message||String(e)}var In="gengage-agentic-activity-overlay",Re="all",Gt="all",Ln=["Flow","Tools","Backend","Intent","Telemetry","Runtime"],On=["info","warn","error"];function Bn(e){if(!e||typeof e.subscribe!="function")return null;const t=document.getElementById(In);if(t?.shadowRoot)return t;const r=document.createElement("div");r.id=In,r.style.cssText="position:fixed;left:10px;top:10px;z-index:2147483647;";const n=r.attachShadow({mode:"open"});n.innerHTML=Qc(e.accountId),document.documentElement.appendChild(r);const o={entries:[],section:Re,severity:Gt,search:"",grouped:!0,follow:!0,stateVisible:!0,verbose:!1},i={stateView:n.querySelector('[data-role="state-view"]'),list:n.querySelector('[data-role="list"]'),count:n.querySelector('[data-role="count"]'),visibleCount:n.querySelector('[data-role="visible-count"]'),panel:n.querySelector('[data-role="panel"]'),search:n.querySelector('[data-role="search"]'),sections:n.querySelector('[data-role="section-filters"]'),severities:n.querySelector('[data-role="severity-filters"]'),groupToggle:n.querySelector('[data-action="group"]'),followToggle:n.querySelector('[data-action="follow"]'),stateToggle:n.querySelector('[data-action="state"]'),verboseToggle:n.querySelector('[data-action="verbose"]')};Rc(r,i.list);const a=()=>Ic(i,o);return n.querySelector('[data-action="clear"]')?.addEventListener("click",()=>e.clear()),n.querySelector('[data-action="toggle"]')?.addEventListener("click",s=>{i.panel.classList.toggle("is-minimized"),s.currentTarget.textContent=i.panel.classList.contains("is-minimized")?"Open":"Min"}),i.search?.addEventListener("input",()=>{o.search=i.search.value||"",a()}),i.sections?.addEventListener("click",s=>{const c=s.target?.closest?.("[data-section-filter]")?.dataset?.sectionFilter;c&&(o.section=c,a())}),i.severities?.addEventListener("click",s=>{const c=s.target?.closest?.("[data-severity-filter]")?.dataset?.severityFilter;c&&(o.severity=c,a())}),i.groupToggle?.addEventListener("click",()=>{o.grouped=!o.grouped,i.groupToggle.setAttribute("aria-pressed",String(o.grouped)),i.groupToggle.textContent=o.grouped?"Grouped":"Flat",a()}),i.followToggle?.addEventListener("click",()=>{o.follow=!o.follow,i.followToggle.setAttribute("aria-pressed",String(o.follow)),i.followToggle.textContent=o.follow?"Follow":"Paused"}),i.stateToggle?.addEventListener("click",()=>{o.stateVisible=!o.stateVisible,i.stateToggle.setAttribute("aria-pressed",String(o.stateVisible)),i.stateToggle.textContent=o.stateVisible?"State":"State off",a()}),i.verboseToggle?.addEventListener("click",()=>{o.verbose=!o.verbose,i.verboseToggle.setAttribute("aria-pressed",String(o.verbose)),i.verboseToggle.textContent=o.verbose?"Verbose":"Concise",a()}),n.querySelector('[data-action="expand-all"]')?.addEventListener("click",()=>{i.list?.querySelectorAll("details").forEach(s=>{s.open=!0})}),n.querySelector('[data-action="collapse-all"]')?.addEventListener("click",()=>{i.list?.querySelectorAll("details").forEach(s=>{s.open=!1})}),i.list?.addEventListener("click",s=>{const c=s.target?.closest?.('[data-action="copy-json"]');if(!c)return;const u=Number(c.dataset.entryId||0);Jc(o.entries.find(l=>l.id===u),c)}),e.subscribe((s,c)=>{o.entries=c.slice(),a()}),r}function Rc(e,t){e.addEventListener("wheel",r=>{const n=jc(r.composedPath?.()||[],t);n&&(n.scrollTop+=r.deltaY,n.scrollLeft+=r.deltaX,r.preventDefault(),r.stopPropagation())},{passive:!1,capture:!0})}function jc(e,t){for(const r of e)if(!(!r||r.nodeType!==1)&&Mn(r))return r;return Mn(t)?t:null}function Mn(e){return!!(e&&(e.scrollHeight>e.clientHeight+1||e.scrollWidth>e.clientWidth+1)&&getComputedStyle(e).overflow!=="hidden")}function Ic(e,t){const r=Nn(t.entries,t),n=r.slice(-260);$n(e.sections,t.entries,t.section,"section"),$n(e.severities,t.entries,t.severity,"severity"),e.count&&(e.count.textContent=String(t.entries.length)),e.visibleCount&&(e.visibleCount.textContent=String(r.length)),Mc(e.stateView,Tn(t.entries),t.stateVisible),Bc(e.list,n,t)}function Nn(e,t={}){const r=t.section||Re,n=t.severity||Gt,o=zn(t.search),i=t.verbose===!0;return(Array.isArray(e)?e:[]).filter(a=>!i&&a.noise===!0||r!==Re&&a.section!==r||n!==Gt&&a.severity!==n?!1:o?Yc(a).includes(o):!0)}function $n(e,t,r,n){if(!e)return;e.textContent="";const o=n==="section"?Lc(t):Oc(t),i=document.createElement("button");i.type="button",i.dataset[`${n}Filter`]=Re,i.className=r===Re?"chip is-active":"chip",i.textContent=`All ${t.length}`,e.appendChild(i);for(const a of o){const s=t.filter(u=>u[n]===a).length,c=document.createElement("button");c.type="button",c.dataset[`${n}Filter`]=a,c.className=r===a?`chip is-active ${n}-${ge(a)}`:`chip ${n}-${ge(a)}`,c.textContent=`${Vn(a)} ${s}`,e.appendChild(c)}}function Lc(e){const t=new Set(e.map(r=>r.section).filter(Boolean));return Ln.filter(r=>t.has(r)).concat([...t].filter(r=>!Ln.includes(r)).sort())}function Oc(e){const t=new Set(e.map(r=>r.severity).filter(Boolean));return On.filter(r=>t.has(r)).concat([...t].filter(r=>!On.includes(r)).sort())}function Bc(e,t,r){if(!e)return;if(e.textContent="",!t.length){const o=document.createElement("div");o.className="empty",o.textContent=r.entries.length?"No activity matches the current filters.":"Waiting for agentic activity...",e.appendChild(o);return}const n=document.createDocumentFragment();if(r.grouped)for(const o of Kc(t))n.appendChild(Wc(o));else for(const o of t)n.appendChild(qn(o));e.appendChild(n),r.follow&&requestAnimationFrame(()=>e.scrollTop=e.scrollHeight)}function Mc(e,t,r){if(!e||(e.textContent="",e.classList.toggle("is-hidden",!r),!r))return;const{flow:n,context:o}=t,i=document.createDocumentFragment();i.appendChild(Nc(n)),i.appendChild($c(o)),i.appendChild(Fc(n.timeline)),e.appendChild(i)}function Nc(e){const t=document.createElement("section");return t.className=`viz-card flow-card status-${ge(e.status)}`,t.appendChild(Ht("Flow State",e.status)),Fn(t,[["Current",e.current],["Session",e.sessionId],["Request",[e.requestType,e.actionType].filter(Boolean).join(" / ")],["Model",e.model],["Tools",e.tools?.join(", ")],["BE ops",e.beOps?.join(", ")],["UI",e.uiSurfaces?.join(", ")],["Health",qc(e)]]),t}function $c(e){const t=document.createElement("section");return t.className="viz-card context-card",t.appendChild(Ht("Context State",e.panel?.screenType||e.ui?.rootType||"empty")),Fn(t,[["Intent",Uc(e.intent)],["Route",Dc(e.route)],["Screen",zc(e)],["Last search",Gc(e.panel?.lastSearch)],["Products",Hc(e.panel,e.products)],["Page product",Vc(e.pageProduct)],["Extensions",Object.keys(e.threadExtensions||{}).join(", ")],["Last text",e.lastText]]),t}function Fc(e){const t=document.createElement("section");t.className="viz-card timeline-card",t.appendChild(Ht("Flow Timeline",`${e.length} steps`));const r=document.createElement("ol");if(r.className="timeline",e.length)for(const n of e){const o=document.createElement("li");o.className=`timeline-step step-${ge(n.status||"done")}`;const i=document.createElement("span");i.className="timeline-time",i.textContent=Hn(n.at);const a=document.createElement("span");a.className="timeline-label",a.textContent=n.label||n.kind||"Step";const s=document.createElement("span");s.className="timeline-detail",s.textContent=n.detail||n.kind||"",o.append(i,a,s),r.appendChild(o)}else{const n=document.createElement("li");n.className="timeline-empty",n.textContent="No flow events yet.",r.appendChild(n)}return t.appendChild(r),t}function Ht(e,t){const r=document.createElement("div");r.className="viz-title";const n=document.createElement("span");n.textContent=e;const o=document.createElement("span");return o.className="viz-badge",o.textContent=t||"idle",r.append(n,o),r}function Fn(e,t){for(const[r,n]of t){if(n==null||n==="")continue;const o=document.createElement("div");o.className="viz-row";const i=document.createElement("span");i.className="viz-key",i.textContent=r;const a=document.createElement("span");a.className="viz-value",a.textContent=String(n),o.append(i,a),e.appendChild(o)}}function qc(e){return!e.errors&&!e.warnings?"clean":`${e.errors||0} errors, ${e.warnings||0} warnings`}function Uc(e){return e?[e.kind,e.target,e.confidence!=null?`conf ${e.confidence}`:""].filter(Boolean).join(" / "):""}function Dc(e){return e?[e.search?[e.search.query,e.search.category,e.search.categoryId,e.search.facets?`${e.search.facets} facets`:""].filter(Boolean).join(" / "):"",e.flow?[e.flow.target,e.flow.sku,e.flow.skus?.join(", "),e.flow.action].filter(Boolean).join(" / "):""].filter(Boolean).join(" -> "):""}function zc(e){const t=e.panel||{},r=e.ui||{};return[t.screenType,r.rootType,r.widget,r.panelHint].filter(Boolean).join(" / ")}function Gc(e){return e?[e.query,e.source,e.category,e.count!=null?`${e.count} results`:""].filter(Boolean).join(" / "):""}function Hc(e,t){const r=e?.productSkus||e?.screenSkus||t?.skus||[],n=e?.productCount??t?.count;return n==null&&!r.length?"":[`${n??r.length} products`,r.join(", ")].filter(Boolean).join(" / ")}function Vc(e){return e?[e.sku,e.name,e.category].filter(Boolean).join(" / "):""}function Kc(e){const t=new Map;for(const r of e){const n=`${r.section||"Runtime"}:${r.group||r.kind}`,o=t.get(n)||{key:n,section:r.section||"Runtime",severity:r.severity||"info",title:r.group||r.kind,entries:[]};o.entries.push(r),o.severity=Zc(o.severity,r.severity),t.set(n,o)}return[...t.values()]}function Wc(e){const t=document.createElement("section");t.className=`group group-${ge(e.severity)}`,t.dataset.section=e.section;const r=document.createElement("div");r.className="group-head";const n=document.createElement("span");n.className="section",n.textContent=e.section;const o=document.createElement("span");o.className="group-title",o.textContent=e.title;const i=document.createElement("span");i.className="group-count",i.textContent=String(e.entries.length),r.append(n,o,i),t.appendChild(r);for(const a of e.entries)t.appendChild(qn(a));return t}function qn(e){const t=document.createElement("details");t.dataset.entryId=String(e.id||""),t.dataset.section=e.section||"Runtime",t.dataset.severity=e.severity||"info",t.className=`entry entry-${ge(e.severity||"info")}`,t.open=e.severity==="error";const r=document.createElement("summary"),n=document.createElement("span");n.className="time",n.textContent=Hn(e.at);const o=document.createElement("span");o.className="section",o.textContent=e.section||"Runtime";const i=document.createElement("span");i.className="severity",i.textContent=Vn(e.severity||"info");const a=document.createElement("span");a.className="title",a.textContent=Gn(e),r.append(n,o,i,a);const s=document.createElement("div");s.className="entry-body";const c=document.createElement("div");c.className="entry-toolbar";const u=document.createElement("span");u.className="kind",u.textContent=e.kind;const l=document.createElement("span");l.className="kind",l.textContent=e.group||"";const f=document.createElement("button");f.type="button",f.dataset.action="copy-json",f.dataset.entryId=String(e.id||""),f.textContent="Copy JSON",c.append(u,l,f);const m=document.createElement("pre"),p=document.createElement("code");return p.innerHTML=Un(e),m.appendChild(p),s.append(c,m),t.append(r,s),t}function Un(e){const t=Vt(e),r=/("(?:\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|\btrue\b|\bfalse\b|\bnull\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/gu;let n="",o=0;for(const i of t.matchAll(r)){const a=i[0];n+=Ke(t.slice(o,i.index));let s="json-number";a.startsWith('"')?s=a.endsWith(":")?"json-key":"json-string":a==="true"||a==="false"?s="json-boolean":a==="null"&&(s="json-null"),n+=`<span class="${s}">${Ke(a)}</span>`,o=i.index+a.length}return n+Ke(t.slice(o))}function Jc(e,t){if(!e)return;const r=Vt(e),n=()=>{const o=t.textContent;t.textContent="Copied",setTimeout(()=>{t.textContent=o},900)};if(navigator.clipboard?.writeText){navigator.clipboard.writeText(r).then(n).catch(()=>Dn(r,n));return}Dn(r,n)}function Dn(e,t){const r=document.createElement("textarea");r.value=e,r.style.cssText="position:fixed;left:-9999px;top:-9999px;",document.body.appendChild(r),r.select();try{document.execCommand("copy"),t()}finally{r.remove()}}function Zc(e,t){const r={info:0,warn:1,error:2};return(r[t]||0)>(r[e]||0)?t:e}function Yc(e){return zn([e.kind,e.section,e.severity,e.group,Gn(e),e.tool,e.op,e.request?.type,e.request?.action?.type,e.event?.name,e.event?.action,e.event?.type,Vt(e)].join(" "))}function zn(e){return String(e||"").toLocaleLowerCase("tr-TR").trim()}function Gn(e){if(e.kind==="flow/request")return e.request?.type||e.request?.action?.type||"request";if(e.kind==="flow/action")return e.event?.name||e.event?.action||e.event?.type||"action";if(e.kind==="flow/metadata")return e.event?.name||e.event?.phase||e.event?.type||"metadata";if(e.kind==="flow/ui")return e.widget||e.panelHint||"ui";if(e.kind==="flow/text-final")return Xc(e.content||"final text",90);if(e.kind==="be/request")return e.op||"BE request";if(e.kind==="be/response"){const t=e.result?.intent?.kind||e.result?.intent_kind||e.result?.kind;return t?`intent selected: ${t}`:e.op||"BE response"}return e.kind==="intent/selected"?e.intent?.kind||e.kind:e.kind.startsWith("tool/")?e.tool||"tool":e.kind==="beacon"?e.payload?.type||"beacon":e.title||e.kind}function Qc(e){return`
|
|
9
9
|
<style>
|
|
10
10
|
:host { all: initial; }
|
|
@@ -351,4 +351,4 @@
|
|
|
351
351
|
<div class="state-view" data-role="state-view"></div>
|
|
352
352
|
<div class="list" data-role="list"></div>
|
|
353
353
|
</div>
|
|
354
|
-
`}function Vt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Hn(e){try{return new Date(e||Date.now()).toLocaleTimeString()}catch{return""}}function Xc(e,t){const r=String(e||"");return r.length>t?`${r.slice(0,t-1)}...`:r}function Vn(e){const t=String(e||"");return t?`${t.slice(0,1).toLocaleUpperCase("en-US")}${t.slice(1)}`:""}function ge(e){return String(e||"").toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}function Ke(e){return String(e).replace(/[&<>"']/gu,t=>t==="&"?"&":t==="<"?"<":t===">"?">":t==='"'?""":"'")}function eu({accountId:e,config:t={},tools:r,beacon:n}={}){if(!Kn(e,t))return{enabled:!1,tools:r,beacon:n,record(){},wrapTransport(){}};const o=kn(e);return window.__GENGAGE_AGENTIC_DEBUG_RECORD__=i=>zt(o,i),window.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__=i=>zt(o,i),Bn(o),Rn({accountId:e,collector:o,promptBaseUrl:t.agenticActivityPromptBaseUrl}),o.record({kind:"runtime/debug-enabled",title:"Agentic activity debug enabled"}),{enabled:!0,collector:o,tools:En(r,o),beacon:Cn(n,o),record:i=>o.record(i),wrapTransport:()=>Pn(e,o)}}function Kn(e,t={}){return t.agenticActivityDebug===!1?!1:t.agenticActivityDebug===!0||window.__GENGAGE_PWTEST_ACCOUNT__===e||window.__GENGAGE_AGENTIC_ACTIVITY_DEBUG__===!0?!0:!!(t.debug===!0&&tu(e))}function tu(e){return Array.from(document.scripts||[]).some(t=>{const r=t?.src||"";return r.includes(`/${e}/glov.js`)&&/[?&]pwtest=/u.test(r)})}var ru="input-hash";function Wn({ttlS:e,promptVersion:t="current"}={}){if(!Number.isFinite(e)||e<=0)throw new Error("inputHashCachePolicy requires a positive ttlS");return{strategy:ru,ttlS:e,promptVersion:t}}function Jn({accountId:e="",op:t,ttlS:r,promptVersion:n="current",input:o,keyParts:i,locale:a}={}){if(!t)throw new Error("declarativeBeOpCache requires an op");return{cache:Wn({ttlS:r,promptVersion:n}),cacheTtlS:r,cacheKey:(s={})=>kt(t,{account:e,locale:Kt(a,s)||s.context?.meta?.locale||s.locale||"",promptVersion:n,payload:Wt(Kt(o,s)),...ou(Kt(i,s))})}}function nu(e,t={}){return!e||e.kind!=="be_op"?e:{...e,...Jn({op:e.op,ttlS:e.cacheTtlS,input:e.input,...t})}}function Kt(e,t){return typeof e=="function"?e(t):e}function Wt(e){return Array.isArray(e)?e.map(Wt):!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,Wt(r)]))}function ou(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}var iu=Object.freeze({FALLBACK_RESULTS:"fallback_results",FALLBACK_NO_RESULTS:"fallback_no_results",FALLBACK_PARTIAL:"fallback_partial",OP_UNAVAILABLE:"op_unavailable"});function au(e,t={}){return{status:e,...t}}function su(e){return!!(e&&typeof e=="object"&&typeof e.status=="string")}function cu(e){return function(){return[{kind:"tool",name:"readPage",input:()=>({}),out:"page",patch:(r,n)=>n?.product&&typeof e=="function"?e(r,n.product):null,onError:[]}]}}var uu=["sku","group_id","name","brand","rating","review_count","cart_code","images","price_currency","price","price_discounted","discount_reason","url","category_ids","category_names","facet_hits","in_stock","promotions","variants"],lu=["description","description_html","features","service","sellers","reviews","qna","documents","delivery","payment"],du=["accountId","query","products","pendingProducts","rankedSkus","facets","facetsUsed","available_facets","logs","meta"],fu=["source","sourceType","sourceProfile","products","queries","logs"],pu=["items","kind","label","href","count","privacy"];function mu({accountId:e,search:t,facetedSearch:r,similaritySearch:n,searchGiftOptions:o,filters:i={},resultContract:a={},limitations:s=[],extraTools:c=[]}={}){return{searchKeyword:async(l={},f={})=>t(gu(l,f)),facetedSearch:typeof r=="function"?(l={},f={})=>r(Yn(l,f)):async(l={},f={})=>t(Yn(l,f)),getSearchCapabilities:()=>Zn({accountId:e,hasSimilarity:typeof n=="function",hasGiftSearch:typeof o=="function",filters:i,resultContract:a,limitations:s,extraTools:c})}}function Zn({accountId:e,hasSimilarity:t=!0,hasGiftSearch:r=!1,filters:n={},resultContract:o={},limitations:i=[],extraTools:a=[]}={}){return{accountId:e,tools:yu(["search","searchKeyword","facetedSearch",r?"searchGiftOptions":"",t?"similaritySearch":"","scanSite","siteGrep","discoverSiteContent","runSiteCommand","describeVisualContext","inspectProductSurface","openProductPage",...a].filter(Boolean)),filters:{query:"LLM-selected merchant search phrase or empty string when structured metadata is enough.",categoryId:"Optional native merchant category id selected from account metadata or visible page state.",categoryName:"Optional shopper-facing category label selected by the LLM/router.",categoryHints:"Optional category hints supplied by the LLM/router.",brandHints:"Optional brand hints supplied by the LLM/router.",featureHints:"Optional feature, material, style, size, compatibility, or project hints supplied by the LLM/router.",facets:"Optional structured facet array of { key, value } selected from route payloads or merchant metadata.",facetParams:"Optional native account facet map selected from account metadata.",priceMin:"Optional numeric lower price bound.",priceMax:"Optional numeric upper price bound.",...n},resultContract:{productItemFields:uu,productDetailFields:lu,searchResultFields:du,similarityResultFields:fu,siteContentFields:pu,...o},privacy:["Runs in the shopper browser with merchant-origin state.","Does not expose raw HTML, cookies, storage, cart/session tokens, CSRF values, or form values.","Returns compact product, content, and visible-page facts only.","Free-text intent and search planning stay LLM-owned; runtime wrappers only forward structured inputs."],limitations:i}}function gu(e,t){return Jt(typeof e=="string"?{...t,query:e}:{...t,...e||{}})}function Yn(e,t){const r=typeof e=="string"?{query:e}:e||{},n=r.query??t.query??"",o=Jt({...t,...r,query:n,categoryId:r.categoryId??r.category_id??t.categoryId??t.category_id,categoryName:r.categoryName??r.category_name??t.categoryName??t.category_name,facets:r.facets??t.facets,facetParams:r.facetParams??r.facet_params??t.facetParams??t.facet_params,priceMin:r.priceMin??r.price_min??r.budgetMin??r.min_budget??t.priceMin,priceMax:r.priceMax??r.price_max??r.budgetMax??r.max_budget??t.priceMax,limit:r.limit??r.pageSize??t.limit??t.pageSize});return n===""&&(o.query=""),o}function yu(e){const t=new Set;return e.filter(r=>{const n=String(r||"");return!n||t.has(n)?!1:(t.add(n),!0)})}function Jt(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var hu=15e3,bu="glov_agentic_iframe",wu="position:absolute;width:1px;height:1px;left:-9999px;top:-9999px;opacity:0;pointer-events:none;";function ku({markerParam:e=bu,markerValue:t="agentic-scraper",frameName:r=t,sandbox:n="allow-same-origin",timeoutMs:o=hu,hiddenStyle:i=wu,messageType:a,parser:s,isBlockedDocument:c}={}){const u=a||`gengage:agentic-iframe-scraper:${t}`;function l(g,h={}){const y=new URL(String(g),Zt());for(const[b,w]of Object.entries(h||{}))w!=null&&w!==""&&y.searchParams.set(b,String(w));return y.searchParams.set(e,t),y.href}function f(g=globalThis.window?.location,h=globalThis.window?.name||""){if(h===r||h===t)return!0;try{return new URL(g?.href||String(g||""),Zt()).searchParams.get(e)===t}catch{return!1}}async function m(g,h={},y={}){const b=y.parser||s,w=y.isBlockedDocument||c,v=globalThis.document,S=globalThis.window;if(!v?.body||typeof v.createElement!="function"||typeof v.body.appendChild!="function")return{attempted:!1,doc:null,result:null,blocked:!1,timedOut:!1,via:"unavailable"};const E=l(g),k=v.createElement("iframe");k.name=r;try{k.sandbox=n}catch{}return k.style&&(k.style.cssText=i),new Promise(N=>{let Z=!1;const rt=typeof S?.addEventListener=="function"&&typeof S?.removeEventListener=="function",sd=S.setTimeout(()=>{fr({attempted:!0,doc:null,result:null,blocked:!1,timedOut:!0,via:"timeout"})},o);function cd(){S.clearTimeout(sd),rt&&S.removeEventListener("message",Eo),typeof k.remove=="function"&&k.remove()}function fr(Y){Z||(Z=!0,cd(),N(Y))}function Eo(Y){if(Y.source&&k.contentWindow&&Y.source!==k.contentWindow)return;const ne=Y.data;!ne||ne.type!==u||ne.marker!==t||fr({attempted:!0,doc:null,result:ne.payload||null,blocked:!!ne.blocked,timedOut:!1,via:"postMessage"})}k.addEventListener("load",()=>{if(k.contentWindow?.location?.href!=="about:blank")try{const Y=k.contentDocument||k.contentWindow?.document||null,ne=!!w?.(Y);fr({attempted:!0,doc:Y,result:typeof b=="function"?b(Y,{url:E,input:h}):null,blocked:ne,timedOut:!1,via:"contentDocument"})}catch{}}),rt&&S.addEventListener("message",Eo),v.body.appendChild(k),k.src=E})}function p(g=s,{targetOrigin:h=Zt()}={}){const y=globalThis.window;if(!y?.parent||!f(y.location,y.name))return!1;const b=typeof g=="function"?g(globalThis.document,{url:y.location?.href||"",input:{}}):g;return y.parent.postMessage({type:u,marker:t,payload:b},h||"*"),!0}return{markerParam:e,markerValue:t,frameName:r,messageType:u,decorateUrl:l,isScraperFrame:f,load:m,postCurrentDocument:p}}function _u(e,{accountId:t,type:r="agenticSearchFrame"}={}){return e?.isScraperFrame?.()?(t&&globalThis.window&&(globalThis.window.GengageAssistantInjector||={},globalThis.window.GengageAssistantInjector[t]||={type:r}),!0):!1}function Zt(){return globalThis.window?.location?.origin||globalThis.location?.origin||"https://example.invalid"}function Su(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length>0)))}function Au({rootUrl:e,successMessage:t,alreadyCurrentPageMessage:r=t,missingUrlMessage:n="Ürün sayfasını açmak için ürün bağlantısı gerekiyor."}={}){const o=new URL(e).origin;return async function(a={}){const s=a.product||{},c=Qn(a.url||a.productUrl||s.url,e,o),u=a.sku||s.sku||null;return c?vu(c)?{ok:!0,sku:u,url:c,method:"already-current-page",alreadyCurrentPage:!0,message:r||t}:(Xn(c),{ok:!0,sku:u,url:c,method:"browser-navigation",message:t}):{ok:!1,sku:u,reason:"missing-url",message:n}}}function Qn(e,t,r=new URL(t).origin){if(!e)return"";try{const n=new URL(e,t);return n.protocol!=="https:"||n.origin!==r?"":(n.hash="",n.href)}catch{return""}}function Xn(e){if(typeof document>"u"){window.location.href=e;return}const t=document.createElement("a");t.href=e,t.target="_self",t.rel="noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>{window.location.href!==e&&window.location.assign(e)},0)}function vu(e){try{const t=new URL(globalThis.window?.location?.href||"",e),r=new URL(e,t.href);return t.hash="",r.hash="",t.href===r.href}catch{return!1}}function Tu(e,{screenSummary:t}={}){return{panel:{...e?.panel||{},screen_type:"homepage",screen_sku_list:[],screen_summary:t||null,last_search_products:[],last_search:null,chat_mentioned_skus:[],reviews_summary_skus:[],ai_plist_summary:null,search_suggestions_skus:[],list_source:null,active_product_panel:!1,assistant_mode:"shopping",redirected_agent_state:null,ui_hints:null}}}function eo({patterns:e,messageFilter:t,messageNormalizer:r=o=>o,messageLimit:n=10}={}){const o={patterns:[...Bt,...Array.isArray(e)?e:[]]};function i(c){return Nt(c,o)}function a(c){return gn(c,o)}function s(c=[]){const u=(Array.isArray(c)?c:[]).filter(l=>typeof t=="function"?t(l):l&&typeof l=="object").filter(Boolean);return(Number.isFinite(n)&&n>0?u.slice(-n):u).map(l=>({role:l.role,content:i(r(l.content)).slice(0,1e3)}))}return{redactPii:i,anonymousRequestText:a,anonymizeMessages:s}}function xu(e){return String(e||"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(/ /giu," ").replace(/&/giu,"&").replace(/<|>/giu," ").replace(/\s+/gu," ").trim()}function to({accountId:e,supplied:t=[],pageProduct:r=null,listingProducts:n=[],skus:o=[],limit:i=4,storedProducts:a=[],getStoredPanelProducts:s}={}){const c=no(o),u=Array.isArray(n)?n:[],l=typeof s=="function"?s({accountId:e,visibleProducts:u}):a;return ro([...Je(t),...Je(l),r,...u],{skus:c,limit:i})}function Eu({accountId:e,rootUrl:t,getProduct:r,getProducts:n,getStoredPanelProducts:o,limit:i=4}={}){return async function(s={}){return{accountId:e,products:to({accountId:e,supplied:Array.isArray(s.products)?s.products:[],pageProduct:r?.(),listingProducts:n?.(),getStoredPanelProducts:o,skus:s.skus||s.sku_list||[],limit:i}),rootUrl:t}}}function ro(e,{skus:t=[],limit:r=4}={}){const n=new Set(no(t)),o=new Set,i=[];for(const a of Je(e)){if(!a)continue;const s=We(a?.sku);if(n.size&&!n.has(s))continue;const c=s||We(a?.url)||We(a?.name||a?.title);if(!(c&&o.has(c))&&(c&&o.add(c),i.push(a),i.length>=r))break}return i}function no(e){return Je(e).map(We).filter(Boolean)}function We(e){return String(e||"").trim()}function Je(e){return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}var O={features:18,reviews:4,qna:4,sellers:4,variants:12,documents:6,textBlocks:6,relatedProducts:8,textChars:220},Yt={description:/\b(?:description|details|product information|urun bilgisi|urun aciklamasi|açıklama|aciklama)\b/iu,seller:/\b(?:seller|merchant|store|satici|satıcı|magaza|mağaza)\b/iu,review:/\b(?:review|reviews|rating|ratings|yorum|degerlendirme|değerlendirme|puan)\b/iu,qna:/\b(?:questions?|answers?|qna|q&a|soru|cevap)\b/iu,payment:/\b(?:installment|instalment|payment|pay in|taksit|odeme|ödeme|vade)\b/iu,delivery:/\b(?:delivery|shipping|cargo|stock|availability|teslimat|kargo|stok|gonderim|gönderim)\b/iu,promotion:/\b(?:campaign|promotion|discount|coupon|deal|kampanya|indirim|kupon|firsat|fırsat)\b/iu,variant:/\b(?:variant|size|colour|color|beden|olcu|ölçü|renk|numara)\b/iu},Cu=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b|\b(?:token|session|csrf|secret)\s*[:=]\s*[\w.-]+/giu,Pu=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,Ru=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}|[A-Za-z0-9_-]{24,}/iu;function oo({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return(i={})=>io({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i})}function io({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=a=>a,input:i={}}){const a=nl(i),s=o(i.product||nr(r)),c=(nr(n)||[]).map(o).filter(Boolean),u=P(i.sku||s?.sku||i.product?.sku),l=u?c.find(Z=>P(Z?.sku)===u)||s:s||c[0]||null,f=Ou(u||l?.sku),m=mo({...f.product,...l}),p=rr(Ye(l?.features),Ye(l?.specs),Vu(l?.facet_hits),Ye(f.product?.features),Mu(),Nu(),$u()).slice(0,a.features),g=co(Qe(l?.reviews),f.reviews,Fu()).slice(0,a.reviews),h=uo(Xt(l?.qna),qu()).slice(0,a.qna),y=lo(er(l?.sellers),Uu()).slice(0,a.sellers),b=te([...l?.payment||[],...Ze("payment",a)]),w=te([...l?.delivery||[],...Ze("delivery",a)]),v=te([...l?.promotions||[],...Ze("promotion",a)]),S=fo(tr(l?.variants),Du()).slice(0,a.variants),E=zu(a.documents),k=go(l?.description,f.product?.description,Gu("description"),Ze("description",{...a,textBlocks:2})[0]),N=c.filter(Z=>!u||P(Z?.sku)!==u).map(mo).filter(Boolean).slice(0,a.relatedProducts);return ye({accountId:e,pageType:nr(t)||"other",url:rl(),product:m,description:k,features:p,sellers:y,reviews:g,qna:h,rating:M(l?.rating??f.rating),review_count:M(l?.review_count??f.review_count),payment:b,delivery:w,promotions:v,variants:S,documents:E,related_products:N,capabilities:Qu({description:k,features:p,sellers:y,reviews:g,qna:h,payment:b,delivery:w,promotions:v,variants:S,documents:E,relatedProducts:N}),privacy:{browserLocal:!0,rawHtml:!1,formValues:!1,cookies:!1,storage:!1,redacted:!0}})}function ju(e,t){const r=Array.isArray(e)?e.filter(Boolean):[];if(!t||typeof t!="object"||!r.length)return r;const n=P(t.product?.sku);return r.map((o,i)=>{const a=P(o?.sku);return r.length===1||n&&a&&n===a||i===0?Lu(o,t):o})}function ao(e){return!e||typeof e!="object"?null:ye({product:e.product,description:T(e.description,500),features:Ku(e.features,14),sellers:Zu(e.sellers,4),reviews:Wu(e.reviews,4),qna:Ju(e.qna,4),rating:e.rating,review_count:e.review_count,payment:X(e.payment,5,160),delivery:X(e.delivery,5,160),promotions:X(e.promotions,5,160),variants:Yu(e.variants,10),documents:X(e.documents,5,220),capabilities:Array.isArray(e.capabilities)?e.capabilities.slice(0,12):void 0})}function Iu(e,t,r={}){const n=ao(e);if(!n)return t;const o=String(r.locale||"").toLowerCase().startsWith("en"),i=[],a=[n.rating?`${n.rating}/5`:"",n.review_count?`${n.review_count} ${o?"reviews":"yorum"}`:""].filter(Boolean).join(", ");return a&&i.push(o?`Visible rating: ${a}.`:`Görünür puan bilgisi: ${a}.`),n.reviews?.length&&i.push(`${o?"Visible review highlights":"Görünür yorumlardan öne çıkanlar"}: ${n.reviews.map(s=>[s.star?`${s.star}/5`:"",s.content].filter(Boolean).join(" ")).filter(Boolean).slice(0,3).join(" | ")}.`),i.length?(i.push(o?"This summary only uses product review and rating fields visible in the browser.":"Bu özet yalnızca tarayıcıda görünen ürün yorumu ve puan alanlarından hazırlandı."),i.join(" ")):t}function Lu(e,t){return ye({...e,description:go(e.description,t.description),features:rr(Ye(e.features),t.features).slice(0,24),specs:e.specs||(t.features?.length?Object.fromEntries(t.features.map(Xu)):void 0),sellers:lo(er(e.sellers),t.sellers),reviews:co(Qe(e.reviews),t.reviews),qna:uo(Xt(e.qna),t.qna),rating:e.rating??t.rating,review_count:e.review_count??t.review_count,payment:te([...e.payment||[],...t.payment||[]]),delivery:te([...e.delivery||[],...t.delivery||[]]),promotions:te([...e.promotions||[],...t.promotions||[]]),variants:fo(tr(e.variants),t.variants),documents:te([...e.documents||[],...t.documents||[]])})}function Ou(e){const t=[];for(const o of G('script[type="application/ld+json"]')){const i=Bu(o.textContent);for(const a of Qt(i))String(a?.["@type"]||"").toLowerCase()==="product"&&t.push(a)}const r=t.find(o=>P(o.sku||o.productID||o.mpn)===P(e))||t[0];if(!r)return{};const n=r.aggregateRating||{};return{product:ye({sku:P(r.sku||r.productID||r.mpn),name:A(r.name),brand:A(r.brand?.name||r.brand),description:A(r.description),images:X(r.image,8,280),url:je(r.url),rating:M(n.ratingValue),review_count:M(n.reviewCount||n.ratingCount)}),reviews:Qe(r.review),rating:M(n.ratingValue),review_count:M(n.reviewCount||n.ratingCount)}}function Qt(e){return Array.isArray(e)?e.flatMap(Qt):!e||typeof e!="object"?[]:[e,...Qt(e["@graph"])]}function Bu(e){try{return JSON.parse(String(e||""))}catch{return null}}function Mu(){const e=[];for(const t of G("table tr")){const r=[...t.querySelectorAll?.("th,td")||[]].map(n=>A(n.textContent));r.length>=2&&r[0]&&r[1]&&e.push({key:r[0],value:r.slice(1).join(" ")})}return e}function Nu(){const e=[];for(const t of G("dt")){const r=A(t.textContent),n=A(t.nextElementSibling?.matches?.("dd")?t.nextElementSibling.textContent:"");r&&n&&e.push({key:r,value:n})}return e}function $u(){return G('[class*="spec" i], [class*="feature" i], [class*="attribute" i], li').map(e=>so(A(e.textContent))).filter(Boolean).slice(0,O.features)}function Fu(){return G('[class*="review" i], [data-review], [itemprop="review"]').map(e=>{const t=A(e.textContent);return!t||t.length<8||Yt.qna.test(t)?null:{content:T(t,260),star:M(e.getAttribute?.("data-rating"))}}).filter(Boolean)}function qu(){const e=G('[class*="question" i], [class*="answer" i], [data-question], [data-answer]'),t=[];for(const r of e){const n=A(r.textContent);if(!n||!Yt.qna.test(n))continue;const o=A(r.getAttribute?.("data-question")||n),i=A(r.getAttribute?.("data-answer")||r.nextElementSibling?.textContent||"");t.push({question:T(o,220),answer:T(i,260)})}return t}function Uu(){return G('[class*="seller" i], [class*="merchant" i], [data-seller], [data-merchant]').map(e=>A(e.getAttribute?.("data-seller")||e.getAttribute?.("data-merchant")||e.textContent)).filter(Boolean).map(e=>({merchant:T(e,120)}))}function Du(){return G('[class*="variant" i] a,[class*="variant" i] button,[class*="size" i] button,[class*="color" i] button,[data-variant],[data-size],[data-color]').map(e=>ye({name:T(yo(e),120),value:T(e.getAttribute?.("data-value")||e.getAttribute?.("data-size")||e.getAttribute?.("data-color"),120),sku:P(e.getAttribute?.("data-sku")||e.getAttribute?.("data-product-id")),url:je(e.getAttribute?.("href")),in_stock:e.getAttribute?.("disabled")==null&&e.getAttribute?.("aria-disabled")!=="true"})).filter(e=>e.name||e.value||e.sku)}function zu(e){return G("a[href]").filter(t=>/\.pdf(?:$|[?#])/iu.test(t.getAttribute?.("href")||"")).map(t=>{const r=yo(t)||"PDF",n=je(t.getAttribute?.("href"));return n?`${r}: ${n}`:""}).filter(Boolean).slice(0,e)}function Ze(e,t){const r=Yt[e];return r?G("section,article,div,li,p,span,button,a").map(n=>A(n.textContent)).filter(n=>n&&r.test(n)&&n.length<=900).map(n=>T(n,t.textChars||O.textChars)).filter(po()).slice(0,t.textBlocks||O.textBlocks):[]}function Gu(e){return A(document.querySelector?.(`meta[name="${e}"]`)?.getAttribute?.("content")||document.querySelector?.(`meta[property="og:${e}"]`)?.getAttribute?.("content"))}function G(e){try{return[...document.querySelectorAll?.(e)||[]].filter(Hu)}catch{return[]}}function Hu(e){if(!e)return!1;if(!e.getBoundingClientRect)return!0;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const r=window.getComputedStyle?.(e);return!r||r.visibility!=="hidden"&&r.display!=="none"&&Number(r.opacity||1)>0}function Ye(e){return e?(Array.isArray(e)?e:Object.entries(e).map(([t,r])=>({key:t,value:r}))).map(t=>typeof t=="string"?so(t)||{key:"",value:A(t)}:{key:A(t.key||t.name||t.label),value:A(t.value||t.text||"")}).filter(t=>t.key||t.value):[]}function Vu(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([t,r])=>({key:A(t),value:A(r)}))}function so(e){const t=/^(.{2,80}?)\s*[::]\s*(.{1,220})$/u.exec(A(e));return t?{key:t[1],value:t[2]}:null}function Qe(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>typeof t=="string"?{content:T(t,260)}:{content:T(t.content||t.reviewBody||t.description||t.text,260),star:M(t.star||t.rating||t.reviewRating?.ratingValue)}).filter(t=>t.content||t.star)}function Xt(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>({question:T(t.question||t.name||"",220),answer:T(t.answer||t.acceptedAnswer?.text||t.text||"",260)})).filter(t=>t.question||t.answer)}function er(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>typeof t=="string"?{merchant:T(t,120)}:{merchant:T(t.merchant||t.name||t.seller||"",120),merchant_id:P(t.merchant_id||t.id||""),merchant_rating:M(t.merchant_rating||t.rating),price_offer:M(t.price_offer||t.price)}).filter(t=>t.merchant||t.merchant_id)}function tr(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>({name:T(t.name||t.label||t.title||"",120),value:T(t.value||t.size||t.color||"",120),sku:P(t.sku||t.code||""),url:je(t.url),in_stock:t.in_stock})).filter(t=>t.name||t.value||t.sku||t.url)}function rr(...e){const t=new Set,r=[];for(const n of e.flat().filter(Boolean)){const o={key:T(n.key||n.name||"",90),value:T(n.value||n.text||"",180)},i=`${o.key}:${o.value}`.toLocaleLowerCase("tr-TR");!o.key&&!o.value||t.has(i)||(t.add(i),r.push(o))}return r}function co(...e){return Xe(e.flat().filter(Boolean),t=>`${t.star||""}:${t.content||""}`)}function uo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.question||""}:${t.answer||""}`)}function lo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.merchant||""}:${t.merchant_id||""}`)}function fo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.sku||""}:${t.name||""}:${t.value||""}`)}function Xe(e,t){const r=new Set;return e.filter(n=>{const o=t(n).toLocaleLowerCase("tr-TR");return!o.trim()||r.has(o)?!1:(r.add(o),!0)})}function te(e){return X(e,20,O.textChars)}function X(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>T(n,r)).filter(Boolean).filter(po()).slice(0,t)}function po(){const e=new Set;return t=>{const r=A(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function Ku(e,t){return rr(e).slice(0,t)}function Wu(e,t){return Qe(e).slice(0,t)}function Ju(e,t){return Xt(e).slice(0,t)}function Zu(e,t){return er(e).slice(0,t)}function Yu(e,t){return tr(e).slice(0,t)}function mo(e){return!e||typeof e!="object"?null:ye({sku:P(e.sku||e.id||""),group_id:P(e.group_id||e.groupId||""),name:A(e.name||e.title||""),brand:A(e.brand||""),url:je(e.url),images:X(e.images||e.image,8,280),price:M(e.price),price_discounted:M(e.price_discounted||e.discountedPrice),price_text:A(e.price_text||e.priceText||""),price_currency:A(e.price_currency||e.currency||""),category_ids:el(e.category_ids||e.categoryIds,8,90),category_names:X(e.category_names||e.categoryNames||e.category,8,140),in_stock:e.in_stock})}function Qu(e){return[e.description?"description":"",e.features?.length?"features":"",e.sellers?.length?"seller":"",e.reviews?.length||e.rating||e.review_count?"reviews_ratings":"",e.qna?.length?"qna":"",e.payment?.length?"installment_payment":"",e.delivery?.length?"shipping_delivery_stock":"",e.promotions?.length?"campaigns_promotions":"",e.variants?.length?"variants":"",e.documents?.length?"documents":"",e.relatedProducts?.length?"related_products":""].filter(Boolean)}function Xu(e){return[A(e.key||e.name),A(e.value||e.text)]}function go(...e){return e.map(t=>T(t,700)).find(Boolean)||""}function T(e,t){return A(e).slice(0,t)}function yo(e){return A(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.textContent)}function A(e){return String(e??"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(Cu,"[redacted]").replace(/\s+/gu," ").trim()}function P(e){const t=String(e??"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(/\s+/gu," ").trim();return!t||/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu.test(t)||/\b(?:token|session|csrf|secret|password|passwd|jwt|bearer)\s*[:=]\s*[\w.-]+/iu.test(t)?"":t.slice(0,120)}function el(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>P(n).slice(0,r)).filter(Boolean).filter(tl()).slice(0,t)}function tl(){const e=new Set;return t=>{const r=P(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function M(e){const t=Number(String(e??"").replace(",","."));return Number.isFinite(t)&&t>0?t:void 0}function je(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",ho(t),t.href):""}catch{return""}}function rl(){try{const e=new URL(window.location.href);return e.hash="",ho(e),`${e.origin}${e.pathname}${e.search}`}catch{return""}}function ho(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(Pu.test(t)||Ru.test(n))&&e.searchParams.set(t,"redacted")}return e}function nl(e={}){return{features:K(e.maxFeatures,O.features,40),reviews:K(e.maxReviews,O.reviews,12),qna:K(e.maxQna,O.qna,12),sellers:K(e.maxSellers,O.sellers,12),variants:K(e.maxVariants,O.variants,30),documents:K(e.maxDocuments,O.documents,12),textBlocks:K(e.maxTextBlocks,O.textBlocks,16),relatedProducts:K(e.maxRelatedProducts,O.relatedProducts,20),textChars:K(e.textChars,O.textChars,420)}}function K(e,t,r){const n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.min(Math.floor(n),r)}function nr(e){try{return typeof e=="function"?e():null}catch{return null}}function ye(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var{redactPii:ol,anonymousRequestText:il,anonymizeMessages:al}=eo({patterns:[{pattern:/\b\d{5}\b/gu,replacement:"[postcode]"},{pattern:/\b(?:adresim|adres|mahalle|sokak|cadde)\b[^,.!?\n]{8,160}/giu,replacement:"[address]"}]});function bo(e){return(e?.route?.flow_params&&typeof e.route.flow_params=="object"?e.route.flow_params:null)||(e?.route?.flowParams&&typeof e.route.flowParams=="object"?e.route.flowParams:null)||{}}function sl(e){return Array.isArray(e)?e.find(t=>String(t||"").trim()):void 0}function cl(e){const t=bo(e);return[...t.sku?[t.sku]:[],...Array.isArray(t.sku_list)?t.sku_list:[],...Array.isArray(t.skus)?t.skus:[],...Array.isArray(t.target_skus)?t.target_skus:[]].map(r=>String(r||"").trim()).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n)}var he={headings:8,products:8,controls:12,textMatches:8,snippetChars:180},et=/\b(?:checkout|payment|pay now|place order|delete|remove|confirm|submit|ödeme|odeme|siparişi tamamla|siparisi tamamla|satın al|satin al|sil|kaldır|kaldir|onayla|gönder|gonder)\b/iu,ul=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,ll=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}|[A-Za-z0-9_-]{24,}/iu,dl={campaign:/\b(?:campaign|promotion|discount|deal|coupon|kampanya|indirim|firsat|fırsat|kupon)\b/iu,blog:/\b(?:blog|journal|guide|article|editorial|inspiration|rehber|makale|ilham|icerik|içerik)\b/iu,category:/\b(?:category|collection|department|kategori|koleksiyon|reyon)\b/iu};function fl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return{scanSite:(i={})=>pl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}),siteGrep:(i={})=>ml(i),discoverSiteContent:(i={})=>wo(i,e),runSiteCommand:(i={})=>gl(i),describeVisualContext:(i={})=>yl(i,e),inspectProductSurface:oo({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o}),getSiteCapabilities:()=>wl(e)}}function pl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}){const a=x(i.query||i.text||""),s=cr(i),c=lr(r),u=lr(n)||[];return ur({accountId:e,url:Ll(),title:ee(document.title||""),pageType:lr(t)||"other",viewport:Ol(),product:ko(o(c)),products:u.map(o).map(ko).filter(Boolean).slice(0,s.products),content:i.includeContent===!1?void 0:wo(i,e).items,headings:kl(s.headings),controls:i.includeControls===!1?void 0:_l(s.controls),textMatches:a?or(a,s):[],privacy:{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}})}function wo(e={},t=""){const r=cr(e),n=new Set(vl(e.kinds||e.kind)),o=Sl(r.controls).filter(i=>!n.size||n.has(i.kind)).slice(0,r.controls);return{accountId:t,items:o,count:o.length,privacy:W()}}function ml(e={}){const t=x(e.query||e.text||e.pattern||"");if(!t)return{ok:!1,matches:[],message:"Provide a query to scan visible page text.",privacy:W()};const r=or(t,cr(e));return{ok:r.length>0,query:t,matches:r,count:r.length,privacy:W()}}function gl(e={}){const t=x(e.command||e.action||"").toLowerCase();return t==="scroll_to_text"||t==="scrolltotext"?hl(e):t==="click_visible_text"||t==="clickvisibletext"?bl(e):t==="scroll_top"||t==="scrolltotop"?(window.scrollTo({top:0,behavior:"smooth"}),{ok:!0,command:"scroll_top",message:"Scrolled to the top of the page.",privacy:W()}):{ok:!1,command:t,message:"Supported commands are scroll_to_text, click_visible_text, and scroll_top.",privacy:W()}}function yl(e={},t){const r=e.visual_consent===!0||e.visualConsent===!0||e.consent===!0,n=r?xl(e.visual_observations||e.visualObservations):[],o=Tl(Number(e.maxImages||8));return{accountId:t,ok:r||o.length>0,consentedObservations:n,visibleImages:o,message:El({consented:r,observations:n,visibleImages:o}),privacy:{rawHtml:!1,formValues:!1,screenshotPixels:!1,redacted:!0,browserLocal:!0,requiresConsentForExternalVisualFacts:!0}}}function hl(e){const t=x(e.query||e.text||e.label||""),r=t?Rl(t):null;return r?(r.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"}),{ok:!0,command:"scroll_to_text",label:be(r),message:"Scrolled to the matching page area.",privacy:W()}):{ok:!1,command:"scroll_to_text",message:"No visible matching text found."}}function bl(e){const t=x(e.label||e.query||e.text||"");if(!t)return{ok:!1,command:"click_visible_text",message:"Provide a visible label to click."};if(et.test(t))return{ok:!1,blocked:!0,command:"click_visible_text",message:"This looks like a checkout, payment, destructive, or final confirmation action, so it was not clicked.",privacy:W()};const r=Pl(t);if(!r)return{ok:!1,command:"click_visible_text",message:"No safe visible clickable control found."};const n=be(r);return et.test(n)?{ok:!1,blocked:!0,command:"click_visible_text",label:n,message:"The matched control is blocked by the safe-click policy.",privacy:W()}:(r.click(),{ok:!0,command:"click_visible_text",label:n,message:"Clicked the safe visible control.",privacy:W()})}function wl(e){return{accountId:e,tools:["scanSite","siteGrep","discoverSiteContent","runSiteCommand","describeVisualContext","inspectProductSurface"],commands:{scanSite:"Returns a compact browser-local summary of page type, title, headings, products, controls, and matching visible text.",siteGrep:"Finds capped visible text snippets by plain query, like grep for the rendered page.",discoverSiteContent:"Returns visible campaign, blog/editorial, and category/content links as compact browser-local metadata.",runSiteCommand:"Runs guarded browser-local page commands: scroll_to_text, click_visible_text, scroll_top. Checkout, payment, destructive, and final-confirm controls are blocked.",describeVisualContext:"Summarizes visible image metadata and explicit shopper-consented redacted visual observations without capturing screenshots or pixels.",inspectProductSurface:"Returns compact GSS-style product detail evidence visible in the browser: description, specs, seller, QNA, reviews/ratings, installment/payment, shipping/stock, campaigns, variants, documents, and related visible products."},privacy:["Runs in the shopper browser.","Does not return raw HTML, cookies, storage, hidden text, or form values.","Redacts emails, phone numbers, tokens, and address-like postal snippets before returning text.","Returns compact capped snippets only.","Does not send screenshots or pixels implicitly; external visual observations must be explicitly consented."]}}function kl(e){return[...document.querySelectorAll('h1,h2,h3,[role="heading"]')].filter(re).map(t=>ee(x(t.textContent))).filter(Boolean).slice(0,e)}function _l(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(re).map(t=>({label:be(t),tag:t.tagName?.toLowerCase(),role:t.getAttribute?.("role")||null,href:_o(t),safeClick:!et.test(be(t))})).filter(t=>t.label).filter(tt(t=>`${t.tag}:${t.label}:${t.href||""}`)).slice(0,e)}function Sl(e){return[...document.querySelectorAll('a[href],button,[role="button"],summary')].filter(re).map(t=>{const r=be(t),n=_o(t),o=Al([r,n,ir(t)].join(" "));return o?ur({kind:o,label:r,href:n,heading:ir(t),safeClick:!et.test(r)}):null}).filter(Boolean).filter(tt(t=>`${t.kind}:${t.label}:${t.href||""}`)).slice(0,Math.max(1,Math.min(e,30)))}function Al(e){for(const[t,r]of Object.entries(dl))if(r.test(e))return t;return""}function vl(e){return(Array.isArray(e)?e:String(e||"").split(/[,|]/u)).map(t=>x(t).toLowerCase()).filter(Boolean)}function or(e,t){const r=e.toLocaleLowerCase("tr-TR");return Cl(document.body).map(n=>({node:n,text:x(n.nodeValue||"")})).filter(({text:n})=>n&&n.toLocaleLowerCase("tr-TR").includes(r)).map(({node:n,text:o})=>({snippet:jl(o,e,t.snippetChars),tag:n.parentElement?.tagName?.toLowerCase()||"",heading:ir(n.parentElement)})).filter(n=>n.snippet).filter(tt(n=>n.snippet)).slice(0,t.textMatches)}function Tl(e){return[...document.querySelectorAll("img")].filter(re).map(t=>({alt:ee(x(t.getAttribute("alt")||t.getAttribute("aria-label")||"")),title:ee(x(t.getAttribute("title")||"")),src:ar(t.currentSrc||t.getAttribute("src")),width:Math.round(t.getBoundingClientRect().width),height:Math.round(t.getBoundingClientRect().height)})).filter(t=>t.alt||t.title||t.src).filter(tt(t=>`${t.alt}:${t.title}:${t.src}`)).slice(0,Math.max(1,Math.min(Number.isFinite(e)&&e>0?Math.floor(e):8,20)))}function xl(e){return(Array.isArray(e)?e:String(e||"").split(/\n|;|\|/u)).map(t=>ee(t).slice(0,180)).filter(Boolean).slice(0,8)}function El({consented:e,observations:t,visibleImages:r}){const n=[];if(t.length&&n.push(`Consented visual observations: ${t.slice(0,3).join(" | ")}.`),r.length){const o=r.map(i=>i.alt||i.title).filter(Boolean).slice(0,3);n.push(o.length?`Visible image labels: ${o.join(", ")}.`:`${r.length} visible images found.`)}return!n.length&&!e&&n.push("I can use visible image labels, but external visual observations need explicit shopper consent."),n.push("No screenshots or pixels were captured or sent."),n.join(" ")}function Cl(e){if(!e)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(n){const o=n.parentElement;return!o||!re(o)||/^(script|style|noscript|template|svg)$/iu.test(o.tagName||"")||Il(o)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),r=[];for(;r.length<500;){const n=t.nextNode();if(!n)break;r.push(n)}return r}function Pl(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(re).find(t=>be(t).toLocaleLowerCase("tr-TR").includes(e.toLocaleLowerCase("tr-TR")))}function Rl(e){const t=or(e,{...he,textMatches:1})[0];return t?[...document.querySelectorAll("body *")].filter(re).find(r=>x(r.textContent).includes(t.snippet.slice(0,24))):null}function be(e){return e?ee(x(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.value||e.textContent||"")).slice(0,90):""}function ir(e){let t=e;for(let r=0;t&&r<5;r+=1){const n=x((t.matches?.('h1,h2,h3,[role="heading"]')?t:t.querySelector?.('h1,h2,h3,[role="heading"]'))?.textContent||"");if(n)return ee(n).slice(0,90);t=t.parentElement}return""}function ko(e){return e?ur({sku:x(e.sku||e.id||""),name:x(e.name||e.title||""),url:ar(e.url),price_text:x(e.price_text||e.priceText||""),price:e.price,currency:e.price_currency||e.currency,in_stock:e.in_stock,category:x(e.category||"")}):null}function jl(e,t,r){const n=ee(e),o=n.toLocaleLowerCase("tr-TR").indexOf(t.toLocaleLowerCase("tr-TR")),i=Math.max(0,o-Math.floor(r/3));return n.slice(i,i+r).trim()}function re(e){if(!e||!e.getBoundingClientRect)return!1;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const r=window.getComputedStyle(e);return r.visibility!=="hidden"&&r.display!=="none"&&Number(r.opacity||1)>0}function Il(e){return!!e.closest?.('input,textarea,select,[contenteditable="true"]')}function _o(e){return e.tagName?.toLowerCase()!=="a"?null:ar(e.getAttribute("href"))}function ar(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",sr(t),t.href):""}catch{return""}}function Ll(){const e=new URL(window.location.href);return sr(e),`${e.origin}${e.pathname}${e.search}`}function Ol(){return{width:window.innerWidth,height:window.innerHeight,scrollY:Math.round(window.scrollY||0),documentHeight:Math.round(document.documentElement?.scrollHeight||0)}}function ee(e){return x(e).replace(/https?:\/\/[^\s?#]+(?:\?[^#\s]*)?/giu,Bl).replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"<email>").replace(/\b(?:\+?\d[\d\s().-]{8,}\d)\b/gu,"<phone>").replace(/\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b/giu,"<postcode>").replace(/\btoken\s*=\s*[\w.-]+/giu,"token=<redacted>").replace(/\b(?:api[_-]?key|session|csrf|secret)\s*[:=]\s*[\w.-]+/giu,"<secret>")}function Bl(e){try{const t=new URL(e);return t.hash="",sr(t),t.href}catch{return String(e||"").replace(/\?[^#\s]*/u,"?redacted")}}function sr(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(ul.test(t)||ll.test(n))&&e.searchParams.set(t,"redacted")}return e}function x(e){return String(e||"").replace(/\s+/gu," ").trim()}function cr(e){return{headings:Ie(e.maxHeadings,he.headings,20),products:Ie(e.maxProducts,he.products,20),controls:Ie(e.maxControls,he.controls,30),textMatches:Ie(e.maxMatches||e.limit,he.textMatches,20),snippetChars:Ie(e.snippetChars,he.snippetChars,320)}}function Ie(e,t,r){const n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.min(Math.floor(n),r)}function W(){return{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}}function ur(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function lr(e){try{return typeof e=="function"?e():null}catch{return null}}function tt(e){const t=new Set;return r=>{const n=e(r);return!n||t.has(n)?!1:(t.add(n),!0)}}var Ml=3e4;function So(e,t,r={}){const n=r.ttlMs??Ml,o=r.clock??Date.now,i=new Map,a=new Map;return async function(c){const u=String(t(c)??"");if(!u)return e(c);const l=o();Nl(a,l,n);const f=i.get(u);if(f)return f;const m=a.get(u);if(m&&l-m.at<n)return $l(m.observation,u);const p=(async()=>{try{const g=await e(c);return a.set(u,{at:o(),observation:g}),g}finally{i.delete(u)}})();return i.set(u,p),p}}function Nl(e,t,r){for(const[n,o]of e)t-o.at>=r&&e.delete(n)}function $l(e,t){return!e||typeof e!="object"?e:{...e,deduped:!0,dedupe_key:t}}var Fl=3e4,Ao=new Set;function ql(e){const t=()=>So(async o=>e(o||{}),o=>{const i=Dl(o),a=Number(o?.quantity||o?.qty||1)||1,s=zl(o);return i?`${i}|${a}|${s}`:""},{ttlMs:Fl});let r=t();const n=async function(i={}){return r(i)};return n.__resetForTesting=()=>{r=t()},Ao.add(n),n}function Ul(){for(const e of Ao)typeof e.__resetForTesting=="function"&&e.__resetForTesting()}function Dl(e){const t=e?.cartCode??e?.sku??e?.productCode??e?.product?.sku??e?.product?.cart_code;return t==null?"":String(t).trim()}function zl(e){const t=e?.variantId??e?.variantCode??e?.product?.variantId??"";return t==null?"":String(t).trim()}var Gl=32,vo=new Set;function Hl(e,t){const{accountId:r,allowedHostnames:n,productFromPage:o,mergeProduct:i=Wl,needsHydration:a=Kl,fetchOptions:s={credentials:"include"},maxConcurrency:c=4}=t;if(!r)throw new Error("wrapResolveProductsWithPdpHydration: accountId is required");if(typeof o!="function")throw new Error("wrapResolveProductsWithPdpHydration: productFromPage(doc, url) is required");if(!Array.isArray(n)||!n.length)throw new Error("wrapResolveProductsWithPdpHydration: allowedHostnames must be a non-empty array");const u=new Map,l=Yl({productFromPage:o,fetchOptions:s,isAllowed:Jl(n)}),f=async function(p={}){const g=await e(p||{});if(p?.hydrateFromPdp===!1)return g;const h=Array.isArray(g?.products)?g.products:[];if(!h.length)return g;const y=await Ql(h,l,u,c,i,a);return{...g,products:y}};return f.__resetCacheForTesting=()=>u.clear(),f.__cacheSizeForTesting=()=>u.size,vo.add(f),f}function Vl(){for(const e of vo)typeof e.__resetCacheForTesting=="function"&&e.__resetCacheForTesting()}function Kl(e){if(!e||!e.url)return!1;const t=e,r=t.features,n=t.specs,o=t.category_names,i=Array.isArray(r)&&r.length>0,a=!!n&&typeof n=="object"&&Object.keys(n).length>0,s=Array.isArray(o)&&o.length>0;return!i&&!a&&!s}function Wl(e,t){return e?t?{...e,...t}:e:t}function Jl(e){const t=e.map(r=>String(r||"").toLowerCase().trim()).filter(Boolean);return r=>{const n=String(r||"").toLowerCase();if(!n)return!1;for(const o of t)if(n===o||n.endsWith(`.${o}`))return!0;return!1}}function Zl(e,t){if(!e)return null;try{const r=new URL(String(e));return r.protocol!=="https:"||!t(r.hostname)?null:r.href}catch{return null}}function Yl(e){const{productFromPage:t,fetchOptions:r,isAllowed:n}=e;return async function(i){const a=Zl(i?.url,n);if(!a||typeof fetch!="function")return null;let s;try{const u=await fetch(a,r);if(!u?.ok)return null;s=await u.text()}catch{return null}if(!s||typeof DOMParser>"u")return null;let c;try{c=new DOMParser().parseFromString(s,"text/html")}catch{return null}if(!c)return null;try{return t(c,a)||null}catch{return null}}}async function Ql(e,t,r,n,o,i){const a=new Array(e.length);let s=0;const c=Math.max(1,Math.min(n,e.length)),u=new Array(c).fill(null).map(()=>l());return await Promise.all(u),a;async function l(){for(;;){const m=s++;if(m>=e.length)return;a[m]=await f(e[m])}}async function f(m){if(!m||!i(m))return m;const p=m?.sku==null?"":String(m.sku).trim();if(p&&r.has(p)){const h=r.get(p);return h?o(m,h):m}const g=await t(m);return p&&(r.set(p,g||null),Xl(r)),g?o(m,g):m}}function Xl(e){for(;e.size>Gl;){const t=e.keys().next().value;if(t===void 0)break;e.delete(t)}}var ed=20;function To(e,t={}){const{context:r,accountConfig:n}=t,o=Array.isArray(e)?e.filter(Boolean):[];if(!o.length)return[];const i=String(r?.meta?.locale||n?.locale||n?.defaultLocale||"tr-TR").toLowerCase().startsWith("en"),a=i?"Compare the first two":"İlk ikisini karşılaştır",s=i?"Open product page":"Ürün sayfasını aç",c=i?"Tell me the comfort details":"Konfor özelliklerini anlat",u=i?"Show similar":"Benzerlerini göster",l=[];o.length>=2&&l.push({label:a,action:{type:"getComparisonTable",payload:{skus:o.slice(0,2).map(m=>m.sku).filter(Boolean),limit:2}}});const f=o[0]?.sku;return f&&!i&&(l.push({label:s,action:{type:"openProductPage",payload:{sku:f,url:o[0]?.url}}}),l.push({label:c,action:{type:"productQuestion",payload:{sku_list:[f]}}})),l.push({label:u,action:{type:"findSimilar",payload:{sku:f}}}),l}function dr(e,t=ed){const r=[];if(!Array.isArray(e))return[];for(const a of e){const s=Array.isArray(a?.observation?.products)?a.observation.products:[];s.length&&r.push([...s])}if(r.length<=1)return(r[0]||[]).slice(0,t);const n=[],o=new Set;let i=0;for(;n.length<t;){let a=!1;for(const s of r){const c=s[i];if(!c)continue;const u=String(c.sku||c.url||c.name||"");if(u&&o.has(u)){a=!0;continue}if(u&&o.add(u),n.push(c),a=!0,n.length>=t)break}if(!a)break;i+=1}return n}function td(e){if(!e?.spec?.elements)return e;const t=e.spec.root;if(!t)return e;const r=e.spec.elements[t];return!r||r.type!=="ProductGrid"?(typeof console<"u"&&console.warn&&console.warn("[agentic] withSimilarsAppend: products envelope root is not ProductGrid",r?.type),e):{...e,spec:{...e.spec,elements:{...e.spec.elements,[t]:{...r,props:{...r.props||{},similarsAppend:!0}}}}}}function rd(e,t={}){const r=t.threshold??0;return!r||r<=0||!Array.isArray(e)?!1:e.length>r}function nd(e,t={}){const r=Math.max(0,t.retainTail??4);if(!Array.isArray(e)||e.length===0||e.length<=r)return null;const n=e.slice(e.length-r),o=e.slice(0,e.length-r);return o.length?{messagesToSummarize:o,retainedTail:n}:null}function od(e,t,r={}){const n=String(t||"").trim();if(!n)return e;const o=Math.max(0,r.retainTail??4),i=Array.isArray(e.messages)?e.messages:[],a=i.slice(Math.max(0,i.length-o));return{...e,messages:[{role:"assistant",content:n,name:"compaction"},...a],panel:{...e.panel||{},compaction_summary:{summary:n,replacedCount:i.length-a.length,retainedTailCount:a.length,compactedAt:new Date().toISOString()}}}}function J(e,t){const r=e?.[t];return Array.isArray(r)?r:[]}function Le(e,t,r=!1){return[...e].reverse().find(n=>n?.name===t&&(!r||n?.observation?.status==="ok"))}function id(e){return{kind:"patch",patch:(t,r,n)=>{const o=Le(J(n.bag,e),"search_catalog"),i=Array.isArray(o?.observation?.products)?o.observation.products:null;return i?.length?{panel:{...t.panel,screen_type:"product_list",list_source:"agent",last_search_products:i,last_search:{query:o.observation.query,source:o.observation.source,count:o.observation.count},screen_sku_list:i.map(a=>a?.sku).filter(Boolean).slice(0,24)}}:null}}}function ad(e){const t=e.obsKey||"roundObservations",r=e.gridLimit??20,n=e.similarsFollowupSteps?e.similarsFollowupSteps():[];return[id(t),{kind:"branch",on:({bag:o})=>J(o,t).some(i=>Array.isArray(i?.observation?.products)&&i.observation.products.length)?"has_products":"no_products",cases:{has_products:[{kind:"emit",build:({bag:o})=>{const i=dr(J(o,t),r);return e.uiSpec(e.productsUiSpec(i))}},{kind:"emit",build:({bag:o,context:i,accountConfig:a})=>{const s=dr(J(o,t),r);return e.uiSpec(e.actionButtonsUiSpec(To(s,{context:i,accountConfig:a})))}}],no_products:[]}},{kind:"branch",on:({bag:o})=>Le(J(o,t),"compare_products",!0)?"has_compare":"no_compare",cases:{has_compare:[{kind:"emit",build:({context:o,bag:i})=>{const a=Le(J(i,t),"compare_products"),s=a?.observation||{},c=a?.arguments||{},u=Array.isArray(c.target_skus)?c.target_skus.map(String):[],l=Array.isArray(o?.panel?.last_search_products)?o.panel.last_search_products:[],f=u.length?u.map(m=>l.find(p=>String(p?.sku)===m)).filter(Boolean):l.slice(0,4);return e.uiSpec(e.comparisonUiSpec({products:f,comparison_table:s.comparison_table,key_differences:s.key_differences,recommended_choice_sku:s.recommendation?.sku,recommended_choice:s.recommendation?.reason}))}}],no_compare:[]}},{kind:"branch",on:({bag:o})=>Le(J(o,t),"get_product_details",!0)?"has_details":"no_details",cases:{has_details:[{kind:"emit",build:({context:o,bag:i})=>{const a=Le(J(i,t),"get_product_details"),s=a?.observation?.surface||{},c=a?.arguments||{},u=Array.isArray(o?.panel?.last_search_products)?o.panel.last_search_products:[],l=c.sku?u.find(m=>String(m?.sku)===String(c.sku)):null,f=s.product||l||s||{};return e.uiSpec(e.productDetailsUiSpec(f))}},...n],no_details:[]}},...xo({...e,obsKey:t})]}function xo(e){const t=e.obsKey||"roundObservations",r=e.pdpFollowupProduct;return r?[{kind:"branch",on:({bag:n,context:o})=>n.pdpFollowupRendered||J(n,t).some(i=>{const a=i?.name;return a==="search_catalog"||a==="compare_products"||a==="get_product_details"||Array.isArray(i?.observation?.products)&&i.observation.products.length})?"skip":r(n,o)?"render":"skip",cases:{render:[{kind:"emit",build:({bag:n,context:o})=>e.uiSpec(e.productDetailsUiSpec(r(n,o)))},{kind:"patch",patch:(n,o,i)=>(i.bag.pdpFollowupRendered=!0,null)},...e.similarsFollowupSteps?e.similarsFollowupSteps():[]],skip:[]}}]:[]}d.AgentError=B,d.ContextStore=Sr,d.FALLBACK_STATUS=iu,d.__resetAllCartCoalescersForTesting=Ul,d.__resetAllPdpHydratorsForTesting=Vl,d.action=$i,d.actionButtonsUiSpec=ys,d.alignProductsToTable=un,d.anonymousRequestText=gn,d.applyCompactionResult=od,d.beErrorToAgentError=yt,d.buildActivityVisualization=Tn,d.buildCompactionRequest=nd,d.buildPdpFollowupSteps=xo,d.buildPhotoSimilarityProfile=vs,d.buildProductSimilarityProfile=le,d.buildSimilarityQueries=Ts,d.buildToolUiSteps=ad,d.canUseModuleWorker=It,d.caughtToStreamError=Er,d.coalesceAddToCart=ql,d.compactAccountConfig=yn,d.compactContextProducts=is,d.compactObject=Su,d.compactProductSurfaceForLlm=ao,d.comparisonResultForUi=ls,d.comparisonUiSpec=ms,d.createActivityCollector=wn,d.createBrowserMemory=jt,d.createDiagnosticsTool=Qs,d.createEndpointCachePolicies=bs,d.createEndpointHandlers=ws,d.createFlow=hs,d.createGssToolAliases=mu,d.createIframeScraper=ku,d.createInjectorAdapter=Gr,d.createLocalRefStore=pr,d.createMainThreadInjectorAdapter=Vr,d.createModuleWorker=cn,d.createOpenProductPageTool=Au,d.createPrivacyHelpers=eo,d.createProductSurfaceInspector=oo,d.createReadPageStep=cu,d.createReadPageTool=Ys,d.createResolveProductsTool=Eu,d.createSiteAwarenessTools=fl,d.declarativeBeOpCache=Jn,d.defaultPiiPatternPack=Mt,d.defaultPiiPatterns=Bt,d.done=wt,d.elapsedMs=q,d.endpointStableKey=ln,d.error=Lr,d.fallbackStatus=au,d.filterActivityEntries=Nn,d.firstArrayValue=sl,d.formatJsonHtml=Un,d.getOrCreateActivityCollector=kn,d.groupForEntry=vn,d.gssSearchCapabilities=Zn,d.homePanelReset=Tu,d.httpErrorToAgentError=xr,d.inputHashCachePolicy=Wn,d.inspectProductSurface=io,d.installActivityFetchPatch=Rn,d.installBrowserTools=Zs,d.installFetchTransportBridge=$a,d.installIframeScraperBypass=_u,d.installLocalAgenticActivityDebug=eu,d.isFallbackStatus=su,d.isRef=mr,d.jsonResponse=_s,d.llmCacheKey=kt,d.mergeProductSurfaceEvidence=ju,d.mergeRoundProducts=dr,d.metadata=Mi,d.mountAccount=os,d.mountActivityOverlay=Bn,d.navigateSameTab=Xn,d.ndjsonResponse=ks,d.normalizeComparisonTable=Lt,d.normalizeEntry=_n,d.normalizeProduct=Fe,d.normalizeSameOriginUrl=Qn,d.normalizeSimilarityText=H,d.nowIso=br,d.plainMessageContent=xu,d.productDetailsUiSpec=ps,d.productFactsKey=Ui,d.productSkuKey=qi,d.productSurfaceReviewText=Iu,d.productsUiSpec=fs,d.rankSimilarProducts=xs,d.rankSimilarProductsAsync=Es,d.recordBeDebugPayload=zt,d.redactPii=Nt,d.requestText=mn,d.resolveBeUrl=Ds,d.resolveFlow=Or,d.resolveProductCandidates=to,d.retailAnonymizeMessages=al,d.retailAnonymousRequestText=il,d.retailRedactPii=ol,d.routeFlowParams=bo,d.routeSkuList=cl,d.scoreSimilarityCandidate=Ot,d.searchFollowUpPills=To,d.sectionForKind=Sn,d.setAssistantHostVisible=qs,d.severityForEntry=An,d.shouldCompact=rd,d.shouldInstallActivityDebug=Kn,d.singleFlight=So,d.stableKey=ie,d.startLazyRuntimeLoader=Xs,d.stickyContextKey=lt,d.summarizeDebugState=Pe,d.summarizePanelState=Ge,d.summarizeUiSpec=Ft,d.textChunk=Ir,d.textKey=Di,d.tokenizeSimilarityText=$,d.trimProductFactsCore=qe,d.trimProductFactsListCore=Fi,d.uiSpec=Ni,d.uniqueProductsBySku=ro,d.validateToolArgs=Fr,d.withAccountConfig=Ks,d.withDeclarativeBeOpCache=nu,d.withSimilarsAppend=td,d.wrapActivityBeacon=Cn,d.wrapActivityTools=En,d.wrapActivityTransport=Pn,d.wrapResolveProductsWithPdpHydration=Hl})(this.Gengage=this.Gengage||{});
|
|
354
|
+
`}function Vt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Hn(e){try{return new Date(e||Date.now()).toLocaleTimeString()}catch{return""}}function Xc(e,t){const r=String(e||"");return r.length>t?`${r.slice(0,t-1)}...`:r}function Vn(e){const t=String(e||"");return t?`${t.slice(0,1).toLocaleUpperCase("en-US")}${t.slice(1)}`:""}function ge(e){return String(e||"").toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}function Ke(e){return String(e).replace(/[&<>"']/gu,t=>t==="&"?"&":t==="<"?"<":t===">"?">":t==='"'?""":"'")}function eu({accountId:e,config:t={},tools:r,beacon:n}={}){if(!Kn(e,t))return{enabled:!1,tools:r,beacon:n,record(){},wrapTransport(){}};const o=kn(e);return window.__GENGAGE_AGENTIC_DEBUG_RECORD__=i=>zt(o,i),window.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__=i=>zt(o,i),Bn(o),Rn({accountId:e,collector:o,promptBaseUrl:t.agenticActivityPromptBaseUrl}),o.record({kind:"runtime/debug-enabled",title:"Agentic activity debug enabled"}),{enabled:!0,collector:o,tools:En(r,o),beacon:Cn(n,o),record:i=>o.record(i),wrapTransport:()=>Pn(e,o)}}function Kn(e,t={}){return t.agenticActivityDebug===!1?!1:t.agenticActivityDebug===!0||window.__GENGAGE_PWTEST_ACCOUNT__===e||window.__GENGAGE_AGENTIC_ACTIVITY_DEBUG__===!0?!0:!!(t.debug===!0&&tu(e))}function tu(e){return Array.from(document.scripts||[]).some(t=>{const r=t?.src||"";return r.includes(`/${e}/glov.js`)&&/[?&]pwtest=/u.test(r)})}var ru="input-hash";function Wn({ttlS:e,promptVersion:t="current"}={}){if(!Number.isFinite(e)||e<=0)throw new Error("inputHashCachePolicy requires a positive ttlS");return{strategy:ru,ttlS:e,promptVersion:t}}function Jn({accountId:e="",op:t,ttlS:r,promptVersion:n="current",input:o,keyParts:i,locale:a}={}){if(!t)throw new Error("declarativeBeOpCache requires an op");return{cache:Wn({ttlS:r,promptVersion:n}),cacheTtlS:r,cacheKey:(s={})=>kt(t,{account:e,locale:Kt(a,s)||s.context?.meta?.locale||s.locale||"",promptVersion:n,payload:Wt(Kt(o,s)),...ou(Kt(i,s))})}}function nu(e,t={}){return!e||e.kind!=="be_op"?e:{...e,...Jn({op:e.op,ttlS:e.cacheTtlS,input:e.input,...t})}}function Kt(e,t){return typeof e=="function"?e(t):e}function Wt(e){return Array.isArray(e)?e.map(Wt):!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,Wt(r)]))}function ou(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}var iu=Object.freeze({FALLBACK_RESULTS:"fallback_results",FALLBACK_NO_RESULTS:"fallback_no_results",FALLBACK_PARTIAL:"fallback_partial",OP_UNAVAILABLE:"op_unavailable"});function au(e,t={}){return{status:e,...t}}function su(e){return!!(e&&typeof e=="object"&&typeof e.status=="string")}function cu(e){return function(){return[{kind:"tool",name:"readPage",input:()=>({}),out:"page",patch:(r,n)=>n?.product&&typeof e=="function"?e(r,n.product):null,onError:[]}]}}var uu=["sku","group_id","name","brand","rating","review_count","cart_code","images","price_currency","price","price_discounted","discount_reason","url","category_ids","category_names","facet_hits","in_stock","promotions","variants"],lu=["description","description_html","features","service","sellers","reviews","qna","documents","delivery","payment"],du=["accountId","query","products","pendingProducts","rankedSkus","facets","facetsUsed","available_facets","logs","meta"],fu=["source","sourceType","sourceProfile","products","queries","logs"],pu=["items","kind","label","href","count","privacy"];function mu({accountId:e,search:t,facetedSearch:r,similaritySearch:n,searchGiftOptions:o,filters:i={},resultContract:a={},limitations:s=[],extraTools:c=[]}={}){return{searchKeyword:async(l={},f={})=>t(gu(l,f)),facetedSearch:typeof r=="function"?(l={},f={})=>r(Yn(l,f)):async(l={},f={})=>t(Yn(l,f)),getSearchCapabilities:()=>Zn({accountId:e,hasSimilarity:typeof n=="function",hasGiftSearch:typeof o=="function",filters:i,resultContract:a,limitations:s,extraTools:c})}}function Zn({accountId:e,hasSimilarity:t=!0,hasGiftSearch:r=!1,filters:n={},resultContract:o={},limitations:i=[],extraTools:a=[]}={}){return{accountId:e,tools:yu(["search","searchKeyword","facetedSearch",r?"searchGiftOptions":"",t?"similaritySearch":"","scanSite","siteGrep","discoverSiteContent","runSiteCommand","describeVisualContext","inspectProductSurface","openProductPage",...a].filter(Boolean)),filters:{query:"LLM-selected merchant search phrase or empty string when structured metadata is enough.",categoryId:"Optional native merchant category id selected from account metadata or visible page state.",categoryName:"Optional shopper-facing category label selected by the LLM/router.",categoryHints:"Optional category hints supplied by the LLM/router.",brandHints:"Optional brand hints supplied by the LLM/router.",featureHints:"Optional feature, material, style, size, compatibility, or project hints supplied by the LLM/router.",facets:"Optional structured facet array of { key, value } selected from route payloads or merchant metadata.",facetParams:"Optional native account facet map selected from account metadata.",priceMin:"Optional numeric lower price bound.",priceMax:"Optional numeric upper price bound.",...n},resultContract:{productItemFields:uu,productDetailFields:lu,searchResultFields:du,similarityResultFields:fu,siteContentFields:pu,...o},privacy:["Runs in the shopper browser with merchant-origin state.","Does not expose raw HTML, cookies, storage, cart/session tokens, CSRF values, or form values.","Returns compact product, content, and visible-page facts only.","Free-text intent and search planning stay LLM-owned; runtime wrappers only forward structured inputs."],limitations:i}}function gu(e,t){return Jt(typeof e=="string"?{...t,query:e}:{...t,...e||{}})}function Yn(e,t){const r=typeof e=="string"?{query:e}:e||{},n=r.query??t.query??"",o=Jt({...t,...r,query:n,categoryId:r.categoryId??r.category_id??t.categoryId??t.category_id,categoryName:r.categoryName??r.category_name??t.categoryName??t.category_name,facets:r.facets??t.facets,facetParams:r.facetParams??r.facet_params??t.facetParams??t.facet_params,priceMin:r.priceMin??r.price_min??r.budgetMin??r.min_budget??t.priceMin,priceMax:r.priceMax??r.price_max??r.budgetMax??r.max_budget??t.priceMax,limit:r.limit??r.pageSize??t.limit??t.pageSize});return n===""&&(o.query=""),o}function yu(e){const t=new Set;return e.filter(r=>{const n=String(r||"");return!n||t.has(n)?!1:(t.add(n),!0)})}function Jt(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var hu=15e3,bu="glov_agentic_iframe",wu="position:absolute;width:1px;height:1px;left:-9999px;top:-9999px;opacity:0;pointer-events:none;";function ku({markerParam:e=bu,markerValue:t="agentic-scraper",frameName:r=t,sandbox:n="allow-same-origin",timeoutMs:o=hu,hiddenStyle:i=wu,messageType:a,parser:s,isBlockedDocument:c}={}){const u=a||`gengage:agentic-iframe-scraper:${t}`;function l(g,h={}){const y=new URL(String(g),Zt());for(const[b,w]of Object.entries(h||{}))w!=null&&w!==""&&y.searchParams.set(b,String(w));return y.searchParams.set(e,t),y.href}function f(g=globalThis.window?.location,h=globalThis.window?.name||""){if(h===r||h===t)return!0;try{return new URL(g?.href||String(g||""),Zt()).searchParams.get(e)===t}catch{return!1}}async function m(g,h={},y={}){const b=y.parser||s,w=y.isBlockedDocument||c,v=globalThis.document,_=globalThis.window;if(!v?.body||typeof v.createElement!="function"||typeof v.body.appendChild!="function")return{attempted:!1,doc:null,result:null,blocked:!1,timedOut:!1,via:"unavailable"};const C=l(g),A=v.createElement("iframe");A.name=r;try{A.sandbox=n}catch{}return A.style&&(A.style.cssText=i),new Promise(T=>{let Z=!1;const rt=typeof _?.addEventListener=="function"&&typeof _?.removeEventListener=="function",sd=_.setTimeout(()=>{fr({attempted:!0,doc:null,result:null,blocked:!1,timedOut:!0,via:"timeout"})},o);function cd(){_.clearTimeout(sd),rt&&_.removeEventListener("message",Eo),typeof A.remove=="function"&&A.remove()}function fr(Y){Z||(Z=!0,cd(),T(Y))}function Eo(Y){if(Y.source&&A.contentWindow&&Y.source!==A.contentWindow)return;const ne=Y.data;!ne||ne.type!==u||ne.marker!==t||fr({attempted:!0,doc:null,result:ne.payload||null,blocked:!!ne.blocked,timedOut:!1,via:"postMessage"})}A.addEventListener("load",()=>{if(A.contentWindow?.location?.href!=="about:blank")try{const Y=A.contentDocument||A.contentWindow?.document||null,ne=!!w?.(Y);fr({attempted:!0,doc:Y,result:typeof b=="function"?b(Y,{url:C,input:h}):null,blocked:ne,timedOut:!1,via:"contentDocument"})}catch{}}),rt&&_.addEventListener("message",Eo),v.body.appendChild(A),A.src=C})}function p(g=s,{targetOrigin:h=Zt()}={}){const y=globalThis.window;if(!y?.parent||!f(y.location,y.name))return!1;const b=typeof g=="function"?g(globalThis.document,{url:y.location?.href||"",input:{}}):g;return y.parent.postMessage({type:u,marker:t,payload:b},h||"*"),!0}return{markerParam:e,markerValue:t,frameName:r,messageType:u,decorateUrl:l,isScraperFrame:f,load:m,postCurrentDocument:p}}function _u(e,{accountId:t,type:r="agenticSearchFrame"}={}){return e?.isScraperFrame?.()?(t&&globalThis.window&&(globalThis.window.GengageAssistantInjector||={},globalThis.window.GengageAssistantInjector[t]||={type:r}),!0):!1}function Zt(){return globalThis.window?.location?.origin||globalThis.location?.origin||"https://example.invalid"}function Su(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length>0)))}function vu({rootUrl:e,successMessage:t,alreadyCurrentPageMessage:r=t,missingUrlMessage:n="Ürün sayfasını açmak için ürün bağlantısı gerekiyor."}={}){const o=new URL(e).origin;return async function(a={}){const s=a.product||{},c=Qn(a.url||a.productUrl||s.url,e,o),u=a.sku||s.sku||null;return c?Au(c)?{ok:!0,sku:u,url:c,method:"already-current-page",alreadyCurrentPage:!0,message:r||t}:(Xn(c),{ok:!0,sku:u,url:c,method:"browser-navigation",message:t}):{ok:!1,sku:u,reason:"missing-url",message:n}}}function Qn(e,t,r=new URL(t).origin){if(!e)return"";try{const n=new URL(e,t);return n.protocol!=="https:"||n.origin!==r?"":(n.hash="",n.href)}catch{return""}}function Xn(e){if(typeof document>"u"){window.location.href=e;return}const t=document.createElement("a");t.href=e,t.target="_self",t.rel="noreferrer",t.style.display="none",document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>{window.location.href!==e&&window.location.assign(e)},0)}function Au(e){try{const t=new URL(globalThis.window?.location?.href||"",e),r=new URL(e,t.href);return t.hash="",r.hash="",t.href===r.href}catch{return!1}}function Tu(e,{screenSummary:t}={}){return{panel:{...e?.panel||{},screen_type:"homepage",screen_sku_list:[],screen_summary:t||null,last_search_products:[],last_search:null,chat_mentioned_skus:[],reviews_summary_skus:[],ai_plist_summary:null,search_suggestions_skus:[],list_source:null,active_product_panel:!1,assistant_mode:"shopping",redirected_agent_state:null,ui_hints:null}}}function eo({patterns:e,messageFilter:t,messageNormalizer:r=o=>o,messageLimit:n=10}={}){const o={patterns:[...Bt,...Array.isArray(e)?e:[]]};function i(c){return Nt(c,o)}function a(c){return gn(c,o)}function s(c=[]){const u=(Array.isArray(c)?c:[]).filter(l=>typeof t=="function"?t(l):l&&typeof l=="object").filter(Boolean);return(Number.isFinite(n)&&n>0?u.slice(-n):u).map(l=>({role:l.role,content:i(r(l.content)).slice(0,1e3)}))}return{redactPii:i,anonymousRequestText:a,anonymizeMessages:s}}function xu(e){return String(e||"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(/ /giu," ").replace(/&/giu,"&").replace(/<|>/giu," ").replace(/\s+/gu," ").trim()}function to({accountId:e,supplied:t=[],pageProduct:r=null,listingProducts:n=[],skus:o=[],limit:i=4,storedProducts:a=[],getStoredPanelProducts:s}={}){const c=no(o),u=Array.isArray(n)?n:[],l=typeof s=="function"?s({accountId:e,visibleProducts:u}):a;return ro([...Je(t),...Je(l),r,...u],{skus:c,limit:i})}function Eu({accountId:e,rootUrl:t,getProduct:r,getProducts:n,getStoredPanelProducts:o,limit:i=4}={}){return async function(s={}){return{accountId:e,products:to({accountId:e,supplied:Array.isArray(s.products)?s.products:[],pageProduct:r?.(),listingProducts:n?.(),getStoredPanelProducts:o,skus:s.skus||s.sku_list||[],limit:i}),rootUrl:t}}}function ro(e,{skus:t=[],limit:r=4}={}){const n=new Set(no(t)),o=new Set,i=[];for(const a of Je(e)){if(!a)continue;const s=We(a?.sku);if(n.size&&!n.has(s))continue;const c=s||We(a?.url)||We(a?.name||a?.title);if(!(c&&o.has(c))&&(c&&o.add(c),i.push(a),i.length>=r))break}return i}function no(e){return Je(e).map(We).filter(Boolean)}function We(e){return String(e||"").trim()}function Je(e){return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}var B={features:18,reviews:4,qna:4,sellers:4,variants:12,documents:6,textBlocks:6,relatedProducts:8,textChars:220},Yt={description:/\b(?:description|details|product information|urun bilgisi|urun aciklamasi|açıklama|aciklama)\b/iu,seller:/\b(?:seller|merchant|store|satici|satıcı|magaza|mağaza)\b/iu,review:/\b(?:review|reviews|rating|ratings|yorum|degerlendirme|değerlendirme|puan)\b/iu,qna:/\b(?:questions?|answers?|qna|q&a|soru|cevap)\b/iu,payment:/\b(?:installment|instalment|payment|pay in|taksit|odeme|ödeme|vade)\b/iu,delivery:/\b(?:delivery|shipping|cargo|stock|availability|teslimat|kargo|stok|gonderim|gönderim)\b/iu,promotion:/\b(?:campaign|promotion|discount|coupon|deal|kampanya|indirim|kupon|firsat|fırsat)\b/iu,variant:/\b(?:variant|size|colour|color|beden|olcu|ölçü|renk|numara)\b/iu},Cu=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b|\b(?:token|session|csrf|secret)\s*[:=]\s*[\w.-]+/giu,Pu=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,Ru=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}|[A-Za-z0-9_-]{24,}/iu;function oo({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return(i={})=>io({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i})}function io({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=a=>a,input:i={}}){const a=nl(i),s=o(i.product||nr(r)),c=(nr(n)||[]).map(o).filter(Boolean),u=j(i.sku||s?.sku||i.product?.sku),l=u?c.find(Z=>j(Z?.sku)===u)||s:s||c[0]||null,f=Ou(u||l?.sku),m=mo({...f.product,...l}),p=rr(Ye(l?.features),Ye(l?.specs),Vu(l?.facet_hits),Ye(f.product?.features),Mu(),Nu(),$u()).slice(0,a.features),g=co(Qe(l?.reviews),f.reviews,Fu()).slice(0,a.reviews),h=uo(Xt(l?.qna),qu()).slice(0,a.qna),y=lo(er(l?.sellers),Uu()).slice(0,a.sellers),b=te([...l?.payment||[],...Ze("payment",a)]),w=te([...l?.delivery||[],...Ze("delivery",a)]),v=te([...l?.promotions||[],...Ze("promotion",a)]),_=fo(tr(l?.variants),Du()).slice(0,a.variants),C=zu(a.documents),A=go(l?.description,f.product?.description,Gu("description"),Ze("description",{...a,textBlocks:2})[0]),T=c.filter(Z=>!u||j(Z?.sku)!==u).map(mo).filter(Boolean).slice(0,a.relatedProducts);return ye({accountId:e,pageType:nr(t)||"other",url:rl(),product:m,description:A,features:p,sellers:y,reviews:g,qna:h,rating:N(l?.rating??f.rating),review_count:N(l?.review_count??f.review_count),payment:b,delivery:w,promotions:v,variants:_,documents:C,related_products:T,capabilities:Qu({description:A,features:p,sellers:y,reviews:g,qna:h,payment:b,delivery:w,promotions:v,variants:_,documents:C,relatedProducts:T}),privacy:{browserLocal:!0,rawHtml:!1,formValues:!1,cookies:!1,storage:!1,redacted:!0}})}function ju(e,t){const r=Array.isArray(e)?e.filter(Boolean):[];if(!t||typeof t!="object"||!r.length)return r;const n=j(t.product?.sku);return r.map((o,i)=>{const a=j(o?.sku);return r.length===1||n&&a&&n===a||i===0?Lu(o,t):o})}function ao(e){return!e||typeof e!="object"?null:ye({product:e.product,description:x(e.description,500),features:Ku(e.features,14),sellers:Zu(e.sellers,4),reviews:Wu(e.reviews,4),qna:Ju(e.qna,4),rating:e.rating,review_count:e.review_count,payment:X(e.payment,5,160),delivery:X(e.delivery,5,160),promotions:X(e.promotions,5,160),variants:Yu(e.variants,10),documents:X(e.documents,5,220),capabilities:Array.isArray(e.capabilities)?e.capabilities.slice(0,12):void 0})}function Iu(e,t,r={}){const n=ao(e);if(!n)return t;const o=String(r.locale||"").toLowerCase().startsWith("en"),i=[],a=[n.rating?`${n.rating}/5`:"",n.review_count?`${n.review_count} ${o?"reviews":"yorum"}`:""].filter(Boolean).join(", ");return a&&i.push(o?`Visible rating: ${a}.`:`Görünür puan bilgisi: ${a}.`),n.reviews?.length&&i.push(`${o?"Visible review highlights":"Görünür yorumlardan öne çıkanlar"}: ${n.reviews.map(s=>[s.star?`${s.star}/5`:"",s.content].filter(Boolean).join(" ")).filter(Boolean).slice(0,3).join(" | ")}.`),i.length?(i.push(o?"This summary only uses product review and rating fields visible in the browser.":"Bu özet yalnızca tarayıcıda görünen ürün yorumu ve puan alanlarından hazırlandı."),i.join(" ")):t}function Lu(e,t){return ye({...e,description:go(e.description,t.description),features:rr(Ye(e.features),t.features).slice(0,24),specs:e.specs||(t.features?.length?Object.fromEntries(t.features.map(Xu)):void 0),sellers:lo(er(e.sellers),t.sellers),reviews:co(Qe(e.reviews),t.reviews),qna:uo(Xt(e.qna),t.qna),rating:e.rating??t.rating,review_count:e.review_count??t.review_count,payment:te([...e.payment||[],...t.payment||[]]),delivery:te([...e.delivery||[],...t.delivery||[]]),promotions:te([...e.promotions||[],...t.promotions||[]]),variants:fo(tr(e.variants),t.variants),documents:te([...e.documents||[],...t.documents||[]])})}function Ou(e){const t=[];for(const o of G('script[type="application/ld+json"]')){const i=Bu(o.textContent);for(const a of Qt(i))String(a?.["@type"]||"").toLowerCase()==="product"&&t.push(a)}const r=t.find(o=>j(o.sku||o.productID||o.mpn)===j(e))||t[0];if(!r)return{};const n=r.aggregateRating||{};return{product:ye({sku:j(r.sku||r.productID||r.mpn),name:S(r.name),brand:S(r.brand?.name||r.brand),description:S(r.description),images:X(r.image,8,280),url:je(r.url),rating:N(n.ratingValue),review_count:N(n.reviewCount||n.ratingCount)}),reviews:Qe(r.review),rating:N(n.ratingValue),review_count:N(n.reviewCount||n.ratingCount)}}function Qt(e){return Array.isArray(e)?e.flatMap(Qt):!e||typeof e!="object"?[]:[e,...Qt(e["@graph"])]}function Bu(e){try{return JSON.parse(String(e||""))}catch{return null}}function Mu(){const e=[];for(const t of G("table tr")){const r=[...t.querySelectorAll?.("th,td")||[]].map(n=>S(n.textContent));r.length>=2&&r[0]&&r[1]&&e.push({key:r[0],value:r.slice(1).join(" ")})}return e}function Nu(){const e=[];for(const t of G("dt")){const r=S(t.textContent),n=S(t.nextElementSibling?.matches?.("dd")?t.nextElementSibling.textContent:"");r&&n&&e.push({key:r,value:n})}return e}function $u(){return G('[class*="spec" i], [class*="feature" i], [class*="attribute" i], li').map(e=>so(S(e.textContent))).filter(Boolean).slice(0,B.features)}function Fu(){return G('[class*="review" i], [data-review], [itemprop="review"]').map(e=>{const t=S(e.textContent);return!t||t.length<8||Yt.qna.test(t)?null:{content:x(t,260),star:N(e.getAttribute?.("data-rating"))}}).filter(Boolean)}function qu(){const e=G('[class*="question" i], [class*="answer" i], [data-question], [data-answer]'),t=[];for(const r of e){const n=S(r.textContent);if(!n||!Yt.qna.test(n))continue;const o=S(r.getAttribute?.("data-question")||n),i=S(r.getAttribute?.("data-answer")||r.nextElementSibling?.textContent||"");t.push({question:x(o,220),answer:x(i,260)})}return t}function Uu(){return G('[class*="seller" i], [class*="merchant" i], [data-seller], [data-merchant]').map(e=>S(e.getAttribute?.("data-seller")||e.getAttribute?.("data-merchant")||e.textContent)).filter(Boolean).map(e=>({merchant:x(e,120)}))}function Du(){return G('[class*="variant" i] a,[class*="variant" i] button,[class*="size" i] button,[class*="color" i] button,[data-variant],[data-size],[data-color]').map(e=>ye({name:x(yo(e),120),value:x(e.getAttribute?.("data-value")||e.getAttribute?.("data-size")||e.getAttribute?.("data-color"),120),sku:j(e.getAttribute?.("data-sku")||e.getAttribute?.("data-product-id")),url:je(e.getAttribute?.("href")),in_stock:e.getAttribute?.("disabled")==null&&e.getAttribute?.("aria-disabled")!=="true"})).filter(e=>e.name||e.value||e.sku)}function zu(e){return G("a[href]").filter(t=>/\.pdf(?:$|[?#])/iu.test(t.getAttribute?.("href")||"")).map(t=>{const r=yo(t)||"PDF",n=je(t.getAttribute?.("href"));return n?`${r}: ${n}`:""}).filter(Boolean).slice(0,e)}function Ze(e,t){const r=Yt[e];return r?G("section,article,div,li,p,span,button,a").map(n=>S(n.textContent)).filter(n=>n&&r.test(n)&&n.length<=900).map(n=>x(n,t.textChars||B.textChars)).filter(po()).slice(0,t.textBlocks||B.textBlocks):[]}function Gu(e){return S(document.querySelector?.(`meta[name="${e}"]`)?.getAttribute?.("content")||document.querySelector?.(`meta[property="og:${e}"]`)?.getAttribute?.("content"))}function G(e){try{return[...document.querySelectorAll?.(e)||[]].filter(Hu)}catch{return[]}}function Hu(e){if(!e)return!1;if(!e.getBoundingClientRect)return!0;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const r=window.getComputedStyle?.(e);return!r||r.visibility!=="hidden"&&r.display!=="none"&&Number(r.opacity||1)>0}function Ye(e){return e?(Array.isArray(e)?e:Object.entries(e).map(([t,r])=>({key:t,value:r}))).map(t=>typeof t=="string"?so(t)||{key:"",value:S(t)}:{key:S(t.key||t.name||t.label),value:S(t.value||t.text||"")}).filter(t=>t.key||t.value):[]}function Vu(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([t,r])=>({key:S(t),value:S(r)}))}function so(e){const t=/^(.{2,80}?)\s*[::]\s*(.{1,220})$/u.exec(S(e));return t?{key:t[1],value:t[2]}:null}function Qe(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>typeof t=="string"?{content:x(t,260)}:{content:x(t.content||t.reviewBody||t.description||t.text,260),star:N(t.star||t.rating||t.reviewRating?.ratingValue)}).filter(t=>t.content||t.star)}function Xt(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>({question:x(t.question||t.name||"",220),answer:x(t.answer||t.acceptedAnswer?.text||t.text||"",260)})).filter(t=>t.question||t.answer)}function er(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>typeof t=="string"?{merchant:x(t,120)}:{merchant:x(t.merchant||t.name||t.seller||"",120),merchant_id:j(t.merchant_id||t.id||""),merchant_rating:N(t.merchant_rating||t.rating),price_offer:N(t.price_offer||t.price)}).filter(t=>t.merchant||t.merchant_id)}function tr(e){return(Array.isArray(e)?e:e?[e]:[]).map(t=>({name:x(t.name||t.label||t.title||"",120),value:x(t.value||t.size||t.color||"",120),sku:j(t.sku||t.code||""),url:je(t.url),in_stock:t.in_stock})).filter(t=>t.name||t.value||t.sku||t.url)}function rr(...e){const t=new Set,r=[];for(const n of e.flat().filter(Boolean)){const o={key:x(n.key||n.name||"",90),value:x(n.value||n.text||"",180)},i=`${o.key}:${o.value}`.toLocaleLowerCase("tr-TR");!o.key&&!o.value||t.has(i)||(t.add(i),r.push(o))}return r}function co(...e){return Xe(e.flat().filter(Boolean),t=>`${t.star||""}:${t.content||""}`)}function uo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.question||""}:${t.answer||""}`)}function lo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.merchant||""}:${t.merchant_id||""}`)}function fo(...e){return Xe(e.flat().filter(Boolean),t=>`${t.sku||""}:${t.name||""}:${t.value||""}`)}function Xe(e,t){const r=new Set;return e.filter(n=>{const o=t(n).toLocaleLowerCase("tr-TR");return!o.trim()||r.has(o)?!1:(r.add(o),!0)})}function te(e){return X(e,20,B.textChars)}function X(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>x(n,r)).filter(Boolean).filter(po()).slice(0,t)}function po(){const e=new Set;return t=>{const r=S(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function Ku(e,t){return rr(e).slice(0,t)}function Wu(e,t){return Qe(e).slice(0,t)}function Ju(e,t){return Xt(e).slice(0,t)}function Zu(e,t){return er(e).slice(0,t)}function Yu(e,t){return tr(e).slice(0,t)}function mo(e){return!e||typeof e!="object"?null:ye({sku:j(e.sku||e.id||""),group_id:j(e.group_id||e.groupId||""),name:S(e.name||e.title||""),brand:S(e.brand||""),url:je(e.url),images:X(e.images||e.image,8,280),price:N(e.price),price_discounted:N(e.price_discounted||e.discountedPrice),price_text:S(e.price_text||e.priceText||""),price_currency:S(e.price_currency||e.currency||""),category_ids:el(e.category_ids||e.categoryIds,8,90),category_names:X(e.category_names||e.categoryNames||e.category,8,140),in_stock:e.in_stock})}function Qu(e){return[e.description?"description":"",e.features?.length?"features":"",e.sellers?.length?"seller":"",e.reviews?.length||e.rating||e.review_count?"reviews_ratings":"",e.qna?.length?"qna":"",e.payment?.length?"installment_payment":"",e.delivery?.length?"shipping_delivery_stock":"",e.promotions?.length?"campaigns_promotions":"",e.variants?.length?"variants":"",e.documents?.length?"documents":"",e.relatedProducts?.length?"related_products":""].filter(Boolean)}function Xu(e){return[S(e.key||e.name),S(e.value||e.text)]}function go(...e){return e.map(t=>x(t,700)).find(Boolean)||""}function x(e,t){return S(e).slice(0,t)}function yo(e){return S(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.textContent)}function S(e){return String(e??"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(Cu,"[redacted]").replace(/\s+/gu," ").trim()}function j(e){const t=String(e??"").replace(/<script\b[\s\S]*?<\/script>/giu," ").replace(/<style\b[\s\S]*?<\/style>/giu," ").replace(/<[^>]+>/gu," ").replace(/\s+/gu," ").trim();return!t||/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu.test(t)||/\b(?:token|session|csrf|secret|password|passwd|jwt|bearer)\s*[:=]\s*[\w.-]+/iu.test(t)?"":t.slice(0,120)}function el(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>j(n).slice(0,r)).filter(Boolean).filter(tl()).slice(0,t)}function tl(){const e=new Set;return t=>{const r=j(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function N(e){const t=Number(String(e??"").replace(",","."));return Number.isFinite(t)&&t>0?t:void 0}function je(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",ho(t),t.href):""}catch{return""}}function rl(){try{const e=new URL(window.location.href);return e.hash="",ho(e),`${e.origin}${e.pathname}${e.search}`}catch{return""}}function ho(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(Pu.test(t)||Ru.test(n))&&e.searchParams.set(t,"redacted")}return e}function nl(e={}){return{features:K(e.maxFeatures,B.features,40),reviews:K(e.maxReviews,B.reviews,12),qna:K(e.maxQna,B.qna,12),sellers:K(e.maxSellers,B.sellers,12),variants:K(e.maxVariants,B.variants,30),documents:K(e.maxDocuments,B.documents,12),textBlocks:K(e.maxTextBlocks,B.textBlocks,16),relatedProducts:K(e.maxRelatedProducts,B.relatedProducts,20),textChars:K(e.textChars,B.textChars,420)}}function K(e,t,r){const n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.min(Math.floor(n),r)}function nr(e){try{return typeof e=="function"?e():null}catch{return null}}function ye(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var{redactPii:ol,anonymousRequestText:il,anonymizeMessages:al}=eo({patterns:[{pattern:/\b\d{5}\b/gu,replacement:"[postcode]"},{pattern:/\b(?:adresim|adres|mahalle|sokak|cadde)\b[^,.!?\n]{8,160}/giu,replacement:"[address]"}]});function bo(e){return(e?.route?.flow_params&&typeof e.route.flow_params=="object"?e.route.flow_params:null)||(e?.route?.flowParams&&typeof e.route.flowParams=="object"?e.route.flowParams:null)||{}}function sl(e){return Array.isArray(e)?e.find(t=>String(t||"").trim()):void 0}function cl(e){const t=bo(e);return[...t.sku?[t.sku]:[],...Array.isArray(t.sku_list)?t.sku_list:[],...Array.isArray(t.skus)?t.skus:[],...Array.isArray(t.target_skus)?t.target_skus:[]].map(r=>String(r||"").trim()).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n)}var he={headings:8,products:8,controls:12,textMatches:8,snippetChars:180},et=/\b(?:checkout|payment|pay now|place order|delete|remove|confirm|submit|ödeme|odeme|siparişi tamamla|siparisi tamamla|satın al|satin al|sil|kaldır|kaldir|onayla|gönder|gonder)\b/iu,ul=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,ll=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}|[A-Za-z0-9_-]{24,}/iu,dl={campaign:/\b(?:campaign|promotion|discount|deal|coupon|kampanya|indirim|firsat|fırsat|kupon)\b/iu,blog:/\b(?:blog|journal|guide|article|editorial|inspiration|rehber|makale|ilham|icerik|içerik)\b/iu,category:/\b(?:category|collection|department|kategori|koleksiyon|reyon)\b/iu};function fl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return{scanSite:(i={})=>pl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}),siteGrep:(i={})=>ml(i),discoverSiteContent:(i={})=>wo(i,e),runSiteCommand:(i={})=>gl(i),describeVisualContext:(i={})=>yl(i,e),inspectProductSurface:oo({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o}),getSiteCapabilities:()=>wl(e)}}function pl({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}){const a=E(i.query||i.text||""),s=cr(i),c=lr(r),u=lr(n)||[];return ur({accountId:e,url:Ll(),title:ee(document.title||""),pageType:lr(t)||"other",viewport:Ol(),product:ko(o(c)),products:u.map(o).map(ko).filter(Boolean).slice(0,s.products),content:i.includeContent===!1?void 0:wo(i,e).items,headings:kl(s.headings),controls:i.includeControls===!1?void 0:_l(s.controls),textMatches:a?or(a,s):[],privacy:{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}})}function wo(e={},t=""){const r=cr(e),n=new Set(Al(e.kinds||e.kind)),o=Sl(r.controls).filter(i=>!n.size||n.has(i.kind)).slice(0,r.controls);return{accountId:t,items:o,count:o.length,privacy:W()}}function ml(e={}){const t=E(e.query||e.text||e.pattern||"");if(!t)return{ok:!1,matches:[],message:"Provide a query to scan visible page text.",privacy:W()};const r=or(t,cr(e));return{ok:r.length>0,query:t,matches:r,count:r.length,privacy:W()}}function gl(e={}){const t=E(e.command||e.action||"").toLowerCase();return t==="scroll_to_text"||t==="scrolltotext"?hl(e):t==="click_visible_text"||t==="clickvisibletext"?bl(e):t==="scroll_top"||t==="scrolltotop"?(window.scrollTo({top:0,behavior:"smooth"}),{ok:!0,command:"scroll_top",message:"Scrolled to the top of the page.",privacy:W()}):{ok:!1,command:t,message:"Supported commands are scroll_to_text, click_visible_text, and scroll_top.",privacy:W()}}function yl(e={},t){const r=e.visual_consent===!0||e.visualConsent===!0||e.consent===!0,n=r?xl(e.visual_observations||e.visualObservations):[],o=Tl(Number(e.maxImages||8));return{accountId:t,ok:r||o.length>0,consentedObservations:n,visibleImages:o,message:El({consented:r,observations:n,visibleImages:o}),privacy:{rawHtml:!1,formValues:!1,screenshotPixels:!1,redacted:!0,browserLocal:!0,requiresConsentForExternalVisualFacts:!0}}}function hl(e){const t=E(e.query||e.text||e.label||""),r=t?Rl(t):null;return r?(r.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"}),{ok:!0,command:"scroll_to_text",label:be(r),message:"Scrolled to the matching page area.",privacy:W()}):{ok:!1,command:"scroll_to_text",message:"No visible matching text found."}}function bl(e){const t=E(e.label||e.query||e.text||"");if(!t)return{ok:!1,command:"click_visible_text",message:"Provide a visible label to click."};if(et.test(t))return{ok:!1,blocked:!0,command:"click_visible_text",message:"This looks like a checkout, payment, destructive, or final confirmation action, so it was not clicked.",privacy:W()};const r=Pl(t);if(!r)return{ok:!1,command:"click_visible_text",message:"No safe visible clickable control found."};const n=be(r);return et.test(n)?{ok:!1,blocked:!0,command:"click_visible_text",label:n,message:"The matched control is blocked by the safe-click policy.",privacy:W()}:(r.click(),{ok:!0,command:"click_visible_text",label:n,message:"Clicked the safe visible control.",privacy:W()})}function wl(e){return{accountId:e,tools:["scanSite","siteGrep","discoverSiteContent","runSiteCommand","describeVisualContext","inspectProductSurface"],commands:{scanSite:"Returns a compact browser-local summary of page type, title, headings, products, controls, and matching visible text.",siteGrep:"Finds capped visible text snippets by plain query, like grep for the rendered page.",discoverSiteContent:"Returns visible campaign, blog/editorial, and category/content links as compact browser-local metadata.",runSiteCommand:"Runs guarded browser-local page commands: scroll_to_text, click_visible_text, scroll_top. Checkout, payment, destructive, and final-confirm controls are blocked.",describeVisualContext:"Summarizes visible image metadata and explicit shopper-consented redacted visual observations without capturing screenshots or pixels.",inspectProductSurface:"Returns compact GSS-style product detail evidence visible in the browser: description, specs, seller, QNA, reviews/ratings, installment/payment, shipping/stock, campaigns, variants, documents, and related visible products."},privacy:["Runs in the shopper browser.","Does not return raw HTML, cookies, storage, hidden text, or form values.","Redacts emails, phone numbers, tokens, and address-like postal snippets before returning text.","Returns compact capped snippets only.","Does not send screenshots or pixels implicitly; external visual observations must be explicitly consented."]}}function kl(e){return[...document.querySelectorAll('h1,h2,h3,[role="heading"]')].filter(re).map(t=>ee(E(t.textContent))).filter(Boolean).slice(0,e)}function _l(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(re).map(t=>({label:be(t),tag:t.tagName?.toLowerCase(),role:t.getAttribute?.("role")||null,href:_o(t),safeClick:!et.test(be(t))})).filter(t=>t.label).filter(tt(t=>`${t.tag}:${t.label}:${t.href||""}`)).slice(0,e)}function Sl(e){return[...document.querySelectorAll('a[href],button,[role="button"],summary')].filter(re).map(t=>{const r=be(t),n=_o(t),o=vl([r,n,ir(t)].join(" "));return o?ur({kind:o,label:r,href:n,heading:ir(t),safeClick:!et.test(r)}):null}).filter(Boolean).filter(tt(t=>`${t.kind}:${t.label}:${t.href||""}`)).slice(0,Math.max(1,Math.min(e,30)))}function vl(e){for(const[t,r]of Object.entries(dl))if(r.test(e))return t;return""}function Al(e){return(Array.isArray(e)?e:String(e||"").split(/[,|]/u)).map(t=>E(t).toLowerCase()).filter(Boolean)}function or(e,t){const r=e.toLocaleLowerCase("tr-TR");return Cl(document.body).map(n=>({node:n,text:E(n.nodeValue||"")})).filter(({text:n})=>n&&n.toLocaleLowerCase("tr-TR").includes(r)).map(({node:n,text:o})=>({snippet:jl(o,e,t.snippetChars),tag:n.parentElement?.tagName?.toLowerCase()||"",heading:ir(n.parentElement)})).filter(n=>n.snippet).filter(tt(n=>n.snippet)).slice(0,t.textMatches)}function Tl(e){return[...document.querySelectorAll("img")].filter(re).map(t=>({alt:ee(E(t.getAttribute("alt")||t.getAttribute("aria-label")||"")),title:ee(E(t.getAttribute("title")||"")),src:ar(t.currentSrc||t.getAttribute("src")),width:Math.round(t.getBoundingClientRect().width),height:Math.round(t.getBoundingClientRect().height)})).filter(t=>t.alt||t.title||t.src).filter(tt(t=>`${t.alt}:${t.title}:${t.src}`)).slice(0,Math.max(1,Math.min(Number.isFinite(e)&&e>0?Math.floor(e):8,20)))}function xl(e){return(Array.isArray(e)?e:String(e||"").split(/\n|;|\|/u)).map(t=>ee(t).slice(0,180)).filter(Boolean).slice(0,8)}function El({consented:e,observations:t,visibleImages:r}){const n=[];if(t.length&&n.push(`Consented visual observations: ${t.slice(0,3).join(" | ")}.`),r.length){const o=r.map(i=>i.alt||i.title).filter(Boolean).slice(0,3);n.push(o.length?`Visible image labels: ${o.join(", ")}.`:`${r.length} visible images found.`)}return!n.length&&!e&&n.push("I can use visible image labels, but external visual observations need explicit shopper consent."),n.push("No screenshots or pixels were captured or sent."),n.join(" ")}function Cl(e){if(!e)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(n){const o=n.parentElement;return!o||!re(o)||/^(script|style|noscript|template|svg)$/iu.test(o.tagName||"")||Il(o)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),r=[];for(;r.length<500;){const n=t.nextNode();if(!n)break;r.push(n)}return r}function Pl(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(re).find(t=>be(t).toLocaleLowerCase("tr-TR").includes(e.toLocaleLowerCase("tr-TR")))}function Rl(e){const t=or(e,{...he,textMatches:1})[0];return t?[...document.querySelectorAll("body *")].filter(re).find(r=>E(r.textContent).includes(t.snippet.slice(0,24))):null}function be(e){return e?ee(E(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.value||e.textContent||"")).slice(0,90):""}function ir(e){let t=e;for(let r=0;t&&r<5;r+=1){const n=E((t.matches?.('h1,h2,h3,[role="heading"]')?t:t.querySelector?.('h1,h2,h3,[role="heading"]'))?.textContent||"");if(n)return ee(n).slice(0,90);t=t.parentElement}return""}function ko(e){return e?ur({sku:E(e.sku||e.id||""),name:E(e.name||e.title||""),url:ar(e.url),price_text:E(e.price_text||e.priceText||""),price:e.price,currency:e.price_currency||e.currency,in_stock:e.in_stock,category:E(e.category||"")}):null}function jl(e,t,r){const n=ee(e),o=n.toLocaleLowerCase("tr-TR").indexOf(t.toLocaleLowerCase("tr-TR")),i=Math.max(0,o-Math.floor(r/3));return n.slice(i,i+r).trim()}function re(e){if(!e||!e.getBoundingClientRect)return!1;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const r=window.getComputedStyle(e);return r.visibility!=="hidden"&&r.display!=="none"&&Number(r.opacity||1)>0}function Il(e){return!!e.closest?.('input,textarea,select,[contenteditable="true"]')}function _o(e){return e.tagName?.toLowerCase()!=="a"?null:ar(e.getAttribute("href"))}function ar(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",sr(t),t.href):""}catch{return""}}function Ll(){const e=new URL(window.location.href);return sr(e),`${e.origin}${e.pathname}${e.search}`}function Ol(){return{width:window.innerWidth,height:window.innerHeight,scrollY:Math.round(window.scrollY||0),documentHeight:Math.round(document.documentElement?.scrollHeight||0)}}function ee(e){return E(e).replace(/https?:\/\/[^\s?#]+(?:\?[^#\s]*)?/giu,Bl).replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"<email>").replace(/\b(?:\+?\d[\d\s().-]{8,}\d)\b/gu,"<phone>").replace(/\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b/giu,"<postcode>").replace(/\btoken\s*=\s*[\w.-]+/giu,"token=<redacted>").replace(/\b(?:api[_-]?key|session|csrf|secret)\s*[:=]\s*[\w.-]+/giu,"<secret>")}function Bl(e){try{const t=new URL(e);return t.hash="",sr(t),t.href}catch{return String(e||"").replace(/\?[^#\s]*/u,"?redacted")}}function sr(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(ul.test(t)||ll.test(n))&&e.searchParams.set(t,"redacted")}return e}function E(e){return String(e||"").replace(/\s+/gu," ").trim()}function cr(e){return{headings:Ie(e.maxHeadings,he.headings,20),products:Ie(e.maxProducts,he.products,20),controls:Ie(e.maxControls,he.controls,30),textMatches:Ie(e.maxMatches||e.limit,he.textMatches,20),snippetChars:Ie(e.snippetChars,he.snippetChars,320)}}function Ie(e,t,r){const n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.min(Math.floor(n),r)}function W(){return{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}}function ur(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function lr(e){try{return typeof e=="function"?e():null}catch{return null}}function tt(e){const t=new Set;return r=>{const n=e(r);return!n||t.has(n)?!1:(t.add(n),!0)}}var Ml=3e4;function So(e,t,r={}){const n=r.ttlMs??Ml,o=r.clock??Date.now,i=new Map,a=new Map;return async function(c){const u=String(t(c)??"");if(!u)return e(c);const l=o();Nl(a,l,n);const f=i.get(u);if(f)return f;const m=a.get(u);if(m&&l-m.at<n)return $l(m.observation,u);const p=(async()=>{try{const g=await e(c);return a.set(u,{at:o(),observation:g}),g}finally{i.delete(u)}})();return i.set(u,p),p}}function Nl(e,t,r){for(const[n,o]of e)t-o.at>=r&&e.delete(n)}function $l(e,t){return!e||typeof e!="object"?e:{...e,deduped:!0,dedupe_key:t}}var Fl=3e4,vo=new Set;function ql(e){const t=()=>So(async o=>e(o||{}),o=>{const i=Dl(o),a=Number(o?.quantity||o?.qty||1)||1,s=zl(o);return i?`${i}|${a}|${s}`:""},{ttlMs:Fl});let r=t();const n=async function(i={}){return r(i)};return n.__resetForTesting=()=>{r=t()},vo.add(n),n}function Ul(){for(const e of vo)typeof e.__resetForTesting=="function"&&e.__resetForTesting()}function Dl(e){const t=e?.cartCode??e?.sku??e?.productCode??e?.product?.sku??e?.product?.cart_code;return t==null?"":String(t).trim()}function zl(e){const t=e?.variantId??e?.variantCode??e?.product?.variantId??"";return t==null?"":String(t).trim()}var Gl=32,Ao=new Set;function Hl(e,t){const{accountId:r,allowedHostnames:n,productFromPage:o,mergeProduct:i=Wl,needsHydration:a=Kl,fetchOptions:s={credentials:"include"},maxConcurrency:c=4}=t;if(!r)throw new Error("wrapResolveProductsWithPdpHydration: accountId is required");if(typeof o!="function")throw new Error("wrapResolveProductsWithPdpHydration: productFromPage(doc, url) is required");if(!Array.isArray(n)||!n.length)throw new Error("wrapResolveProductsWithPdpHydration: allowedHostnames must be a non-empty array");const u=new Map,l=Yl({productFromPage:o,fetchOptions:s,isAllowed:Jl(n)}),f=async function(p={}){const g=await e(p||{});if(p?.hydrateFromPdp===!1)return g;const h=Array.isArray(g?.products)?g.products:[];if(!h.length)return g;const y=await Ql(h,l,u,c,i,a);return{...g,products:y}};return f.__resetCacheForTesting=()=>u.clear(),f.__cacheSizeForTesting=()=>u.size,Ao.add(f),f}function Vl(){for(const e of Ao)typeof e.__resetCacheForTesting=="function"&&e.__resetCacheForTesting()}function Kl(e){if(!e||!e.url)return!1;const t=e,r=t.features,n=t.specs,o=t.category_names,i=Array.isArray(r)&&r.length>0,a=!!n&&typeof n=="object"&&Object.keys(n).length>0,s=Array.isArray(o)&&o.length>0;return!i&&!a&&!s}function Wl(e,t){return e?t?{...e,...t}:e:t}function Jl(e){const t=e.map(r=>String(r||"").toLowerCase().trim()).filter(Boolean);return r=>{const n=String(r||"").toLowerCase();if(!n)return!1;for(const o of t)if(n===o||n.endsWith(`.${o}`))return!0;return!1}}function Zl(e,t){if(!e)return null;try{const r=new URL(String(e));return r.protocol!=="https:"||!t(r.hostname)?null:r.href}catch{return null}}function Yl(e){const{productFromPage:t,fetchOptions:r,isAllowed:n}=e;return async function(i){const a=Zl(i?.url,n);if(!a||typeof fetch!="function")return null;let s;try{const u=await fetch(a,r);if(!u?.ok)return null;s=await u.text()}catch{return null}if(!s||typeof DOMParser>"u")return null;let c;try{c=new DOMParser().parseFromString(s,"text/html")}catch{return null}if(!c)return null;try{return t(c,a)||null}catch{return null}}}async function Ql(e,t,r,n,o,i){const a=new Array(e.length);let s=0;const c=Math.max(1,Math.min(n,e.length)),u=new Array(c).fill(null).map(()=>l());return await Promise.all(u),a;async function l(){for(;;){const m=s++;if(m>=e.length)return;a[m]=await f(e[m])}}async function f(m){if(!m||!i(m))return m;const p=m?.sku==null?"":String(m.sku).trim();if(p&&r.has(p)){const h=r.get(p);return h?o(m,h):m}const g=await t(m);return p&&(r.set(p,g||null),Xl(r)),g?o(m,g):m}}function Xl(e){for(;e.size>Gl;){const t=e.keys().next().value;if(t===void 0)break;e.delete(t)}}var ed=20;function To(e,t={}){const{context:r,accountConfig:n}=t,o=Array.isArray(e)?e.filter(Boolean):[];if(!o.length)return[];const i=String(r?.meta?.locale||n?.locale||n?.defaultLocale||"tr-TR").toLowerCase().startsWith("en"),a=i?"Compare the first two":"İlk ikisini karşılaştır",s=i?"Open product page":"Ürün sayfasını aç",c=i?"Tell me the comfort details":"Konfor özelliklerini anlat",u=i?"Show similar":"Benzerlerini göster",l=[];o.length>=2&&l.push({label:a,action:{type:"getComparisonTable",payload:{skus:o.slice(0,2).map(m=>m.sku).filter(Boolean),limit:2}}});const f=o[0]?.sku;return f&&!i&&(l.push({label:s,action:{type:"openProductPage",payload:{sku:f,url:o[0]?.url}}}),l.push({label:c,action:{type:"productQuestion",payload:{sku_list:[f]}}})),l.push({label:u,action:{type:"findSimilar",payload:{sku:f}}}),l}function dr(e,t=ed){const r=[];if(!Array.isArray(e))return[];for(const a of e){const s=Array.isArray(a?.observation?.products)?a.observation.products:[];s.length&&r.push([...s])}if(r.length<=1)return(r[0]||[]).slice(0,t);const n=[],o=new Set;let i=0;for(;n.length<t;){let a=!1;for(const s of r){const c=s[i];if(!c)continue;const u=String(c.sku||c.url||c.name||"");if(u&&o.has(u)){a=!0;continue}if(u&&o.add(u),n.push(c),a=!0,n.length>=t)break}if(!a)break;i+=1}return n}function td(e){if(!e?.spec?.elements)return e;const t=e.spec.root;if(!t)return e;const r=e.spec.elements[t];return!r||r.type!=="ProductGrid"?(typeof console<"u"&&console.warn&&console.warn("[agentic] withSimilarsAppend: products envelope root is not ProductGrid",r?.type),e):{...e,spec:{...e.spec,elements:{...e.spec.elements,[t]:{...r,props:{...r.props||{},similarsAppend:!0}}}}}}function rd(e,t={}){const r=t.threshold??0;return!r||r<=0||!Array.isArray(e)?!1:e.length>r}function nd(e,t={}){const r=Math.max(0,t.retainTail??4);if(!Array.isArray(e)||e.length===0||e.length<=r)return null;const n=e.slice(e.length-r),o=e.slice(0,e.length-r);return o.length?{messagesToSummarize:o,retainedTail:n}:null}function od(e,t,r={}){const n=String(t||"").trim();if(!n)return e;const o=Math.max(0,r.retainTail??4),i=Array.isArray(e.messages)?e.messages:[],a=i.slice(Math.max(0,i.length-o));return{...e,messages:[{role:"assistant",content:n,name:"compaction"},...a],panel:{...e.panel||{},compaction_summary:{summary:n,replacedCount:i.length-a.length,retainedTailCount:a.length,compactedAt:new Date().toISOString()}}}}function J(e,t){const r=e?.[t];return Array.isArray(r)?r:[]}function Le(e,t,r=!1){return[...e].reverse().find(n=>n?.name===t&&(!r||n?.observation?.status==="ok"))}function id(e){return{kind:"patch",patch:(t,r,n)=>{const o=Le(J(n.bag,e),"search_catalog"),i=Array.isArray(o?.observation?.products)?o.observation.products:null;return i?.length?{panel:{...t.panel,screen_type:"product_list",list_source:"agent",last_search_products:i,last_search:{query:o.observation.query,source:o.observation.source,count:o.observation.count},screen_sku_list:i.map(a=>a?.sku).filter(Boolean).slice(0,24)}}:null}}}function ad(e){const t=e.obsKey||"roundObservations",r=e.gridLimit??20,n=e.similarsFollowupSteps?e.similarsFollowupSteps():[];return[id(t),{kind:"branch",on:({bag:o})=>J(o,t).some(i=>Array.isArray(i?.observation?.products)&&i.observation.products.length)?"has_products":"no_products",cases:{has_products:[{kind:"emit",build:({bag:o})=>{const i=dr(J(o,t),r);return e.uiSpec(e.productsUiSpec(i))}},{kind:"emit",build:({bag:o,context:i,accountConfig:a})=>{const s=dr(J(o,t),r);return e.uiSpec(e.actionButtonsUiSpec(To(s,{context:i,accountConfig:a})))}}],no_products:[]}},{kind:"branch",on:({bag:o})=>Le(J(o,t),"compare_products",!0)?"has_compare":"no_compare",cases:{has_compare:[{kind:"emit",build:({context:o,bag:i})=>{const a=Le(J(i,t),"compare_products"),s=a?.observation||{},c=a?.arguments||{},u=Array.isArray(c.target_skus)?c.target_skus.map(String):[],l=Array.isArray(o?.panel?.last_search_products)?o.panel.last_search_products:[],f=u.length?u.map(m=>l.find(p=>String(p?.sku)===m)).filter(Boolean):l.slice(0,4);return e.uiSpec(e.comparisonUiSpec({products:f,comparison_table:s.comparison_table,key_differences:s.key_differences,recommended_choice_sku:s.recommendation?.sku,recommended_choice:s.recommendation?.reason}))}}],no_compare:[]}},{kind:"branch",on:({bag:o})=>Le(J(o,t),"get_product_details",!0)?"has_details":"no_details",cases:{has_details:[{kind:"emit",build:({context:o,bag:i})=>{const a=Le(J(i,t),"get_product_details"),s=a?.observation?.surface||{},c=a?.arguments||{},u=Array.isArray(o?.panel?.last_search_products)?o.panel.last_search_products:[],l=c.sku?u.find(m=>String(m?.sku)===String(c.sku)):null,f=s.product||l||s||{};return e.uiSpec(e.productDetailsUiSpec(f))}},...n],no_details:[]}},...xo({...e,obsKey:t})]}function xo(e){const t=e.obsKey||"roundObservations",r=e.pdpFollowupProduct;return r?[{kind:"branch",on:({bag:n,context:o})=>n.pdpFollowupRendered||J(n,t).some(i=>{const a=i?.name;return a==="search_catalog"||a==="compare_products"||a==="get_product_details"||Array.isArray(i?.observation?.products)&&i.observation.products.length})?"skip":r(n,o)?"render":"skip",cases:{render:[{kind:"emit",build:({bag:n,context:o})=>e.uiSpec(e.productDetailsUiSpec(r(n,o)))},{kind:"patch",patch:(n,o,i)=>(i.bag.pdpFollowupRendered=!0,null)},...e.similarsFollowupSteps?e.similarsFollowupSteps():[]],skip:[]}}]:[]}d.AgentError=M,d.ContextStore=Sr,d.FALLBACK_STATUS=iu,d.__resetAllCartCoalescersForTesting=Ul,d.__resetAllPdpHydratorsForTesting=Vl,d.action=$i,d.actionButtonsUiSpec=ys,d.alignProductsToTable=un,d.anonymousRequestText=gn,d.applyCompactionResult=od,d.beErrorToAgentError=yt,d.buildActivityVisualization=Tn,d.buildCompactionRequest=nd,d.buildPdpFollowupSteps=xo,d.buildPhotoSimilarityProfile=As,d.buildProductSimilarityProfile=le,d.buildSimilarityQueries=Ts,d.buildToolUiSteps=ad,d.canUseModuleWorker=It,d.caughtToStreamError=Er,d.coalesceAddToCart=ql,d.compactAccountConfig=yn,d.compactContextProducts=is,d.compactObject=Su,d.compactProductSurfaceForLlm=ao,d.comparisonResultForUi=ls,d.comparisonUiSpec=ms,d.createActivityCollector=wn,d.createBrowserMemory=jt,d.createDiagnosticsTool=Qs,d.createEndpointCachePolicies=bs,d.createEndpointHandlers=ws,d.createFlow=hs,d.createGssToolAliases=mu,d.createIframeScraper=ku,d.createInjectorAdapter=Gr,d.createLocalRefStore=pr,d.createMainThreadInjectorAdapter=Vr,d.createModuleWorker=cn,d.createOpenProductPageTool=vu,d.createPrivacyHelpers=eo,d.createProductSurfaceInspector=oo,d.createReadPageStep=cu,d.createReadPageTool=Ys,d.createResolveProductsTool=Eu,d.createSiteAwarenessTools=fl,d.declarativeBeOpCache=Jn,d.defaultPiiPatternPack=Mt,d.defaultPiiPatterns=Bt,d.done=wt,d.elapsedMs=q,d.endpointStableKey=ln,d.error=Lr,d.fallbackStatus=au,d.filterActivityEntries=Nn,d.firstArrayValue=sl,d.formatJsonHtml=Un,d.getOrCreateActivityCollector=kn,d.groupForEntry=An,d.gssSearchCapabilities=Zn,d.homePanelReset=Tu,d.httpErrorToAgentError=xr,d.inputHashCachePolicy=Wn,d.inspectProductSurface=io,d.installActivityFetchPatch=Rn,d.installBrowserTools=Zs,d.installFetchTransportBridge=$a,d.installIframeScraperBypass=_u,d.installLocalAgenticActivityDebug=eu,d.isFallbackStatus=su,d.isRef=mr,d.jsonResponse=_s,d.llmCacheKey=kt,d.mergeProductSurfaceEvidence=ju,d.mergeRoundProducts=dr,d.metadata=Mi,d.mountAccount=os,d.mountActivityOverlay=Bn,d.navigateSameTab=Xn,d.ndjsonResponse=ks,d.normalizeComparisonTable=Lt,d.normalizeEntry=_n,d.normalizeProduct=Fe,d.normalizeSameOriginUrl=Qn,d.normalizeSimilarityText=H,d.nowIso=br,d.plainMessageContent=xu,d.productDetailsUiSpec=ps,d.productFactsKey=Ui,d.productSkuKey=qi,d.productSurfaceReviewText=Iu,d.productsUiSpec=fs,d.rankSimilarProducts=xs,d.rankSimilarProductsAsync=Es,d.recordBeDebugPayload=zt,d.redactPii=Nt,d.requestText=mn,d.resolveBeUrl=Ds,d.resolveFlow=Or,d.resolveProductCandidates=to,d.retailAnonymizeMessages=al,d.retailAnonymousRequestText=il,d.retailRedactPii=ol,d.routeFlowParams=bo,d.routeSkuList=cl,d.scoreSimilarityCandidate=Ot,d.searchFollowUpPills=To,d.sectionForKind=Sn,d.setAssistantHostVisible=qs,d.severityForEntry=vn,d.shouldCompact=rd,d.shouldInstallActivityDebug=Kn,d.singleFlight=So,d.stableKey=ie,d.startLazyRuntimeLoader=Xs,d.stickyContextKey=lt,d.summarizeDebugState=Pe,d.summarizePanelState=Ge,d.summarizeUiSpec=Ft,d.textChunk=Ir,d.textKey=Di,d.tokenizeSimilarityText=$,d.trimProductFactsCore=qe,d.trimProductFactsListCore=Fi,d.uiSpec=Ni,d.uniqueProductsBySku=ro,d.validateToolArgs=Fr,d.withAccountConfig=Ks,d.withDeclarativeBeOpCache=nu,d.withSimilarsAppend=td,d.wrapActivityBeacon=Cn,d.wrapActivityTools=En,d.wrapActivityTransport=Pn,d.wrapResolveProductsWithPdpHydration=Hl})(this.Gengage=this.Gengage||{});
|