@gengage/assistant-fe 0.6.24 → 0.6.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agentic/index.d.ts +1 -1
- package/dist/agentic/index.js +684 -639
- package/dist/agentic/types.d.ts +17 -2
- package/dist/agentic/worker.d.ts +1 -1
- package/dist/agentic/worker.js +294 -237
- package/dist/agentic.iife.js +8 -8
- package/dist/api-paths-CmFRzaMd.js +1274 -0
- package/dist/chat-runtime.js +1 -1
- package/dist/chat.iife.js +13 -13
- package/dist/chat.js +1 -1
- package/dist/{common-CzYj5Rg3.js → common-uHKZ-s5H.js} +1 -1
- package/dist/common.js +5 -5
- package/dist/{connection-warning-B1BbjAAP.js → connection-warning-xRmq7uJ3.js} +1 -1
- package/dist/{fastIntent-DtvKVSIo.js → fastIntent-B3qZhCis.js} +1 -1
- package/dist/index.js +10 -10
- package/dist/native.iife.js +11 -11
- package/dist/qna-runtime.js +1 -1
- package/dist/qna.iife.js +25 -25
- package/dist/qna.js +1 -1
- package/dist/{route-params-5KSvTyeb.js → route-params-UDemctx_.js} +330 -313
- package/dist/{runtime-C2RFDcMJ.js → runtime-C1mVW5y1.js} +4 -4
- package/dist/{runtime-BwKxrcVs.js → runtime-Cpi9hXiL.js} +3 -3
- package/dist/{runtime-DLqO5X8q.js → runtime-DhhnaNUQ.js} +3 -3
- package/dist/{simbut-C5AbbA4L.js → simbut-csGdfd9_.js} +1 -1
- package/dist/simbut.iife.js +1 -1
- package/dist/simbut.js +1 -1
- package/dist/{simrel-mH70kmF9.js → simrel-B1VHfhBf.js} +1 -1
- package/dist/simrel-runtime.js +1 -1
- package/dist/simrel.iife.js +38 -38
- package/dist/simrel.js +2 -2
- package/dist/{widget-base-Cfjsry5x.js → widget-base-DNT8SYtf.js} +1 -1
- package/package.json +1 -1
- package/dist/api-paths-Bgg7-gUO.js +0 -1235
package/dist/agentic.iife.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
(function(d){Object.defineProperty(d,Symbol.toStringTag,{value:"Module"});var lo=120*1e3,fo="gengage-agentic-ref";function or({namespace:e=fo,ttlMs:t=lo,maxEntries:r=100}={}){const n=new Map;async function o(u,l={}){c();const f=po(),g=l.kind||"pageRef",p={kind:g,value:u,expiresAt:Date.now()+(l.ttlMs||t)};for(n.set(f,p);n.size>r;)n.delete(n.keys().next().value);return await mo(e,f,p),{kind:g,id:f}}async function i(u){const l=typeof u=="string"?u:u?.id;if(!l)return;const f=n.get(l)||await go(e,l);if(f){if(f.expiresAt<=Date.now()){n.delete(l),await ar(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 ar(e,l))}async function s(u){if(ir(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,g])=>[f,await s(g)]));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 ir(e){return!!(e&&typeof e=="object"&&typeof e.kind=="string"&&typeof e.id=="string")}function po(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function mo(e,t,r){const n=await Qe(e);n&&(await Te(n.transaction("refs","readwrite").objectStore("refs").put(r,t)),n.close())}async function go(e,t){const r=await Qe(e);if(!r)return;const n=await Te(r.transaction("refs","readonly").objectStore("refs").get(t));return r.close(),n}async function ar(e,t){const r=await Qe(e);r&&(await Te(r.transaction("refs","readwrite").objectStore("refs").delete(t)),r.close())}async function Qe(e){if(!globalThis.indexedDB)return null;try{const t=globalThis.indexedDB.open(e,1);return t.onupgradeneeded=()=>{t.result.createObjectStore("refs")},await Te(t)}catch{return null}}function Te(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function yo(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function ho({worker:e,tools:t={},beacon:r,confirmation:n,memory:o=et(),refStore:i}){e.addEventListener("message",a=>{const s=a.data;yo(s)&&bo(e,s,{tools:t,beacon:r,confirmation:n,memory:o,refStore:i})})}async function bo(e,t,r){try{const n=await cr(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 Xe=new Map,sr=null;function et(){try{if(typeof sessionStorage<"u")return sessionStorage}catch{}return{getItem:e=>Xe.get(e)??null,setItem:(e,t)=>{Xe.set(e,t)},removeItem:e=>{Xe.delete(e)}}}function wo(){return sr||=or(),sr}function ko(e){if(e&&typeof e=="object"&&typeof e.name=="string")return e;throw new Error("tool.invoke requires { name, input }")}function So(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.get requires { key }")}function vo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}function _o(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.remove requires { key }")}function Ao(e){return!e||typeof e!="object"?{value:e}:e}function xo(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 tt(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 rt(e){return typeof e.getItem=="function"&&typeof e.setItem=="function"}function nt(e){return typeof e.get=="function"&&typeof e.set=="function"}function ot(e){return typeof e.accountId=="string"&&!!e.session&&!!e.indexedDb}function To(e){const t=e.options?.ttlMs??e.ttlMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?{ttlMs:t}:void 0}async function Eo(e,t,r){if(rt(e)){const n=e.getItem(r);if(!n)return null;try{return JSON.parse(n)}catch{return e.removeItem?.(r),null}}return nt(e)&&!ot(e)?await e.get(t,r)??null:await e[t].get(r)??null}async function Co(e,t,r,n,o){return rt(e)?(e.setItem(r,JSON.stringify(n??null)),!0):nt(e)&&!ot(e)?await e.set(t,r,n??null,o)!==!1:await e[t].set(r,n??null,o)!==!1}async function Po(e,t,r){return rt(e)?(e.removeItem?.(r),!0):nt(e)&&!ot(e)?e.remove?(await e.remove(t,r),!0):!1:(await e[t].remove(r),!0)}async function cr(e,t,{tools:r,beacon:n,confirmation:o,memory:i,refStore:a}){if(e==="tool.invoke"){const{name:s,input:c}=ko(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}=So(t);return Eo(i,tt(c),String(s))}if(e==="memory.set"){const s=vo(t);return{ok:await Co(i,tt(s.tier),String(s.key),s.value,To(s))}}if(e==="memory.remove"){const{key:s,tier:c}=_o(t);return{ok:await Po(i,tt(c),String(s))}}if(e==="ref.put"){const s=Ee({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}),c=Ao(t);return s.put(c.value,xo(c))}if(e==="ref.get")return Ee({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).get(t);if(e==="ref.materialize")return Ee({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).materialize(t);if(e==="ref.remove")return await Ee({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).delete(t),{ok:!0};throw new Error(`Unknown RPC method: ${e}`)}function Ee(e){const t=e.refStore||wo();if(!t||typeof t.put!="function"||typeof t.get!="function")throw new Error("No ref store is configured.");return t}function ur(){return new Date().toISOString()}function q(e){return Math.max(0,Math.round(performance.now()-e))}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jo(e){const{accountId:t,locale:r="en-GB",parentUrl:n="",threadId:o,incomingContext:i,messageLimit:a}=e,s=me(i)?i:{},c=me(s.thread)?s.thread:{},u=me(s.panel)?s.panel:{},l=me(s.meta)?s.meta:{},f=lr(s.messages,a),g={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||ur()),extensions:me(c.extensions)?{...c.extensions}:{}},p=String(l.locale||r),y=String(l.parentUrl||n||typeof self<"u"&&self.location?.href||"");return{panel:{...u},messages:f,thread:g,meta:{locale:p,parentUrl:y,accountId:t}}}function Ro(e,t,r){const n=lr([t],r)[0];return n?{...e,messages:Ce([...e.messages,n],r)}:e}function Ce(e,t){const r=Lo(t);return r===1/0?[...e]:e.slice(-r)}function lr(e,t){return Array.isArray(e)?Ce(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.content),t):[]}function Lo(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 Io="gengage:agent:context:";async function Oo({accountId:e,threadId:t,rpc:r}){const n=await r("memory.get",{tier:"session",key:it(e,t)});return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function Bo({accountId:e,threadId:t,extensions:r,panel:n,rpc:o}){await o("memory.set",{tier:"session",key:it(e,t),value:{thread:{extensions:r},...n&&Object.keys(n).length>0?{panel:n}:{}}})}function it(e,t){return`${Io}${e}:${t}`}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var dr=class{#e=new Map;#r=new Map;#o;#c;#u;#i;#l;#d;#n;#a;#s;constructor({accountId:e,locale:t,parentUrl:r,rpc:n,persistentPanelKeys:o=[],panelKeyLimits:i={},messageLimit:a,maxThreads:s,threadTtlMs:c}){this.#o=e,this.#c=t,this.#u=r,this.#i=n,this.#l=[...new Set(o.filter(Boolean))],this.#d=No(i),this.#n=at(a),this.#a=at(s),this.#s=at(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.#t(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?.meta?.threadId||e?.session_id||e?.sessionId,r=String(t||"default"),n=this.#e.get(r);if(n){const a=Fo(n,e?.context,this.#n);return this.#t(r,a),a}const o=await Oo({accountId:this.#o,threadId:r,rpc:this.#i}),i=jo({accountId:this.#o,locale:e?.locale||this.#c,parentUrl:this.#u,threadId:r,incomingContext:qo(o,e?.context),messageLimit:this.#n});return this.#t(r,i),this.#f(),i}patch(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=st(n,typeof t=="function"?t(n):t,this.#n);return this.#t(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=Ro(n,{role:"user",content:t},this.#n);return this.#t(r,o),o}async commit(e){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#t(t,r),await Bo({accountId:this.#o,threadId:t,extensions:r.thread.extensions,panel:Mo(r.panel,this.#l,this.#d),rpc:this.#i}),r):null}delete(e){const t=String(e||"default");return this.#r.delete(t),this.#e.delete(t)}clear(){this.#e.clear(),this.#r.clear()}pruneExpired(e=Date.now()){if(!this.#s)return 0;let t=0;for(const[r,n]of this.#r)e-n<=this.#s||(this.#r.delete(r),this.#e.delete(r)&&(t+=1));return t}#t(e,t){this.#e.delete(e),this.#e.set(e,t),this.#r.set(e,Date.now())}#f(){if(this.#a)for(;this.#e.size>this.#a;){const e=this.#e.keys().next().value;if(!e)return;this.delete(e)}}};function Mo(e,t,r){if(!t.length||!E(e))return;const n={};for(const o of t)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=$o(e[o],r[o]));return n}function No(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 at(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function $o(e,t){return!t||!Array.isArray(e)?e:e.slice(-t)}function qo(e,t){return!E(e)&&!E(t)?{}:st(E(e)?e:{},E(t)?t:{})}function Fo(e,t,r){if(!E(t))return e;const n=st(e,t,r);return{...n,thread:{...n.thread,id:e.thread.id,started_at:e.thread.started_at},meta:{...n.meta,accountId:e.meta.accountId}}}function st(e,t,r){if(!E(t))return e;const n=e,o=t,i=E(n.panel)?n.panel:{},a=E(o.panel)?o.panel:{},s=E(n.thread)?n.thread:{},c=E(o.thread)?o.thread:{},u=E(s.extensions)?s.extensions:{},l=E(c.extensions)?c.extensions:{},f=E(n.meta)?n.meta:{},g=E(o.meta)?o.meta:{};return{...e,...t,panel:{...i,...a},thread:{...s,...c,extensions:{...u,...l}},meta:{...f,...g},messages:Array.isArray(o.messages)?Ce(o.messages,r):e.messages??[]}}function fr(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function pr(e){return fr(new TextEncoder().encode(JSON.stringify(e)))}async function Uo({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=`${pr({alg:"HS256",typ:"JWT"})}.${pr({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}.${fr(new Uint8Array(a))}`}function ct({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 Uo({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 Do({accountId:e,tokenBrokerUrl:r,tokenBrokerAudience:n,parentUrl:c,signal:s,fetchImpl:i})),a.token}}async function Do({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:zo(s)||Go(c)||Math.floor(Date.now()/1e3)+300}}function zo(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 Go(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 mr={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."}},z=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 ut(e){const t=String(e?.code||"upstream_llm"),r=mr[t]||mr.upstream_llm;return new z(r.code,r.message,{source:"be",sourceCode:t,detail:e?.detail})}function gr(e,t){const r=t?.error&&typeof t.error=="object"?t.error:{};return ut({code:String(r.code||Vo(e)),detail:r.detail})}function yr(e){return e instanceof z?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function Vo(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var Ho=7200*1e3,hr=200,Ko=5*1024*1024,Wo="gengage_request_response_cache",Jo=1,F="responses",Zo=new Set(["addToCart","like"]),U=new Map,br=null;async function Yo(e,t={},r={}){const n=Qo(e,t);if(!n)return fetch(e,t);const o=Date.now(),i=await ei(n,o);if(i)return ni(i);const a=await fetch(e,t);return a.ok&&ti(n,a.clone(),o,{ttlMs:r.ttlMs??Ho,maxEntries:r.maxEntries??hr,maxBodyBytes:r.maxBodyBytes??Ko}),a}function Qo(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"||Xo(t.body)?null:`rr:${li(ui({url:String(e),method:r,headers:oi(t.headers),body:t.body}))}`}function Xo(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"&&Zo.has(r)}catch{return!1}}async function ei(e,t){const r=U.get(e);if(r)if(r.expiresAt<=t)U.delete(e);else return r.lastAccessedAt=t,U.delete(e),U.set(e,r),lt(r),r;const n=await ai(e);return n?n.expiresAt<=t?(U.delete(e),si(e),null):(n.lastAccessedAt=t,U.set(e,n),lt(n),wr(hr),n):null}async function ti(e,t,r,n){try{const o=await t.text();if(di(o)>n.maxBodyBytes||ri(o))return;const i={key:e,status:t.status,statusText:t.statusText,headers:ii(t.headers),body:o,createdAt:r,expiresAt:r+n.ttlMs,lastAccessedAt:r};U.set(e,i),wr(n.maxEntries),await lt(i),await ci(n.maxEntries,r)}catch{}}function ri(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function ni(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function oi(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 ii(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 wr(e){for(;U.size>e;){const t=[...U.values()].sort((r,n)=>r.lastAccessedAt-n.lastAccessedAt)[0];if(!t)break;U.delete(t.key)}}async function Pe(){return typeof indexedDB>"u"?null:(br??=new Promise(e=>{const t=indexedDB.open(Wo,Jo);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(F)||r.createObjectStore(F,{keyPath:"key"}).createIndex("lastAccessedAt","lastAccessedAt",{unique:!1})},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),br)}async function ai(e){const t=await Pe();return t?new Promise(r=>{const n=t.transaction(F,"readonly"),o=n.objectStore(F).get(e);o.onsuccess=()=>r(o.result??null),o.onerror=()=>r(null),n.onerror=()=>r(null)}):null}async function lt(e){const t=await Pe();t&&await new Promise(r=>{const n=t.transaction(F,"readwrite");n.objectStore(F).put(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function si(e){const t=await Pe();t&&await new Promise(r=>{const n=t.transaction(F,"readwrite");n.objectStore(F).delete(e),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}async function ci(e,t){const r=await Pe();r&&await new Promise(n=>{const o=r.transaction(F,"readwrite"),i=o.objectStore(F),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,g)=>f.lastAccessedAt-g.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 ui(e){return JSON.stringify(dt(e))}function dt(e){return Array.isArray(e)?e.map(dt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,dt(r)]))}function li(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 di(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function fi({beUrl:e,accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,jwtProvider:i,parentUrl:a,op:s,input:c,cacheTtlS:u,cacheKey:l,browserCache:f,signal:g}){const p=await(i||ct({accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o}))({...g?{signal:g}:{},...a?{parentUrl:a}:{}}),{opDomain:y,opName:h}=pi(s,t),m={method:"POST",headers:{authorization:`Bearer ${p}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:y,op_name:h,op_payload:c,...u!==void 0?{cache_ttl_s:u}:{},...l!==void 0?{cache_key:l}:{}}),...g?{signal:g}:{}},b=`${String(e).replace(/\/+$/u,"")}/v1/execute`,w=f===!1?await fetch(b,m):await Yo(b,m,typeof f=="object"?f:{});if(!w.ok)throw gr(w.status,await gi(w));return yi(w)}function pi(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:mi(t),opName:e}}function mi(e){return e.replace(/-agentic$/u,"")}async function gi(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function yi(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
|
-
`);for(;c>=0;){const u=n.slice(0,c).trim();n=n.slice(c+1),u&&
|
|
3
|
-
`)}}const i=n.trim();return i&&kr(JSON.parse(i),o),o}function kr(e,t){if(e._error)throw ut(e._error);if(!e._end)for(const[r,n]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,r))throw new z("op_failed",`BE streamed duplicate field "${r}".`,{source:"be",sourceCode:"schema_mismatch"});t[r]=n}}function hi(e={}){return{type:"metadata",...e}}function Sr(e,t=!1,r={}){return{type:"text_chunk",content:e,final:t,...r}}function bi(e){return{type:"ui_spec",...e}}function wi(e){return{type:"action",action:e}}function vr(e,t){return{type:"error",code:e,message:t}}function ft(){return{type:"done"}}function _r(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}function Ar(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function je(e,t={}){const r=Ar(e);if(!r)return null;const n=t.catalogMapper?.(r);if(n)return n;const o=ne(r.sku,r.SKU);if(!o)return null;const i={sku:o,name:ne(r.name,r.title,r.short_name,o)||o,url:ne(r.url)||""},a=Array.isArray(r.images)?r.images:void 0,s=ne(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=ge(r.price_discounted),u=ge(r.price),l=c||u;l>0&&(i.price=String(l));const f=c>0?u:0;f>0&&(i.originalPrice=String(f));const g=ne(r.brand);g&&(i.brand=g);const p=ge(r.rating);p>0&&(i.rating=p);const y=ge(r.review_count)||ge(r.reviewCount);y>0&&(i.reviewCount=y);const h=ne(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 m=r.category_names;return Array.isArray(m)&&(i.categoryNames=m.map(String)),i}function Re(e){const t=Ar(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 ki(e){return Array.isArray(e)?e.map(Re).filter(t=>!!t):[]}function ne(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function ge(e){const t=Number(e);return Number.isFinite(t)?t:0}function xr(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function pt(e,t,r={}){return`${e}:${r.version||"v2"}:${oe(t)}`}function Si(e,t={}){return Tr(e).map(r=>Er(typeof r=="string"?r:r.sku,t.locale)).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n).sort((r,n)=>mt(r,n,t.locale)).slice(0,t.limit||16).join(",")}function vi(e,t={}){return oe(Tr(e).map(r=>Ai(r,t)).filter(r=>!!r).sort((r,n)=>mt(String(r.sku||r.name||""),String(n.sku||n.name||""),t.locale)).slice(0,t.limit||16))}function _i(e,t){return Y(e,t)}function oe(e){let t=2166136261;const r=xi(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 Ai(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=t.mapProduct?.(r);if(n)return ye(n);const o=Re(r);return o&&typeof o=="object"&&!Array.isArray(o)?ye(Ti(o,t)):null}function Tr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function xi(e){return JSON.stringify(ye(e))}function ye(e){return Array.isArray(e)?e.map(ye):!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,ye(r)]))}function Ti(e,t){return{sku:Er(e.sku,t.locale),name:Y(e.name,t.locale),url:Y(e.url,t.locale),price:e.price,currency:Y(e.currency,t.locale),category:Y(e.category,t.locale),category_names:Ei(e.category_names,t.locale,16),image:Y(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function Er(e,t){return Y(e,t).toUpperCase()}function Y(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function mt(e,t,r){return e.localeCompare(t,r,{numeric:!0})}function Ei(e,t,r){return Array.isArray(e)?e.map(n=>Y(n,t)).filter(Boolean).sort((n,o)=>mt(n,o,t)).slice(0,r):void 0}async function Ci({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=Zi(e);Ui(u,f)&&r.appendUserMessage(l,f);const g=_r(t.flows,e);if(!g)return i(vr("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(ft()),{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:Ji(t.contextPersistence?.messageLimit),catalogMapper:t.catalogMapper,similarityMapper:t.similarityMapper},y={contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...s?{signal:s}:{},...t.trace?{trace:t.trace}:{}};await G(y,we("turn:start",p));try{await he(g,p,y),p.committed||await gt(p,y)}catch(h){throw await G(y,{...we("turn:error",p),latencyMs:q(c),errorCode:kt(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 G(y,{...we("turn:end",p),latencyMs:q(c)}),{steps:p.steps,productSkusEmitted:[...p.productSkusEmitted]}}async function he(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 G(r,bt("step:start",t,n,o));try{await Pi(n,t,r),await G(r,{...bt("step:end",t,n,o),latencyMs:q(i)})}catch(a){throw await G(r,{...bt("step:error",t,n,o),latencyMs:q(i),errorCode:kt(a)}),a}t.context=r.contextStore.patch(t.threadId,{})||t.context}}async function Pi(e,t,r){const n=Ie(t);if(e.kind==="be_op"){await ji(e,t,r,n);return}if(e.kind==="tool"){await Ii(e,t,r,n);return}if(e.kind==="adapter"){await Oi(e,t,r,n);return}if(e.kind==="emit"){await Bi(e,t,r);return}if(e.kind==="patch"){await Mi(e,t,r);return}if(e.kind==="branch"){await Ni(e,t,r,n);return}if(e.kind==="parallel"){await $i(e,t,r);return}if(e.kind==="refusal"){await qi(e,t,r,n);return}e.kind==="commit"&&await Fi(e,t,r)}async function ji(e,t,r,n){const o=performance.now();let i;try{const s=await P(e.input,n),c=Ri(e,t,s,await P(e.cache,n)),u=await P(e.cacheTtlS,n)??c.cacheTtlS,l=await P(e.cacheKey,n)??c.cacheKey,f=await P(e.browserCache,n),g=be(await P(e.timeoutMs,n));await ht(e,t,r,n);const p=g?new AbortController:null,y=jr(r.signal,p?.signal);i=await Be(r.beClient.invoke({op:e.op,input:s,...u!==void 0?{cacheTtlS:u}:{},...l!==void 0?{cacheKey:l}:{},...f!==void 0?{browserCache:f}:{},...y?{signal:y}:{}}),g,()=>new z("op_timeout","The assistant took too long to respond.",{source:"be",sourceCode:"timeout"}),()=>p?.abort())}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 he(e.onError,t,r);return}throw s}e.out&&(t.bag[e.out]=i),await Le(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 Ri(e,t,r,n){if(!n||n.strategy!=="input-hash")return{};const o=be(n.ttlS);if(!o)return{};const i=t.context.meta.locale,a=n.promptVersion||Li(r)||"current";return{cacheTtlS:o,cacheKey:pt(e.op,{account:t.context.meta.accountId,locale:i,promptVersion:a,payload:r},{version:"input-hash"})}}function Li(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 Ii(e,t,r,n){const o=performance.now();try{await ht(e,t,r,n);const i=be(await P(e.timeoutMs,n)),a=await Be(r.toolBridge.invoke(e.name,await P(e.input,n)),i,()=>new z("tool_timeout","The assistant tool took too long to respond.",{source:"tool",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Le(e,a,t,r.contextStore),await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Oe(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:Oe(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 he(e.onError,t,r);return}throw i}}async function Oi(e,t,r,n){const o=r.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);await ht(e,t,r,n);const i=be(await P(e.timeoutMs,n)),a=await Be(o(await P(e.input,n),n),i,()=>new z("adapter_timeout","The assistant adapter took too long to respond.",{source:"adapter",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Le(e,a,t,r.contextStore)}async function Bi(e,t,r){const n=await e.build(Ie(t));Yi(n,t.productSkusEmitted),r.emit(n)}async function Mi(e,t,r){await Le(e,void 0,t,r.contextStore)}async function Ni(e,t,r,n){const o=String(await P(e.on,n)||"default");await he(e.cases[o]||e.cases.default||[],t,r)}async function $i(e,t,r){const n=be(await P(e.timeoutMs,Ie(t))),o=n?new AbortController:null,i=jr(r.signal,o?.signal),a=e.steps.map(u=>{const l={...t,context:Di(t.context),bag:yt(t.bag),productSkusEmitted:new Set(t.productSkusEmitted),committed:!1},f=[];return he(u,l,{...r,emit:g=>{!i?.aborted&&g.type!=="done"&&f.push(g)},contextStore:zi(l),...i?{signal:i}:{}}).then(()=>({state:l,events:f}))}),s=await Be(Promise.all(a),n,()=>new z("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=Cr(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=Cr(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 qi(e,t,r,n){r.emit(Sr(await P(e.message,n),!0)),await gt(t,r)}async function Fi(e,t,r){await gt(t,r)}async function gt(e,{contextStore:t,emit:r}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,r(ft()))}async function Le(e,t,r,n){if(typeof e.patch!="function")return;const o=await e.patch(r.context,t,Ie(r));o&&(r.context=n.patch(r.threadId,o)||r.context)}function Ie(e){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig,catalogMapper:e.catalogMapper,similarityMapper:e.similarityMapper}}function Oe(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function Ui(e,t){if(!t)return!1;const r=e.messages[e.messages.length-1];return r?.role!=="user"||r.content!==t}function Cr(e,t){const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function Di(e){return{...e,panel:yt(e.panel||{}),thread:{...e.thread,extensions:yt(e.thread?.extensions||{})},meta:e.meta,messages:e.messages}}function zi(e){return{async load(){return e.context},patch(t,r){return e.context=Gi(e.context,r,e.messageLimit),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function Gi(e,t,r){if(!t||typeof t!="object")return e;const n=Pr(e.panel,t.panel),o=Pr(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)?Ce(t.messages,r):e.messages}}function Pr(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 yt(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(Vi(o)){const i=Hi(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 Vi(e){return!!(e&&typeof e=="object")}function Hi(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}async function P(e,t){return typeof e=="function"?await e(t):e}function be(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}async function Be(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 jr(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 ht(e,t,r,n){if(!e.confirm)return;const o=await P(e.confirm,n);if(!o)return;const i=Ki(o,e,t);await G(r,wt("confirmation:start",t,e));try{const a=await r.rpc("confirmation.request",i),s=typeof a=="boolean"?a:a?.confirmed===!0;if(await G(r,wt("confirmation:end",t,e)),s)return;throw new z("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 G(r,{...wt("confirmation:error",t,e),errorCode:kt(a)}),a}}function Ki(e,t,r){return{...Wi(e),accountId:r.context.meta.accountId,threadId:r.threadId,sessionId:Oe(r),stepKind:t.kind,...t.kind==="be_op"?{stepName:t.op}:{stepName:t.name}}}function Wi(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 G(e,t){try{await e.trace?.(t)}catch{}}function we(e,t){return{type:e,accountId:t.context.meta.accountId,threadId:t.threadId,sessionId:Oe(t)}}function bt(e,t,r,n){const o=Rr(r);return{...we(e,t),stepIndex:n,stepKind:r.kind,...o?{stepName:o}:{}}}function wt(e,t,r){const n=Rr(r);return{...we(e,t),stepKind:r.kind,...n?{stepName:n}:{}}}function Rr(e){if(e.kind==="be_op")return e.op;if(e.kind==="tool"||e.kind==="adapter")return e.name}function kt(e){if(e&&typeof e=="object"){const t=e;return String(t.sourceCode||t.code||t.name||"unknown")}return"unknown"}function Ji(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function Zi(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 Yi(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 Qi(e){return{invoke(t,r){return e("tool.invoke",{name:t,input:r})}}}var Xi=512,ea=.74;function Lr({accountId:e,worker:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l=et()}){let f=1;const g=new Map;return ho({worker:t,tools:s,beacon:p=>c?.({...p,accountId:p.accountId||e}),...u?{confirmation:u}:{},memory:l}),t.addEventListener("message",p=>{const y=p.data||{},h=typeof y.id=="number"?y.id:null;if(h==null)return;const m=g.get(h);if(m){if(y.type==="event"&&y.event){St(m,y.event);return}if(y.type==="error"){m.onError(new Error(y.message||"Agent worker failed")),g.delete(h);return}y.type==="end"&&g.delete(h)}}),(p,y,h,m)=>{const b=f++;g.set(b,y);const w=()=>{g.delete(b),t.postMessage({id:b,type:"abort"})},A=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:v,parentUrl:window.location.href})};if(h.aborted){w();return}if(h.addEventListener("abort",w,{once:!0}),m){Or(p,m).then(A).catch(v=>{g.delete(b),y.onError(v instanceof Error?v:new Error("Failed to read image attachment"))});return}A(p)}}function Ir({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 g=ta({accountId:e,tools:s,beacon:c,confirmation:u,memory:l??et()}),p=Qi(g),y=ct({accountId:e,...n?{devJwtSecret:n}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(h,m,b,w)=>{const A=await Or(h||{},w);f||=new dr({accountId:e,locale:A?.locale||a,parentUrl:window.location.href,rpc:g,persistentPanelKeys:t.contextPersistence?.panelKeys,panelKeyLimits:t.contextPersistence?.panelKeyLimits,messageLimit:t.contextPersistence?.messageLimit,maxThreads:t.contextPersistence?.maxThreads,threadTtlMs:t.contextPersistence?.threadTtlMs});try{await Ci({request:A,accountModule:{...t,accountId:e},contextStore:f,beClient:{invoke({op:v,input:O,signal:_,cacheTtlS:M,cacheKey:J,browserCache:Ye}){return fi({beUrl:r,accountId:e,jwtProvider:y,parentUrl:window.location.href,op:v,input:O,cacheTtlS:M,cacheKey:J,browserCache:Ye,..._?{signal:_}:{}})}},toolBridge:p,emit:v=>St(m,v),rpc:g,signal:b})}catch(v){b?.aborted||(St(m,yr(v)),m.onDone())}}}function ta({accountId:e,tools:t,beacon:r,confirmation:n,memory:o}){const i=a=>r?.({...a,accountId:a.accountId||e});return((a,s)=>cr(a,s,{tools:t,beacon:i,confirmation:n,memory:o}))}async function Or(e,t){if(!t||!t.type?.startsWith("image/"))return e;const r=await oa(t),n={...ra(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 ra(e){return na(e)?{...e}:typeof e=="string"?{text:e}:{}}function na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function oa(e){const t=await ia(e);return t||{dataUrl:await Br(e),mime:e.type}}async function ia(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const r=Math.min(1,Xi/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",ea));return s?{dataUrl:await Br(s),mime:s.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function Br(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 St(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(aa(t));break;case"done":e.onDone();break;default:break}}function aa(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}var sa="entries",ca=1,ua={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."},Mr=new Map;function vt(){return Date.now()}function ie(e){return e?.expiresAt!=null&&e.expiresAt<=vt()}function _t(e,t){return{value:e,createdAt:vt(),expiresAt:t?vt()+t:null}}function la(e,t,r){try{const n=e.getItem(`${t}${r}`);if(!n)return null;const o=JSON.parse(n);return ie(o)?(e.removeItem(`${t}${r}`),null):o.value}catch{return null}}function da(e,t,r,n,o){try{return e.setItem(`${t}${r}`,JSON.stringify(_t(n,o))),!0}catch{return!1}}function fa(e,t,r){try{e.removeItem(`${t}${r}`)}catch{}}function Nr(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||ie(i))&&(e.removeItem(o),r+=1)}catch{e.removeItem(o),r+=1}}catch{return r}return r}function $r(e){try{return window[e]}catch{return null}}function qr(e,t){return e?{get:r=>la(e,t,r),set:(r,n,o={})=>da(e,t,r,n,o.ttlMs),remove:r=>fa(e,t,r)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function pa(e,t){const r=t.dbName||`gengage-${e}`,n=t.dbStore||sa,o=t.dbVersion||ca,i=new Map;let a=null;const s=()=>"indexedDB"in window?a||(a=new Promise(g=>{const p=indexedDB.open(r,o);p.onupgradeneeded=()=>{p.result.createObjectStore(n,{keyPath:"key"})},p.onsuccess=()=>g(p.result),p.onerror=()=>g(null),p.onblocked=()=>g(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async g=>{const p=await s();return p?new Promise(y=>{const h=p.transaction(n,"readwrite").objectStore(n),m=h.get(g);m.onsuccess=()=>{const b=m.result;if(!b||ie(b)){b&&h.delete(g),y(null);return}y(b.value)},m.onerror=()=>y(null)}):null},idbSet:async(g,p,y={})=>{const h=await s();return h?new Promise(m=>{const b=h.transaction(n,"readwrite");b.oncomplete=()=>m(!0),b.onerror=()=>m(!1),b.objectStore(n).put({key:g,..._t(p,y.ttlMs)})}):!1},idbRemove:async g=>{const p=await s();p&&p.transaction(n,"readwrite").objectStore(n).delete(g)},idbGc:async()=>{const g=await s();return g?new Promise(p=>{let y=0;const h=g.transaction(n,"readwrite"),m=h.objectStore(n).openCursor();m.onsuccess=()=>{const b=m.result;if(!b)return;const w=b.value;(!w||ie(w))&&(b.delete(),y+=1),b.continue()},h.oncomplete=()=>p(y),h.onerror=()=>p(y),m.onerror=()=>p(y)}):0}}}function At(e,t={}){const r=window,n=r.gengage||(r.gengage={}),o=n.memory||(n.memory={}),i=o[e];if(i)return i;const a=Mr.get(e)||pa(e,t);Mr.set(e,a);const s=t.sessionPrefix||`gengage:${e}:session:`,c=t.localPrefix||`gengage:${e}:local:`,u=$r("sessionStorage"),l=$r("localStorage"),g={get:m=>{const b=a.volatileEntries.get(m);return b?ie(b)?(a.volatileEntries.delete(m),null):b.value:null},set:(m,b,w={})=>(a.volatileEntries.set(m,_t(b,w.ttlMs)),!0),remove:m=>{a.volatileEntries.delete(m)},clear:()=>a.volatileEntries.clear()},p={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},y=async()=>{let m=0;for(const[v,O]of a.volatileEntries)ie(O)&&(a.volatileEntries.delete(v),m+=1);const b=Nr(u,s),w=Nr(l,c),A=await a.idbGc();return{volatile:m,session:b,local:w,indexedDb:A}},h={accountId:e,volatile:g,session:qr(u,s),local:qr(l,c),indexedDb:p,gc:y,stableKey:oe,policy:{...ua,...t.policy||{}}};o[e]=h;for(const m of t.aliases||[])o[m]=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 Me="__gengageAgentFetchBridge",ga=1e3*60*60*24*14;function ya({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=ha(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,s=n?_a({accountId:e,endpointCache:n,fetchImpl:o.originalFetch}):void 0,c=u=>{const l=`${i}/chat/${u}`;a.add(l);const f=r[u],g={streamTransport:t,endpoint:u};f&&(g.endpointHandler=f),s&&(g.endpointCache=s),o.routes.set(l,g)};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);ba(o)}}}function ha(){const e=window,t=e[Me];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=Fr(o),s=n.routes.get(a);return s?ka(s,o,i):r(o,i)},e.fetch=n.installedFetch,e[Me]=n,n}function ba(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[Me]===e&&delete t[Me]}function Fr(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function Ur(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function Dr(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function wa(e,t){const r=Dr(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 ka(e,t,r){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const u=new AbortController,l=Ur(t,r);let f=null;if(l){const g=()=>u.abort();l.aborted&&g(),l.addEventListener("abort",g,{once:!0}),f=()=>l.removeEventListener("abort",g)}try{const g=await Sa(t,r),p={accountId:va(t),endpoint:e.endpoint,signal:u.signal},y=Aa(e.endpointCache,e.endpoint,g,p.accountId);if(y){const m=await xa(e.endpointCache,y,u.signal);if(m)return Ra(m)}const h=await e.endpointHandler(g,p);return y&&h.ok&&await Ta(e.endpointCache,y,h.clone(),u.signal),h}finally{f?.()}}const n=new TextEncoder,o=new AbortController,i=Ur(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())},g=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:y}=await
|
|
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
|
|
1
|
+
(function(d){Object.defineProperty(d,Symbol.toStringTag,{value:"Module"});var fo=120*1e3,po="gengage-agentic-ref";function ir({namespace:e=po,ttlMs:t=fo,maxEntries:r=100}={}){const n=new Map;async function o(u,l={}){c();const f=mo(),g=l.kind||"pageRef",p={kind:g,value:u,expiresAt:Date.now()+(l.ttlMs||t)};for(n.set(f,p);n.size>r;)n.delete(n.keys().next().value);return await go(e,f,p),{kind:g,id:f}}async function i(u){const l=typeof u=="string"?u:u?.id;if(!l)return;const f=n.get(l)||await yo(e,l);if(f){if(f.expiresAt<=Date.now()){n.delete(l),await sr(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 sr(e,l))}async function s(u){if(ar(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,g])=>[f,await s(g)]));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 ar(e){return!!(e&&typeof e=="object"&&typeof e.kind=="string"&&typeof e.id=="string")}function mo(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function go(e,t,r){const n=await Qe(e);n&&(await Ce(n.transaction("refs","readwrite").objectStore("refs").put(r,t)),n.close())}async function yo(e,t){const r=await Qe(e);if(!r)return;const n=await Ce(r.transaction("refs","readonly").objectStore("refs").get(t));return r.close(),n}async function sr(e,t){const r=await Qe(e);r&&(await Ce(r.transaction("refs","readwrite").objectStore("refs").delete(t)),r.close())}async function Qe(e){if(!globalThis.indexedDB)return null;try{const t=globalThis.indexedDB.open(e,1);return t.onupgradeneeded=()=>{t.result.createObjectStore("refs")},await Ce(t)}catch{return null}}function Ce(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function ho(e){return!!e&&typeof e=="object"&&e.type==="rpc.req"}function bo({worker:e,tools:t={},beacon:r,confirmation:n,memory:o=et(),refStore:i}){e.addEventListener("message",a=>{const s=a.data;ho(s)&&wo(e,s,{tools:t,beacon:r,confirmation:n,memory:o,refStore:i})})}async function wo(e,t,r){try{const n=await ur(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 Xe=new Map,cr=null;function et(){try{if(typeof sessionStorage<"u")return sessionStorage}catch{}return{getItem:e=>Xe.get(e)??null,setItem:(e,t)=>{Xe.set(e,t)},removeItem:e=>{Xe.delete(e)}}}function ko(){return cr||=ir(),cr}function So(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 vo(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.set requires { key }")}function Ao(e){if(e&&typeof e=="object"&&e.key!==void 0)return e;throw new Error("memory.remove requires { key }")}function xo(e){return!e||typeof e!="object"?{value:e}:e}function Eo(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 tt(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 rt(e){return typeof e.getItem=="function"&&typeof e.setItem=="function"}function nt(e){return typeof e.get=="function"&&typeof e.set=="function"}function ot(e){return typeof e.accountId=="string"&&!!e.session&&!!e.indexedDb}function To(e){const t=e.options?.ttlMs??e.ttlMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?{ttlMs:t}:void 0}async function Co(e,t,r){if(rt(e)){const n=e.getItem(r);if(!n)return null;try{return JSON.parse(n)}catch{return e.removeItem?.(r),null}}return nt(e)&&!ot(e)?await e.get(t,r)??null:await e[t].get(r)??null}async function Po(e,t,r,n,o){return rt(e)?(e.setItem(r,JSON.stringify(n??null)),!0):nt(e)&&!ot(e)?await e.set(t,r,n??null,o)!==!1:await e[t].set(r,n??null,o)!==!1}async function jo(e,t,r){return rt(e)?(e.removeItem?.(r),!0):nt(e)&&!ot(e)?e.remove?(await e.remove(t,r),!0):!1:(await e[t].remove(r),!0)}async function ur(e,t,{tools:r,beacon:n,confirmation:o,memory:i,refStore:a}){if(e==="tool.invoke"){const{name:s,input:c}=So(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 Co(i,tt(c),String(s))}if(e==="memory.set"){const s=vo(t);return{ok:await Po(i,tt(s.tier),String(s.key),s.value,To(s))}}if(e==="memory.remove"){const{key:s,tier:c}=Ao(t);return{ok:await jo(i,tt(c),String(s))}}if(e==="ref.put"){const s=Pe({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}),c=xo(t);return s.put(c.value,Eo(c))}if(e==="ref.get")return Pe({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).get(t);if(e==="ref.materialize")return Pe({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).materialize(t);if(e==="ref.remove")return await Pe({tools:r,beacon:n,confirmation:o,memory:i,refStore:a}).delete(t),{ok:!0};throw new Error(`Unknown RPC method: ${e}`)}function Pe(e){const t=e.refStore||ko();if(!t||typeof t.put!="function"||typeof t.get!="function")throw new Error("No ref store is configured.");return t}function lr(){return new Date().toISOString()}function q(e){return Math.max(0,Math.round(performance.now()-e))}function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ro(e){const{accountId:t,locale:r="en-GB",parentUrl:n="",threadId:o,incomingContext:i,messageLimit:a}=e,s=he(i)?i:{},c=he(s.thread)?s.thread:{},u=he(s.panel)?s.panel:{},l=he(s.meta)?s.meta:{},f=dr(s.messages,a),g={id:String(o||c.id||self.crypto.randomUUID()),started_at:String(c.started_at||lr()),extensions:he(c.extensions)?{...c.extensions}:{}},p=String(l.locale||r),y=String(l.parentUrl||n||typeof self<"u"&&self.location?.href||"");return{panel:{...u},messages:f,thread:g,meta:{locale:p,parentUrl:y,accountId:t}}}function Io(e,t,r){const n=dr([t],r)[0];return n?{...e,messages:je([...e.messages,n],r)}:e}function je(e,t){const r=Lo(t);return r===1/0?[...e]:e.slice(-r)}function dr(e,t){return Array.isArray(e)?je(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.content),t):[]}function Lo(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 Oo="gengage:agent:context:";async function Bo({accountId:e,threadId:t,rpc:r}){const n=await r("memory.get",{tier:"session",key:it(e,t)});return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function Mo({accountId:e,threadId:t,extensions:r,panel:n,rpc:o}){await o("memory.set",{tier:"session",key:it(e,t),value:{thread:{extensions:r},...n&&Object.keys(n).length>0?{panel:n}:{}}})}function it(e,t){return`${Oo}${e}:${t}`}function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fr=class{#e=new Map;#r=new Map;#o;#c;#u;#i;#l;#d;#n;#a;#s;constructor({accountId:e,locale:t,parentUrl:r,rpc:n,persistentPanelKeys:o=[],panelKeyLimits:i={},messageLimit:a,maxThreads:s,threadTtlMs:c}){this.#o=e,this.#c=t,this.#u=r,this.#i=n,this.#l=[...new Set(o.filter(Boolean))],this.#d=$o(i),this.#n=at(a),this.#a=at(s),this.#s=at(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.#t(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=Fo(n,e?.context,this.#n);return this.#t(r,a),a}const o=await Bo({accountId:this.#o,threadId:r,rpc:this.#i}),i=Ro({accountId:this.#o,locale:e?.locale||this.#c,parentUrl:this.#u,threadId:r,incomingContext:Uo(o,e?.context),messageLimit:this.#n});return this.#t(r,i),this.#f(),i}patch(e,t){this.pruneExpired();const r=String(e||"default"),n=this.#e.get(r);if(!n)return null;const o=st(n,typeof t=="function"?t(n):t,this.#n);return this.#t(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=Io(n,{role:"user",content:t},this.#n);return this.#t(r,o),o}async commit(e){this.pruneExpired();const t=String(e||"default"),r=this.#e.get(t);return r?(this.#t(t,r),await Mo({accountId:this.#o,threadId:t,extensions:r.thread.extensions,panel:No(r.panel,this.#l,this.#d),rpc:this.#i}),r):null}delete(e){const t=String(e||"default");return this.#r.delete(t),this.#e.delete(t)}clear(){this.#e.clear(),this.#r.clear()}pruneExpired(e=Date.now()){if(!this.#s)return 0;let t=0;for(const[r,n]of this.#r)e-n<=this.#s||(this.#r.delete(r),this.#e.delete(r)&&(t+=1));return t}#t(e,t){this.#e.delete(e),this.#e.set(e,t),this.#r.set(e,Date.now())}#f(){if(this.#a)for(;this.#e.size>this.#a;){const e=this.#e.keys().next().value;if(!e)return;this.delete(e)}}};function No(e,t,r){if(!t.length||!T(e))return;const n={};for(const o of t)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=qo(e[o],r[o]));return n}function $o(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 at(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function qo(e,t){return!t||!Array.isArray(e)?e:e.slice(-t)}function Uo(e,t){if(!T(e)&&!T(t))return{};const r=T(e)?e:{},n=st(r,T(t)?t:{});return T(r.panel)&&(n.panel=r.panel),n}function Fo(e,t,r){if(!T(t))return e;const n=st(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 st(e,t,r){if(!T(t))return e;const n=e,o=t,i=T(n.panel)?n.panel:{},a=T(o.panel)?o.panel:{},s=T(n.thread)?n.thread:{},c=T(o.thread)?o.thread:{},u=T(s.extensions)?s.extensions:{},l=T(c.extensions)?c.extensions:{},f=T(n.meta)?n.meta:{},g=T(o.meta)?o.meta:{};return{...e,...t,panel:{...i,...a},thread:{...s,...c,extensions:{...u,...l}},meta:{...f,...g},messages:Array.isArray(o.messages)?je(o.messages,r):e.messages??[]}}function pr(e){const t=String.fromCharCode(...e);return btoa(t).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")}function mr(e){return pr(new TextEncoder().encode(JSON.stringify(e)))}async function Do({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=`${mr({alg:"HS256",typ:"JWT"})}.${mr({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}.${pr(new Uint8Array(a))}`}function ct({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 Do({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 zo({accountId:e,tokenBrokerUrl:r,tokenBrokerAudience:n,parentUrl:c,signal:s,fetchImpl:i})),a.token}}async function zo({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:Go(s)||Vo(c)||Math.floor(Date.now()/1e3)+300}}function Go(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 Vo(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 gr={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."}},z=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 ut(e){const t=String(e?.code||"upstream_llm"),r=gr[t]||gr.upstream_llm;return new z(r.code,r.message,{source:"be",sourceCode:t,detail:e?.detail})}function yr(e,t){const r=t?.error&&typeof t.error=="object"?t.error:{};return ut({code:String(r.code||Ko(e)),detail:r.detail})}function hr(e){return e instanceof z?{type:"error",code:e.code,message:e.message}:{type:"error",code:"agent_invoke_failed",message:"The assistant could not complete that request."}}function Ko(e){return e===401?"unauthorized":e===403?"forbidden":e===413?"payload_too_large":e===429?"rate_limited":"internal"}var Ho=7200*1e3,br=200,Wo=5*1024*1024,Jo="gengage_request_response_cache",Zo=1,U="responses",Yo=new Set(["addToCart","like"]),F=new Map,wr=null;async function Qo(e,t={},r={}){const n=Xo(e,t);if(!n)return fetch(e,t);const o=Date.now(),i=await ti(n,o);if(i)return oi(i);const a=await fetch(e,t);return a.ok&&ri(n,a.clone(),o,{ttlMs:r.ttlMs??Ho,maxEntries:r.maxEntries??br,maxBodyBytes:r.maxBodyBytes??Wo}),a}function Xo(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"||ei(t.body)?null:`rr:${di(li({url:String(e),method:r,headers:ii(t.headers),body:t.body}))}`}function ei(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"&&Yo.has(r)}catch{return!1}}async function ti(e,t){const r=F.get(e);if(r)if(r.expiresAt<=t)F.delete(e);else return r.lastAccessedAt=t,F.delete(e),F.set(e,r),lt(r),r;const n=await si(e);return n?n.expiresAt<=t?(F.delete(e),ci(e),null):(n.lastAccessedAt=t,F.set(e,n),lt(n),kr(br),n):null}async function ri(e,t,r,n){try{const o=await t.text();if(fi(o)>n.maxBodyBytes||ni(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};F.set(e,i),kr(n.maxEntries),await lt(i),await ui(n.maxEntries,r)}catch{}}function ni(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function oi(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function ii(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 kr(e){for(;F.size>e;){const t=[...F.values()].sort((r,n)=>r.lastAccessedAt-n.lastAccessedAt)[0];if(!t)break;F.delete(t.key)}}async function Re(){return typeof indexedDB>"u"?null:(wr??=new Promise(e=>{const t=indexedDB.open(Jo,Zo);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)}),wr)}async function si(e){const t=await Re();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 lt(e){const t=await Re();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 ci(e){const t=await Re();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 ui(e,t){const r=await Re();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,g)=>f.lastAccessedAt-g.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 li(e){return JSON.stringify(dt(e))}function dt(e){return Array.isArray(e)?e.map(dt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,dt(r)]))}function di(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 fi(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:e.length}async function pi({beUrl:e,accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o,jwtProvider:i,parentUrl:a,op:s,input:c,cacheTtlS:u,cacheKey:l,browserCache:f,signal:g}){const p=await(i||ct({accountId:t,devJwtSecret:r,tokenBrokerUrl:n,tokenBrokerAudience:o}))({...g?{signal:g}:{},...a?{parentUrl:a}:{}}),{opDomain:y,opName:h}=mi(s,t),m={method:"POST",headers:{authorization:`Bearer ${p}`,"content-type":"application/json",accept:"application/x-ndjson"},body:JSON.stringify({op_domain:y,op_name:h,op_payload:c,...u!==void 0?{cache_ttl_s:u}:{},...l!==void 0?{cache_key:l}:{}}),...g?{signal:g}:{}},b=`${String(e).replace(/\/+$/u,"")}/v1/execute`,w=f===!1?await fetch(b,m):await Qo(b,m,typeof f=="object"?f:{});if(!w.ok)throw yr(w.status,await yi(w));return hi(w)}function mi(e,t){if(!e||e.startsWith("-")||e.endsWith("-"))throw new Error(`Invalid BE op name: ${e}`);return{opDomain:gi(t),opName:e}}function gi(e){return e.replace(/-agentic$/u,"")}async function yi(e){try{return await e.json()}catch{return{error:{code:e.statusText||"internal"}}}}async function hi(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
|
+
`);for(;c>=0;){const u=n.slice(0,c).trim();n=n.slice(c+1),u&&Sr(JSON.parse(u),o),c=n.indexOf(`
|
|
3
|
+
`)}}const i=n.trim();return i&&Sr(JSON.parse(i),o),o}function Sr(e,t){if(e._error)throw ut(e._error);if(!e._end)for(const[r,n]of Object.entries(e)){if(Object.prototype.hasOwnProperty.call(t,r))throw new z("op_failed",`BE streamed duplicate field "${r}".`,{source:"be",sourceCode:"schema_mismatch"});t[r]=n}}function bi(e={}){return{type:"metadata",...e}}function _r(e,t=!1,r={}){return{type:"text_chunk",content:e,final:t,...r}}function wi(e){return{type:"ui_spec",...e}}function ki(e){return{type:"action",action:e}}function vr(e,t){return{type:"error",code:e,message:t}}function ft(){return{type:"done"}}function Ar(e,t){return e[t?.type||t?.action?.type||"inputText"]||e.inputText}function xr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ie(e,t={}){const r=xr(e);if(!r)return null;const n=t.catalogMapper?.(r);if(n)return n;const o=ne(r.sku,r.SKU);if(!o)return null;const i={sku:o,name:ne(r.name,r.title,r.short_name,o)||o,url:ne(r.url)||""},a=Array.isArray(r.images)?r.images:void 0,s=ne(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=be(r.price_discounted),u=be(r.price),l=c||u;l>0&&(i.price=String(l));const f=c>0?u:0;f>0&&(i.originalPrice=String(f));const g=ne(r.brand);g&&(i.brand=g);const p=be(r.rating);p>0&&(i.rating=p);const y=be(r.review_count)||be(r.reviewCount);y>0&&(i.reviewCount=y);const h=ne(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 m=r.category_names;return Array.isArray(m)&&(i.categoryNames=m.map(String)),i}function Le(e){const t=xr(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 Si(e){return Array.isArray(e)?e.map(Le).filter(t=>!!t):[]}function ne(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function be(e){const t=Number(e);return Number.isFinite(t)?t:0}function Er(e){return Array.isArray(e)?e.map(String).filter(Boolean):typeof e=="string"&&e?[e]:[]}function pt(e,t,r={}){return`${e}:${r.version||"v2"}:${oe(t)}`}function _i(e,t={}){return Tr(e).map(r=>Cr(typeof r=="string"?r:r.sku,t.locale)).filter(Boolean).filter((r,n,o)=>o.indexOf(r)===n).sort((r,n)=>mt(r,n,t.locale)).slice(0,t.limit||16).join(",")}function vi(e,t={}){return oe(Tr(e).map(r=>xi(r,t)).filter(r=>!!r).sort((r,n)=>mt(String(r.sku||r.name||""),String(n.sku||n.name||""),t.locale)).slice(0,t.limit||16))}function Ai(e,t){return Y(e,t)}function oe(e){let t=2166136261;const r=Ei(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 xi(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=t.mapProduct?.(r);if(n)return we(n);const o=Le(r);return o&&typeof o=="object"&&!Array.isArray(o)?we(Ti(o,t)):null}function Tr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"||!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function Ei(e){return JSON.stringify(we(e))}function we(e){return Array.isArray(e)?e.map(we):!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,we(r)]))}function Ti(e,t){return{sku:Cr(e.sku,t.locale),name:Y(e.name,t.locale),url:Y(e.url,t.locale),price:e.price,currency:Y(e.currency,t.locale),category:Y(e.category,t.locale),category_names:Ci(e.category_names,t.locale,16),image:Y(e.image,t.locale),in_stock:e.in_stock,rating:e.rating,review_count:e.review_count}}function Cr(e,t){return Y(e,t).toUpperCase()}function Y(e,t){return typeof e=="string"?e.trim().replace(/\s+/gu," ").toLocaleLowerCase(t||void 0):""}function mt(e,t,r){return e.localeCompare(t,r,{numeric:!0})}function Ci(e,t,r){return Array.isArray(e)?e.map(n=>Y(n,t)).filter(Boolean).sort((n,o)=>mt(n,o,t)).slice(0,r):void 0}async function Pi({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=Qi(e);zi(u,f)&&r.appendUserMessage(l,f);const g=Ar(t.flows,e);if(!g)return i(vr("unknown_action",`No agent flow for request type ${e?.type||"inputText"}`)),i(ft()),{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:Yi(t.contextPersistence?.messageLimit),catalogMapper:t.catalogMapper,similarityMapper:t.similarityMapper},y={contextStore:r,beClient:n,toolBridge:o,emit:i,rpc:a,adapters:t.adapters||{},...s?{signal:s}:{},...t.trace?{trace:t.trace}:{}};await G(y,Se("turn:start",p));try{await ie(g,p,y),p.committed||await gt(p,y)}catch(h){throw await G(y,{...Se("turn:error",p),latencyMs:q(c),errorCode:kt(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 G(y,{...Se("turn:end",p),latencyMs:q(c)}),{steps:p.steps,productSkusEmitted:[...p.productSkusEmitted]}}async function ie(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 G(r,bt("step:start",t,n,o));try{await ji(n,t,r),await G(r,{...bt("step:end",t,n,o),latencyMs:q(i)})}catch(a){throw await G(r,{...bt("step:error",t,n,o),latencyMs:q(i),errorCode:kt(a)}),a}t.context=r.contextStore.patch(t.threadId,{})||t.context}}async function ji(e,t,r){const n=ae(t);if(e.kind==="be_op"){await Ri(e,t,r,n);return}if(e.kind==="tool"){await Oi(e,t,r,n);return}if(e.kind==="adapter"){await Bi(e,t,r,n);return}if(e.kind==="emit"){await Mi(e,t,r);return}if(e.kind==="patch"){await Ni(e,t,r);return}if(e.kind==="branch"){await $i(e,t,r,n);return}if(e.kind==="agent_loop"){await qi(e,t,r,n);return}if(e.kind==="parallel"){await Ui(e,t,r);return}if(e.kind==="refusal"){await Fi(e,t,r,n);return}e.kind==="commit"&&await Di(e,t,r)}async function Ri(e,t,r,n){const o=performance.now();let i;try{const s=await P(e.input,n),c=Ii(e,t,s,await P(e.cache,n)),u=await P(e.cacheTtlS,n)??c.cacheTtlS,l=await P(e.cacheKey,n)??c.cacheKey,f=await P(e.browserCache,n),g=ke(await P(e.timeoutMs,n));await ht(e,t,r,n);const p=g?new AbortController:null,y=Rr(r.signal,p?.signal);i=await Me(r.beClient.invoke({op:e.op,input:s,...u!==void 0?{cacheTtlS:u}:{},...l!==void 0?{cacheKey:l}:{},...f!==void 0?{browserCache:f}:{},...y?{signal:y}:{}}),g,()=>new z("op_timeout","The assistant took too long to respond.",{source:"be",sourceCode:"timeout"}),()=>p?.abort())}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 ie(e.onError,t,r);return}throw s}e.out&&(t.bag[e.out]=i),await Oe(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 Ii(e,t,r,n){if(!n||n.strategy!=="input-hash")return{};const o=ke(n.ttlS);if(!o)return{};const i=t.context.meta.locale,a=n.promptVersion||Li(r)||"current";return{cacheTtlS:o,cacheKey:pt(e.op,{account:t.context.meta.accountId,locale:i,promptVersion:a,payload:r},{version:"input-hash"})}}function Li(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 Oi(e,t,r,n){const o=performance.now();try{await ht(e,t,r,n);const i=ke(await P(e.timeoutMs,n)),a=await Me(r.toolBridge.invoke(e.name,await P(e.input,n)),i,()=>new z("tool_timeout","The assistant tool took too long to respond.",{source:"tool",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Oe(e,a,t,r.contextStore),await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Be(t),accountId:t.context.meta.accountId,tool:e.name,status:"ok",latencyMs:q(o)})}catch(i){const a=i;if(await r.rpc("beacon.send",{type:"agentTool",threadId:t.threadId,sessionId:Be(t),accountId:t.context.meta.accountId,tool:e.name,status:"error",latencyMs:q(o),errorCode:String(a?.code||a?.name||"unknown")}),e.onError){e.errorOut&&(t.bag[e.errorOut]=i),await ie(e.onError,t,r);return}throw i}}async function Bi(e,t,r,n){const o=r.adapters?.[e.name];if(typeof o!="function")throw new Error(`Unknown flow adapter: ${e.name}`);await ht(e,t,r,n);const i=ke(await P(e.timeoutMs,n)),a=await Me(o(await P(e.input,n),n),i,()=>new z("adapter_timeout","The assistant adapter took too long to respond.",{source:"adapter",sourceCode:"timeout"}));e.out&&(t.bag[e.out]=a),await Oe(e,a,t,r.contextStore)}async function Mi(e,t,r){const n=await e.build(ae(t));Xi(n,t.productSkusEmitted),r.emit(n)}async function Ni(e,t,r){await Oe(e,void 0,t,r.contextStore)}async function $i(e,t,r,n){const o=String(await P(e.on,n)||"default");await ie(e.cases[o]||e.cases.default||[],t,r)}async function qi(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 ie(e.body,t,r),r.signal?.aborted||t.committed||!await e.shouldContinue(t.bag,ae(t))||i>=o)return;const a=await e.onIterate?.(t.bag,ae(t));a&&typeof a=="object"&&Object.assign(t.bag,a),i+=1}}async function Ui(e,t,r){const n=ke(await P(e.timeoutMs,ae(t))),o=n?new AbortController:null,i=Rr(r.signal,o?.signal),a=e.steps.map(u=>{const l={...t,context:Gi(t.context),bag:yt(t.bag),productSkusEmitted:new Set(t.productSkusEmitted),committed:!1},f=[];return ie(u,l,{...r,emit:g=>{!i?.aborted&&g.type!=="done"&&f.push(g)},contextStore:Vi(l),...i?{signal:i}:{}}).then(()=>({state:l,events:f}))}),s=await Me(Promise.all(a),n,()=>new z("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=Pr(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=Pr(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 Fi(e,t,r,n){r.emit(_r(await P(e.message,n),!0)),await gt(t,r)}async function Di(e,t,r){await gt(t,r)}async function gt(e,{contextStore:t,emit:r}){e.committed||(e.context=await t.commit(e.threadId)||e.context,e.committed=!0,r(ft()))}async function Oe(e,t,r,n){if(typeof e.patch!="function")return;const o=await e.patch(r.context,t,ae(r));o&&(r.context=n.patch(r.threadId,o)||r.context)}function ae(e){return{request:e.request,context:e.context,bag:e.bag,accountConfig:e.accountConfig,catalogMapper:e.catalogMapper,similarityMapper:e.similarityMapper}}function Be(e){return e.request?.session_id||e.request?.sessionId||e.threadId}function zi(e,t){if(!t)return!1;const r=e.messages[e.messages.length-1];return r?.role!=="user"||r.content!==t}function Pr(e,t){const r={};for(const n of t)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function Gi(e){return{...e,panel:yt(e.panel||{}),thread:{...e.thread,extensions:yt(e.thread?.extensions||{})},meta:e.meta,messages:e.messages}}function Vi(e){return{async load(){return e.context},patch(t,r){return e.context=Ki(e.context,r,e.messageLimit),e.context},appendUserMessage(){return e.context},async commit(){return e.context}}}function Ki(e,t,r){if(!t||typeof t!="object")return e;const n=jr(e.panel,t.panel),o=jr(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)?je(t.messages,r):e.messages}}function jr(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 yt(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(Hi(o)){const i=Wi(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 Hi(e){return!!(e&&typeof e=="object")}function Wi(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}async function P(e,t){return typeof e=="function"?await e(t):e}function ke(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}async function Me(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 Rr(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 ht(e,t,r,n){if(!e.confirm)return;const o=await P(e.confirm,n);if(!o)return;const i=Ji(o,e,t);await G(r,wt("confirmation:start",t,e));try{const a=await r.rpc("confirmation.request",i),s=typeof a=="boolean"?a:a?.confirmed===!0;if(await G(r,wt("confirmation:end",t,e)),s)return;throw new z("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 G(r,{...wt("confirmation:error",t,e),errorCode:kt(a)}),a}}function Ji(e,t,r){return{...Zi(e),accountId:r.context.meta.accountId,threadId:r.threadId,sessionId:Be(r),stepKind:t.kind,...t.kind==="be_op"?{stepName:t.op}:{stepName:t.name}}}function Zi(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 G(e,t){try{await e.trace?.(t)}catch{}}function Se(e,t){return{type:e,accountId:t.context.meta.accountId,threadId:t.threadId,sessionId:Be(t)}}function bt(e,t,r,n){const o=Ir(r);return{...Se(e,t),stepIndex:n,stepKind:r.kind,...o?{stepName:o}:{}}}function wt(e,t,r){const n=Ir(r);return{...Se(e,t),stepKind:r.kind,...n?{stepName:n}:{}}}function Ir(e){if(e.kind==="be_op")return e.op;if(e.kind==="tool"||e.kind==="adapter")return e.name}function kt(e){if(e&&typeof e=="object"){const t=e;return String(t.sourceCode||t.code||t.name||"unknown")}return"unknown"}function Yi(e){if(e===void 0)return;const t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:void 0}function Qi(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 Xi(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 ea(e){return{invoke(t,r){return e("tool.invoke",{name:t,input:r})}}}var ta=512,ra=.74;function Lr({accountId:e,worker:t,beUrl:r,devJwtSecret:n,tokenBrokerUrl:o,tokenBrokerAudience:i,defaultLocale:a,tools:s={},beacon:c,confirmation:u,memory:l=et()}){let f=1;const g=new Map;return bo({worker:t,tools:s,beacon:p=>c?.({...p,accountId:p.accountId||e}),...u?{confirmation:u}:{},memory:l}),t.addEventListener("message",p=>{const y=p.data||{};if(y.type==="activity"&&y.entry){Or(y.entry);return}const h=typeof y.id=="number"?y.id:null;if(h==null)return;const m=g.get(h);if(m){if(y.type==="event"&&y.event){St(m,y.event);return}if(y.type==="error"){m.onError(new Error(y.message||"Agent worker failed")),g.delete(h);return}y.type==="end"&&g.delete(h)}}),(p,y,h,m)=>{const b=f++;g.set(b,y);const w=()=>{g.delete(b),t.postMessage({id:b,type:"abort"})},A=_=>{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:na()})};if(h.aborted){w();return}if(h.addEventListener("abort",w,{once:!0}),m){Mr(p,m).then(A).catch(_=>{g.delete(b),y.onError(_ instanceof Error?_:new Error("Failed to read image attachment"))});return}A(p)}}function Or(e){const t=window;(t.__GENGAGE_AGENTIC_DEBUG_RECORD__||t.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)?.(e)}function na(){const e=window;return typeof(e.__GENGAGE_AGENTIC_DEBUG_RECORD__||e.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__)=="function"}function Br({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 g=oa({accountId:e,tools:s,beacon:c,confirmation:u,memory:l??et()}),p=ea(g),y=ct({accountId:e,...n?{devJwtSecret:n}:{},...o?{tokenBrokerUrl:o}:{},...i?{tokenBrokerAudience:i}:{}});return async(h,m,b,w)=>{const A=await Mr(h||{},w);f||=new fr({accountId:e,locale:A?.locale||a,parentUrl:window.location.href,rpc:g,persistentPanelKeys:t.contextPersistence?.panelKeys,panelKeyLimits:t.contextPersistence?.panelKeyLimits,messageLimit:t.contextPersistence?.messageLimit,maxThreads:t.contextPersistence?.maxThreads,threadTtlMs:t.contextPersistence?.threadTtlMs});try{await Pi({request:A,accountModule:{...t,accountId:e,trace:async _=>{Or({kind:"flow/trace",event:_}),await t.trace?.(_)}},contextStore:f,beClient:{invoke({op:_,input:O,signal:v,cacheTtlS:M,cacheKey:J,browserCache:Ye}){return pi({beUrl:r,accountId:e,jwtProvider:y,parentUrl:window.location.href,op:_,input:O,cacheTtlS:M,cacheKey:J,browserCache:Ye,...v?{signal:v}:{}})}},toolBridge:p,emit:_=>St(m,_),rpc:g,signal:b})}catch(_){b?.aborted||(St(m,hr(_)),m.onDone())}}}function oa({accountId:e,tools:t,beacon:r,confirmation:n,memory:o}){const i=a=>r?.({...a,accountId:a.accountId||e});return((a,s)=>ur(a,s,{tools:t,beacon:i,confirmation:n,memory:o}))}async function Mr(e,t){if(!t||!t.type?.startsWith("image/"))return e;const r=await sa(t),n={...ia(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 ia(e){return aa(e)?{...e}:typeof e=="string"?{text:e}:{}}function aa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function sa(e){const t=await ca(e);return t||{dataUrl:await Nr(e),mime:e.type}}async function ca(e){if(typeof createImageBitmap!="function"||typeof document>"u")return null;let t=null;try{t=await createImageBitmap(e);const r=Math.min(1,ta/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",ra));return s?{dataUrl:await Nr(s),mime:s.type||"image/jpeg"}:null}catch{return null}finally{t?.close()}}async function Nr(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 St(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(ua(t));break;case"done":e.onDone();break;default:break}}function ua(e){const t=new Error(e.message||e.code||"Agent error");return e.code&&(t.code=e.code),t}var la="entries",da=1,fa={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."},$r=new Map;function _t(){return Date.now()}function se(e){return e?.expiresAt!=null&&e.expiresAt<=_t()}function vt(e,t){return{value:e,createdAt:_t(),expiresAt:t?_t()+t:null}}function pa(e,t,r){try{const n=e.getItem(`${t}${r}`);if(!n)return null;const o=JSON.parse(n);return se(o)?(e.removeItem(`${t}${r}`),null):o.value}catch{return null}}function ma(e,t,r,n,o){try{return e.setItem(`${t}${r}`,JSON.stringify(vt(n,o))),!0}catch{return!1}}function ga(e,t,r){try{e.removeItem(`${t}${r}`)}catch{}}function qr(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||se(i))&&(e.removeItem(o),r+=1)}catch{e.removeItem(o),r+=1}}catch{return r}return r}function Ur(e){try{return window[e]}catch{return null}}function Fr(e,t){return e?{get:r=>pa(e,t,r),set:(r,n,o={})=>ma(e,t,r,n,o.ttlMs),remove:r=>ga(e,t,r)}:{get:()=>null,set:()=>!1,remove:()=>{}}}function ya(e,t){const r=t.dbName||`gengage-${e}`,n=t.dbStore||la,o=t.dbVersion||da,i=new Map;let a=null;const s=()=>"indexedDB"in window?a||(a=new Promise(g=>{const p=indexedDB.open(r,o);p.onupgradeneeded=()=>{p.result.createObjectStore(n,{keyPath:"key"})},p.onsuccess=()=>g(p.result),p.onerror=()=>g(null),p.onblocked=()=>g(null)}),a):Promise.resolve(null);return{volatileEntries:i,idbGet:async g=>{const p=await s();return p?new Promise(y=>{const h=p.transaction(n,"readwrite").objectStore(n),m=h.get(g);m.onsuccess=()=>{const b=m.result;if(!b||se(b)){b&&h.delete(g),y(null);return}y(b.value)},m.onerror=()=>y(null)}):null},idbSet:async(g,p,y={})=>{const h=await s();return h?new Promise(m=>{const b=h.transaction(n,"readwrite");b.oncomplete=()=>m(!0),b.onerror=()=>m(!1),b.objectStore(n).put({key:g,...vt(p,y.ttlMs)})}):!1},idbRemove:async g=>{const p=await s();p&&p.transaction(n,"readwrite").objectStore(n).delete(g)},idbGc:async()=>{const g=await s();return g?new Promise(p=>{let y=0;const h=g.transaction(n,"readwrite"),m=h.objectStore(n).openCursor();m.onsuccess=()=>{const b=m.result;if(!b)return;const w=b.value;(!w||se(w))&&(b.delete(),y+=1),b.continue()},h.oncomplete=()=>p(y),h.onerror=()=>p(y),m.onerror=()=>p(y)}):0}}}function At(e,t={}){const r=window,n=r.gengage||(r.gengage={}),o=n.memory||(n.memory={}),i=o[e];if(i)return i;const a=$r.get(e)||ya(e,t);$r.set(e,a);const s=t.sessionPrefix||`gengage:${e}:session:`,c=t.localPrefix||`gengage:${e}:local:`,u=Ur("sessionStorage"),l=Ur("localStorage"),g={get:m=>{const b=a.volatileEntries.get(m);return b?se(b)?(a.volatileEntries.delete(m),null):b.value:null},set:(m,b,w={})=>(a.volatileEntries.set(m,vt(b,w.ttlMs)),!0),remove:m=>{a.volatileEntries.delete(m)},clear:()=>a.volatileEntries.clear()},p={get:a.idbGet,set:a.idbSet,remove:a.idbRemove},y=async()=>{let m=0;for(const[_,O]of a.volatileEntries)se(O)&&(a.volatileEntries.delete(_),m+=1);const b=qr(u,s),w=qr(l,c),A=await a.idbGc();return{volatile:m,session:b,local:w,indexedDb:A}},h={accountId:e,volatile:g,session:Fr(u,s),local:Fr(l,c),indexedDb:p,gc:y,stableKey:oe,policy:{...fa,...t.policy||{}}};o[e]=h;for(const m of t.aliases||[])o[m]=h;return ha(h),h}function ha(e){const t=window,r=()=>{e.gc().catch(()=>{})};if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(r);return}setTimeout(r,5e3)}var Ne="__gengageAgentFetchBridge",ba=1e3*60*60*24*14;function wa({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=ka(),i=`https://gengage-injector.invalid/${encodeURIComponent(e)}`,a=new Set,s=n?Ea({accountId:e,endpointCache:n,fetchImpl:o.originalFetch}):void 0,c=u=>{const l=`${i}/chat/${u}`;a.add(l);const f=r[u],g={streamTransport:t,endpoint:u};f&&(g.endpointHandler=f),s&&(g.endpointCache=s),o.routes.set(l,g)};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);Sa(o)}}}function ka(){const e=window,t=e[Ne];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=Dr(o),s=n.routes.get(a);return s?va(s,o,i):r(o,i)},e.fetch=n.installedFetch,e[Ne]=n,n}function Sa(e){if(e.routes.size>0)return;const t=window;t.fetch===e.installedFetch&&(t.fetch=e.originalFetch),t[Ne]===e&&delete t[Ne]}function Dr(e){return typeof e=="string"?e:e instanceof URL?e.href:e?.url||""}function zr(e,t){if(t?.signal)return t.signal;if(typeof Request<"u"&&e instanceof Request)return e.signal}function Gr(e,t){return t?.body!==void 0&&t?.body!==null?t.body:typeof Request<"u"&&e instanceof Request?e.clone().text():null}async function _a(e,t){const r=Gr(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 va(e,t,r){if(e.endpoint&&e.endpoint!=="process_action"&&e.endpointHandler){const u=new AbortController,l=zr(t,r);let f=null;if(l){const g=()=>u.abort();l.aborted&&g(),l.addEventListener("abort",g,{once:!0}),f=()=>l.removeEventListener("abort",g)}try{const g=await Aa(t,r),p={accountId:xa(t),endpoint:e.endpoint,signal:u.signal},y=Ta(e.endpointCache,e.endpoint,g,p.accountId);if(y){const m=await Ca(e.endpointCache,y,u.signal);if(m)return Oa(m)}const h=await e.endpointHandler(g,p);return y&&h.ok&&await Pa(e.endpointCache,y,h.clone(),u.signal),h}finally{f?.()}}const n=new TextEncoder,o=new AbortController,i=zr(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())},g=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:y}=await _a(t,r),h=e.streamTransport(p,{onTextChunk:(m,b,w={})=>l({type:"text_chunk",content:m,final:b===!0,...w}),onUISpec:(m,b,w,A)=>l({type:"ui_spec",spec:m,widget:b,...w?{panelHint:w}:{},...A?{clearPanel:!0}:{}}),onAction:m=>{l(m?.type==="action"?m:{type:"action",action:m})},onMetadata:m=>{l(m?.type==="metadata"?m:{type:"metadata",...m})},onError:g,onDone:()=>{l({type:"done"}),f()}},o.signal,y);$a(h)&&(await h,o.signal.aborted||(l({type:"done"}),f()))}catch(p){o.signal.aborted||g(p)}},cancel(){o.abort(),s?.(),a=!0}});return new Response(c,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}async function Aa(e,t){const r=await Promise.resolve(Gr(e,t));return typeof r!="string"||r.trim()===""?{}:JSON.parse(r)}function xa(e){try{const[t]=new URL(Dr(e)).pathname.split("/").filter(Boolean);return decodeURIComponent(t||"")}catch{return""}}function Ea({accountId:e,endpointCache:t,fetchImpl:r}){return{accountId:e,beUrl:t.beUrl,...t.parentUrl?{parentUrl:t.parentUrl}:{},ttlMs:t.ttlMs??ba,policies:t.policies,fetchImpl:r,jwtProvider:ct({accountId:e,...t.devJwtSecret?{devJwtSecret:t.devJwtSecret}:{},...t.tokenBrokerUrl?{tokenBrokerUrl:t.tokenBrokerUrl}:{},...t.tokenBrokerAudience?{tokenBrokerAudience:t.tokenBrokerAudience}:{},fetchImpl:r})}}function Ta(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 Ca(e,t,r){const n=Wr(e.accountId,t),o=await Ba(e.accountId,n);if(Hr(o))return o;const i=await ja(e,t,r);return i?(await Jr(e.accountId,n,i,t.ttlMs),i):null}async function Pa(e,t,r,n){try{const o=await La(r);if(Na(o.body))return;const i=Wr(e.accountId,t);await Jr(e.accountId,i,o,t.ttlMs),Ra(e,t,o,n)}catch{}}async function ja(e,t,r){try{const n=await e.fetchImpl(Kr(e.beUrl),{method:"POST",headers:await Vr(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&&Hr(o.payload)?o.payload:null}catch{return null}}async function Ra(e,t,r,n){try{await e.fetchImpl(Kr(e.beUrl),{method:"POST",headers:await Vr(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 Vr(e,t){return{authorization:`Bearer ${await e.jwtProvider({signal:t,parentUrl:e.parentUrl||Ia()})}`,"content-type":"application/json",accept:"application/json"}}function Ia(){try{return window.location?.href||""}catch{return""}}function Kr(e){return`${String(e).replace(/\/+$/u,"")}/v1/cache`}async function La(e){return{status:e.status,statusText:e.statusText,headers:[...e.headers.entries()].filter(([t])=>Ma(t)),body:await e.text()}}function Oa(e){return new Response(e.body,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}function Hr(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 Wr(e,t){return`endpoint-response:${oe({accountId:e,partition:t.partition,key:t.key})}`}async function Ba(e,t){const r=At(e);return r.volatile.get(t)||await r.indexedDb.get(t)||r.local.get(t)}async function Jr(e,t,r,n){const o=At(e);o.volatile.set(t,r,{ttlMs:n}),await o.indexedDb.set(t,r,{ttlMs:n})||o.local.set(t,r,{ttlMs:n})}function Ma(e){return["content-type","cache-control"].includes(e.toLowerCase())}function Na(e){return/"_error"\s*:/u.test(e)||/"type"\s*:\s*"error"/u.test(e)}function $a(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function qa({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:g=!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 y=window,h=y.GengageAssistantInjector||(y.GengageAssistantInjector={}),m=h[e]||(h[e]={});if(m.agentController)return m.agentController;const b=xt(i)||g?Zr(i,`gengage-${e}-agent`,{allowBlobWorker:g}):null;b||u?.({type:"agentRuntime",accountId:e,transport:"main-thread",reason:"cross-origin-worker-url",workerUrl:i}),m.streamTransport=b?Lr({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}:{}}):Br({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,A=[],_=()=>{for(;A.length;){const M=A.pop();try{M?.()}catch{}}},O=()=>{w.signal.aborted||(w.abort(),p?.removeEventListener("abort",O),delete m.streamTransport,b?.worker.terminate(),b?.cleanup(),_(),delete m.agentController)};p?.addEventListener("abort",O,{once:!0});const v={type:"agent",signal:w.signal,addCleanup(M){if(typeof M=="function"){if(w.signal.aborted){M();return}A.push(M)}},stop:O,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 m.agentController=v,v}function xt(e){const t=new URL(e,window.location.href);return t.origin===window.location.origin||t.protocol==="blob:"}function Zr(e,t,r={}){const n=new URL(e,window.location.href);if(xt(e))return{worker:new Worker(n.href,{type:"module",name:t}),cleanup(){}};if(!r.allowBlobWorker)throw new Error("Cross-origin agent workers require allowBlobWorker=true or a same-origin workerUrl.");const o=new Blob([`import ${JSON.stringify(n.href)};
|
|
5
|
+
`],{type:"text/javascript"}),i=URL.createObjectURL(o);try{return{worker:new Worker(i,{type:"module",name:t}),cleanup(){URL.revokeObjectURL(i)}}}catch(a){throw URL.revokeObjectURL(i),a}}function Ua(e,t={}){if(!Array.isArray(e))return[];const r=t.maxItems??8,n=t.maxFeatures??8;return e.map(o=>Fa(o,t.defaultBrand,n)).filter(o=>!!o).slice(0,r)}function Fa(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,o=Le(n);return o?Ga({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:Da(n.features,r),specs:za(n.specs,r),in_stock:o.in_stock}):null}function Da(e,t){return Array.isArray(e)?e.filter(Boolean).slice(0,t):void 0}function za(e,t){if(!(!e||typeof e!="object"||Array.isArray(e)))return Object.fromEntries(Object.entries(e).filter(([,r])=>r!=null).slice(0,t))}function Ga(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function Et(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(Ka).filter(Boolean)}}function Yr(e,t){const r=Array.isArray(e)?e.filter(s=>!!(s&&typeof s=="object"&&!Array.isArray(s))):[],n=Et(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 Va(e,t){const r=Et(e?.table),n=Yr(t,r);return{...e||{},table:r,products:n,multiple_product_details:n}}function Ka(e){return!e||typeof e!="object"||Array.isArray(e)?null:Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ha(e=[],t={}){const r={},n=[];return(Array.isArray(e)?e.map(o=>Ie(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 Wa(e,t={}){return{widget:"chat",panelHint:"panel",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:Ie(e,t)||e||{}}}}}}}function Ja(e={},t={}){const r=(e.multiple_product_details||e.products||[]).map(o=>Ie(o,t)).filter(o=>!!o),n=e.table||Za(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:Er(e.key_differences),specialCases:Er(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 Za(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 Ya(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 Qa(e){return Object.freeze([...e])}function Qr(e,t,r="v1"){return`endpoint:${r}:${oe({endpoint:e,request:t})}`}function Xa(e){const t=e.version||"v1",r=n=>o=>({partition:`${e.partitionPrefix}/${n}`,key:Qr(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 es(e){return{...e}}function ts(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 Xa(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}var ke=new Set(["and","are","for","from","the","with"]),es={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},ts=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function V(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 N(e,t=ke,r){const n=t instanceof Set?t:new Set([...ke,...t]),o=new Set,i=[];for(const a of V(e,r).split(/\s+/u))a.length<3||n.has(a)||o.has(a)||(o.add(a),i.push(a));return i}function ae(e,t={}){if(ss(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=cs(e.facet_hits),s=Object.entries(a).filter(([m])=>!n||n.some(b=>V(b,t.locale)===V(m,t.locale))).map(([,m])=>m),c=$(e.name,e.title),u=$(e.brand),l=t.sourceKeywords??[],f=[c,u,...o,...s,...j(e.promotions),$(e.description),...l].join(" "),g=N(f,t.stopWords,t.locale),p=$(t.sourceProductType,ds(o,c,g,t.locale),g[0]),y=H([...ls(f,ts,t.locale),...Object.entries(a).filter(([m])=>/colou?r/iu.test(m)).flatMap(([,m])=>N(m,t.stopWords,t.locale))],t.locale),h=H([...s.flatMap(m=>N(m,t.stopWords,t.locale)),...j(e.promotions).flatMap(m=>N(m,t.stopWords,t.locale))],t.locale).slice(0,24);return{sku:$(e.sku),title:c,brand:u,productType:p,categoryNames:o,categoryIds:i,facets:a,keywords:H([...l.flatMap(m=>N(m,t.stopWords,t.locale)),...g],t.locale).slice(0,12),tokens:g,colors:y,attributes:h,price:us(e)}}function rs(e,t={}){const r=$(e.product_type,e.productType),n=$(e.title,r,j(e.keywords).join(" ")),o=H([...j(e.keywords),...j(e.colors),...j(e.materials),...j(e.styles),...j(e.attributes)]);return ae({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 ns(e,t={}){const r=ae(e,t);return H([...t.sourceQueries??[],Ne([r.productType,...r.colors.slice(0,1),...r.attributes.slice(0,2)]),Ne([r.productType,...r.keywords.slice(0,3)]),Ne([r.categoryNames[r.categoryNames.length-1],...r.keywords.slice(0,2)]),Ne(r.title.split(/\s+/u).slice(0,6)),r.productType].map(n=>n.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function Et(e,t,r={}){const n={...es,...r.weights},o=ae(t,r),i=[],a=se(e.tokens,o.tokens,r.locale),s=se(e.keywords,o.tokens,r.locale),c=fs(e.categoryNames,o.categoryNames,r.locale)||se(Xr(e.categoryNames,r.locale),Xr(o.categoryNames,r.locale),r.locale),u=se(e.attributes,o.attributes,r.locale),l=se(e.colors,o.colors,r.locale),f=se(e.attributes,o.tokens,r.locale),g=ps(e.price,o.price),p=ms(o.sku,r.hitCounts)>0?1:0,y=gs(e,o),h=a*n.token+s*n.keyword+c*n.category+u*n.facet+l*n.color+f*n.attribute+g*n.price+p*n.retrieval,m=ys(y?h:h*.35);return y&&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"),g>.8&&i.push("similar price"),y||i.push("weaker product-type match"),{score:Number(m.toFixed(4)),reasons:i}}function os(e,t,r={}){const n=ae(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean));return Yr(t.filter(i=>{const a=$(i.sku);return a&&!o.has(a)}),r.maxCandidates).map(i=>{const a=Et(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 is(e,t,r={}){const n=ae(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean)),i=Yr(t.filter(c=>{const u=$(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){Qr(r.signal);const u=i[c],l=Et(n,u,r);s.push({...u,similarity_score:l.score,similarity_reasons:l.reasons}),(c+1)%a===0&&await as(r.yield)}return Qr(r.signal),s.sort((c,u)=>u.similarity_score-c.similarity_score).slice(0,Math.max(1,Math.min(r.limit??12,100)))}function Yr(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 as(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 Qr(e){if(e?.aborted)throw new DOMException("Similarity ranking aborted.","AbortError")}function ss(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function $(...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=>$(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function cs(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$(r)]).filter(([,t])=>t))}function us(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 H(e,t){const r=new Set,n=[];for(const o of e){const i=V(o,t);!i||r.has(i)||(r.add(i),n.push(i))}return n}function ls(e,t,r){const n=` ${V(e,r)} `;return t.filter(o=>n.includes(` ${V(o,r)} `))}function ds(e,t,r,n){const o=V(e[e.length-1]??e[0]??"",n);if(o){const i=N(o,ke,n),a=new Set(N(t,ke,n));return i.find(s=>a.has(s))??i[0]??o}return r[0]??""}function Ne(e){return e.map(t=>V(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function Xr(e,t){return e.flatMap(r=>N(r,ke,t))}function se(e,t,r){const n=H(e,r),o=new Set(H(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function fs(e,t,r){const n=H(e,r),o=new Set(H(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function ps(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 gs(e,t){if(!e.productType||!t.productType||e.productType===t.productType)return!0;const r=new Set(N(e.productType)),n=new Set([...N(t.productType),...t.tokens]);return[...r].some(o=>n.has(o))}function ys(e){return Math.max(0,Math.min(1,e))}function hs(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 bs(e,t){const r=hs(e);r?.style&&(t?r.style.removeProperty("display"):r.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var ws="nd_be_url";function ks(e,t){const r=Ss()||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 Ss(){try{const e=new URLSearchParams(window.location.search).get(ws)?.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 en(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 Ct=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:vs},{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]"}],Pt={patterns:Ct};function jt(e,t=Pt){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 tn(e,t=Pt){return jt(en(e),t)}function vs(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var _s=["assistantName","homeDomain","categories","policyTopics"],As={intent:["searchContract","competitorBrands"]};function xs(e,t,r,n={}){const o=rn(t,r,n);return Object.keys(o).length?{...e,account_config:o}:e}function rn(e,t,r={}){if(!e)return{};const n={},o=r.baseKeys||_s;for(const s of o)nn(n,e,s);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(n,Ts(i));const a=r.opAllowlist||As;for(const s of a[t]||[])nn(n,e,s);return n}function nn(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ts(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Es=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Cs(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||Es){const s=t[a];typeof s=="function"&&(i[a]=i[a]||s)}return t}function Ps({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function js({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 Rs({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||{},y=p[e]||{};return{...p,...y}},u=()=>{const p=c();if(p.runtimeUrl)return p.runtimeUrl;const y=p.assetBaseUrl||p.baseUrl||document.currentScript?.getAttribute("src")||(n?s[n]:null);if(!y)throw new Error(`${a} runtime URL cannot be resolved.`);return new URL(t,y).href},l=p=>{if(i===!0)return p;const y=new URL(p,window.location.href).origin,h=new Set([window.location.origin]),m=c();Se(h,document.currentScript?.getAttribute("src")),Se(h,m.assetBaseUrl),Se(h,m.baseUrl),Se(h,n?s[n]:void 0);for(const b of i||[])Se(h,b);if(!h.has(y))throw new Error(`${a} runtime origin ${y} is not trusted.`);return p},f=s.GengageAssistantInjector||(s.GengageAssistantInjector={}),g=f[e]||(f[e]={});return g.loaderPromise||(g.loaderPromise=import(l(u())).then(p=>{const y=p[r];if(typeof y!="function")throw new Error(`${a} runtime export ${r} is unavailable.`);return y()}).catch(p=>{throw delete g.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,p),p})),g.loaderPromise}function Se(e,t){if(t)try{const r=new URL(t,window.location.href);e.add(r.origin)}catch{e.add(t)}}var Ls=500,on="__GENGAGE_AGENTIC_ACTIVITY__";function an({accountId:e,clock:t=()=>Date.now()}={}){const r=new Set;let n=1;const o={accountId:e,entries:[]};function i(a){const s=cn({id:n++,at:t(),accountId:e,...a});o.entries.push(s),o.entries.length>Ls&&(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 sn(e){const t=window[on];if(t?.accountId===e&&typeof t.record=="function")return t;const r=an({accountId:e});return window[on]=r,r}function cn(e){const t=String(e.kind||e.type||"activity"),r=un(t);return{...e,kind:t,section:r,severity:e.severity||ln({...e,kind:t}),group:e.group||dn({...e,kind:t,section:r})}}function un(e){return e.startsWith("flow/")?"Flow":e.startsWith("intent/")?"Intent":e.startsWith("be/")?"Backend":e.startsWith("tool/")?"Tools":e==="beacon"?"Telemetry":"Runtime"}function ln(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 dn(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 Is=8,Rt=120;function fn(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)Os(r,n,o);return r.tools=Ot(r.tools).slice(-8),r.beOps=Ot(r.beOps).slice(-8),r.uiSurfaces=Ot(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 ve(e,t=""){if(!e||typeof e!="object")return null;const r=L({source:t,panel:$e(e.panel||e.panel_state),threadExtensions:Ds(e.thread?.extensions||e.threadExtensions||e.extensions),pageProduct:Gs(e.product||e.page?.product),products:Ue(e.products||e.last_search_products||e.items),ui:Lt(e.spec),intent:It(e.intent),route:Fe({searchParams:e.searchParams||e.search_params,flowParams:e.flowParams||e.flow_params})});return Object.keys(r).some(n=>n!=="source")?r:null}function $e(e){if(!e||typeof e!="object")return null;const t=Ue(e.last_search_products||e.current_panel_products),r=ce(e.screen_sku_list||e.search_suggestions_skus);return L({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:ce(e.chat_mentioned_skus),lastSearch:zs(e.last_search),productCount:t?.count??Bt(e.current_panel_product_count),productSkus:t?.skus})}function Lt(e,t="",r=""){if(!e||typeof e!="object")return null;const n=Vs(e);if(!n)return null;const o=n.props||{},i=n.type==="ProductDetailsPanel"?Ue([o.product||o.item].filter(Boolean)):Ue(o.products||o.items||o.cards),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?ce(a.map(c=>c.label||c.title)):void 0,comparisonRows:s})}function Os(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&&qe(t,r.state),r.kind){case"flow/request":Bs(e,t,r);break;case"flow/metadata":Ms(e,t,r);break;case"flow/ui":Ns(e,t,r);break;case"flow/text-final":t.lastText=k(r.content,Rt),R(e,r,"Text",t.lastText,"done");break;case"flow/done":e.status=e.status==="error"?"error":"done",e.current="Done",R(e,r,"Done","Flow completed","done");break;case"flow/error":case"flow/rejected":case"flow/thrown":e.status="error",e.current="Flow error",R(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"),R(e,r,"Tool",r.tool||"tool","running");break;case"tool/done":e.tools.push(r.tool||"tool"),R(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"),R(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"),$s(t,r),R(e,r,"BE",r.op||"request","running");break;case"be/response":e.beOps.push(r.op||r.result?.op||"unknown"),qs(t,r.result),R(e,r,"BE",r.op||r.result?.intent?.kind||"response",r.severity||"done");break;case"intent/selected":t.intent=It(r.intent),t.route=Fe({searchParams:r.searchParams,flowParams:r.flowParams}),e.current=`Intent: ${t.intent?.kind||"selected"}`,R(e,r,"Intent",t.intent?.kind||"selected","done");break;default:r.kind?.startsWith?.("runtime/")&&R(e,r,"Runtime",r.title||r.kind,"done");break}}function Bs(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",qe(t,ve(n.context||{},"request.context")),R(e,r,"Request",[e.requestType,e.actionType].filter(Boolean).join(" / ")||"request","running")}function Ms(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"),qe(t,ve(n,"flow.metadata")),R(e,r,"Metadata",k(n.name||n.phase||n.type||"metadata"),r.severity)}function Ns(e,t,r){const n=Lt(r.spec,r.widget,r.panelHint);n&&(t.ui=n,t.products=n.productCount?{count:n.productCount,skus:n.productSkus||[]}:t.products,e.uiSurfaces.push(n.rootType),e.current=`UI: ${n.rootType}`,R(e,r,"UI",n.rootType||"ui","done"))}function $s(e,t){const r=t.params||{};qe(e,ve(r,"be.params")),r.panel_state&&(e.panel=$e(r.panel_state)),r.structured_context&&(e.panel=pn(e.panel,$e(r.structured_context)));const n=Fe({searchParams:r.search_params,flowParams:r.flow_params});n&&(e.route=n)}function qs(e,t){if(!t||typeof t!="object")return;t.intent&&(e.intent=It(t.intent));const r=Fe({searchParams:t.search_params,flowParams:t.flow_params});r&&(e.route=r)}function qe(e,t){!t||typeof t!="object"||(t.panel&&(e.panel=pn(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 pn(e,t){return e?t?L({...e,...t}):e:t||null}function R(e,t,r,n,o="done"){e.timeline.push(L({id:t.id,at:t.at,label:r,detail:k(n,Rt),status:o==="info"?"done":o,kind:t.kind}))}function It(e){return!e||typeof e!="object"?null:L({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 Fe({searchParams:e,flowParams:t}={}){const r=L({search:Fs(e),flow:Us(t)});return Object.keys(r).length?r:null}function Fs(e){return!e||typeof e!="object"?null:L({query:k(e.query||e.search_query),category:k(e.category||e.category_name||e.categoryName),categoryId:k(e.categoryId||e.category_id),limit:Bt(e.limit),facets:Array.isArray(e.facets)?e.facets.length:void 0})}function Us(e){return!e||typeof e!="object"?null:L({target:k(e.target),sku:k(e.sku||e.product_sku),skus:ce(e.skus||e.sku_list),action:k(e.action||e.action_type)})}function Ds(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:k(n.summary||n.occasion||n.target_date_iso||n.type)}):k(n));return t}function zs(e){return!e||typeof e!="object"?null:L({query:k(e.query),source:k(e.source),category:k(e.category||e.category_name),count:Bt(e.count)})}function Ue(e){if(!Array.isArray(e))return null;const t=e.filter(Boolean);return L({count:t.length,skus:ce(t.map(r=>r?.sku||r?.code||r?.id)),names:ce(t.map(r=>r?.name||r?.title),4)})}function Gs(e){return!e||typeof e!="object"?null:L({sku:k(e.sku||e.code||e.id),name:k(e.name||e.title),category:k(e.category),url:k(e.url)})}function Vs(e){const t=e.elements||{};return t[e.root||"root"]||t.root||e.rootElement||null}function ce(e,t=Is){if(!Array.isArray(e))return;const r=e.map(n=>k(n)).filter(Boolean);return r.length?r.slice(0,t):void 0}function Ot(e){return[...new Set(e.map(t=>k(t)).filter(Boolean))]}function Bt(e){return Number.isFinite(Number(e))?Number(e):void 0}function k(e,t=Rt){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 mn(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:tc(c),state:ve(c,`tool:${n}`)}),c}catch(c){throw t.record({kind:"tool/error",tool:n,params:a,error:ue(c)}),c}},Object.defineProperty(r[n],"__gengageActivityWrapped",{value:!0}));return r}function gn(e,t){return t?r=>(t.record({kind:"beacon",payload:r}),e?.(r)):e}function yn(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,Hs(s,t),c,u);return l&&typeof l.then=="function"?l.catch(f=>{throw t.record({kind:"flow/rejected",requestType:a?.type,error:ue(f)}),f}):l}catch(l){throw t.record({kind:"flow/thrown",requestType:a?.type,error:ue(l)}),l}};return Object.defineProperty(o,"__gengageActivityWrapped",{value:!0}),r.streamTransport=o,t.record({kind:"runtime/transport-wrapped",title:"streamTransport wrapped"}),!0}function hn({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=Ys(o,i),s=Xs(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 Ks({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=ec(l);t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,result:f,rawText:l}),wn(t,f)}).catch(l=>{t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,error:ue(l)})}),u})}function Hs(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:ue(o[0])}):n==="onDone"&&t.record({kind:"flow/done"}),e[n](...o)));return r}function bn(e,t){!e||!t||(e.record(t),t.kind==="be/response"&&wn(e,t.result))}async function Ks({accountId:e,opName:t,promptBaseUrl:r}){if(!e||!t)return null;const n=Ws({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:ue(o)}}}function Ws({accountId:e,baseId:t,promptBaseUrl:r}){if(typeof r=="string"&&r.trim())return r;const n=Js(e,t);return n||Zs(t)}function Js(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 Zs(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 wn(e,t){const r=t?.intent;r&&e.record({kind:"intent/selected",intent:r,searchParams:t?.search_params,flowParams:t?.flow_params})}function Ys(e,t){const r=typeof e=="string"?e:e?.url||"",n=t?.body||(typeof e!="string"?e?.body:null);return{url:String(r||""),body:Qs(n)}}function Qs(e){if(!e||typeof e!="string")return{};try{return JSON.parse(e)}catch{return{raw:e}}}function Xs(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 ec(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
|
-
`)}}return t}function tc(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 ue(e){return e?.message||String(e)}var kn="gengage-agentic-activity-overlay",_e="all",Mt="all",Sn=["Flow","Tools","Backend","Intent","Telemetry","Runtime"],vn=["info","warn","error"];function _n(e){if(!e||typeof e.subscribe!="function")return null;const t=document.getElementById(kn);if(t?.shadowRoot)return t;const r=document.createElement("div");r.id=kn,r.style.cssText="position:fixed;left:10px;top:10px;z-index:2147483647;";const n=r.attachShadow({mode:"open"});n.innerHTML=Ac(e.accountId),document.documentElement.appendChild(r);const o={entries:[],section:_e,severity:Mt,search:"",grouped:!0,follow:!0,stateVisible:!0},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"]')};rc(r,i.list);const a=()=>oc(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()}),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);Sc(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=nc(r.composedPath?.()||[],t);n&&(n.scrollTop+=r.deltaY,n.scrollLeft+=r.deltaX,r.preventDefault(),r.stopPropagation())},{passive:!1,capture:!0})}function nc(e,t){for(const r of e)if(!(!r||r.nodeType!==1)&&An(r))return r;return An(t)?t:null}function An(e){return!!(e&&(e.scrollHeight>e.clientHeight+1||e.scrollWidth>e.clientWidth+1)&&getComputedStyle(e).overflow!=="hidden")}function oc(e,t){const r=xn(t.entries,t),n=r.slice(-260);Tn(e.sections,t.entries,t.section,"section"),Tn(e.severities,t.entries,t.severity,"severity"),e.count&&(e.count.textContent=String(t.entries.length)),e.visibleCount&&(e.visibleCount.textContent=String(r.length)),cc(e.stateView,fn(t.entries),t.stateVisible),sc(e.list,n,t)}function xn(e,t={}){const r=t.section||_e,n=t.severity||Mt,o=Rn(t.search);return(Array.isArray(e)?e:[]).filter(i=>r!==_e&&i.section!==r||n!==Mt&&i.severity!==n?!1:o?_c(i).includes(o):!0)}function Tn(e,t,r,n){if(!e)return;e.textContent="";const o=n==="section"?ic(t):ac(t),i=document.createElement("button");i.type="button",i.dataset[`${n}Filter`]=_e,i.className=r===_e?"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}-${le(a)}`:`chip ${n}-${le(a)}`,c.textContent=`${On(a)} ${s}`,e.appendChild(c)}}function ic(e){const t=new Set(e.map(r=>r.section).filter(Boolean));return Sn.filter(r=>t.has(r)).concat([...t].filter(r=>!Sn.includes(r)).sort())}function ac(e){const t=new Set(e.map(r=>r.severity).filter(Boolean));return vn.filter(r=>t.has(r)).concat([...t].filter(r=>!vn.includes(r)).sort())}function sc(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 wc(t))n.appendChild(kc(o));else for(const o of t)n.appendChild(Cn(o));e.appendChild(n),r.follow&&requestAnimationFrame(()=>e.scrollTop=e.scrollHeight)}function cc(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(uc(n)),i.appendChild(lc(o)),i.appendChild(dc(n.timeline)),e.appendChild(i)}function uc(e){const t=document.createElement("section");return t.className=`viz-card flow-card status-${le(e.status)}`,t.appendChild(Nt("Flow State",e.status)),En(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",fc(e)]]),t}function lc(e){const t=document.createElement("section");return t.className="viz-card context-card",t.appendChild(Nt("Context State",e.panel?.screenType||e.ui?.rootType||"empty")),En(t,[["Intent",pc(e.intent)],["Route",mc(e.route)],["Screen",gc(e)],["Last search",yc(e.panel?.lastSearch)],["Products",hc(e.panel,e.products)],["Page product",bc(e.pageProduct)],["Extensions",Object.keys(e.threadExtensions||{}).join(", ")],["Last text",e.lastText]]),t}function dc(e){const t=document.createElement("section");t.className="viz-card timeline-card",t.appendChild(Nt("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-${le(n.status||"done")}`;const i=document.createElement("span");i.className="timeline-time",i.textContent=In(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 Nt(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 En(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 fc(e){return!e.errors&&!e.warnings?"clean":`${e.errors||0} errors, ${e.warnings||0} warnings`}function pc(e){return e?[e.kind,e.target,e.confidence!=null?`conf ${e.confidence}`:""].filter(Boolean).join(" / "):""}function mc(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 gc(e){const t=e.panel||{},r=e.ui||{};return[t.screenType,r.rootType,r.widget,r.panelHint].filter(Boolean).join(" / ")}function yc(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 bc(e){return e?[e.sku,e.name,e.category].filter(Boolean).join(" / "):""}function wc(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=vc(o.severity,r.severity),t.set(n,o)}return[...t.values()]}function kc(e){const t=document.createElement("section");t.className=`group group-${le(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(Cn(a));return t}function Cn(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-${le(e.severity||"info")}`,t.open=e.severity==="error";const r=document.createElement("summary"),n=document.createElement("span");n.className="time",n.textContent=In(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=On(e.severity||"info");const a=document.createElement("span");a.className="title",a.textContent=Ln(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 g=document.createElement("pre"),p=document.createElement("code");return p.innerHTML=Pn(e),g.appendChild(p),s.append(c,g),t.append(r,s),t}function Pn(e){const t=$t(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+=De(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}">${De(a)}</span>`,o=i.index+a.length}return n+De(t.slice(o))}function Sc(e,t){if(!e)return;const r=$t(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(()=>jn(r,n));return}jn(r,n)}function jn(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 vc(e,t){const r={info:0,warn:1,error:2};return(r[t]||0)>(r[e]||0)?t:e}function _c(e){return Rn([e.kind,e.section,e.severity,e.group,Ln(e),e.tool,e.op,e.request?.type,e.request?.action?.type,e.event?.name,e.event?.action,e.event?.type,$t(e)].join(" "))}function Rn(e){return String(e||"").toLocaleLowerCase("tr-TR").trim()}function Ln(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 Ac(e){return`
|
|
7
|
+
`,{...t,headers:{"content-type":"application/x-ndjson",...t.headers||{}}})}function rs(e,t={}){return new Response(JSON.stringify(e),{...t,headers:{"content-type":"application/json",...t.headers||{}}})}var _e=new Set(["and","are","for","from","the","with"]),ns={token:.26,keyword:.22,category:.18,facet:.16,color:.08,attribute:.06,price:.08,retrieval:.08},os=["amber","beige","black","blue","blush","bronze","brown","cream","gold","green","grey","ivory","lilac","mixed","orange","pastel","pink","purple","red","silver","white","yellow"];function V(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 N(e,t=_e,r){const n=t instanceof Set?t:new Set([..._e,...t]),o=new Set,i=[];for(const a of V(e,r).split(/\s+/u))a.length<3||n.has(a)||o.has(a)||(o.add(a),i.push(a));return i}function ce(e,t={}){if(ls(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=ds(e.facet_hits),s=Object.entries(a).filter(([m])=>!n||n.some(b=>V(b,t.locale)===V(m,t.locale))).map(([,m])=>m),c=$(e.name,e.title),u=$(e.brand),l=t.sourceKeywords??[],f=[c,u,...o,...s,...j(e.promotions),$(e.description),...l].join(" "),g=N(f,t.stopWords,t.locale),p=$(t.sourceProductType,ms(o,c,g,t.locale),g[0]),y=K([...ps(f,os,t.locale),...Object.entries(a).filter(([m])=>/colou?r/iu.test(m)).flatMap(([,m])=>N(m,t.stopWords,t.locale))],t.locale),h=K([...s.flatMap(m=>N(m,t.stopWords,t.locale)),...j(e.promotions).flatMap(m=>N(m,t.stopWords,t.locale))],t.locale).slice(0,24);return{sku:$(e.sku),title:c,brand:u,productType:p,categoryNames:o,categoryIds:i,facets:a,keywords:K([...l.flatMap(m=>N(m,t.stopWords,t.locale)),...g],t.locale).slice(0,12),tokens:g,colors:y,attributes:h,price:fs(e)}}function is(e,t={}){const r=$(e.product_type,e.productType),n=$(e.title,r,j(e.keywords).join(" ")),o=K([...j(e.keywords),...j(e.colors),...j(e.materials),...j(e.styles),...j(e.attributes)]);return ce({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 as(e,t={}){const r=ce(e,t);return K([...t.sourceQueries??[],$e([r.productType,...r.colors.slice(0,1),...r.attributes.slice(0,2)]),$e([r.productType,...r.keywords.slice(0,3)]),$e([r.categoryNames[r.categoryNames.length-1],...r.keywords.slice(0,2)]),$e(r.title.split(/\s+/u).slice(0,6)),r.productType].map(n=>n.trim()).filter(Boolean)).slice(0,t.queryLimit??6)}function Tt(e,t,r={}){const n={...ns,...r.weights},o=ce(t,r),i=[],a=ue(e.tokens,o.tokens,r.locale),s=ue(e.keywords,o.tokens,r.locale),c=gs(e.categoryNames,o.categoryNames,r.locale)||ue(tn(e.categoryNames,r.locale),tn(o.categoryNames,r.locale),r.locale),u=ue(e.attributes,o.attributes,r.locale),l=ue(e.colors,o.colors,r.locale),f=ue(e.attributes,o.tokens,r.locale),g=ys(e.price,o.price),p=hs(o.sku,r.hitCounts)>0?1:0,y=bs(e,o),h=a*n.token+s*n.keyword+c*n.category+u*n.facet+l*n.color+f*n.attribute+g*n.price+p*n.retrieval,m=ws(y?h:h*.35);return y&&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"),g>.8&&i.push("similar price"),y||i.push("weaker product-type match"),{score:Number(m.toFixed(4)),reasons:i}}function ss(e,t,r={}){const n=ce(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean));return Xr(t.filter(i=>{const a=$(i.sku);return a&&!o.has(a)}),r.maxCandidates).map(i=>{const a=Tt(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 cs(e,t,r={}){const n=ce(e,r),o=new Set([n.sku,...r.ignoreSkus??[]].filter(Boolean)),i=Xr(t.filter(c=>{const u=$(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){en(r.signal);const u=i[c],l=Tt(n,u,r);s.push({...u,similarity_score:l.score,similarity_reasons:l.reasons}),(c+1)%a===0&&await us(r.yield)}return en(r.signal),s.sort((c,u)=>u.similarity_score-c.similarity_score).slice(0,Math.max(1,Math.min(r.limit??12,100)))}function Xr(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 us(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 en(e){if(e?.aborted)throw new DOMException("Similarity ranking aborted.","AbortError")}function ls(e){return!!(e&&typeof e=="object"&&Array.isArray(e.tokens))}function $(...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=>$(t)).filter(Boolean):typeof e=="string"&&e.trim()?e.split(/[,;/|]+/u).map(t=>t.trim()).filter(Boolean):[]}function ds(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$(r)]).filter(([,t])=>t))}function fs(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 K(e,t){const r=new Set,n=[];for(const o of e){const i=V(o,t);!i||r.has(i)||(r.add(i),n.push(i))}return n}function ps(e,t,r){const n=` ${V(e,r)} `;return t.filter(o=>n.includes(` ${V(o,r)} `))}function ms(e,t,r,n){const o=V(e[e.length-1]??e[0]??"",n);if(o){const i=N(o,_e,n),a=new Set(N(t,_e,n));return i.find(s=>a.has(s))??i[0]??o}return r[0]??""}function $e(e){return e.map(t=>V(t)).filter(Boolean).join(" ").replace(/\s+/gu," ").trim().slice(0,120)}function tn(e,t){return e.flatMap(r=>N(r,_e,t))}function ue(e,t,r){const n=K(e,r),o=new Set(K(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function gs(e,t,r){const n=K(e,r),o=new Set(K(t,r));return n.length===0||o.size===0?0:n.filter(i=>o.has(i)).length/n.length}function ys(e,t){return e<=0||t<=0?0:Math.min(e,t)/Math.max(e,t)}function hs(e,t){return!e||!t?0:typeof t.get=="function"?t.get(e)??0:t[e]??0}function bs(e,t){if(!e.productType||!t.productType||e.productType===t.productType)return!0;const r=new Set(N(e.productType)),n=new Set([...N(t.productType),...t.tokens]);return[...r].some(o=>n.has(o))}function ws(e){return Math.max(0,Math.min(1,e))}function ks(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 Ss(e,t){const r=ks(e);r?.style&&(t?r.style.removeProperty("display"):r.style.setProperty("display","none","important")),t||(e?.chat||e?._chat)?.close?.()}var _s="nd_be_url";function vs(e,t){const r=As()||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 As(){try{const e=new URLSearchParams(window.location.search).get(_s)?.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 rn(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 Ct=[{pattern:/\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,replacement:xs},{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]"}],Pt={patterns:Ct};function jt(e,t=Pt){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 nn(e,t=Pt){return jt(rn(e),t)}function xs(e){try{const t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?[query]":""}`}catch{return"[url]"}}var Es=["assistantName","homeDomain","categories","policyTopics"],Ts={intent:["searchContract","competitorBrands"]};function Cs(e,t,r,n={}){const o=on(t,r,n);return Object.keys(o).length?{...e,account_config:o}:e}function on(e,t,r={}){if(!e)return{};const n={},o=r.baseKeys||Es;for(const s of o)an(n,e,s);const i=e[t];i&&typeof i=="object"&&!Array.isArray(i)&&Object.assign(n,Ps(i));const a=r.opAllowlist||Ts;for(const s of a[t]||[])an(n,e,s);return n}function an(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ps(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var js=["addToCart","search","searchKeyword","facetedSearch","searchGiftOptions","similaritySearch"];function Rs(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 Is({getPageType:e,getProduct:t}){return()=>({url:window.location.href,title:document.title,pageType:e(),product:t()})}function Ls({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 Os({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||{},y=p[e]||{};return{...p,...y}},u=()=>{const p=c();if(p.runtimeUrl)return p.runtimeUrl;const y=p.assetBaseUrl||p.baseUrl||document.currentScript?.getAttribute("src")||(n?s[n]:null);if(!y)throw new Error(`${a} runtime URL cannot be resolved.`);return new URL(t,y).href},l=p=>{if(i===!0)return p;const y=new URL(p,window.location.href).origin,h=new Set([window.location.origin]),m=c();ve(h,document.currentScript?.getAttribute("src")),ve(h,m.assetBaseUrl),ve(h,m.baseUrl),ve(h,n?s[n]:void 0);for(const b of i||[])ve(h,b);if(!h.has(y))throw new Error(`${a} runtime origin ${y} is not trusted.`);return p},f=s.GengageAssistantInjector||(s.GengageAssistantInjector={}),g=f[e]||(f[e]={});return g.loaderPromise||(g.loaderPromise=import(l(u())).then(p=>{const y=p[r];if(typeof y!="function")throw new Error(`${a} runtime export ${r} is unavailable.`);return y()}).catch(p=>{throw delete g.loaderPromise,console.error(`[Gengage][${e}] runtime load failed`,p),p})),g.loaderPromise}function ve(e,t){if(t)try{const r=new URL(t,window.location.href);e.add(r.origin)}catch{e.add(t)}}var Bs=500,sn="__GENGAGE_AGENTIC_ACTIVITY__";function cn({accountId:e,clock:t=()=>Date.now()}={}){const r=new Set;let n=1;const o={accountId:e,entries:[]};function i(a){const s=ln({id:n++,at:t(),accountId:e,...a});o.entries.push(s),o.entries.length>Bs&&(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 un(e){const t=window[sn];if(t?.accountId===e&&typeof t.record=="function")return t;const r=cn({accountId:e});return window[sn]=r,r}function ln(e){const t=String(e.kind||e.type||"activity"),r=dn(t);return{...e,kind:t,section:r,severity:e.severity||fn({...e,kind:t}),group:e.group||pn({...e,kind:t,section:r})}}function dn(e){return e.startsWith("flow/")?"Flow":e.startsWith("intent/")?"Intent":e.startsWith("be/")?"Backend":e.startsWith("tool/")?"Tools":e==="beacon"?"Telemetry":"Runtime"}function fn(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 pn(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 Ms=8,Rt=120;function mn(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)Ns(r,n,o);return r.tools=Ot(r.tools).slice(-8),r.beOps=Ot(r.beOps).slice(-8),r.uiSurfaces=Ot(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 Ae(e,t=""){if(!e||typeof e!="object")return null;const r=I({source:t,panel:qe(e.panel||e.panel_state),threadExtensions:Ks(e.thread?.extensions||e.threadExtensions||e.extensions),pageProduct:Ys(e.product||e.page?.product),products:le(e.products||e.last_search_products||e.items),ui:It(e.spec),intent:Lt(e.intent),route:Fe({searchParams:e.searchParams||e.search_params,flowParams:e.flowParams||e.flow_params})});return Object.keys(r).some(n=>n!=="source")?r:null}function qe(e){if(!e||typeof e!="object")return null;const t=le(e.last_search_products||e.current_panel_products),r=de(e.screen_sku_list||e.search_suggestions_skus);return I({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:de(e.chat_mentioned_skus),lastSearch:Hs(e.last_search),productCount:t?.count??Bt(e.current_panel_product_count),productSkus:t?.skus})}function It(e,t="",r=""){if(!e||typeof e!="object")return null;const n=Qs(e);if(!n)return null;const o=n.props||{},i=Ws(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 I({widget:t,panelHint:r,rootType:n.type,productCount:i?.count,productSkus:i?.skus,buttonCount:a.length||void 0,buttonLabels:a.length?de(a.map(c=>c.label||c.title)):void 0,comparisonRows:s})}function Ns(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&&Ue(t,r.state),r.kind){case"flow/request":$s(e,t,r);break;case"flow/metadata":qs(e,t,r);break;case"flow/trace":Fs(e,r);break;case"flow/ui":Us(e,t,r);break;case"flow/text-final":t.lastText=k(r.content,Rt),R(e,r,"Text",t.lastText,"done");break;case"flow/done":e.status=e.status==="error"?"error":"done",e.current="Done",R(e,r,"Done","Flow completed","done");break;case"flow/error":case"flow/rejected":case"flow/thrown":e.status="error",e.current="Flow error",R(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"),R(e,r,"Tool",r.tool||"tool","running");break;case"tool/done":e.tools.push(r.tool||"tool"),R(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"),R(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"),Ds(t,r),R(e,r,"BE",r.op||"request","running");break;case"be/response":e.beOps.push(r.op||r.result?.op||"unknown"),zs(t,r.result),R(e,r,"BE",r.op||r.result?.intent?.kind||"response",r.severity||"done");break;case"intent/selected":t.intent=Lt(r.intent),t.route=Fe({searchParams:r.searchParams,flowParams:r.flowParams}),e.current=`Intent: ${t.intent?.kind||"selected"}`,R(e,r,"Intent",t.intent?.kind||"selected","done");break;default:r.kind?.startsWith?.("runtime/")&&R(e,r,"Runtime",r.title||r.kind,"done");break}}function $s(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",Ue(t,Ae(n.context||{},"request.context")),R(e,r,"Request",[e.requestType,e.actionType].filter(Boolean).join(" / ")||"request","running")}function qs(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"),Ue(t,Ae(n,"flow.metadata")),R(e,r,"Metadata",k(n.name||n.phase||n.type||"metadata"),r.severity)}function Us(e,t,r){const n=It(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}`,R(e,r,"UI",n.rootType||"ui","done"))}function Fs(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,R(e,t,"Trace",[n,o].filter(Boolean).join(" / ")||"trace",Xs(n))}function Ds(e,t){const r=t.params||{};Ue(e,Ae(r,"be.params")),r.panel_state&&(e.panel=qe(r.panel_state)),r.structured_context&&(e.panel=gn(e.panel,qe(r.structured_context)));const n=Fe({searchParams:r.search_params,flowParams:r.flow_params});n&&(e.route=n)}function zs(e,t){if(!t||typeof t!="object")return;t.intent&&(e.intent=Lt(t.intent));const r=Fe({searchParams:t.search_params,flowParams:t.flow_params});r&&(e.route=r)}function Ue(e,t){!t||typeof t!="object"||(t.panel&&(e.panel=gn(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 gn(e,t){return e?t?I({...e,...t}):e:t||null}function R(e,t,r,n,o="done"){e.timeline.push(I({id:t.id,at:t.at,label:r,detail:k(n,Rt),status:o==="info"?"done":o,kind:t.kind}))}function Lt(e){return!e||typeof e!="object"?null:I({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 Fe({searchParams:e,flowParams:t}={}){const r=I({search:Gs(e),flow:Vs(t)});return Object.keys(r).length?r:null}function Gs(e){return!e||typeof e!="object"?null:I({query:k(e.query||e.search_query),category:k(e.category||e.category_name||e.categoryName),categoryId:k(e.categoryId||e.category_id),limit:Bt(e.limit),facets:Array.isArray(e.facets)?e.facets.length:void 0})}function Vs(e){return!e||typeof e!="object"?null:I({target:k(e.target),sku:k(e.sku||e.product_sku),skus:de(e.skus||e.sku_list),action:k(e.action||e.action_type)})}function Ks(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"?I({keys:Object.keys(n).slice(0,8),summary:k(n.summary||n.occasion||n.target_date_iso||n.type)}):k(n));return t}function Hs(e){return!e||typeof e!="object"?null:I({query:k(e.query),source:k(e.source),category:k(e.category||e.category_name),count:Bt(e.count)})}function le(e){if(!Array.isArray(e))return null;const t=e.filter(Boolean);return I({count:t.length,skus:de(t.map(r=>r?.sku||r?.code||r?.id)),names:de(t.map(r=>r?.name||r?.title),4)})}function Ws(e,t,r){if(t.type==="ProductDetailsPanel")return le([r.product||r.item].filter(Boolean));if(t.type==="ProductGrid"){const n=Js(r.products,r.items,r.cards);return le(n||Zs(e,t))}return le(r.products||r.items||r.cards)}function Js(...e){return e.find(t=>Array.isArray(t))||null}function Zs(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 Ys(e){return!e||typeof e!="object"?null:I({sku:k(e.sku||e.code||e.id),name:k(e.name||e.title),category:k(e.category),url:k(e.url)})}function Qs(e){const t=e.elements||{};return t[e.root||"root"]||t.root||e.rootElement||null}function de(e,t=Ms){if(!Array.isArray(e))return;const r=e.map(n=>k(n)).filter(Boolean);return r.length?r.slice(0,t):void 0}function Ot(e){return[...new Set(e.map(t=>k(t)).filter(Boolean))]}function Bt(e){return Number.isFinite(Number(e))?Number(e):void 0}function Xs(e){return/error$/u.test(e)?"error":/start$/u.test(e)?"running":"done"}function k(e,t=Rt){const r=String(e??"").replace(/\s+/gu," ").trim();return r.length>t?`${r.slice(0,t-1)}...`:r}function I(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 yn(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:uc(c),state:Ae(c,`tool:${n}`)}),c}catch(c){throw t.record({kind:"tool/error",tool:n,params:a,error:fe(c)}),c}},Object.defineProperty(r[n],"__gengageActivityWrapped",{value:!0}));return r}function hn(e,t){return t?r=>(t.record({kind:"beacon",payload:r}),e?.(r)):e}function bn(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,ec(s,t),c,u);return l&&typeof l.then=="function"?l.catch(f=>{throw t.record({kind:"flow/rejected",requestType:a?.type,error:fe(f)}),f}):l}catch(l){throw t.record({kind:"flow/thrown",requestType:a?.type,error:fe(l)}),l}};return Object.defineProperty(o,"__gengageActivityWrapped",{value:!0}),r.streamTransport=o,t.record({kind:"runtime/transport-wrapped",title:"streamTransport wrapped"}),!0}function wn({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=ic(o,i),s=sc(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 tc({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}),kn(t,f)}).catch(l=>{t.record({kind:"be/response",source:"main-thread-fetch",url:a.url,status:u.status,op:c,error:fe(l)})}),u})}function ec(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:fe(o[0])}):n==="onDone"&&t.record({kind:"flow/done"}),e[n](...o)));return r}function Mt(e,t){!e||!t||(e.record(t),t.kind==="be/response"&&kn(e,t.result))}async function tc({accountId:e,opName:t,promptBaseUrl:r}){if(!e||!t)return null;const n=rc({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:fe(o)}}}function rc({accountId:e,baseId:t,promptBaseUrl:r}){if(typeof r=="string"&&r.trim())return r;const n=nc(e,t);return n||oc(t)}function nc(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 oc(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 kn(e,t){const r=t?.intent;r&&e.record({kind:"intent/selected",intent:r,searchParams:t?.search_params,flowParams:t?.flow_params})}function ic(e,t){const r=typeof e=="string"?e:e?.url||"",n=t?.body||(typeof e!="string"?e?.body:null);return{url:String(r||""),body:ac(n)}}function ac(e){if(!e||typeof e!="string")return{};try{return JSON.parse(e)}catch{return{raw:e}}}function sc(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
|
+
`)}}return t}function uc(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 fe(e){return e?.message||String(e)}var Sn="gengage-agentic-activity-overlay",xe="all",Nt="all",_n=["Flow","Tools","Backend","Intent","Telemetry","Runtime"],vn=["info","warn","error"];function An(e){if(!e||typeof e.subscribe!="function")return null;const t=document.getElementById(Sn);if(t?.shadowRoot)return t;const r=document.createElement("div");r.id=Sn,r.style.cssText="position:fixed;left:10px;top:10px;z-index:2147483647;";const n=r.attachShadow({mode:"open"});n.innerHTML=Ic(e.accountId),document.documentElement.appendChild(r);const o={entries:[],section:xe,severity:Nt,search:"",grouped:!0,follow:!0,stateVisible:!0},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"]')};lc(r,i.list);const a=()=>fc(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()}),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);Pc(o.entries.find(l=>l.id===u),c)}),e.subscribe((s,c)=>{o.entries=c.slice(),a()}),r}function lc(e,t){e.addEventListener("wheel",r=>{const n=dc(r.composedPath?.()||[],t);n&&(n.scrollTop+=r.deltaY,n.scrollLeft+=r.deltaX,r.preventDefault(),r.stopPropagation())},{passive:!1,capture:!0})}function dc(e,t){for(const r of e)if(!(!r||r.nodeType!==1)&&xn(r))return r;return xn(t)?t:null}function xn(e){return!!(e&&(e.scrollHeight>e.clientHeight+1||e.scrollWidth>e.clientWidth+1)&&getComputedStyle(e).overflow!=="hidden")}function fc(e,t){const r=En(t.entries,t),n=r.slice(-260);Tn(e.sections,t.entries,t.section,"section"),Tn(e.severities,t.entries,t.severity,"severity"),e.count&&(e.count.textContent=String(t.entries.length)),e.visibleCount&&(e.visibleCount.textContent=String(r.length)),yc(e.stateView,mn(t.entries),t.stateVisible),gc(e.list,n,t)}function En(e,t={}){const r=t.section||xe,n=t.severity||Nt,o=In(t.search);return(Array.isArray(e)?e:[]).filter(i=>r!==xe&&i.section!==r||n!==Nt&&i.severity!==n?!1:o?Rc(i).includes(o):!0)}function Tn(e,t,r,n){if(!e)return;e.textContent="";const o=n==="section"?pc(t):mc(t),i=document.createElement("button");i.type="button",i.dataset[`${n}Filter`]=xe,i.className=r===xe?"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}-${pe(a)}`:`chip ${n}-${pe(a)}`,c.textContent=`${Bn(a)} ${s}`,e.appendChild(c)}}function pc(e){const t=new Set(e.map(r=>r.section).filter(Boolean));return _n.filter(r=>t.has(r)).concat([...t].filter(r=>!_n.includes(r)).sort())}function mc(e){const t=new Set(e.map(r=>r.severity).filter(Boolean));return vn.filter(r=>t.has(r)).concat([...t].filter(r=>!vn.includes(r)).sort())}function gc(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 Tc(t))n.appendChild(Cc(o));else for(const o of t)n.appendChild(Pn(o));e.appendChild(n),r.follow&&requestAnimationFrame(()=>e.scrollTop=e.scrollHeight)}function yc(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(hc(n)),i.appendChild(bc(o)),i.appendChild(wc(n.timeline)),e.appendChild(i)}function hc(e){const t=document.createElement("section");return t.className=`viz-card flow-card status-${pe(e.status)}`,t.appendChild($t("Flow State",e.status)),Cn(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",kc(e)]]),t}function bc(e){const t=document.createElement("section");return t.className="viz-card context-card",t.appendChild($t("Context State",e.panel?.screenType||e.ui?.rootType||"empty")),Cn(t,[["Intent",Sc(e.intent)],["Route",_c(e.route)],["Screen",vc(e)],["Last search",Ac(e.panel?.lastSearch)],["Products",xc(e.panel,e.products)],["Page product",Ec(e.pageProduct)],["Extensions",Object.keys(e.threadExtensions||{}).join(", ")],["Last text",e.lastText]]),t}function wc(e){const t=document.createElement("section");t.className="viz-card timeline-card",t.appendChild($t("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-${pe(n.status||"done")}`;const i=document.createElement("span");i.className="timeline-time",i.textContent=On(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 $t(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 Cn(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 kc(e){return!e.errors&&!e.warnings?"clean":`${e.errors||0} errors, ${e.warnings||0} warnings`}function Sc(e){return e?[e.kind,e.target,e.confidence!=null?`conf ${e.confidence}`:""].filter(Boolean).join(" / "):""}function _c(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 vc(e){const t=e.panel||{},r=e.ui||{};return[t.screenType,r.rootType,r.widget,r.panelHint].filter(Boolean).join(" / ")}function Ac(e){return e?[e.query,e.source,e.category,e.count!=null?`${e.count} results`:""].filter(Boolean).join(" / "):""}function xc(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 Ec(e){return e?[e.sku,e.name,e.category].filter(Boolean).join(" / "):""}function Tc(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=jc(o.severity,r.severity),t.set(n,o)}return[...t.values()]}function Cc(e){const t=document.createElement("section");t.className=`group group-${pe(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(Pn(a));return t}function Pn(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-${pe(e.severity||"info")}`,t.open=e.severity==="error";const r=document.createElement("summary"),n=document.createElement("span");n.className="time",n.textContent=On(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=Bn(e.severity||"info");const a=document.createElement("span");a.className="title",a.textContent=Ln(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 g=document.createElement("pre"),p=document.createElement("code");return p.innerHTML=jn(e),g.appendChild(p),s.append(c,g),t.append(r,s),t}function jn(e){const t=qt(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+=De(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}">${De(a)}</span>`,o=i.index+a.length}return n+De(t.slice(o))}function Pc(e,t){if(!e)return;const r=qt(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(()=>Rn(r,n));return}Rn(r,n)}function Rn(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 jc(e,t){const r={info:0,warn:1,error:2};return(r[t]||0)>(r[e]||0)?t:e}function Rc(e){return In([e.kind,e.section,e.severity,e.group,Ln(e),e.tool,e.op,e.request?.type,e.request?.action?.type,e.event?.name,e.event?.action,e.event?.type,qt(e)].join(" "))}function In(e){return String(e||"").toLocaleLowerCase("tr-TR").trim()}function Ln(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 Lc(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 Ic(e){return`
|
|
9
9
|
<style>
|
|
10
10
|
:host { all: initial; }
|
|
11
11
|
.panel {
|
|
@@ -350,4 +350,4 @@
|
|
|
350
350
|
<div class="state-view" data-role="state-view"></div>
|
|
351
351
|
<div class="list" data-role="list"></div>
|
|
352
352
|
</div>
|
|
353
|
-
`}function $t(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function In(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 On(e){const t=String(e||"");return t?`${t.slice(0,1).toLocaleUpperCase("en-US")}${t.slice(1)}`:""}function le(e){return String(e||"").toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}function De(e){return String(e).replace(/[&<>"']/gu,t=>t==="&"?"&":t==="<"?"<":t===">"?">":t==='"'?""":"'")}function Tc({accountId:e,config:t={},tools:r,beacon:n}={}){if(!Bn(e,t))return{enabled:!1,tools:r,beacon:n,record(){},wrapTransport(){}};const o=sn(e);return window.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__=i=>bn(o,i),_n(o),hn({accountId:e,collector:o,promptBaseUrl:t.agenticActivityPromptBaseUrl}),o.record({kind:"runtime/debug-enabled",title:"Agentic activity debug enabled"}),{enabled:!0,collector:o,tools:mn(r,o),beacon:gn(n,o),record:i=>o.record(i),wrapTransport:()=>yn(e,o)}}function Bn(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&&Ec(e))}function Ec(e){return Array.from(document.scripts||[]).some(t=>{const r=t?.src||"";return r.includes(`/${e}/glov.js`)&&/[?&]pwtest=/u.test(r)})}var Cc="input-hash";function Mn({ttlS:e,promptVersion:t="current"}={}){if(!Number.isFinite(e)||e<=0)throw new Error("inputHashCachePolicy requires a positive ttlS");return{strategy:Cc,ttlS:e,promptVersion:t}}function Nn({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:Mn({ttlS:r,promptVersion:n}),cacheTtlS:r,cacheKey:(s={})=>pt(t,{account:e,locale:qt(a,s)||s.context?.meta?.locale||s.locale||"",promptVersion:n,payload:Ft(qt(o,s)),...jc(qt(i,s))})}}function Pc(e,t={}){return!e||e.kind!=="be_op"?e:{...e,...Nn({op:e.op,ttlS:e.cacheTtlS,input:e.input,...t})}}function qt(e,t){return typeof e=="function"?e(t):e}function Ft(e){return Array.isArray(e)?e.map(Ft):!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,Ft(r)]))}function jc(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}var Rc=Object.freeze({FALLBACK_RESULTS:"fallback_results",FALLBACK_NO_RESULTS:"fallback_no_results",FALLBACK_PARTIAL:"fallback_partial",OP_UNAVAILABLE:"op_unavailable"});function Lc(e,t={}){return{status:e,...t}}function Ic(e){return!!(e&&typeof e=="object"&&typeof e.status=="string")}function Oc(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 Bc=["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"],Mc=["description","description_html","features","service","sellers","reviews","qna","documents","delivery","payment"],Nc=["accountId","query","products","pendingProducts","rankedSkus","facets","facetsUsed","available_facets","logs","meta"],$c=["source","sourceType","sourceProfile","products","queries","logs"],qc=["items","kind","label","href","count","privacy"];function Fc({accountId:e,search:t,facetedSearch:r,similaritySearch:n,searchGiftOptions:o,filters:i={},resultContract:a={},limitations:s=[],extraTools:c=[]}={}){return{searchKeyword:async(l={},f={})=>t(Uc(l,f)),facetedSearch:typeof r=="function"?(l={},f={})=>r(qn(l,f)):async(l={},f={})=>t(qn(l,f)),getSearchCapabilities:()=>$n({accountId:e,hasSimilarity:typeof n=="function",hasGiftSearch:typeof o=="function",filters:i,resultContract:a,limitations:s,extraTools:c})}}function $n({accountId:e,hasSimilarity:t=!0,hasGiftSearch:r=!1,filters:n={},resultContract:o={},limitations:i=[],extraTools:a=[]}={}){return{accountId:e,tools:Dc(["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:Bc,productDetailFields:Mc,searchResultFields:Nc,similarityResultFields:$c,siteContentFields:qc,...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 Uc(e,t){return Ut(typeof e=="string"?{...t,query:e}:{...t,...e||{}})}function qn(e,t){const r=typeof e=="string"?{query:e}:e||{},n=r.query??t.query??"",o=Ut({...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 Dc(e){const t=new Set;return e.filter(r=>{const n=String(r||"");return!n||t.has(n)?!1:(t.add(n),!0)})}function Ut(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var zc=15e3,Gc="glov_agentic_iframe",Vc="position:absolute;width:1px;height:1px;left:-9999px;top:-9999px;opacity:0;pointer-events:none;";function Hc({markerParam:e=Gc,markerValue:t="agentic-scraper",frameName:r=t,sandbox:n="allow-same-origin",timeoutMs:o=zc,hiddenStyle:i=Vc,messageType:a,parser:s,isBlockedDocument:c}={}){const u=a||`gengage:agentic-iframe-scraper:${t}`;function l(y,h={}){const m=new URL(String(y),Dt());for(const[b,w]of Object.entries(h||{}))w!=null&&w!==""&&m.searchParams.set(b,String(w));return m.searchParams.set(e,t),m.href}function f(y=globalThis.window?.location,h=globalThis.window?.name||""){if(h===r||h===t)return!0;try{return new URL(y?.href||String(y||""),Dt()).searchParams.get(e)===t}catch{return!1}}async function g(y,h={},m={}){const b=m.parser||s,w=m.isBlockedDocument||c,A=globalThis.document,v=globalThis.window;if(!A?.body||typeof A.createElement!="function"||typeof A.body.appendChild!="function")return{attempted:!1,doc:null,result:null,blocked:!1,timedOut:!1,via:"unavailable"};const O=l(y),_=A.createElement("iframe");_.name=r;try{_.sandbox=n}catch{}return _.style&&(_.style.cssText=i),new Promise(M=>{let J=!1;const Ye=typeof v?.addEventListener=="function"&&typeof v?.removeEventListener=="function",cl=v.setTimeout(()=>{nr({attempted:!0,doc:null,result:null,blocked:!1,timedOut:!0,via:"timeout"})},o);function ul(){v.clearTimeout(cl),Ye&&v.removeEventListener("message",uo),typeof _.remove=="function"&&_.remove()}function nr(Z){J||(J=!0,ul(),M(Z))}function uo(Z){if(Z.source&&_.contentWindow&&Z.source!==_.contentWindow)return;const re=Z.data;!re||re.type!==u||re.marker!==t||nr({attempted:!0,doc:null,result:re.payload||null,blocked:!!re.blocked,timedOut:!1,via:"postMessage"})}_.addEventListener("load",()=>{if(_.contentWindow?.location?.href!=="about:blank")try{const Z=_.contentDocument||_.contentWindow?.document||null,re=!!w?.(Z);nr({attempted:!0,doc:Z,result:typeof b=="function"?b(Z,{url:O,input:h}):null,blocked:re,timedOut:!1,via:"contentDocument"})}catch{}}),Ye&&v.addEventListener("message",uo),A.body.appendChild(_),_.src=O})}function p(y=s,{targetOrigin:h=Dt()}={}){const m=globalThis.window;if(!m?.parent||!f(m.location,m.name))return!1;const b=typeof y=="function"?y(globalThis.document,{url:m.location?.href||"",input:{}}):y;return m.parent.postMessage({type:u,marker:t,payload:b},h||"*"),!0}return{markerParam:e,markerValue:t,frameName:r,messageType:u,decorateUrl:l,isScraperFrame:f,load:g,postCurrentDocument:p}}function Kc(e,{accountId:t,type:r="agenticSearchFrame"}={}){return e?.isScraperFrame?.()?(t&&globalThis.window&&(globalThis.window.GengageAssistantInjector||={},globalThis.window.GengageAssistantInjector[t]||={type:r}),!0):!1}function Dt(){return globalThis.window?.location?.origin||globalThis.location?.origin||"https://example.invalid"}function Wc(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 Jc({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=Fn(a.url||a.productUrl||s.url,e,o),u=a.sku||s.sku||null;return c?Zc(c)?{ok:!0,sku:u,url:c,method:"already-current-page",alreadyCurrentPage:!0,message:r||t}:(Un(c),{ok:!0,sku:u,url:c,method:"browser-navigation",message:t}):{ok:!1,sku:u,reason:"missing-url",message:n}}}function Fn(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 Un(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 Zc(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 Yc(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 Dn({patterns:e,messageFilter:t,messageNormalizer:r=o=>o,messageLimit:n=10}={}){const o={patterns:[...Ct,...Array.isArray(e)?e:[]]};function i(c){return jt(c,o)}function a(c){return tn(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 Qc(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 zn({accountId:e,supplied:t=[],pageProduct:r=null,listingProducts:n=[],skus:o=[],limit:i=4,storedProducts:a=[],getStoredPanelProducts:s}={}){const c=Vn(o),u=Array.isArray(n)?n:[],l=typeof s=="function"?s({accountId:e,visibleProducts:u}):a;return Gn([...Ge(t),...Ge(l),r,...u],{skus:c,limit:i})}function Xc({accountId:e,rootUrl:t,getProduct:r,getProducts:n,getStoredPanelProducts:o,limit:i=4}={}){return async function(s={}){return{accountId:e,products:zn({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 Gn(e,{skus:t=[],limit:r=4}={}){const n=new Set(Vn(t)),o=new Set,i=[];for(const a of Ge(e)){if(!a)continue;const s=ze(a?.sku);if(n.size&&!n.has(s))continue;const c=s||ze(a?.url)||ze(a?.name||a?.title);if(!(c&&o.has(c))&&(c&&o.add(c),i.push(a),i.length>=r))break}return i}function Vn(e){return Ge(e).map(ze).filter(Boolean)}function ze(e){return String(e||"").trim()}function Ge(e){return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}var I={features:18,reviews:4,qna:4,sellers:4,variants:12,documents:6,textBlocks:6,relatedProducts:8,textChars:220},zt={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},eu=/[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,tu=/(?: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 Hn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return(i={})=>Kn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i})}function Kn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=a=>a,input:i={}}){const a=Pu(i),s=o(i.product||Jt(r)),c=(Jt(n)||[]).map(o).filter(Boolean),u=C(i.sku||s?.sku||i.product?.sku),l=u?c.find(J=>C(J?.sku)===u)||s:s||c[0]||null,f=au(u||l?.sku),g=to({...f.product,...l}),p=Wt(He(l?.features),He(l?.specs),bu(l?.facet_hits),He(f.product?.features),cu(),uu(),lu()).slice(0,a.features),y=Zn(Ke(l?.reviews),f.reviews,du()).slice(0,a.reviews),h=Yn(Vt(l?.qna),fu()).slice(0,a.qna),m=Qn(Ht(l?.sellers),pu()).slice(0,a.sellers),b=ee([...l?.payment||[],...Ve("payment",a)]),w=ee([...l?.delivery||[],...Ve("delivery",a)]),A=ee([...l?.promotions||[],...Ve("promotion",a)]),v=Xn(Kt(l?.variants),mu()).slice(0,a.variants),O=gu(a.documents),_=ro(l?.description,f.product?.description,yu("description"),Ve("description",{...a,textBlocks:2})[0]),M=c.filter(J=>!u||C(J?.sku)!==u).map(to).filter(Boolean).slice(0,a.relatedProducts);return de({accountId:e,pageType:Jt(t)||"other",url:Cu(),product:g,description:_,features:p,sellers:m,reviews:y,qna:h,rating:B(l?.rating??f.rating),review_count:B(l?.review_count??f.review_count),payment:b,delivery:w,promotions:A,variants:v,documents:O,related_products:M,capabilities:Au({description:_,features:p,sellers:m,reviews:y,qna:h,payment:b,delivery:w,promotions:A,variants:v,documents:O,relatedProducts:M}),privacy:{browserLocal:!0,rawHtml:!1,formValues:!1,cookies:!1,storage:!1,redacted:!0}})}function nu(e,t){const r=Array.isArray(e)?e.filter(Boolean):[];if(!t||typeof t!="object"||!r.length)return r;const n=C(t.product?.sku);return r.map((o,i)=>{const a=C(o?.sku);return r.length===1||n&&a&&n===a||i===0?iu(o,t):o})}function Wn(e){return!e||typeof e!="object"?null:de({product:e.product,description:x(e.description,500),features:wu(e.features,14),sellers:vu(e.sellers,4),reviews:ku(e.reviews,4),qna:Su(e.qna,4),rating:e.rating,review_count:e.review_count,payment:Q(e.payment,5,160),delivery:Q(e.delivery,5,160),promotions:Q(e.promotions,5,160),variants:_u(e.variants,10),documents:Q(e.documents,5,220),capabilities:Array.isArray(e.capabilities)?e.capabilities.slice(0,12):void 0})}function ou(e,t,r={}){const n=Wn(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 iu(e,t){return de({...e,description:ro(e.description,t.description),features:Wt(He(e.features),t.features).slice(0,24),specs:e.specs||(t.features?.length?Object.fromEntries(t.features.map(xu)):void 0),sellers:Qn(Ht(e.sellers),t.sellers),reviews:Zn(Ke(e.reviews),t.reviews),qna:Yn(Vt(e.qna),t.qna),rating:e.rating??t.rating,review_count:e.review_count??t.review_count,payment:ee([...e.payment||[],...t.payment||[]]),delivery:ee([...e.delivery||[],...t.delivery||[]]),promotions:ee([...e.promotions||[],...t.promotions||[]]),variants:Xn(Kt(e.variants),t.variants),documents:ee([...e.documents||[],...t.documents||[]])})}function au(e){const t=[];for(const o of D('script[type="application/ld+json"]')){const i=su(o.textContent);for(const a of Gt(i))String(a?.["@type"]||"").toLowerCase()==="product"&&t.push(a)}const r=t.find(o=>C(o.sku||o.productID||o.mpn)===C(e))||t[0];if(!r)return{};const n=r.aggregateRating||{};return{product:de({sku:C(r.sku||r.productID||r.mpn),name:S(r.name),brand:S(r.brand?.name||r.brand),description:S(r.description),images:Q(r.image,8,280),url:Ae(r.url),rating:B(n.ratingValue),review_count:B(n.reviewCount||n.ratingCount)}),reviews:Ke(r.review),rating:B(n.ratingValue),review_count:B(n.reviewCount||n.ratingCount)}}function Gt(e){return Array.isArray(e)?e.flatMap(Gt):!e||typeof e!="object"?[]:[e,...Gt(e["@graph"])]}function su(e){try{return JSON.parse(String(e||""))}catch{return null}}function cu(){const e=[];for(const t of D("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 uu(){const e=[];for(const t of D("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 lu(){return D('[class*="spec" i], [class*="feature" i], [class*="attribute" i], li').map(e=>Jn(S(e.textContent))).filter(Boolean).slice(0,I.features)}function du(){return D('[class*="review" i], [data-review], [itemprop="review"]').map(e=>{const t=S(e.textContent);return!t||t.length<8||zt.qna.test(t)?null:{content:x(t,260),star:B(e.getAttribute?.("data-rating"))}}).filter(Boolean)}function fu(){const e=D('[class*="question" i], [class*="answer" i], [data-question], [data-answer]'),t=[];for(const r of e){const n=S(r.textContent);if(!n||!zt.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 pu(){return D('[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 mu(){return D('[class*="variant" i] a,[class*="variant" i] button,[class*="size" i] button,[class*="color" i] button,[data-variant],[data-size],[data-color]').map(e=>de({name:x(no(e),120),value:x(e.getAttribute?.("data-value")||e.getAttribute?.("data-size")||e.getAttribute?.("data-color"),120),sku:C(e.getAttribute?.("data-sku")||e.getAttribute?.("data-product-id")),url:Ae(e.getAttribute?.("href")),in_stock:e.getAttribute?.("disabled")==null&&e.getAttribute?.("aria-disabled")!=="true"})).filter(e=>e.name||e.value||e.sku)}function gu(e){return D("a[href]").filter(t=>/\.pdf(?:$|[?#])/iu.test(t.getAttribute?.("href")||"")).map(t=>{const r=no(t)||"PDF",n=Ae(t.getAttribute?.("href"));return n?`${r}: ${n}`:""}).filter(Boolean).slice(0,e)}function Ve(e,t){const r=zt[e];return r?D("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||I.textChars)).filter(eo()).slice(0,t.textBlocks||I.textBlocks):[]}function yu(e){return S(document.querySelector?.(`meta[name="${e}"]`)?.getAttribute?.("content")||document.querySelector?.(`meta[property="og:${e}"]`)?.getAttribute?.("content"))}function D(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 He(e){return e?(Array.isArray(e)?e:Object.entries(e).map(([t,r])=>({key:t,value:r}))).map(t=>typeof t=="string"?Jn(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 bu(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([t,r])=>({key:S(t),value:S(r)}))}function Jn(e){const t=/^(.{2,80}?)\s*[::]\s*(.{1,220})$/u.exec(S(e));return t?{key:t[1],value:t[2]}:null}function Ke(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:B(t.star||t.rating||t.reviewRating?.ratingValue)}).filter(t=>t.content||t.star)}function Vt(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 Ht(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:C(t.merchant_id||t.id||""),merchant_rating:B(t.merchant_rating||t.rating),price_offer:B(t.price_offer||t.price)}).filter(t=>t.merchant||t.merchant_id)}function Kt(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:C(t.sku||t.code||""),url:Ae(t.url),in_stock:t.in_stock})).filter(t=>t.name||t.value||t.sku||t.url)}function Wt(...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 Zn(...e){return We(e.flat().filter(Boolean),t=>`${t.star||""}:${t.content||""}`)}function Yn(...e){return We(e.flat().filter(Boolean),t=>`${t.question||""}:${t.answer||""}`)}function Qn(...e){return We(e.flat().filter(Boolean),t=>`${t.merchant||""}:${t.merchant_id||""}`)}function Xn(...e){return We(e.flat().filter(Boolean),t=>`${t.sku||""}:${t.name||""}:${t.value||""}`)}function We(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 ee(e){return Q(e,20,I.textChars)}function Q(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>x(n,r)).filter(Boolean).filter(eo()).slice(0,t)}function eo(){const e=new Set;return t=>{const r=S(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function wu(e,t){return Wt(e).slice(0,t)}function ku(e,t){return Ke(e).slice(0,t)}function Su(e,t){return Vt(e).slice(0,t)}function vu(e,t){return Ht(e).slice(0,t)}function _u(e,t){return Kt(e).slice(0,t)}function to(e){return!e||typeof e!="object"?null:de({sku:C(e.sku||e.id||""),group_id:C(e.group_id||e.groupId||""),name:S(e.name||e.title||""),brand:S(e.brand||""),url:Ae(e.url),images:Q(e.images||e.image,8,280),price:B(e.price),price_discounted:B(e.price_discounted||e.discountedPrice),price_text:S(e.price_text||e.priceText||""),price_currency:S(e.price_currency||e.currency||""),category_ids:Tu(e.category_ids||e.categoryIds,8,90),category_names:Q(e.category_names||e.categoryNames||e.category,8,140),in_stock:e.in_stock})}function Au(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 ro(...e){return e.map(t=>x(t,700)).find(Boolean)||""}function x(e,t){return S(e).slice(0,t)}function no(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(eu,"[redacted]").replace(/\s+/gu," ").trim()}function C(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 Tu(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>C(n).slice(0,r)).filter(Boolean).filter(Eu()).slice(0,t)}function Eu(){const e=new Set;return t=>{const r=C(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function B(e){const t=Number(String(e??"").replace(",","."));return Number.isFinite(t)&&t>0?t:void 0}function Ae(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",oo(t),t.href):""}catch{return""}}function Cu(){try{const e=new URL(window.location.href);return e.hash="",oo(e),`${e.origin}${e.pathname}${e.search}`}catch{return""}}function oo(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(tu.test(t)||ru.test(n))&&e.searchParams.set(t,"redacted")}return e}function Pu(e={}){return{features:K(e.maxFeatures,I.features,40),reviews:K(e.maxReviews,I.reviews,12),qna:K(e.maxQna,I.qna,12),sellers:K(e.maxSellers,I.sellers,12),variants:K(e.maxVariants,I.variants,30),documents:K(e.maxDocuments,I.documents,12),textBlocks:K(e.maxTextBlocks,I.textBlocks,16),relatedProducts:K(e.maxRelatedProducts,I.relatedProducts,20),textChars:K(e.textChars,I.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 Jt(e){try{return typeof e=="function"?e():null}catch{return null}}function de(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var{redactPii:ju,anonymousRequestText:Ru,anonymizeMessages:Lu}=Dn({patterns:[{pattern:/\b\d{5}\b/gu,replacement:"[postcode]"},{pattern:/\b(?:adresim|adres|mahalle|sokak|cadde)\b[^,.!?\n]{8,160}/giu,replacement:"[address]"}]});function io(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 Iu(e){return Array.isArray(e)?e.find(t=>String(t||"").trim()):void 0}function Ou(e){const t=io(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 fe={headings:8,products:8,controls:12,textMatches:8,snippetChars:180},Je=/\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,Bu=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,Mu=/[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,Nu={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 $u({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return{scanSite:(i={})=>qu({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}),siteGrep:(i={})=>Fu(i),discoverSiteContent:(i={})=>ao(i,e),runSiteCommand:(i={})=>Uu(i),describeVisualContext:(i={})=>Du(i,e),inspectProductSurface:Hn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o}),getSiteCapabilities:()=>Vu(e)}}function qu({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}){const a=T(i.query||i.text||""),s=er(i),c=rr(r),u=rr(n)||[];return tr({accountId:e,url:il(),title:X(document.title||""),pageType:rr(t)||"other",viewport:al(),product:so(o(c)),products:u.map(o).map(so).filter(Boolean).slice(0,s.products),content:i.includeContent===!1?void 0:ao(i,e).items,headings:Hu(s.headings),controls:i.includeControls===!1?void 0:Ku(s.controls),textMatches:a?Zt(a,s):[],privacy:{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}})}function ao(e={},t=""){const r=er(e),n=new Set(Zu(e.kinds||e.kind)),o=Wu(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 Fu(e={}){const t=T(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=Zt(t,er(e));return{ok:r.length>0,query:t,matches:r,count:r.length,privacy:W()}}function Uu(e={}){const t=T(e.command||e.action||"").toLowerCase();return t==="scroll_to_text"||t==="scrolltotext"?zu(e):t==="click_visible_text"||t==="clickvisibletext"?Gu(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 Du(e={},t){const r=e.visual_consent===!0||e.visualConsent===!0||e.consent===!0,n=r?Qu(e.visual_observations||e.visualObservations):[],o=Yu(Number(e.maxImages||8));return{accountId:t,ok:r||o.length>0,consentedObservations:n,visibleImages:o,message:Xu({consented:r,observations:n,visibleImages:o}),privacy:{rawHtml:!1,formValues:!1,screenshotPixels:!1,redacted:!0,browserLocal:!0,requiresConsentForExternalVisualFacts:!0}}}function zu(e){const t=T(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:pe(r),message:"Scrolled to the matching page area.",privacy:W()}):{ok:!1,command:"scroll_to_text",message:"No visible matching text found."}}function Gu(e){const t=T(e.label||e.query||e.text||"");if(!t)return{ok:!1,command:"click_visible_text",message:"Provide a visible label to click."};if(Je.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=tl(t);if(!r)return{ok:!1,command:"click_visible_text",message:"No safe visible clickable control found."};const n=pe(r);return Je.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 Vu(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 Hu(e){return[...document.querySelectorAll('h1,h2,h3,[role="heading"]')].filter(te).map(t=>X(T(t.textContent))).filter(Boolean).slice(0,e)}function Ku(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(te).map(t=>({label:pe(t),tag:t.tagName?.toLowerCase(),role:t.getAttribute?.("role")||null,href:co(t),safeClick:!Je.test(pe(t))})).filter(t=>t.label).filter(Ze(t=>`${t.tag}:${t.label}:${t.href||""}`)).slice(0,e)}function Wu(e){return[...document.querySelectorAll('a[href],button,[role="button"],summary')].filter(te).map(t=>{const r=pe(t),n=co(t),o=Ju([r,n,Yt(t)].join(" "));return o?tr({kind:o,label:r,href:n,heading:Yt(t),safeClick:!Je.test(r)}):null}).filter(Boolean).filter(Ze(t=>`${t.kind}:${t.label}:${t.href||""}`)).slice(0,Math.max(1,Math.min(e,30)))}function Ju(e){for(const[t,r]of Object.entries(Nu))if(r.test(e))return t;return""}function Zu(e){return(Array.isArray(e)?e:String(e||"").split(/[,|]/u)).map(t=>T(t).toLowerCase()).filter(Boolean)}function Zt(e,t){const r=e.toLocaleLowerCase("tr-TR");return el(document.body).map(n=>({node:n,text:T(n.nodeValue||"")})).filter(({text:n})=>n&&n.toLocaleLowerCase("tr-TR").includes(r)).map(({node:n,text:o})=>({snippet:nl(o,e,t.snippetChars),tag:n.parentElement?.tagName?.toLowerCase()||"",heading:Yt(n.parentElement)})).filter(n=>n.snippet).filter(Ze(n=>n.snippet)).slice(0,t.textMatches)}function Yu(e){return[...document.querySelectorAll("img")].filter(te).map(t=>({alt:X(T(t.getAttribute("alt")||t.getAttribute("aria-label")||"")),title:X(T(t.getAttribute("title")||"")),src:Qt(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(Ze(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 Qu(e){return(Array.isArray(e)?e:String(e||"").split(/\n|;|\|/u)).map(t=>X(t).slice(0,180)).filter(Boolean).slice(0,8)}function Xu({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 el(e){if(!e)return[];const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(n){const o=n.parentElement;return!o||!te(o)||/^(script|style|noscript|template|svg)$/iu.test(o.tagName||"")||ol(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 tl(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(te).find(t=>pe(t).toLocaleLowerCase("tr-TR").includes(e.toLocaleLowerCase("tr-TR")))}function rl(e){const t=Zt(e,{...fe,textMatches:1})[0];return t?[...document.querySelectorAll("body *")].filter(te).find(r=>T(r.textContent).includes(t.snippet.slice(0,24))):null}function pe(e){return e?X(T(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.value||e.textContent||"")).slice(0,90):""}function Yt(e){let t=e;for(let r=0;t&&r<5;r+=1){const n=T((t.matches?.('h1,h2,h3,[role="heading"]')?t:t.querySelector?.('h1,h2,h3,[role="heading"]'))?.textContent||"");if(n)return X(n).slice(0,90);t=t.parentElement}return""}function so(e){return e?tr({sku:T(e.sku||e.id||""),name:T(e.name||e.title||""),url:Qt(e.url),price_text:T(e.price_text||e.priceText||""),price:e.price,currency:e.price_currency||e.currency,in_stock:e.in_stock,category:T(e.category||"")}):null}function nl(e,t,r){const n=X(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 te(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 ol(e){return!!e.closest?.('input,textarea,select,[contenteditable="true"]')}function co(e){return e.tagName?.toLowerCase()!=="a"?null:Qt(e.getAttribute("href"))}function Qt(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",Xt(t),t.href):""}catch{return""}}function il(){const e=new URL(window.location.href);return Xt(e),`${e.origin}${e.pathname}${e.search}`}function al(){return{width:window.innerWidth,height:window.innerHeight,scrollY:Math.round(window.scrollY||0),documentHeight:Math.round(document.documentElement?.scrollHeight||0)}}function X(e){return T(e).replace(/https?:\/\/[^\s?#]+(?:\?[^#\s]*)?/giu,sl).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 sl(e){try{const t=new URL(e);return t.hash="",Xt(t),t.href}catch{return String(e||"").replace(/\?[^#\s]*/u,"?redacted")}}function Xt(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(Bu.test(t)||Mu.test(n))&&e.searchParams.set(t,"redacted")}return e}function T(e){return String(e||"").replace(/\s+/gu," ").trim()}function er(e){return{headings:xe(e.maxHeadings,fe.headings,20),products:xe(e.maxProducts,fe.products,20),controls:xe(e.maxControls,fe.controls,30),textMatches:xe(e.maxMatches||e.limit,fe.textMatches,20),snippetChars:xe(e.snippetChars,fe.snippetChars,320)}}function xe(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 tr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function rr(e){try{return typeof e=="function"?e():null}catch{return null}}function Ze(e){const t=new Set;return r=>{const n=e(r);return!n||t.has(n)?!1:(t.add(n),!0)}}d.AgentError=z,d.ContextStore=dr,d.FALLBACK_STATUS=Rc,d.action=wi,d.actionButtonsUiSpec=Wa,d.alignProductsToTable=Jr,d.anonymousRequestText=tn,d.beErrorToAgentError=ut,d.buildActivityVisualization=fn,d.buildPhotoSimilarityProfile=rs,d.buildProductSimilarityProfile=ae,d.buildSimilarityQueries=ns,d.canUseModuleWorker=xt,d.caughtToStreamError=yr,d.compactAccountConfig=rn,d.compactContextProducts=Na,d.compactObject=Wc,d.compactProductSurfaceForLlm=Wn,d.comparisonResultForUi=Da,d.comparisonUiSpec=Ha,d.createActivityCollector=an,d.createBrowserMemory=At,d.createDiagnosticsTool=js,d.createEndpointCachePolicies=Za,d.createEndpointHandlers=Ya,d.createFlow=Ja,d.createGssToolAliases=Fc,d.createIframeScraper=Hc,d.createInjectorAdapter=Lr,d.createLocalRefStore=or,d.createMainThreadInjectorAdapter=Ir,d.createModuleWorker=Wr,d.createOpenProductPageTool=Jc,d.createPrivacyHelpers=Dn,d.createProductSurfaceInspector=Hn,d.createReadPageStep=Oc,d.createReadPageTool=Ps,d.createResolveProductsTool=Xc,d.createSiteAwarenessTools=$u,d.declarativeBeOpCache=Nn,d.defaultPiiPatternPack=Pt,d.defaultPiiPatterns=Ct,d.done=ft,d.elapsedMs=q,d.endpointStableKey=Zr,d.error=vr,d.fallbackStatus=Lc,d.filterActivityEntries=xn,d.firstArrayValue=Iu,d.formatJsonHtml=Pn,d.getOrCreateActivityCollector=sn,d.groupForEntry=dn,d.gssSearchCapabilities=$n,d.homePanelReset=Yc,d.httpErrorToAgentError=gr,d.inputHashCachePolicy=Mn,d.inspectProductSurface=Kn,d.installActivityFetchPatch=hn,d.installBrowserTools=Cs,d.installFetchTransportBridge=ya,d.installIframeScraperBypass=Kc,d.installLocalAgenticActivityDebug=Tc,d.isFallbackStatus=Ic,d.isRef=ir,d.jsonResponse=Xa,d.llmCacheKey=pt,d.mergeProductSurfaceEvidence=nu,d.metadata=hi,d.mountAccount=Ma,d.mountActivityOverlay=_n,d.navigateSameTab=Un,d.ndjsonResponse=Qa,d.normalizeComparisonTable=Tt,d.normalizeEntry=cn,d.normalizeProduct=je,d.normalizeSameOriginUrl=Fn,d.normalizeSimilarityText=V,d.nowIso=ur,d.plainMessageContent=Qc,d.productDetailsUiSpec=Va,d.productFactsKey=vi,d.productSkuKey=Si,d.productSurfaceReviewText=ou,d.productsUiSpec=Ga,d.rankSimilarProducts=os,d.rankSimilarProductsAsync=is,d.recordBeDebugPayload=bn,d.redactPii=jt,d.requestText=en,d.resolveBeUrl=ks,d.resolveFlow=_r,d.resolveProductCandidates=zn,d.retailAnonymizeMessages=Lu,d.retailAnonymousRequestText=Ru,d.retailRedactPii=ju,d.routeFlowParams=io,d.routeSkuList=Ou,d.scoreSimilarityCandidate=Et,d.sectionForKind=un,d.setAssistantHostVisible=bs,d.severityForEntry=ln,d.shouldInstallActivityDebug=Bn,d.stableKey=oe,d.startLazyRuntimeLoader=Rs,d.stickyContextKey=it,d.summarizeDebugState=ve,d.summarizePanelState=$e,d.summarizeUiSpec=Lt,d.textChunk=Sr,d.textKey=_i,d.tokenizeSimilarityText=N,d.trimProductFactsCore=Re,d.trimProductFactsListCore=ki,d.uiSpec=bi,d.uniqueProductsBySku=Gn,d.withAccountConfig=xs,d.withDeclarativeBeOpCache=Pc,d.wrapActivityBeacon=gn,d.wrapActivityTools=mn,d.wrapActivityTransport=yn})(this.Gengage=this.Gengage||{});
|
|
353
|
+
`}function qt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function On(e){try{return new Date(e||Date.now()).toLocaleTimeString()}catch{return""}}function Lc(e,t){const r=String(e||"");return r.length>t?`${r.slice(0,t-1)}...`:r}function Bn(e){const t=String(e||"");return t?`${t.slice(0,1).toLocaleUpperCase("en-US")}${t.slice(1)}`:""}function pe(e){return String(e||"").toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}function De(e){return String(e).replace(/[&<>"']/gu,t=>t==="&"?"&":t==="<"?"<":t===">"?">":t==='"'?""":"'")}function Oc({accountId:e,config:t={},tools:r,beacon:n}={}){if(!Mn(e,t))return{enabled:!1,tools:r,beacon:n,record(){},wrapTransport(){}};const o=un(e);return window.__GENGAGE_AGENTIC_DEBUG_RECORD__=i=>Mt(o,i),window.__GENGAGE_AGENTIC_DEBUG_RECORD_BE__=i=>Mt(o,i),An(o),wn({accountId:e,collector:o,promptBaseUrl:t.agenticActivityPromptBaseUrl}),o.record({kind:"runtime/debug-enabled",title:"Agentic activity debug enabled"}),{enabled:!0,collector:o,tools:yn(r,o),beacon:hn(n,o),record:i=>o.record(i),wrapTransport:()=>bn(e,o)}}function Mn(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&&Bc(e))}function Bc(e){return Array.from(document.scripts||[]).some(t=>{const r=t?.src||"";return r.includes(`/${e}/glov.js`)&&/[?&]pwtest=/u.test(r)})}var Mc="input-hash";function Nn({ttlS:e,promptVersion:t="current"}={}){if(!Number.isFinite(e)||e<=0)throw new Error("inputHashCachePolicy requires a positive ttlS");return{strategy:Mc,ttlS:e,promptVersion:t}}function $n({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:Nn({ttlS:r,promptVersion:n}),cacheTtlS:r,cacheKey:(s={})=>pt(t,{account:e,locale:Ut(a,s)||s.context?.meta?.locale||s.locale||"",promptVersion:n,payload:Ft(Ut(o,s)),...$c(Ut(i,s))})}}function Nc(e,t={}){return!e||e.kind!=="be_op"?e:{...e,...$n({op:e.op,ttlS:e.cacheTtlS,input:e.input,...t})}}function Ut(e,t){return typeof e=="function"?e(t):e}function Ft(e){return Array.isArray(e)?e.map(Ft):!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,Ft(r)]))}function $c(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}var qc=Object.freeze({FALLBACK_RESULTS:"fallback_results",FALLBACK_NO_RESULTS:"fallback_no_results",FALLBACK_PARTIAL:"fallback_partial",OP_UNAVAILABLE:"op_unavailable"});function Uc(e,t={}){return{status:e,...t}}function Fc(e){return!!(e&&typeof e=="object"&&typeof e.status=="string")}function Dc(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 zc=["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"],Gc=["description","description_html","features","service","sellers","reviews","qna","documents","delivery","payment"],Vc=["accountId","query","products","pendingProducts","rankedSkus","facets","facetsUsed","available_facets","logs","meta"],Kc=["source","sourceType","sourceProfile","products","queries","logs"],Hc=["items","kind","label","href","count","privacy"];function Wc({accountId:e,search:t,facetedSearch:r,similaritySearch:n,searchGiftOptions:o,filters:i={},resultContract:a={},limitations:s=[],extraTools:c=[]}={}){return{searchKeyword:async(l={},f={})=>t(Jc(l,f)),facetedSearch:typeof r=="function"?(l={},f={})=>r(Un(l,f)):async(l={},f={})=>t(Un(l,f)),getSearchCapabilities:()=>qn({accountId:e,hasSimilarity:typeof n=="function",hasGiftSearch:typeof o=="function",filters:i,resultContract:a,limitations:s,extraTools:c})}}function qn({accountId:e,hasSimilarity:t=!0,hasGiftSearch:r=!1,filters:n={},resultContract:o={},limitations:i=[],extraTools:a=[]}={}){return{accountId:e,tools:Zc(["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:zc,productDetailFields:Gc,searchResultFields:Vc,similarityResultFields:Kc,siteContentFields:Hc,...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 Jc(e,t){return Dt(typeof e=="string"?{...t,query:e}:{...t,...e||{}})}function Un(e,t){const r=typeof e=="string"?{query:e}:e||{},n=r.query??t.query??"",o=Dt({...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 Zc(e){const t=new Set;return e.filter(r=>{const n=String(r||"");return!n||t.has(n)?!1:(t.add(n),!0)})}function Dt(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var Yc=15e3,Qc="glov_agentic_iframe",Xc="position:absolute;width:1px;height:1px;left:-9999px;top:-9999px;opacity:0;pointer-events:none;";function eu({markerParam:e=Qc,markerValue:t="agentic-scraper",frameName:r=t,sandbox:n="allow-same-origin",timeoutMs:o=Yc,hiddenStyle:i=Xc,messageType:a,parser:s,isBlockedDocument:c}={}){const u=a||`gengage:agentic-iframe-scraper:${t}`;function l(y,h={}){const m=new URL(String(y),zt());for(const[b,w]of Object.entries(h||{}))w!=null&&w!==""&&m.searchParams.set(b,String(w));return m.searchParams.set(e,t),m.href}function f(y=globalThis.window?.location,h=globalThis.window?.name||""){if(h===r||h===t)return!0;try{return new URL(y?.href||String(y||""),zt()).searchParams.get(e)===t}catch{return!1}}async function g(y,h={},m={}){const b=m.parser||s,w=m.isBlockedDocument||c,A=globalThis.document,_=globalThis.window;if(!A?.body||typeof A.createElement!="function"||typeof A.body.appendChild!="function")return{attempted:!1,doc:null,result:null,blocked:!1,timedOut:!1,via:"unavailable"};const O=l(y),v=A.createElement("iframe");v.name=r;try{v.sandbox=n}catch{}return v.style&&(v.style.cssText=i),new Promise(M=>{let J=!1;const Ye=typeof _?.addEventListener=="function"&&typeof _?.removeEventListener=="function",yl=_.setTimeout(()=>{or({attempted:!0,doc:null,result:null,blocked:!1,timedOut:!0,via:"timeout"})},o);function hl(){_.clearTimeout(yl),Ye&&_.removeEventListener("message",lo),typeof v.remove=="function"&&v.remove()}function or(Z){J||(J=!0,hl(),M(Z))}function lo(Z){if(Z.source&&v.contentWindow&&Z.source!==v.contentWindow)return;const re=Z.data;!re||re.type!==u||re.marker!==t||or({attempted:!0,doc:null,result:re.payload||null,blocked:!!re.blocked,timedOut:!1,via:"postMessage"})}v.addEventListener("load",()=>{if(v.contentWindow?.location?.href!=="about:blank")try{const Z=v.contentDocument||v.contentWindow?.document||null,re=!!w?.(Z);or({attempted:!0,doc:Z,result:typeof b=="function"?b(Z,{url:O,input:h}):null,blocked:re,timedOut:!1,via:"contentDocument"})}catch{}}),Ye&&_.addEventListener("message",lo),A.body.appendChild(v),v.src=O})}function p(y=s,{targetOrigin:h=zt()}={}){const m=globalThis.window;if(!m?.parent||!f(m.location,m.name))return!1;const b=typeof y=="function"?y(globalThis.document,{url:m.location?.href||"",input:{}}):y;return m.parent.postMessage({type:u,marker:t,payload:b},h||"*"),!0}return{markerParam:e,markerValue:t,frameName:r,messageType:u,decorateUrl:l,isScraperFrame:f,load:g,postCurrentDocument:p}}function tu(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 ru(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 nu({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=Fn(a.url||a.productUrl||s.url,e,o),u=a.sku||s.sku||null;return c?ou(c)?{ok:!0,sku:u,url:c,method:"already-current-page",alreadyCurrentPage:!0,message:r||t}:(Dn(c),{ok:!0,sku:u,url:c,method:"browser-navigation",message:t}):{ok:!1,sku:u,reason:"missing-url",message:n}}}function Fn(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 Dn(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 ou(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 iu(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 zn({patterns:e,messageFilter:t,messageNormalizer:r=o=>o,messageLimit:n=10}={}){const o={patterns:[...Ct,...Array.isArray(e)?e:[]]};function i(c){return jt(c,o)}function a(c){return nn(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 au(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 Gn({accountId:e,supplied:t=[],pageProduct:r=null,listingProducts:n=[],skus:o=[],limit:i=4,storedProducts:a=[],getStoredPanelProducts:s}={}){const c=Kn(o),u=Array.isArray(n)?n:[],l=typeof s=="function"?s({accountId:e,visibleProducts:u}):a;return Vn([...Ge(t),...Ge(l),r,...u],{skus:c,limit:i})}function su({accountId:e,rootUrl:t,getProduct:r,getProducts:n,getStoredPanelProducts:o,limit:i=4}={}){return async function(s={}){return{accountId:e,products:Gn({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 Vn(e,{skus:t=[],limit:r=4}={}){const n=new Set(Kn(t)),o=new Set,i=[];for(const a of Ge(e)){if(!a)continue;const s=ze(a?.sku);if(n.size&&!n.has(s))continue;const c=s||ze(a?.url)||ze(a?.name||a?.title);if(!(c&&o.has(c))&&(c&&o.add(c),i.push(a),i.length>=r))break}return i}function Kn(e){return Ge(e).map(ze).filter(Boolean)}function ze(e){return String(e||"").trim()}function Ge(e){return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}var L={features:18,reviews:4,qna:4,sellers:4,variants:12,documents:6,textBlocks:6,relatedProducts:8,textChars:220},Gt={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,uu=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,lu=/[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 Hn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return(i={})=>Wn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i})}function Wn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=a=>a,input:i={}}){const a=Nu(i),s=o(i.product||Zt(r)),c=(Zt(n)||[]).map(o).filter(Boolean),u=C(i.sku||s?.sku||i.product?.sku),l=u?c.find(J=>C(J?.sku)===u)||s:s||c[0]||null,f=mu(u||l?.sku),g=ro({...f.product,...l}),p=Jt(Ke(l?.features),Ke(l?.specs),Eu(l?.facet_hits),Ke(f.product?.features),yu(),hu(),bu()).slice(0,a.features),y=Yn(He(l?.reviews),f.reviews,wu()).slice(0,a.reviews),h=Qn(Kt(l?.qna),ku()).slice(0,a.qna),m=Xn(Ht(l?.sellers),Su()).slice(0,a.sellers),b=ee([...l?.payment||[],...Ve("payment",a)]),w=ee([...l?.delivery||[],...Ve("delivery",a)]),A=ee([...l?.promotions||[],...Ve("promotion",a)]),_=eo(Wt(l?.variants),_u()).slice(0,a.variants),O=vu(a.documents),v=no(l?.description,f.product?.description,Au("description"),Ve("description",{...a,textBlocks:2})[0]),M=c.filter(J=>!u||C(J?.sku)!==u).map(ro).filter(Boolean).slice(0,a.relatedProducts);return me({accountId:e,pageType:Zt(t)||"other",url:Mu(),product:g,description:v,features:p,sellers:m,reviews:y,qna:h,rating:B(l?.rating??f.rating),review_count:B(l?.review_count??f.review_count),payment:b,delivery:w,promotions:A,variants:_,documents:O,related_products:M,capabilities:Iu({description:v,features:p,sellers:m,reviews:y,qna:h,payment:b,delivery:w,promotions:A,variants:_,documents:O,relatedProducts:M}),privacy:{browserLocal:!0,rawHtml:!1,formValues:!1,cookies:!1,storage:!1,redacted:!0}})}function du(e,t){const r=Array.isArray(e)?e.filter(Boolean):[];if(!t||typeof t!="object"||!r.length)return r;const n=C(t.product?.sku);return r.map((o,i)=>{const a=C(o?.sku);return r.length===1||n&&a&&n===a||i===0?pu(o,t):o})}function Jn(e){return!e||typeof e!="object"?null:me({product:e.product,description:x(e.description,500),features:Tu(e.features,14),sellers:ju(e.sellers,4),reviews:Cu(e.reviews,4),qna:Pu(e.qna,4),rating:e.rating,review_count:e.review_count,payment:Q(e.payment,5,160),delivery:Q(e.delivery,5,160),promotions:Q(e.promotions,5,160),variants:Ru(e.variants,10),documents:Q(e.documents,5,220),capabilities:Array.isArray(e.capabilities)?e.capabilities.slice(0,12):void 0})}function fu(e,t,r={}){const n=Jn(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 pu(e,t){return me({...e,description:no(e.description,t.description),features:Jt(Ke(e.features),t.features).slice(0,24),specs:e.specs||(t.features?.length?Object.fromEntries(t.features.map(Lu)):void 0),sellers:Xn(Ht(e.sellers),t.sellers),reviews:Yn(He(e.reviews),t.reviews),qna:Qn(Kt(e.qna),t.qna),rating:e.rating??t.rating,review_count:e.review_count??t.review_count,payment:ee([...e.payment||[],...t.payment||[]]),delivery:ee([...e.delivery||[],...t.delivery||[]]),promotions:ee([...e.promotions||[],...t.promotions||[]]),variants:eo(Wt(e.variants),t.variants),documents:ee([...e.documents||[],...t.documents||[]])})}function mu(e){const t=[];for(const o of D('script[type="application/ld+json"]')){const i=gu(o.textContent);for(const a of Vt(i))String(a?.["@type"]||"").toLowerCase()==="product"&&t.push(a)}const r=t.find(o=>C(o.sku||o.productID||o.mpn)===C(e))||t[0];if(!r)return{};const n=r.aggregateRating||{};return{product:me({sku:C(r.sku||r.productID||r.mpn),name:S(r.name),brand:S(r.brand?.name||r.brand),description:S(r.description),images:Q(r.image,8,280),url:Ee(r.url),rating:B(n.ratingValue),review_count:B(n.reviewCount||n.ratingCount)}),reviews:He(r.review),rating:B(n.ratingValue),review_count:B(n.reviewCount||n.ratingCount)}}function Vt(e){return Array.isArray(e)?e.flatMap(Vt):!e||typeof e!="object"?[]:[e,...Vt(e["@graph"])]}function gu(e){try{return JSON.parse(String(e||""))}catch{return null}}function yu(){const e=[];for(const t of D("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 hu(){const e=[];for(const t of D("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 bu(){return D('[class*="spec" i], [class*="feature" i], [class*="attribute" i], li').map(e=>Zn(S(e.textContent))).filter(Boolean).slice(0,L.features)}function wu(){return D('[class*="review" i], [data-review], [itemprop="review"]').map(e=>{const t=S(e.textContent);return!t||t.length<8||Gt.qna.test(t)?null:{content:x(t,260),star:B(e.getAttribute?.("data-rating"))}}).filter(Boolean)}function ku(){const e=D('[class*="question" i], [class*="answer" i], [data-question], [data-answer]'),t=[];for(const r of e){const n=S(r.textContent);if(!n||!Gt.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 Su(){return D('[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 _u(){return D('[class*="variant" i] a,[class*="variant" i] button,[class*="size" i] button,[class*="color" i] button,[data-variant],[data-size],[data-color]').map(e=>me({name:x(oo(e),120),value:x(e.getAttribute?.("data-value")||e.getAttribute?.("data-size")||e.getAttribute?.("data-color"),120),sku:C(e.getAttribute?.("data-sku")||e.getAttribute?.("data-product-id")),url:Ee(e.getAttribute?.("href")),in_stock:e.getAttribute?.("disabled")==null&&e.getAttribute?.("aria-disabled")!=="true"})).filter(e=>e.name||e.value||e.sku)}function vu(e){return D("a[href]").filter(t=>/\.pdf(?:$|[?#])/iu.test(t.getAttribute?.("href")||"")).map(t=>{const r=oo(t)||"PDF",n=Ee(t.getAttribute?.("href"));return n?`${r}: ${n}`:""}).filter(Boolean).slice(0,e)}function Ve(e,t){const r=Gt[e];return r?D("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||L.textChars)).filter(to()).slice(0,t.textBlocks||L.textBlocks):[]}function Au(e){return S(document.querySelector?.(`meta[name="${e}"]`)?.getAttribute?.("content")||document.querySelector?.(`meta[property="og:${e}"]`)?.getAttribute?.("content"))}function D(e){try{return[...document.querySelectorAll?.(e)||[]].filter(xu)}catch{return[]}}function xu(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 Ke(e){return e?(Array.isArray(e)?e:Object.entries(e).map(([t,r])=>({key:t,value:r}))).map(t=>typeof t=="string"?Zn(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 Eu(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([t,r])=>({key:S(t),value:S(r)}))}function Zn(e){const t=/^(.{2,80}?)\s*[::]\s*(.{1,220})$/u.exec(S(e));return t?{key:t[1],value:t[2]}:null}function He(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:B(t.star||t.rating||t.reviewRating?.ratingValue)}).filter(t=>t.content||t.star)}function Kt(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 Ht(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:C(t.merchant_id||t.id||""),merchant_rating:B(t.merchant_rating||t.rating),price_offer:B(t.price_offer||t.price)}).filter(t=>t.merchant||t.merchant_id)}function Wt(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:C(t.sku||t.code||""),url:Ee(t.url),in_stock:t.in_stock})).filter(t=>t.name||t.value||t.sku||t.url)}function Jt(...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 Yn(...e){return We(e.flat().filter(Boolean),t=>`${t.star||""}:${t.content||""}`)}function Qn(...e){return We(e.flat().filter(Boolean),t=>`${t.question||""}:${t.answer||""}`)}function Xn(...e){return We(e.flat().filter(Boolean),t=>`${t.merchant||""}:${t.merchant_id||""}`)}function eo(...e){return We(e.flat().filter(Boolean),t=>`${t.sku||""}:${t.name||""}:${t.value||""}`)}function We(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 ee(e){return Q(e,20,L.textChars)}function Q(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>x(n,r)).filter(Boolean).filter(to()).slice(0,t)}function to(){const e=new Set;return t=>{const r=S(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function Tu(e,t){return Jt(e).slice(0,t)}function Cu(e,t){return He(e).slice(0,t)}function Pu(e,t){return Kt(e).slice(0,t)}function ju(e,t){return Ht(e).slice(0,t)}function Ru(e,t){return Wt(e).slice(0,t)}function ro(e){return!e||typeof e!="object"?null:me({sku:C(e.sku||e.id||""),group_id:C(e.group_id||e.groupId||""),name:S(e.name||e.title||""),brand:S(e.brand||""),url:Ee(e.url),images:Q(e.images||e.image,8,280),price:B(e.price),price_discounted:B(e.price_discounted||e.discountedPrice),price_text:S(e.price_text||e.priceText||""),price_currency:S(e.price_currency||e.currency||""),category_ids:Ou(e.category_ids||e.categoryIds,8,90),category_names:Q(e.category_names||e.categoryNames||e.category,8,140),in_stock:e.in_stock})}function Iu(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 Lu(e){return[S(e.key||e.name),S(e.value||e.text)]}function no(...e){return e.map(t=>x(t,700)).find(Boolean)||""}function x(e,t){return S(e).slice(0,t)}function oo(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 C(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 Ou(e,t,r){return(Array.isArray(e)?e:e?[e]:[]).map(n=>C(n).slice(0,r)).filter(Boolean).filter(Bu()).slice(0,t)}function Bu(){const e=new Set;return t=>{const r=C(t).toLocaleLowerCase("tr-TR");return!r||e.has(r)?!1:(e.add(r),!0)}}function B(e){const t=Number(String(e??"").replace(",","."));return Number.isFinite(t)&&t>0?t:void 0}function Ee(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",io(t),t.href):""}catch{return""}}function Mu(){try{const e=new URL(window.location.href);return e.hash="",io(e),`${e.origin}${e.pathname}${e.search}`}catch{return""}}function io(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(uu.test(t)||lu.test(n))&&e.searchParams.set(t,"redacted")}return e}function Nu(e={}){return{features:H(e.maxFeatures,L.features,40),reviews:H(e.maxReviews,L.reviews,12),qna:H(e.maxQna,L.qna,12),sellers:H(e.maxSellers,L.sellers,12),variants:H(e.maxVariants,L.variants,30),documents:H(e.maxDocuments,L.documents,12),textBlocks:H(e.maxTextBlocks,L.textBlocks,16),relatedProducts:H(e.maxRelatedProducts,L.relatedProducts,20),textChars:H(e.textChars,L.textChars,420)}}function H(e,t,r){const n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.min(Math.floor(n),r)}function Zt(e){try{return typeof e=="function"?e():null}catch{return null}}function me(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t!=null&&t!==""&&(!Array.isArray(t)||t.length)))}var{redactPii:$u,anonymousRequestText:qu,anonymizeMessages:Uu}=zn({patterns:[{pattern:/\b\d{5}\b/gu,replacement:"[postcode]"},{pattern:/\b(?:adresim|adres|mahalle|sokak|cadde)\b[^,.!?\n]{8,160}/giu,replacement:"[address]"}]});function ao(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 Fu(e){return Array.isArray(e)?e.find(t=>String(t||"").trim()):void 0}function Du(e){const t=ao(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 ge={headings:8,products:8,controls:12,textMatches:8,snippetChars:180},Je=/\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,zu=/(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu,Gu=/[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,Vu={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 Ku({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o=i=>i}){return{scanSite:(i={})=>Hu({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}),siteGrep:(i={})=>Wu(i),discoverSiteContent:(i={})=>so(i,e),runSiteCommand:(i={})=>Ju(i),describeVisualContext:(i={})=>Zu(i,e),inspectProductSurface:Hn({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o}),getSiteCapabilities:()=>Xu(e)}}function Hu({accountId:e,getPageType:t,getProduct:r,getProducts:n,normalizeProduct:o,input:i}){const a=E(i.query||i.text||""),s=tr(i),c=nr(r),u=nr(n)||[];return rr({accountId:e,url:pl(),title:X(document.title||""),pageType:nr(t)||"other",viewport:ml(),product:co(o(c)),products:u.map(o).map(co).filter(Boolean).slice(0,s.products),content:i.includeContent===!1?void 0:so(i,e).items,headings:el(s.headings),controls:i.includeControls===!1?void 0:tl(s.controls),textMatches:a?Yt(a,s):[],privacy:{rawHtml:!1,formValues:!1,redacted:!0,browserLocal:!0}})}function so(e={},t=""){const r=tr(e),n=new Set(ol(e.kinds||e.kind)),o=rl(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 Wu(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=Yt(t,tr(e));return{ok:r.length>0,query:t,matches:r,count:r.length,privacy:W()}}function Ju(e={}){const t=E(e.command||e.action||"").toLowerCase();return t==="scroll_to_text"||t==="scrolltotext"?Yu(e):t==="click_visible_text"||t==="clickvisibletext"?Qu(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 Zu(e={},t){const r=e.visual_consent===!0||e.visualConsent===!0||e.consent===!0,n=r?al(e.visual_observations||e.visualObservations):[],o=il(Number(e.maxImages||8));return{accountId:t,ok:r||o.length>0,consentedObservations:n,visibleImages:o,message:sl({consented:r,observations:n,visibleImages:o}),privacy:{rawHtml:!1,formValues:!1,screenshotPixels:!1,redacted:!0,browserLocal:!0,requiresConsentForExternalVisualFacts:!0}}}function Yu(e){const t=E(e.query||e.text||e.label||""),r=t?ll(t):null;return r?(r.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"}),{ok:!0,command:"scroll_to_text",label:ye(r),message:"Scrolled to the matching page area.",privacy:W()}):{ok:!1,command:"scroll_to_text",message:"No visible matching text found."}}function Qu(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(Je.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=ul(t);if(!r)return{ok:!1,command:"click_visible_text",message:"No safe visible clickable control found."};const n=ye(r);return Je.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 Xu(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 el(e){return[...document.querySelectorAll('h1,h2,h3,[role="heading"]')].filter(te).map(t=>X(E(t.textContent))).filter(Boolean).slice(0,e)}function tl(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(te).map(t=>({label:ye(t),tag:t.tagName?.toLowerCase(),role:t.getAttribute?.("role")||null,href:uo(t),safeClick:!Je.test(ye(t))})).filter(t=>t.label).filter(Ze(t=>`${t.tag}:${t.label}:${t.href||""}`)).slice(0,e)}function rl(e){return[...document.querySelectorAll('a[href],button,[role="button"],summary')].filter(te).map(t=>{const r=ye(t),n=uo(t),o=nl([r,n,Qt(t)].join(" "));return o?rr({kind:o,label:r,href:n,heading:Qt(t),safeClick:!Je.test(r)}):null}).filter(Boolean).filter(Ze(t=>`${t.kind}:${t.label}:${t.href||""}`)).slice(0,Math.max(1,Math.min(e,30)))}function nl(e){for(const[t,r]of Object.entries(Vu))if(r.test(e))return t;return""}function ol(e){return(Array.isArray(e)?e:String(e||"").split(/[,|]/u)).map(t=>E(t).toLowerCase()).filter(Boolean)}function Yt(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:dl(o,e,t.snippetChars),tag:n.parentElement?.tagName?.toLowerCase()||"",heading:Qt(n.parentElement)})).filter(n=>n.snippet).filter(Ze(n=>n.snippet)).slice(0,t.textMatches)}function il(e){return[...document.querySelectorAll("img")].filter(te).map(t=>({alt:X(E(t.getAttribute("alt")||t.getAttribute("aria-label")||"")),title:X(E(t.getAttribute("title")||"")),src:Xt(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(Ze(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 al(e){return(Array.isArray(e)?e:String(e||"").split(/\n|;|\|/u)).map(t=>X(t).slice(0,180)).filter(Boolean).slice(0,8)}function sl({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||!te(o)||/^(script|style|noscript|template|svg)$/iu.test(o.tagName||"")||fl(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 ul(e){return[...document.querySelectorAll('button,a,[role="button"],summary,input[type="button"],input[type="submit"]')].filter(te).find(t=>ye(t).toLocaleLowerCase("tr-TR").includes(e.toLocaleLowerCase("tr-TR")))}function ll(e){const t=Yt(e,{...ge,textMatches:1})[0];return t?[...document.querySelectorAll("body *")].filter(te).find(r=>E(r.textContent).includes(t.snippet.slice(0,24))):null}function ye(e){return e?X(E(e.getAttribute?.("aria-label")||e.getAttribute?.("title")||e.getAttribute?.("alt")||e.value||e.textContent||"")).slice(0,90):""}function Qt(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 X(n).slice(0,90);t=t.parentElement}return""}function co(e){return e?rr({sku:E(e.sku||e.id||""),name:E(e.name||e.title||""),url:Xt(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 dl(e,t,r){const n=X(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 te(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 fl(e){return!!e.closest?.('input,textarea,select,[contenteditable="true"]')}function uo(e){return e.tagName?.toLowerCase()!=="a"?null:Xt(e.getAttribute("href"))}function Xt(e){if(!e)return"";try{const t=new URL(e,window.location.href);return/^https?:$/u.test(t.protocol)?(t.hash="",er(t),t.href):""}catch{return""}}function pl(){const e=new URL(window.location.href);return er(e),`${e.origin}${e.pathname}${e.search}`}function ml(){return{width:window.innerWidth,height:window.innerHeight,scrollY:Math.round(window.scrollY||0),documentHeight:Math.round(document.documentElement?.scrollHeight||0)}}function X(e){return E(e).replace(/https?:\/\/[^\s?#]+(?:\?[^#\s]*)?/giu,gl).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 gl(e){try{const t=new URL(e);return t.hash="",er(t),t.href}catch{return String(e||"").replace(/\?[^#\s]*/u,"?redacted")}}function er(e){for(const[t,r]of[...e.searchParams.entries()]){const n=String(r||"");(zu.test(t)||Gu.test(n))&&e.searchParams.set(t,"redacted")}return e}function E(e){return String(e||"").replace(/\s+/gu," ").trim()}function tr(e){return{headings:Te(e.maxHeadings,ge.headings,20),products:Te(e.maxProducts,ge.products,20),controls:Te(e.maxControls,ge.controls,30),textMatches:Te(e.maxMatches||e.limit,ge.textMatches,20),snippetChars:Te(e.snippetChars,ge.snippetChars,320)}}function Te(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 rr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function nr(e){try{return typeof e=="function"?e():null}catch{return null}}function Ze(e){const t=new Set;return r=>{const n=e(r);return!n||t.has(n)?!1:(t.add(n),!0)}}d.AgentError=z,d.ContextStore=fr,d.FALLBACK_STATUS=qc,d.action=ki,d.actionButtonsUiSpec=Ya,d.alignProductsToTable=Yr,d.anonymousRequestText=nn,d.beErrorToAgentError=ut,d.buildActivityVisualization=mn,d.buildPhotoSimilarityProfile=is,d.buildProductSimilarityProfile=ce,d.buildSimilarityQueries=as,d.canUseModuleWorker=xt,d.caughtToStreamError=hr,d.compactAccountConfig=on,d.compactContextProducts=Ua,d.compactObject=ru,d.compactProductSurfaceForLlm=Jn,d.comparisonResultForUi=Va,d.comparisonUiSpec=Ja,d.createActivityCollector=cn,d.createBrowserMemory=At,d.createDiagnosticsTool=Ls,d.createEndpointCachePolicies=Xa,d.createEndpointHandlers=es,d.createFlow=Qa,d.createGssToolAliases=Wc,d.createIframeScraper=eu,d.createInjectorAdapter=Lr,d.createLocalRefStore=ir,d.createMainThreadInjectorAdapter=Br,d.createModuleWorker=Zr,d.createOpenProductPageTool=nu,d.createPrivacyHelpers=zn,d.createProductSurfaceInspector=Hn,d.createReadPageStep=Dc,d.createReadPageTool=Is,d.createResolveProductsTool=su,d.createSiteAwarenessTools=Ku,d.declarativeBeOpCache=$n,d.defaultPiiPatternPack=Pt,d.defaultPiiPatterns=Ct,d.done=ft,d.elapsedMs=q,d.endpointStableKey=Qr,d.error=vr,d.fallbackStatus=Uc,d.filterActivityEntries=En,d.firstArrayValue=Fu,d.formatJsonHtml=jn,d.getOrCreateActivityCollector=un,d.groupForEntry=pn,d.gssSearchCapabilities=qn,d.homePanelReset=iu,d.httpErrorToAgentError=yr,d.inputHashCachePolicy=Nn,d.inspectProductSurface=Wn,d.installActivityFetchPatch=wn,d.installBrowserTools=Rs,d.installFetchTransportBridge=wa,d.installIframeScraperBypass=tu,d.installLocalAgenticActivityDebug=Oc,d.isFallbackStatus=Fc,d.isRef=ar,d.jsonResponse=rs,d.llmCacheKey=pt,d.mergeProductSurfaceEvidence=du,d.metadata=bi,d.mountAccount=qa,d.mountActivityOverlay=An,d.navigateSameTab=Dn,d.ndjsonResponse=ts,d.normalizeComparisonTable=Et,d.normalizeEntry=ln,d.normalizeProduct=Ie,d.normalizeSameOriginUrl=Fn,d.normalizeSimilarityText=V,d.nowIso=lr,d.plainMessageContent=au,d.productDetailsUiSpec=Wa,d.productFactsKey=vi,d.productSkuKey=_i,d.productSurfaceReviewText=fu,d.productsUiSpec=Ha,d.rankSimilarProducts=ss,d.rankSimilarProductsAsync=cs,d.recordBeDebugPayload=Mt,d.redactPii=jt,d.requestText=rn,d.resolveBeUrl=vs,d.resolveFlow=Ar,d.resolveProductCandidates=Gn,d.retailAnonymizeMessages=Uu,d.retailAnonymousRequestText=qu,d.retailRedactPii=$u,d.routeFlowParams=ao,d.routeSkuList=Du,d.scoreSimilarityCandidate=Tt,d.sectionForKind=dn,d.setAssistantHostVisible=Ss,d.severityForEntry=fn,d.shouldInstallActivityDebug=Mn,d.stableKey=oe,d.startLazyRuntimeLoader=Os,d.stickyContextKey=it,d.summarizeDebugState=Ae,d.summarizePanelState=qe,d.summarizeUiSpec=It,d.textChunk=_r,d.textKey=Ai,d.tokenizeSimilarityText=N,d.trimProductFactsCore=Le,d.trimProductFactsListCore=Si,d.uiSpec=wi,d.uniqueProductsBySku=Vn,d.withAccountConfig=Cs,d.withDeclarativeBeOpCache=Nc,d.wrapActivityBeacon=hn,d.wrapActivityTools=yn,d.wrapActivityTransport=bn})(this.Gengage=this.Gengage||{});
|