@rtrvr-ai/rover 1.3.0 → 1.3.1
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/embed.js +1 -1
- package/dist/rover.js +2 -1
- package/package.json +1 -1
package/dist/embed.js
CHANGED
|
@@ -1633,4 +1633,4 @@ Author: ${a.textContent} `),i.textContent&&(t+=`Comment: ${i.textContent}
|
|
|
1633
1633
|
`;let Xt=document.createElement("div");Xt.className="shortcutsEmptyState";let rn=document.createElement("div");rn.className="shortcutsHeading",rn.textContent=o?`Hey ${o}! What can I help with?`:`What can ${t} help you with?`;let qe=document.createElement("div");qe.className="shortcutsGrid",Xt.appendChild(rn),Xt.appendChild(qe),je.appendChild(Xt);let Rn=document.createElement("div");Rn.className="shortcutsBar";let Ut=document.createElement("div");Ut.className="questionPrompt";let kn=document.createElement("div");kn.className="questionPromptTitle",kn.textContent="Need a bit more info";let Ft=document.createElement("form");Ft.className="questionPromptForm";let Sn=document.createElement("div");Sn.className="questionPromptList",Ft.appendChild(Sn);let nr=document.createElement("div");nr.className="questionPromptActions";let mn=document.createElement("button");mn.type="submit",mn.className="questionPromptSubmit",mn.textContent="Continue",nr.appendChild(mn),Ft.appendChild(nr),Ut.appendChild(kn),Ut.appendChild(Ft);let Kt=document.createElement("form");Kt.className="composer";let on=document.createElement("textarea");on.rows=1,on.placeholder=`Ask ${t} to act on this website...`,Kt.appendChild(on);let gn=document.createElement("button");gn.type="submit",gn.className="sendBtn",gn.innerHTML='<svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>',Kt.appendChild(gn);let ye=document.createElement("div");ye.className="resizeHandle",ye.setAttribute("aria-hidden","true"),P.appendChild(q),P.appendChild(qn),P.appendChild(Ht),P.appendChild(Rn),P.appendChild(Ut),P.appendChild(Kt),P.appendChild(ye),m.appendChild(p),m.appendChild(S),m.appendChild(P),s.appendChild(u),s.appendChild(m);let Ue=on,bn=Ht.querySelector(".taskSuggestionText"),ut=Ht.querySelector(".taskSuggestionBtn.primary"),$n=Ht.querySelector(".taskSuggestionBtn.secondary"),vr=new Set,Wn=new Map,We=[],Tr="controller",_r=!1,sn=!1,In=!1,an=e.shortcuts?.slice(0,12)||[],dt=null,Bt=!1,Tt=null,An=!1,qt=!1,Cn=0,Vn=!1,c=null,E=null,y=!1,b=null,f=null,d={};function g(){An=!An,mt.classList.toggle("visible",An)}function T(){An=!1,mt.classList.remove("visible")}function L(N){an=N.filter($=>$&&$.enabled!==!1).slice(0,12),qe.innerHTML="";for(let $ of an){let Q=document.createElement("button");if(Q.type="button",Q.className="shortcutCard",$.icon){let ie=document.createElement("span");ie.className="shortcutCardIcon",ie.textContent=$.icon,Q.appendChild(ie)}let le=document.createElement("span");if(le.className="shortcutCardLabel",le.textContent=$.label,Q.appendChild(le),$.description){let ie=document.createElement("span");ie.className="shortcutCardDesc",ie.textContent=$.description,Q.appendChild(ie)}Q.addEventListener("click",()=>e.onShortcutClick?.($)),qe.appendChild(Q)}Rn.innerHTML="";for(let $ of an){let Q=document.createElement("button");if(Q.type="button",Q.className="shortcutChip",$.icon){let ie=document.createElement("span");ie.className="shortcutChipIcon",ie.textContent=$.icon,Q.appendChild(ie)}let le=document.createTextNode($.label);Q.appendChild(le),Q.addEventListener("click",()=>e.onShortcutClick?.($)),Rn.appendChild(Q)}C()}function C(){let N=an.length>0,$=!!b?.questions?.length,Q=N&&!In&&!sn,le=N&&In&&!sn&&!$;Xt.classList.toggle("visible",Q),Rn.classList.toggle("visible",le)}function D(N){let $=ht(N);if($){if(B.textContent=$,S.classList.contains("visible")){S.classList.add("textVisible");return}Vn||P.classList.contains("open")||(Vn=!0,S.classList.remove("dismissing","textVisible"),S.classList.add("visible"),E&&(clearTimeout(E),E=null),E=setTimeout(()=>{E=null,S.classList.add("textVisible")},800))}}function U(){if(E&&(clearTimeout(E),E=null),!S.classList.contains("visible"))return;S.classList.add("dismissing");let N=()=>{S.classList.remove("visible","dismissing"),S.removeEventListener("animationend",N)};S.addEventListener("animationend",N),c&&(clearTimeout(c),c=null)}function G(N){o=N||void 0,o?rn.textContent=`Hey ${o}! What can I help with?`:rn.textContent=`What can ${t} help you with?`}function X(N){if(!N||!Array.isArray(N.questions))return[];let $=[],Q=new Set;for(let le=0;le<N.questions.length;le+=1){let ie=N.questions[le];if(!ie||typeof ie!="object")continue;let Qe=String(ie.key||ie.id||"").trim()||`clarification_${le+1}`,He=String(ie.query||ie.question||"").trim();if(!He)continue;let Ze=typeof ie.required=="boolean",St=typeof ie.optional=="boolean",Je=Ze?!!ie.required:St?!ie.optional:!0;Q.has(Qe)||(Q.add(Qe),$.push({key:Qe,query:He,...typeof ie.id=="string"&&ie.id.trim()?{id:ie.id.trim()}:{},...typeof ie.question=="string"&&ie.question.trim()?{question:ie.question.trim()}:{},...Array.isArray(ie.choices)?{choices:ie.choices}:{},required:Je}))}return $.slice(0,6)}function oe(N){return N.map($=>{let Q=Array.isArray($.choices)?$.choices.map(ie=>ht(String(ie||""))).filter(Boolean).join("|"):"",le=$.required===!1?"optional":"required";return`${$.key}::${ht($.query)}::${Q}::${le}`}).join("||")}function we(N){let $=ht(N.query||N.question||"");if(!$)return`Answer for ${N.key}`;let Q=$.replace(/\s+/g," ").replace(/[?.!:\s]+$/,"").slice(0,72);return Q?`Answer: ${Q}`:`Answer for ${N.key}`}function ne(N){for(let $ of Array.from(Ft.querySelectorAll(".questionPromptInput"))){let Q=$;if(Q.dataset.key===N)return Q}return null}function ee(N){let $=X(N),Q=document.activeElement,le=Q instanceof HTMLInputElement&&Q.classList.contains("questionPromptInput")&&Ut.contains(Q)?Q:null,ie=le?.dataset.key,Qe=le?.selectionStart??null,He=le?.selectionEnd??null;if(!$.length){b=null,f=null,d={},Sn.innerHTML="",Ut.classList.remove("visible"),C();return}let Ze=oe($),St=Ze!==f||!b;if(b={questions:$},St){let Je=d;d={},Sn.innerHTML="";for(let it of b.questions){let Qt=document.createElement("label");Qt.className="questionPromptItem";let Jt=document.createElement("span");Jt.className="questionPromptLabel",Jt.textContent=it.required===!1?`${it.query} (optional)`:it.query,Qt.appendChild(Jt);let Ct=document.createElement("input");Ct.type="text",Ct.className="questionPromptInput",Ct.dataset.key=it.key,Ct.placeholder=we(it),Ct.required=it.required!==!1;let cn=String(Je[it.key]||"");d[it.key]=cn,Ct.value=cn,Ct.addEventListener("input",()=>{d[it.key]=Ct.value,Ct.classList.remove("invalid")}),Qt.appendChild(Ct),Sn.appendChild(Qt)}f=Ze}if(Ut.classList.add("visible"),Te(),C(),ie){let Je=ne(ie);if(Je){if(Je.focus(),Qe!==null||He!==null){let it=Qe??Je.value.length,Qt=He??it;try{Je.setSelectionRange(it,Qt)}catch{}}return}}if(St){let it=b.questions.find(Ct=>!ht(d[Ct.key]||""))?.key||b.questions[0]?.key;if(!it)return;let Qt=ne(it),Jt=!Q||Q===document.body||!P.contains(Q);Qt&&Jt&&Qt.focus()}}function ce(){sn&&y?(rt.classList.add("visible"),je.appendChild(rt),he()):rt.classList.remove("visible")}function ge(N,$=0){m.dataset.mood=N,Tt!=null&&(window.clearTimeout(Tt),Tt=null),$>0&&N!=="idle"&&(Tt=window.setTimeout(()=>{m.dataset.mood="idle",ce(),Tt=null},$))}function Xe(){return je.scrollHeight-je.scrollTop-je.clientHeight<60}function he(){qt?ot.classList.add("visible"):(requestAnimationFrame(()=>{je.scrollTo({top:je.scrollHeight,behavior:"smooth"}),Cn=Date.now()}),ot.classList.remove("visible"))}je.addEventListener("scroll",()=>{Date.now()-Cn<200||(Xe()?(qt=!1,ot.classList.remove("visible")):(qt=!0,ot.classList.add("visible")))},{passive:!0}),ot.addEventListener("click",()=>{qt=!1,Cn=Date.now(),je.scrollTo({top:je.scrollHeight,behavior:"smooth"}),ot.classList.remove("visible")});function Te(){let N=Tr==="observer"&&!_r;Ue.disabled=N,mn.disabled=N;for(let $ of Array.from(Ft.querySelectorAll(".questionPromptInput")))$.disabled=N}function _e(N){Bt=N,m.dataset.showDetails=N?"true":"false",xn.textContent=Bt?"Hide details":"Show details";for(let $ of We){let Q=$.dataset.status,le=Q==="success"||Q==="error"||Q==="info";$.classList.toggle("compact",!Bt&&le)}}function l(){m.style.display="",P.classList.remove("closing"),P.classList.add("open"),U(),ge("idle"),e.onOpen?.(),Ue.disabled||Ue.focus()}function w(){if(T(),!P.classList.contains("open")){e.onClose?.();return}P.classList.remove("open"),P.classList.add("closing"),ge("idle");let N=()=>{P.classList.remove("closing"),P.removeEventListener("animationend",N)};P.addEventListener("animationend",N),e.onClose?.()}function R(){m.style.display=""}function _(){w(),m.style.display="none"}function k(N,$,Q){let le=ht($),ie=Q?.blocks;if(!le&&(!ie||ie.length===0))return;let Qe=document.createElement("div");Qe.className=`entry message ${N}`;let He=document.createElement("div");He.className="bubble",N==="assistant"?He.appendChild(dp(le,ie)):He.textContent=le;let Ze=document.createElement("div");Ze.className="stamp",Ze.textContent=bl(Date.now()),Qe.appendChild(He),Qe.appendChild(Ze),je.appendChild(Qe),N==="assistant"&&sn&&y&&(y=!1,ce()),In=!0,C(),N==="user"?ge("typing",1200):N==="assistant"?ge("success",1400):ge("running",900),he()}function O(){for(let N of Array.from(je.querySelectorAll(".entry.message")))N.remove();In=!1,ee(void 0),C()}function V(N){let $=Wn.get(N);if($)return $;let Q=document.createElement("div");Q.className="entry trace pending";let le=document.createElement("div");le.className="traceTop";let ie=document.createElement("div");ie.className="traceMeta";let Qe=document.createElement("span");Qe.className="traceStage",Qe.textContent="step";let He=document.createElement("div");He.className="traceTitle";let Ze=document.createElement("div");Ze.className="traceTs",ie.appendChild(Qe),ie.appendChild(He),le.appendChild(ie),le.appendChild(Ze);let St=document.createElement("div");return St.className="traceDetail",Q.appendChild(le),Q.appendChild(St),Wn.set(N,Q),We.push(Q),je.appendChild(Q),Q}function K(N,$){let Q=Number($.ts)||Date.now(),le=Zf($),ie=N.querySelector(".traceTop"),He=ie.querySelector(".traceMeta").querySelector(".traceStage"),Ze=ie.querySelector(".traceTitle"),St=ie.querySelector(".traceTs"),Je=N.querySelector(".traceDetail"),it=yl($.title||"");Ze.textContent=it.plainTitle||"Step",He.textContent=it.stage||$.kind||"step",He.style.display=it.stage||$.kind==="status"||$.kind==="plan"||$.kind==="thought"?"":"none",St.textContent=bl(Q),Je.innerHTML="";let Qt=Array.isArray($.detailBlocks)?$.detailBlocks:[],Jt=ht($.detail||"");if(Qt.length>0){for(let cn of Qt){let ma=vl(cn);ma&&Je.appendChild(ma)}if(Jt){let cn=document.createElement("div");cn.className="rvLine",cn.appendChild(Xn(Jt)),Je.insertBefore(cn,Je.firstChild)}Je.style.display=""}else if(Jt){let cn=$.kind==="thought"?150:$.kind==="tool_start"||$.kind==="tool_result"?100:280;Jt.length>cn?Je.appendChild(pi(Jt,cn)):Je.appendChild(Xn(Jt)),Je.style.display=""}else Je.style.display="none";N.classList.remove("pending","success","error","info"),N.classList.add(le),N.dataset.status=le,N.dataset.kind=$.kind,N.dataset.visibility=op($);let Ct=le==="success"||le==="error"||le==="info";N.classList.toggle("compact",!Bt&&Ct),le==="error"?ge("error",2200):le==="success"?ge("success",1200):le==="pending"&&ge("running",800)}function fe(N){let $=ht(N.title||"");if(!$||$.toLowerCase()==="assistant update")return;let Q=N.id||El("timeline");if(N.id&&vr.has(Q))return;vr.add(Q);let le=ep(N),ie=le==="run"||le.startsWith("tool:")||N.kind==="tool_result"||N.kind==="status"&&Wn.has(le),Qe=V(ie?le:`${le}:${Q}`);K(Qe,{...N,title:$}),N.kind==="thought"&&sn&&y&&(y=!1,ce()),$.toLowerCase()==="run completed"&&_e(!1),he()}function Ae(){vr.clear(),Wn.clear(),We.length=0;for(let N of Array.from(je.querySelectorAll(".entry.trace")))N.remove()}function Se(N){let $=!!N?.visible;Ht.classList.toggle("visible",$),bn.textContent=N?.text||"Looks like a new request. Start a new task?",ut.textContent=N?.primaryLabel||"Start new",$n.textContent=N?.secondaryLabel||"Continue"}function De(N){let $=String(N||"ready");Re.textContent=$;let Q=$.toLowerCase();Q.includes("error")||Q.includes("failed")?ge("error",1800):Q==="ready"||Q.includes("complete")?ge("idle"):ge("running",1e3)}function gt(N){sn=N,N?y=!0:y=!1,ce(),Ot.classList.toggle("visible",N),Ge.style.display=N?"none":"",C()}function $t(N,$){Tr=N,_r=N==="observer"?$?.canComposeInObserver===!0:!0,Te(),Ge.classList.remove("controller","observer"),Ge.classList.add(N),N==="controller"?(Ge.textContent="active",vt.style.display="none",Ue.placeholder=`Ask ${t} to act on this website...`):(Ge.textContent="observer",$?.canTakeControl!==!1?vt.style.display="":vt.style.display="none",$?.note?Ue.placeholder=$.note:_r?Ue.placeholder="Send to take control and run here.":$?.activeLogicalTabId&&$?.localLogicalTabId&&$.activeLogicalTabId!==$.localLogicalTabId?Ue.placeholder=`Observing: ${t} is acting in tab #${$.activeLogicalTabId}`:Ue.placeholder="Observer mode. Take control to run actions here.")}function Gn(){Tt!=null&&(window.clearTimeout(Tt),Tt=null),E&&(window.clearTimeout(E),E=null),c&&(window.clearTimeout(c),c=null),document.removeEventListener("keydown",Ke),a.remove(),i.remove()}p.addEventListener("click",()=>{P.classList.contains("open")?w():l()}),Y.addEventListener("click",N=>{N.stopPropagation(),U()}),S.addEventListener("click",()=>{U(),l()}),Me.addEventListener("click",()=>w()),ve.addEventListener("click",N=>{N.stopPropagation(),g()}),m.addEventListener("click",N=>{An&&!mt.contains(N.target)&&N.target!==ve&&T()}),Le.addEventListener("click",()=>{T(),sn&&e.onCancelRun?(dt="new_task",Se({visible:!0,text:"A task is in progress. Cancel it and start new?",primaryLabel:"Cancel & start new",secondaryLabel:"Keep running"})):e.onNewTask?.()}),Pt.addEventListener("click",()=>{T(),sn&&e.onCancelRun?(dt="end_task",Se({visible:!0,text:"A task is in progress. Cancel and end it?",primaryLabel:"Cancel & end",secondaryLabel:"Keep running"})):e.onEndTask?.()}),xn.addEventListener("click",()=>{T(),_e(!Bt)}),vt.addEventListener("click",()=>{T(),e.onRequestControl?.()}),Ot.addEventListener("click",()=>{e.onCancelRun?.()}),ut.addEventListener("click",()=>{if(dt){let N=dt;dt=null,Se({visible:!1}),e.onCancelRun?.(),N==="new_task"?e.onNewTask?.():N==="end_task"&&e.onEndTask?.();return}e.onTaskSuggestionPrimary?.()}),$n.addEventListener("click",()=>{if(dt){dt=null,Se({visible:!1});return}e.onTaskSuggestionSecondary?.()}),Ue.addEventListener("input",()=>{Ue.style.height="auto",Ue.style.height=`${Math.min(96,Math.max(44,Ue.scrollHeight))}px`}),Ft.addEventListener("submit",N=>{if(N.preventDefault(),Ue.disabled||!b?.questions?.length)return;let $={},Q=[],le=null;for(let He of b.questions){let Ze=ne(He.key);if(!Ze)continue;let St=ht(Ze.value),Je=He.required!==!1;if(!St&&Je){Ze.classList.add("invalid"),le||(le=Ze);continue}if(!St){Ze.classList.remove("invalid"),delete d[He.key];continue}Ze.classList.remove("invalid"),d[He.key]=St,$[He.key]=St,Q.push(`${He.key}: ${St}`)}if(le){le.focus();return}let ie=b.questions.map(He=>He.key),Qe=Q.join(`
|
|
1634
1634
|
`);e.onSend(Qe,{askUserAnswers:{answersByKey:$,rawText:Qe,keys:ie}}),ee(void 0)}),Ue.addEventListener("keydown",N=>{N.key==="Enter"&&!N.shiftKey&&!N.isComposing&&(N.preventDefault(),Kt.requestSubmit())}),Kt.addEventListener("submit",N=>{if(N.preventDefault(),Ue.disabled)return;let $=ht(Ue.value);$&&(Se({visible:!1}),e.onSend($),Ue.value="",Ue.style.height="44px")}),s.addEventListener("keydown",N=>{let $=N;$.key==="Escape"&&P.classList.contains("open")&&($.stopPropagation(),w())});let Ke=N=>{N.code==="Period"&&N.shiftKey&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),N.stopPropagation(),P.classList.contains("open")?w():l())};document.addEventListener("keydown",Ke);let Ce=null,Fe=N=>{if(!Ce)return;let $=Ce.startX-N.clientX,Q=N.clientY-Ce.startY,le=Math.max(320,Math.min(window.innerWidth-16,Ce.startW+$)),ie=Math.max(460,Math.min(window.innerHeight-16,Ce.startH+Q));P.style.width=`${le}px`,P.style.height=`${ie}px`},En=()=>{Ce=null,window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",En)};if(ye.addEventListener("pointerdown",N=>{window.matchMedia("(max-width: 640px)").matches||(N.preventDefault(),Ce={startX:N.clientX,startY:N.clientY,startW:P.getBoundingClientRect().width,startH:P.getBoundingClientRect().height},window.addEventListener("pointermove",Fe),window.addEventListener("pointerup",En))}),I){let N=()=>{I.style.display="none",A.style.display="grid"};I.addEventListener("error",N,{once:!0}),A.style.display="none"}if(ae){let N=()=>{ae.style.display="none",ue.style.display="grid"};ae.addEventListener("error",N,{once:!0}),ue.style.display="none"}return $t("controller"),_e(!1),an.length>0&&L(an),{addMessage:k,setQuestionPrompt:ee,clearMessages:O,addTimelineEvent:fe,clearTimeline:Ae,setTaskSuggestion:Se,setStatus:De,setRunning:gt,setExecutionMode:$t,setShortcuts:L,showGreeting:D,dismissGreeting:U,setVisitorName:G,open:l,close:w,show:R,hide:_,destroy:Gn}}var fp="rover:shared:",pp="rover:channel:";function re(){return Date.now()}function Tn(e){try{return`${e}-${crypto.randomUUID()}`}catch{return`${e}-${Date.now()}-${Math.floor(Math.random()*1e5)}`}}function Ms(e){let t=String(e||"").trim();if(!t)return"";try{return new URL(t,window.location.href).toString()}catch{return t}}function _l(e){try{return new URL(e).hostname.toLowerCase()}catch{return""}}function Rl(e){if(!e||typeof e!="object")return;let t=typeof e.taskId=="string"?e.taskId.trim():"";if(!t)return;let n=e.status==="completed"||e.status==="ended"||e.status==="running"?e.status:"running";return{taskId:t,status:n,startedAt:Number(e.startedAt)||re(),lastUserAt:Number(e.lastUserAt)||void 0,lastAssistantAt:Number(e.lastAssistantAt)||void 0,boundaryReason:typeof e.boundaryReason=="string"?e.boundaryReason:void 0,endedAt:Number(e.endedAt)||void 0}}function kl(e){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return}}}function mi(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n.type;if(r==="text"){let o=String(n.text||"");if(!o)continue;t.push({type:"text",text:o});continue}if(r==="tool_output"||r==="json"){let o=kl(n.data);t.push({type:r,data:o,label:typeof n.label=="string"?n.label:void 0,toolName:typeof n.toolName=="string"?n.toolName:void 0})}}return t.length?t:void 0}function xl(e,t){if(!Array.isArray(e))return[];let n=[];for(let r of e.slice(-t)){let o=kl(r);o!==void 0&&n.push(o)}return n}function Sl(e){if(!e||typeof e!="object")return;let t=Array.isArray(e.pendingAskUser?.questions)?e.pendingAskUser.questions.map((s,a)=>{let u=String(s?.key||s?.id||"").trim()||`clarification_${a+1}`,m=String(s?.query||s?.question||"").trim();if(m)return{key:u,query:m,id:typeof s?.id=="string"?s.id:void 0,question:typeof s?.question=="string"?s.question:void 0,choices:Array.isArray(s?.choices)?s.choices:void 0}}).filter(s=>!!s).slice(0,6):[],n=s=>s.slice(-80).map(a=>({role:typeof a?.role=="string"?a.role:"assistant",content:typeof a?.content=="string"?a.content:""})).filter(a=>!!a.content),r=Array.isArray(e.history)?n(e.history):[],o=xl(e.plannerHistory,40),i=xl(e.agentPrevSteps,80);return{trajectoryId:typeof e.trajectoryId=="string"?e.trajectoryId:void 0,history:r,plannerHistory:o,agentPrevSteps:i,pendingAskUser:t.length?{questions:t,source:e.pendingAskUser?.source==="planner"?"planner":"act",askedAt:Number(e.pendingAskUser?.askedAt)||re()}:void 0,updatedAt:Number(e.updatedAt)||re()}}function Ds(e,t){return{version:2,siteId:e,sessionId:t,seq:1,updatedAt:re(),lease:void 0,tabs:[],nextLogicalTabId:1,activeLogicalTabId:void 0,uiMessages:[],timeline:[],uiStatus:void 0,activeRun:void 0,taskEpoch:1,task:void 0,workerContext:void 0,workflowLock:void 0}}function Hr(e,t,n){let r=Ds(t,n);if(!e||typeof e!="object")return r;let o={...r,version:2,siteId:t,sessionId:n,seq:Math.max(1,Number(e.seq)||1),updatedAt:Number(e.updatedAt)||re(),tabs:Array.isArray(e.tabs)?e.tabs.map(a=>({logicalTabId:Math.max(1,Number(a?.logicalTabId)||0),runtimeId:typeof a?.runtimeId=="string"?a.runtimeId:void 0,url:String(a?.url||""),title:typeof a?.title=="string"?a.title:void 0,openedAt:Number(a?.openedAt)||re(),updatedAt:Number(a?.updatedAt)||re(),external:!!a?.external,openerRuntimeId:typeof a?.openerRuntimeId=="string"?a.openerRuntimeId:void 0})).filter(a=>!!a.logicalTabId):[],nextLogicalTabId:Math.max(1,Number(e.nextLogicalTabId)||1),activeLogicalTabId:Number(e.activeLogicalTabId)||void 0,uiMessages:Array.isArray(e.uiMessages)?e.uiMessages.map(a=>({id:String(a?.id||Tn("msg")),role:a?.role==="user"||a?.role==="assistant"||a?.role==="system"?a.role:"system",text:String(a?.text||""),blocks:mi(a?.blocks),ts:Number(a?.ts)||re(),sourceRuntimeId:typeof a?.sourceRuntimeId=="string"?a.sourceRuntimeId:void 0})).filter(a=>!!a.text||!!a.blocks?.length):[],timeline:Array.isArray(e.timeline)?e.timeline.map(a=>({id:String(a?.id||Tn("timeline")),kind:String(a?.kind||"status"),title:String(a?.title||"Step"),detail:typeof a?.detail=="string"?a.detail:void 0,detailBlocks:mi(a?.detailBlocks),status:a?.status==="pending"||a?.status==="success"||a?.status==="error"||a?.status==="info"?a.status:void 0,ts:Number(a?.ts)||re(),sourceRuntimeId:typeof a?.sourceRuntimeId=="string"?a.sourceRuntimeId:void 0})).filter(a=>!!a.title):[],taskEpoch:Math.max(1,Number(e.taskEpoch)||1),task:Rl(e.task),workerContext:Sl(e.workerContext),uiStatus:typeof e.uiStatus=="string"?e.uiStatus:void 0,activeRun:e.activeRun&&typeof e.activeRun=="object"?{runId:String(e.activeRun.runId||""),text:String(e.activeRun.text||""),runtimeId:String(e.activeRun.runtimeId||""),startedAt:Number(e.activeRun.startedAt)||re(),updatedAt:Number(e.activeRun.updatedAt)||re()}:void 0,lease:e.lease&&typeof e.lease=="object"&&e.lease.holderRuntimeId?{holderRuntimeId:String(e.lease.holderRuntimeId),expiresAt:Number(e.lease.expiresAt)||0,updatedAt:Number(e.lease.updatedAt)||re()}:void 0,workflowLock:e.workflowLock&&typeof e.workflowLock=="object"&&e.workflowLock.runtimeId&&e.workflowLock.runId?{runtimeId:String(e.workflowLock.runtimeId),runId:String(e.workflowLock.runId),lockedAt:Number(e.workflowLock.lockedAt)||re(),expiresAt:Number(e.workflowLock.expiresAt)||0}:void 0},i=o.tabs.length,s=new Set;return o.tabs=o.tabs.filter(a=>s.has(a.logicalTabId)?!1:(s.add(a.logicalTabId),!0)),o.nextLogicalTabId<=(o.tabs.at(-1)?.logicalTabId??0)&&(o.nextLogicalTabId=o.tabs.reduce((a,u)=>Math.max(a,u.logicalTabId),0)+1),i>0&&o.tabs.length<i&&console.warn(`[rover] sanitizeSharedState: dropped ${i-o.tabs.length} invalid/duplicate tab entries`),o}var bi=class bi{constructor(t){W(this,"siteId");W(this,"sessionId");W(this,"runtimeId");W(this,"leaseMs");W(this,"heartbeatMs");W(this,"maxMessages");W(this,"maxTimeline");W(this,"onRoleChange");W(this,"onStateChange");W(this,"onSwitchRequested");W(this,"key");W(this,"channelName");W(this,"state");W(this,"channel",null);W(this,"heartbeatTimer",null);W(this,"storageHandler",null);W(this,"localLogicalTabId");W(this,"closing",!1);W(this,"started",!1);W(this,"pendingRpcRequests",new Map);W(this,"rpcRequestHandler");W(this,"lastNotifiedRole");W(this,"roleChangeTimer",null);this.siteId=t.siteId,this.sessionId=t.sessionId,this.runtimeId=t.runtimeId,this.leaseMs=Math.max(4e3,Number(t.leaseMs)||12e3),this.heartbeatMs=Math.max(800,Number(t.heartbeatMs)||2e3),this.maxMessages=Math.max(40,Number(t.maxMessages)||220),this.maxTimeline=Math.max(40,Number(t.maxTimeline)||280),this.onRoleChange=t.onRoleChange,this.onStateChange=t.onStateChange,this.onSwitchRequested=t.onSwitchRequested,this.key=`${fp}${this.siteId}:${this.sessionId}`,this.channelName=`${pp}${this.siteId}:${this.sessionId}`,this.state=this.loadState()}pruneDetachedTabs(t,n){let r=!!n?.dropRuntimeDetached,o=!!n?.dropAllDetachedExternal,i=re(),s=t.tabs.length;t.tabs=t.tabs.filter(a=>a.runtimeId?a.runtimeId===this.runtimeId?!0:i-Math.max(a.updatedAt||0,a.openedAt||0)<=45e3:r&&a.openerRuntimeId===this.runtimeId?!1:a.external?o?!1:i-Math.max(a.updatedAt||0,a.openedAt||0)<=12e4:i-Math.max(a.updatedAt||0,a.openedAt||0)<=6e5),s!==t.tabs.length&&(t.activeLogicalTabId&&!t.tabs.some(a=>a.logicalTabId===t.activeLogicalTabId)&&(t.activeLogicalTabId=this.localLogicalTabId||t.tabs[0]?.logicalTabId),t.nextLogicalTabId<=(t.tabs.at(-1)?.logicalTabId??0)&&(t.nextLogicalTabId=t.tabs.reduce((a,u)=>Math.max(a,u.logicalTabId),0)+1))}start(){this.started||(this.started=!0,this.mutate("local",t=>{this.pruneDetachedTabs(t,{dropRuntimeDetached:!0,dropAllDetachedExternal:!0})}),this.registerCurrentTab(window.location.href,document.title||void 0),this.claimLease(!1),this.state.task||this.mutate("local",t=>{t.task={taskId:Tn("task"),status:"running",startedAt:re(),boundaryReason:"session_start"}}),typeof BroadcastChannel<"u"&&(this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=t=>{let n=t.data;if(!(!n||typeof n!="object")){if(n.type==="state"&&n.state){let r=Hr(n.state,this.siteId,this.sessionId);this.applyIncomingState(r)}n.type==="switch_request"&&n.targetRuntimeId===this.runtimeId&&this.onSwitchRequested?.(Number(n.logicalTabId)||0),n.type==="rpc_request"&&n.targetRuntimeId===this.runtimeId&&this.handleInboundRpcRequest(n),n.type==="rpc_response"&&n.targetRuntimeId===this.runtimeId&&this.handleInboundRpcResponse(n),n.type==="tab_navigated"&&n.runtimeId&&n.runtimeId!==this.runtimeId&&this.handleRemoteNavigation(n),n.type==="tab_closing"&&n.runtimeId&&n.runtimeId!==this.runtimeId&&this.handleRemoteTabClosing(n)}}),this.storageHandler=t=>{if(!(t.key!==this.key||!t.newValue))try{let n=Hr(JSON.parse(t.newValue),this.siteId,this.sessionId);this.applyIncomingState(n)}catch{}},window.addEventListener("storage",this.storageHandler),this.heartbeatTimer=window.setInterval(()=>{this.heartbeat()},this.heartbeatMs),this.notifyRoleChange(),this.onStateChange?.(this.state,"local"))}stop(){if(this.started){this.started=!1,this.heartbeatTimer!=null&&(window.clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.roleChangeTimer!=null&&(window.clearTimeout(this.roleChangeTimer),this.roleChangeTimer=null),this.storageHandler&&(window.removeEventListener("storage",this.storageHandler),this.storageHandler=null),this.channel&&(this.channel.close(),this.channel=null);for(let[,t]of this.pendingRpcRequests)window.clearTimeout(t.timer),t.reject(new Error("SessionCoordinator stopped"));this.pendingRpcRequests.clear(),this.mutate("local",t=>{t.tabs=t.tabs.filter(n=>n.runtimeId!==this.runtimeId),t.lease?.holderRuntimeId===this.runtimeId&&(t.lease=void 0),t.activeLogicalTabId&&!t.tabs.some(n=>n.logicalTabId===t.activeLogicalTabId)&&(t.activeLogicalTabId=void 0)})}}isController(){let t=this.state.lease;return!t||t.expiresAt<=re()?!1:t.holderRuntimeId===this.runtimeId}getRole(){return this.isController()?"controller":"observer"}getLocalLogicalTabId(){return this.localLogicalTabId}getActiveLogicalTabId(){return this.state.activeLogicalTabId}getCurrentHolderRuntimeId(){return this.state.lease?.holderRuntimeId}getState(){return this.state}getTaskEpoch(){return this.state.taskEpoch}getTask(){return this.state.task}getWorkerContext(){return this.state.workerContext}syncTask(t,n){this.mutate("local",r=>{n&&Number.isFinite(n)&&n>r.taskEpoch&&(r.taskEpoch=Math.max(1,Math.trunc(n))),t&&(r.task=Rl(t)||r.task)})}hydrateExternalState(t){let n=Hr(t,this.siteId,this.sessionId);this.pruneDetachedTabs(n,{dropRuntimeDetached:!0,dropAllDetachedExternal:!0});let r=this.state.seq,o=this.state.updatedAt;this.applyIncomingState(n);let i=this.state.seq!==r||this.state.updatedAt!==o;if(!i&&this.state.tabs.some(a=>a.runtimeId?!1:a.external?!0:a.openerRuntimeId===this.runtimeId)){let a=this.state.tabs.length;this.mutate("local",u=>{this.pruneDetachedTabs(u,{dropRuntimeDetached:!0,dropAllDetachedExternal:!0})}),i=this.state.tabs.length!==a}return i?(this.persistState(),this.localLogicalTabId||this.registerCurrentTab(window.location.href,document.title||void 0),!0):!1}listTabs(){let t=re();return this.state.tabs.filter(n=>n.runtimeId?n.runtimeId===this.runtimeId?!0:t-Math.max(n.updatedAt||0,n.openedAt||0)<=45e3:n.external?t-Math.max(n.updatedAt||0,n.openedAt||0)<=12e4:t-Math.max(n.updatedAt||0,n.openedAt||0)<=6e5)}pruneTabs(t){this.mutate("local",n=>{this.pruneDetachedTabs(n,t)})}startNewTask(t){let n=Number(t.startedAt)||re(),r={taskId:String(t.taskId||Tn("task")),status:t.status==="completed"||t.status==="ended"?t.status:"running",startedAt:n,lastUserAt:Number(t.lastUserAt)||n,lastAssistantAt:Number(t.lastAssistantAt)||void 0,boundaryReason:t.boundaryReason,endedAt:void 0};return this.mutate("local",o=>{o.taskEpoch=Math.max(1,Number(o.taskEpoch)||1)+1,o.task=r,o.uiMessages=[],o.timeline=[],o.uiStatus=void 0,o.activeRun=void 0,o.workerContext=void 0,this.pruneDetachedTabs(o,{dropAllDetachedExternal:!0})}),r}endTask(t){let n;return this.mutate("local",r=>{r.task&&(r.task={...r.task,status:"ended",boundaryReason:t||r.task.boundaryReason,endedAt:re()},r.activeRun=void 0,n=r.task)}),n}markTaskActivity(t,n=re()){t!=="system"&&this.mutate("local",r=>{if(!r.task){r.task={taskId:Tn("task"),status:"running",startedAt:n,boundaryReason:"implicit",lastUserAt:t==="user"?n:void 0,lastAssistantAt:t==="assistant"?n:void 0};return}r.task.status==="running"&&(t==="user"&&(r.task.lastUserAt=n),t==="assistant"&&(r.task.lastAssistantAt=n))})}setWorkerContext(t){this.mutate("local",n=>{if(!t){n.workerContext=void 0;return}n.workerContext=Sl(t)})}setStatus(t){this.mutate("local",n=>{n.uiStatus=t||void 0})}appendMessage(t){let n={id:t.id||Tn("msg"),role:t.role,text:String(t.text||""),blocks:mi(t.blocks),ts:Number(t.ts)||re(),sourceRuntimeId:this.runtimeId};return this.mutate("local",r=>{r.uiMessages.push(n),r.uiMessages.length>this.maxMessages&&(r.uiMessages=r.uiMessages.slice(-this.maxMessages)),r.task||(r.task={taskId:Tn("task"),status:"running",startedAt:n.ts,boundaryReason:"implicit"}),n.role==="user"?r.task.lastUserAt=n.ts:n.role==="assistant"&&(r.task.lastAssistantAt=n.ts)}),n}appendTimeline(t){let n={id:t.id||Tn("timeline"),kind:String(t.kind||"status"),title:String(t.title||"Step"),detail:t.detail?String(t.detail):void 0,detailBlocks:mi(t.detailBlocks),status:t.status,ts:Number(t.ts)||re(),sourceRuntimeId:this.runtimeId};return this.mutate("local",r=>{r.timeline.push(n),r.timeline.length>this.maxTimeline&&(r.timeline=r.timeline.slice(-this.maxTimeline))}),n}clearTimeline(){this.mutate("local",t=>{t.timeline=[]})}setActiveRun(t){this.mutate("local",n=>{if(!t){n.activeRun=void 0;return}if(n.task&&n.task.status!=="running"){n.activeRun=void 0;return}n.activeRun={runId:t.runId,text:t.text,runtimeId:this.runtimeId,startedAt:n.activeRun?.runId===t.runId?n.activeRun.startedAt:re(),updatedAt:re()},n.task||(n.task={taskId:Tn("task"),status:"running",startedAt:re()})})}requestControl(){return this.claimLease(!0)}registerCurrentTab(t,n){let r=Ms(t),o;return this.mutate("local",i=>{let s=i.tabs.find(a=>a.runtimeId===this.runtimeId);if(s)s.url=r||s.url,s.title=n||s.title,s.updatedAt=re(),o=s.logicalTabId;else{let a=i.tabs.find(u=>!u.runtimeId&&u.url===r&&re()-u.openedAt<18e4);if(!a){let u=_l(r);a=i.tabs.filter(p=>!p.runtimeId&&u&&_l(p.url)===u&&re()-p.updatedAt<1e4).sort((p,v)=>v.updatedAt-p.updatedAt)[0]}if(a)a.runtimeId=this.runtimeId,a.url=r||a.url,a.title=n||a.title,a.updatedAt=re(),o=a.logicalTabId;else{let u=i.nextLogicalTabId++;i.tabs.push({logicalTabId:u,runtimeId:this.runtimeId,url:r,title:n,openedAt:re(),updatedAt:re(),external:!1}),o=u}}i.activeLogicalTabId||(i.activeLogicalTabId=o)}),this.notifyRoleChange(),this.localLogicalTabId||o||1}registerOpenedTab(t){let n=Ms(t.url),r=0;return this.mutate("local",o=>{let i=o.tabs.find(s=>!s.runtimeId&&!!s.external==!!t.external&&s.url===n);if(i){i.title=t.title||i.title,i.updatedAt=re(),i.openerRuntimeId=t.openerRuntimeId||i.openerRuntimeId,r=i.logicalTabId;return}r=o.nextLogicalTabId++,o.tabs.push({logicalTabId:r,runtimeId:void 0,url:n,title:t.title,openedAt:re(),updatedAt:re(),external:!!t.external,openerRuntimeId:t.openerRuntimeId})}),{logicalTabId:r}}switchToLogicalTab(t){let n={ok:!1,reason:"Unknown tab"};return this.mutate("local",r=>{let o=r.tabs.find(i=>i.logicalTabId===t);if(!o){n={ok:!1,reason:`Tab ${t} not found`};return}if(r.activeLogicalTabId=t,o.runtimeId&&o.runtimeId!==this.runtimeId){r.lease={holderRuntimeId:o.runtimeId,expiresAt:re()+this.leaseMs,updatedAt:re()},this.channel&&this.channel.postMessage({type:"switch_request",logicalTabId:t,targetRuntimeId:o.runtimeId,sourceRuntimeId:this.runtimeId}),n={ok:!0,delegated:!0};return}if(!o.runtimeId){n={ok:!1,reason:`Tab ${t} is not attached to an active Rover runtime yet`};return}r.lease={holderRuntimeId:this.runtimeId,expiresAt:re()+this.leaseMs,updatedAt:re()},n={ok:!0,delegated:!1}}),this.notifyRoleChange(),n}sendCrossTabRpc(t,n,r,o=15e3){return new Promise((i,s)=>{if(!this.channel){s(new Error("BroadcastChannel not available"));return}let a=Tn("rpc"),u=window.setTimeout(()=>{this.pendingRpcRequests.delete(a),s(new Error(`Cross-tab RPC timed out after ${o}ms (method=${n}, target=${t})`))},o);this.pendingRpcRequests.set(a,{resolve:i,reject:s,timer:u}),this.channel.postMessage({type:"rpc_request",requestId:a,sourceRuntimeId:this.runtimeId,targetRuntimeId:t,method:n,params:r,timeoutMs:o,createdAt:re()})})}setRpcRequestHandler(t){this.rpcRequestHandler=t}broadcastNavigation(t,n){this.channel&&this.channel.postMessage({type:"tab_navigated",runtimeId:this.runtimeId,logicalTabId:this.localLogicalTabId,url:t,title:n})}broadcastClosing(){this.closing=!0,this.channel&&(this.mutate("local",t=>{let n=t.tabs.find(r=>r.runtimeId===this.runtimeId);n&&(n.runtimeId=void 0,n.updatedAt=re())}),this.channel.postMessage({type:"tab_closing",runtimeId:this.runtimeId,logicalTabId:this.localLogicalTabId}))}isTabAlive(t){let n=this.state.tabs.find(r=>r.logicalTabId===t);return n?n.updatedAt>re()-2*this.heartbeatMs:!1}acquireWorkflowLock(t){let n=!1;return this.mutate("local",r=>{let o=r.workflowLock;if(o&&o.runtimeId!==this.runtimeId&&o.expiresAt>re()){let i=r.tabs.find(a=>a.runtimeId===o.runtimeId);if(i&&i.updatedAt>re()-2*this.heartbeatMs){n=!1;return}}r.workflowLock={runtimeId:this.runtimeId,runId:t,lockedAt:re(),expiresAt:re()+this.leaseMs*5},n=!0}),n}clearActiveRunRuntimeId(t){this.mutate("local",n=>{n.activeRun&&n.activeRun.runId===t&&(n.activeRun.runtimeId="")})}releaseWorkflowLock(t){this.mutate("local",n=>{n.workflowLock&&n.workflowLock.runId===t&&(n.workflowLock=void 0)})}isWorkflowLocked(){let t=this.state.workflowLock;return!t||t.runtimeId===this.runtimeId?!1:t.expiresAt>re()}getWorkflowLockInfo(){let t=this.state.workflowLock;return!t||t.expiresAt<=re()?{locked:!1}:{locked:!0,holderRuntimeId:t.runtimeId,runId:t.runId}}async handleInboundRpcRequest(t){let{requestId:n,sourceRuntimeId:r,method:o,params:i}=t;if(!this.rpcRequestHandler){this.channel?.postMessage({type:"rpc_response",requestId:n,sourceRuntimeId:this.runtimeId,targetRuntimeId:r,ok:!1,error:{message:"No RPC handler registered",code:"NO_HANDLER"}});return}try{let s=await this.rpcRequestHandler({method:o,params:i});this.channel?.postMessage({type:"rpc_response",requestId:n,sourceRuntimeId:this.runtimeId,targetRuntimeId:r,ok:!0,result:s})}catch(s){this.channel?.postMessage({type:"rpc_response",requestId:n,sourceRuntimeId:this.runtimeId,targetRuntimeId:r,ok:!1,error:{message:s?.message||String(s)}})}}handleInboundRpcResponse(t){let{requestId:n,ok:r,result:o,error:i}=t,s=this.pendingRpcRequests.get(n);s&&(this.pendingRpcRequests.delete(n),window.clearTimeout(s.timer),r?s.resolve(o):s.reject(new Error(i?.message||"Cross-tab RPC failed")))}handleRemoteNavigation(t){let{runtimeId:n,url:r,title:o}=t;this.mutate("local",i=>{let s=i.tabs.find(a=>a.runtimeId===n);s&&(s.url=r||s.url,s.title=o||s.title,s.updatedAt=re())})}handleRemoteTabClosing(t){let{runtimeId:n}=t;this.mutate("local",r=>{r.tabs=r.tabs.filter(o=>o.runtimeId!==n),r.lease?.holderRuntimeId===n&&(r.lease=void 0),r.workflowLock?.runtimeId===n&&(r.workflowLock=void 0),r.activeRun?.runtimeId===n&&(r.activeRun=void 0),r.activeLogicalTabId&&!r.tabs.some(o=>o.logicalTabId===r.activeLogicalTabId)&&(r.activeLogicalTabId=void 0)}),this.notifyRoleChange()}heartbeat(){if(this.closing)return;let t=Ms(window.location.href),n=document.title||void 0;this.mutate("local",r=>{let o=r.tabs.find(a=>a.runtimeId===this.runtimeId);if(o)o.url=t||o.url,o.title=n||o.title,o.updatedAt=re();else{let a=r.nextLogicalTabId++;r.tabs.push({logicalTabId:a,runtimeId:this.runtimeId,url:t,title:n,openedAt:re(),updatedAt:re(),external:!1})}let i=r.lease;(!i||i.expiresAt<=re()||i?.holderRuntimeId===this.runtimeId)&&(r.lease={holderRuntimeId:this.runtimeId,expiresAt:re()+this.leaseMs,updatedAt:re()},!r.activeLogicalTabId&&this.localLogicalTabId&&(r.activeLogicalTabId=this.localLogicalTabId)),r.workflowLock?.runtimeId===this.runtimeId&&(r.workflowLock.expiresAt=re()+this.leaseMs*5),this.pruneDetachedTabs(r)}),this.notifyRoleChange()}reloadFromStorage(){let t=this.loadState();return(t.seq>this.state.seq||t.seq===this.state.seq&&t.updatedAt>this.state.updatedAt)&&(this.state=t,this.syncLocalLogicalTabId(),this.onStateChange?.(this.state,"remote")),this.closing=!1,this.state}claimLease(t){let n=!1;return this.mutate("local",r=>{let o=r.lease,i=!o||o.expiresAt<=re();(t||i||o?.holderRuntimeId===this.runtimeId)&&(r.lease={holderRuntimeId:this.runtimeId,expiresAt:re()+this.leaseMs,updatedAt:re()},!r.activeLogicalTabId&&this.localLogicalTabId&&(r.activeLogicalTabId=this.localLogicalTabId),n=!0)}),this.notifyRoleChange(),n}notifyRoleChange(){this.getRole()!==this.lastNotifiedRole&&(this.roleChangeTimer!=null&&window.clearTimeout(this.roleChangeTimer),this.roleChangeTimer=window.setTimeout(()=>{this.roleChangeTimer=null;let n=this.getRole();n!==this.lastNotifiedRole&&(this.lastNotifiedRole=n,this.onRoleChange?.(n,{localLogicalTabId:this.localLogicalTabId,activeLogicalTabId:this.state.activeLogicalTabId,holderRuntimeId:this.state.lease?.holderRuntimeId}))},bi.ROLE_CHANGE_DEBOUNCE_MS))}syncLocalLogicalTabId(){let t=this.state.tabs.find(n=>n.runtimeId===this.runtimeId);this.localLogicalTabId=t?.logicalTabId}mutate(t,n){if(t==="local")try{let o=window.localStorage.getItem(this.key);if(o){let i=Hr(JSON.parse(o),this.siteId,this.sessionId);(i.seq>this.state.seq||i.seq===this.state.seq&&i.updatedAt>this.state.updatedAt)&&(this.state=i)}}catch{}let r=Hr(this.state,this.siteId,this.sessionId);n(r),r.seq=Math.max(1,Number(r.seq)||1)+(t==="local"?1:0),r.updatedAt=re(),this.state=r,this.syncLocalLogicalTabId(),t==="local"&&(this.persistState(),this.channel&&this.channel.postMessage({type:"state",sourceRuntimeId:this.runtimeId,state:this.state})),this.onStateChange?.(this.state,t)}applyIncomingState(t){t&&(t.seq<this.state.seq||t.seq===this.state.seq&&t.updatedAt<=this.state.updatedAt||(this.pruneDetachedTabs(t),this.state=t,this.syncLocalLogicalTabId(),this.onStateChange?.(this.state,"remote"),this.notifyRoleChange()))}loadState(){try{let t=window.localStorage.getItem(this.key);if(!t)return Ds(this.siteId,this.sessionId);let n=JSON.parse(t);return Hr(n,this.siteId,this.sessionId)}catch(t){return console.warn("[rover] Failed to load shared state from localStorage:",t),Ds(this.siteId,this.sessionId)}}persistState(){try{window.localStorage.setItem(this.key,JSON.stringify(this.state))}catch{}}};W(bi,"ROLE_CHANGE_DEBOUNCE_MS",200);var gi=bi;var hp="https://extensionrouter.rtrvr.ai";function Ur(e,t){let n=Number(e);return Number.isFinite(n)?n:t}function Il(e,t=8e3){let n=String(e??"");return n.length<=t?n:`${n.slice(0,t)}\u2026`}function mp(e){let t=Number(e.sharedState?.seq||0),n=Array.isArray(e.sharedState?.uiMessages)?e.sharedState.uiMessages.length:0,r=Number(e.runtimeState?.updatedAt||0),o=Array.isArray(e.runtimeState?.uiMessages)?e.runtimeState.uiMessages.length:0;return[e.sessionId,Ur(e.updatedAt,0),t,n,r,o].join(":")}function gp(e){let t=hp,n=String(e||t).trim().replace(/\/+$/,"");if(!n)return t;if(n.endsWith("/extensionRouter"))return n;try{let r=new URL(n),o=r.pathname.replace(/\/+$/,"");if(o&&o!=="/"||r.hostname.toLowerCase()==="extensionrouter.rtrvr.ai")return n}catch{}return`${n}/extensionRouter`}function Os(e,t){let n=new Error(e);return n.details=t,n}var Ei=class{constructor(t){W(this,"endpoint");W(this,"token");W(this,"siteId");W(this,"visitorId");W(this,"ttlHours");W(this,"flushIntervalMs");W(this,"pullIntervalMs");W(this,"minFlushIntervalMs");W(this,"shouldWrite");W(this,"buildCheckpoint");W(this,"onCheckpoint");W(this,"onStateChange");W(this,"onError");W(this,"started",!1);W(this,"dirty",!1);W(this,"flushTimer",null);W(this,"pullTimer",null);W(this,"lastFlushAt",0);W(this,"lastPullAt",0);W(this,"lastUploadedRevision","");W(this,"lastAppliedRemoteUpdatedAt",0);W(this,"pushInFlight",!1);W(this,"pullInFlight",!1);W(this,"state","active");let n=String(t.authToken||t.apiKey||"").trim();if(!n)throw Os("Rover cloud checkpoint requires apiKey or authToken.");this.endpoint=gp(t.apiBase),this.token=n,this.siteId=t.siteId,this.visitorId=t.visitorId,this.ttlHours=Math.max(1,Math.min(168,Math.floor(Ur(t.ttlHours,1)))),this.flushIntervalMs=Math.max(2e3,Math.floor(Ur(t.flushIntervalMs,8e3))),this.pullIntervalMs=Math.max(2e3,Math.floor(Ur(t.pullIntervalMs,9e3))),this.minFlushIntervalMs=Math.max(1e3,Math.floor(Ur(t.minFlushIntervalMs,2500))),this.shouldWrite=t.shouldWrite||(()=>!0),this.buildCheckpoint=t.buildCheckpoint,this.onCheckpoint=t.onCheckpoint,this.onStateChange=t.onStateChange,this.onError=t.onError}start(){this.started||(this.started=!0,this.setState("active"),this.flushTimer=window.setInterval(()=>{this.flush(!1)},this.flushIntervalMs),this.pullTimer=window.setInterval(()=>{this.pull(!1)},this.pullIntervalMs),this.pull(!0))}stop(){this.started&&(this.started=!1,this.flushTimer!=null&&(window.clearInterval(this.flushTimer),this.flushTimer=null),this.pullTimer!=null&&(window.clearInterval(this.pullTimer),this.pullTimer=null),this.flush(!0))}markDirty(){this.dirty=!0}syncNow(){this.flush(!0),this.pull(!0)}async flush(t){if(this.pushInFlight||this.state==="paused_auth"||!this.dirty&&!t||!this.shouldWrite()||!t&&Date.now()-this.lastFlushAt<this.minFlushIntervalMs)return;let n=this.buildCheckpoint();if(!n)return;let r=mp(n);if(!t&&r===this.lastUploadedRevision){this.dirty=!1;return}this.pushInFlight=!0;try{let o=await this.callExtensionRouter("roverSessionCheckpointUpsert",{siteId:this.siteId,visitorId:this.visitorId,sessionId:n.sessionId,ttlHours:this.ttlHours,updatedAt:n.updatedAt,checkpoint:n});this.lastFlushAt=Date.now(),o?.saved&&(this.dirty=!1,this.lastUploadedRevision=r),o?.stale&&o?.checkpoint&&typeof o.checkpoint=="object"&&(this.applyRemoteCheckpoint(o.checkpoint,"push_stale"),this.dirty=!1),this.setState("active")}catch(o){this.handleCheckpointError(o,"roverSessionCheckpointUpsert")}finally{this.pushInFlight=!1}}async pull(t){if(!this.pullInFlight&&this.state!=="paused_auth"&&!(!t&&Date.now()-this.lastPullAt<this.pullIntervalMs)){this.pullInFlight=!0;try{let n=await this.callExtensionRouter("roverSessionCheckpointGet",{siteId:this.siteId,visitorId:this.visitorId});if(this.lastPullAt=Date.now(),!n?.found||!n?.checkpoint||typeof n.checkpoint!="object")return;this.applyRemoteCheckpoint(n.checkpoint,"pull"),this.setState("active")}catch(n){this.handleCheckpointError(n,"roverSessionCheckpointGet")}finally{this.pullInFlight=!1}}}applyRemoteCheckpoint(t,n){let r=Math.max(0,Math.floor(Ur(t?.updatedAt,0)));r<=this.lastAppliedRemoteUpdatedAt||(this.lastAppliedRemoteUpdatedAt=r,this.onCheckpoint(t,n))}async callExtensionRouter(t,n){let r=await fetch(this.endpoint,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({action:t,data:n})});if(!r.ok){let i;try{i=await r.json()}catch{let s=await r.text().catch(()=>"");i=s?{error:Il(s,2e3)}:void 0}throw Os(`Checkpoint HTTP ${r.status}`,{action:t,status:r.status,payload:i})}let o=await r.json();if(o?.success===!1)throw Os("Checkpoint extensionRouter returned success=false",{action:t,status:r.status,payload:o});return o?.data}setState(t,n){this.state!==t&&(this.state=t,this.onStateChange?.(t,n||{}))}handleCheckpointError(t,n){let r=this.normalizeCheckpointError(t),o=this.isAuthFailure(r);o&&this.setState("paused_auth",{reason:"auth_failed",action:n,code:r.code,message:r.message}),this.onError?.(t,{action:n,state:this.state,code:r.code,message:r.message,status:r.status,paused:o})}normalizeCheckpointError(t){let n=t,r=n?.details,o=r?.payload||r?.response||r,i=o?.errorCode||o?.errorDetails?.code||o?.error?.code||o?.code,s=o?.error||o?.errorDetails?.message||o?.error?.message||n?.message||"Checkpoint request failed",a=Number(r?.status);return{code:typeof i=="string"?i:void 0,message:Il(s,1e3),status:Number.isFinite(a)?a:void 0}}isAuthFailure(t){let n=String(t.code||"").toUpperCase();return n==="INVALID_API_KEY"||n==="MISSING_API_KEY"||n==="UNAUTHENTICATED"||n==="PERMISSION_DENIED"?!0:t.status===401||t.status===403}};var bp="rover-runtime-state-db",yi="runtime-state",Ps=class{read(t){try{let n=window.sessionStorage.getItem(t);return n?JSON.parse(n):null}catch{return null}}write(t,n){try{window.sessionStorage.setItem(t,JSON.stringify(n))}catch{}}remove(t){try{window.sessionStorage.removeItem(t)}catch{}}},Hs=class{constructor(){W(this,"dbPromise",null)}openDb(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,n)=>{if(typeof indexedDB>"u"){n(new Error("indexedDB unavailable"));return}let r=indexedDB.open(bp,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(yi)||o.createObjectStore(yi)},r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.error||new Error("indexedDB open failed"))}}).catch(t=>{throw this.dbPromise=null,t}),this.dbPromise)}async withStore(t,n){let r=await this.openDb();return new Promise((o,i)=>{let s=r.transaction(yi,t),a=s.objectStore(yi);n(a,o,i),s.onerror=()=>{i(s.error||new Error("indexedDB transaction failed"))}})}async read(t){try{return await this.withStore("readonly",(n,r,o)=>{let i=n.get(t);i.onsuccess=()=>{let s=i.result;r(s??null)},i.onerror=()=>{o(i.error||new Error("indexedDB read failed"))}})}catch{return null}}async write(t,n){await this.withStore("readwrite",(r,o,i)=>{let s=r.put(n,t);s.onsuccess=()=>o(),s.onerror=()=>{i(s.error||new Error("indexedDB write failed"))}}).catch(()=>{})}async remove(t){await this.withStore("readwrite",(n,r,o)=>{let i=n.delete(t);i.onsuccess=()=>r(),i.onerror=()=>{o(i.error||new Error("indexedDB delete failed"))}}).catch(()=>{})}};function Al(){let e=new Ps,t=new Hs;return{readSync:n=>e.read(n),readAsync:async n=>t.read(n),write:(n,r)=>{e.write(n,r),t.write(n,r)},remove:n=>{e.remove(n),t.remove(n)}}}var Ep="rover_xdr_";function Cl(e){let t=e.split(".").filter(Boolean);return t.length<2?e:`${t[t.length-2]}.${t[t.length-1]}`}function Us(e){return`${Ep}${e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,40)}`}function Fs(e,t){try{let n=Us(e),r=Cl(window.location.hostname),o=encodeURIComponent(JSON.stringify(t)),i=window.location.protocol==="https:",s=[`${n}=${o}`,"path=/",`domain=.${r}`,"max-age=120","SameSite=Lax"];i&&s.push("Secure"),document.cookie=s.join("; ")}catch{}}function Nl(e){try{let t=Us(e),n=document.cookie.split(";");for(let r of n){let[o,...i]=r.trim().split("=");if(o===t){let s=i.join("="),a=JSON.parse(decodeURIComponent(s));if(a.timestamp&&Date.now()-a.timestamp<120*1e3)return a}}}catch{}return null}function Ll(e){try{let t=Us(e),n=Cl(window.location.hostname),r=window.location.protocol==="https:",o=[`${t}=`,"path=/",`domain=.${n}`,"max-age=0","SameSite=Lax"];r&&o.push("Secure"),document.cookie=o.join("; ")}catch{}}function Ml(e){return e==="completed"||e==="ended"}function Dl(e){return e==="running"}function Ol(e){return!(e.taskStatus!=="running"||!e.activeRunId||!e.activeRunText||e.hasPendingRun||e.ignoredRunIds?.has(e.activeRunId))}function Bs(e){return!!(e.localTaskStatus!=="running"||e.remoteTaskStatus&&e.remoteTaskStatus!=="running"||e.mode==="observer"&&!e.hasRemoteActiveRun)}function Pl(e){let{type:t,messageRunId:n,pendingRunId:r,sharedActiveRunId:o,taskStatus:i,ignoredRunIds:s}=e;return!n&&t!=="run_started"?!1:n&&s?.has(n)?!0:t==="run_started"?n?r?r!==n:!0:!1:n?t==="run_completed"?i!=="running"?!0:r?r!==n:!(o&&o===n):r?r!==n:!0:!1}var Ys=1,yp="rover:runtime:",wp="rover:runtime-id:",$l="rover:visitor-id:",qs=160,$s=240,Wl=80,Ci=40,vp=8e3,Tp=15*6e4,_p=12,xp=3600*24*365,Rp=1,kp=3e3,Sp=9e4,Ip=12e3,Ap=30,Ni=240,Hl=5*6e4,Li=100,Mi=12,Cp=80,Np=200,Lp=700,Mp=8,Dp=240,Kn=null,$e=null,Pe=null,te=null,Z=null,Fr=null,h=null,br=null,Oe="",H=null,Mt=null,Ri=null,Lt=[],ki=!1,Br=!1,Vl=0,kt,_n,Jn=!1,gr=!1,co=null,lo=null,Er=null,Di=!1,lt="controller",tr=!1,Hn=!1,ct=null,Ul=!1,qr=null,wi="",Gl,Pn=new Map,Qn=new Set,Op=new Set(["run_started","run_completed","assistant","status","tool_start","tool_result","auth_required","navigation_guardrail","error"]),Si=[],Ii=new Map;function Be(e,t){zp(e,t);let n=Ii.get(e);if(n)for(let r of n)try{r(t)}catch{}}function zl(e,t){Ii.has(e)||Ii.set(e,new Set);let n=Ii.get(e);return n.add(t),()=>{n.delete(t)}}function Pp(e){return typeof e=="string"?{name:e}:e}function Zn(e){try{return`${e}-${crypto.randomUUID()}`}catch{return`${e}-${Date.now()}-${Math.floor(Math.random()*1e5)}`}}function Hp(e){let t=`${wp}${e}`;try{let n=window.sessionStorage.getItem(t);if(n&&n.trim())return n.trim();let r=Zn("runtime");return window.sessionStorage.setItem(t,r),r}catch{return Zn("runtime")}}function Oi(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function vi(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._:-]/g,"").slice(0,180)}function Yl(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]||""):void 0}catch{return}}function Fl(e,t,n){try{let r=n?`; domain=${n}`:"";return document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${xp}; samesite=lax${r}`,Yl(e)===t}catch{return!1}}function Up(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="localhost"||/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return[];let n=t.split(".").filter(Boolean);if(n.length<2)return[];let r=[];for(let o=n.length-2;o>=0;o-=1)r.push(`.${n.slice(o).join(".")}`);return r}function Fp(e,t){let n=`rover_vid_${Oi(e)}`;for(let r of Up(window.location.hostname))if(Fl(n,t,r))return;Fl(n,t)}function Ti(e,t){let n=`${$l}${e}`;try{window.localStorage.setItem(n,t)}catch{}try{window.sessionStorage.setItem(n,t)}catch{}Fp(e,t)}function jl(e,t){h&&(h.visitor=t,Ne());try{localStorage.setItem(`rover:visitor:${e}`,JSON.stringify(t))}catch{}}function Bp(e){if(h?.visitor?.name||h?.visitor?.email)return h.visitor;try{let t=localStorage.getItem(`rover:visitor:${e}`);return t?JSON.parse(t):void 0}catch{return}}function Xl(e){let t=vi(e.visitorId||"");if(t)return t;if(e.checkpointing?.autoVisitorId===!1)return;let n=`${$l}${e.siteId}`,r=`rover_vid_${Oi(e.siteId)}`,o=vi(Yl(r)||"");if(o)return Ti(e.siteId,o),o;try{let s=vi(window.localStorage.getItem(n)||"");if(s)return Ti(e.siteId,s),s}catch{}try{let s=vi(window.sessionStorage.getItem(n)||"");if(s)return Ti(e.siteId,s),s}catch{}let i=`v_${Oi(`${e.siteId}:${Zn("visitor")}`)}_${Date.now().toString(36)}`;return Ti(e.siteId,i),i}function qp(e,t){return`visitor-${Oi(`${e}:${t}`)}`}function Kl(e){!$e||!Pe||($e.registerTool(e.def,e.handler),Pe.postMessage({type:"register_tool",tool:e.def}))}function $p(e){return`${yp}${e}`}function Fn(e="session_start"){let t=Date.now();return{taskId:Zn("task"),status:"running",startedAt:t,lastUserAt:void 0,lastAssistantAt:void 0,boundaryReason:e,endedAt:void 0}}function Ws(e,t){return{version:Ys,sessionId:e,runtimeId:t,uiOpen:!1,uiHidden:!1,uiStatus:void 0,uiMessages:[],timeline:[],executionMode:"controller",workerState:void 0,pendingRun:void 0,taskEpoch:1,activeTask:Fn(),lastRoutingDecision:void 0,updatedAt:Date.now()}}function At(e,t=vp){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function Ai(e){if(e!=null){if(typeof e=="string")return At(e,1200);try{return At(JSON.stringify(e),1200)}catch{try{return At(String(e),1200)}catch{return}}}}function qi(e){let t=e?.telemetry,n=Number(t?.sampleRate),r=Number.isFinite(n)?Math.min(1,Math.max(0,n)):1,o=Number(t?.flushIntervalMs),i=Number.isFinite(o)?Math.min(6e4,Math.max(2e3,Math.floor(o))):Ip,s=Number(t?.maxBatchSize),a=Number.isFinite(s)?Math.min(80,Math.max(1,Math.floor(s))):Ap;return{enabled:t?.enabled!==!1,sampleRate:r,flushIntervalMs:i,maxBatchSize:a,includePayloads:t?.includePayloads===!0}}function js(e){return e==="same_tab"||e==="open_new_tab"?e:"same_tab"}function Xs(e,t){return e==="observer"?"This tab is in observer mode because another tab currently holds Rover action control.":t?"Controller tab ready for actions.":"Actions are disabled by configuration (allowActions=false)."}function Ks(e){return e==="auto"||e==="confirm"||e==="never"?e:"confirm"}function Qs(e){return!(!e||!qi(e).enabled||!(e.authToken||e.apiKey))}function Bl(e){if(e!=null){if(typeof e=="string")return At(e,260);if(typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return{type:"array",length:e.length};if(typeof e=="object"){let n={type:"object",keys:Object.keys(e).slice(0,20)},r=["code","message","stage","status","reason","taskId","runId","policyAction"];for(let o of r){let i=e?.[o];i!=null&&(typeof i=="string"?n[o]=At(i,180):(typeof i=="number"||typeof i=="boolean")&&(n[o]=i))}return n}}}function Wp(e,t){if(!t)return Bl(e);let n=ea(e);if(n!=null)return typeof n=="string"?At(n,1e3):typeof n=="number"||typeof n=="boolean"?n:Array.isArray(n)?{type:"array",length:n.length}:typeof n=="object"?n:Bl(e)}function Js(){Ri&&(clearInterval(Ri),Ri=null)}var Vp="https://extensionrouter.rtrvr.ai";function Ql(e){let t=Vp,n=String(e||t).trim().replace(/\/+$/,"");if(!n)return t;if(n.endsWith("/extensionRouter"))return n;try{let r=new URL(n),o=r.pathname.replace(/\/+$/,"");if(o&&o!=="/"||r.hostname.toLowerCase()==="extensionrouter.rtrvr.ai")return n}catch{}return`${n}/extensionRouter`}function Gp(e){return Ql(e.apiBase)}async function $i(e=!1){if(ki||Br)return;if(!Z||!Qs(Z)){Lt=[];return}if(!Lt.length)return;let t=qi(Z),n=String(Z.authToken||Z.apiKey||"").trim();if(!n)return;let r=Lt.splice(0,t.maxBatchSize);if(r.length){ki=!0;try{let o=await fetch(Gp(Z),{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({action:"roverTelemetryIngest",data:{siteId:Z.siteId,runtimeId:Oe,sessionId:h?.sessionId,visitorId:kt,flushReason:e?"manual":"interval",sdkVersion:"rover_sdk_v1",pageUrl:window.location.href,userAgent:navigator.userAgent,sampleRate:t.sampleRate,events:r}})});if(!o.ok){o.status===401||o.status===403?Br=!0:Lt=[...r,...Lt].slice(-Ni);return}let i=await o.json().catch(()=>{});if(i?.success===!1){let s=String(i?.errorCode||i?.errorDetails?.code||"").toUpperCase();(s==="INVALID_API_KEY"||s==="MISSING_API_KEY"||s==="UNAUTHENTICATED"||s==="PERMISSION_DENIED")&&(Br=!0);return}}catch{Lt=[...r,...Lt].slice(-Ni)}finally{ki=!1}}}function Zs(e){if(Js(),Br=!1,!Qs(e)){Lt=[];return}let t=qi(e);Ri=setInterval(()=>{$i(!1)},t.flushIntervalMs)}function zp(e,t){if(!Qs(Z)||Br)return;let n=qi(Z);if(n.sampleRate<1&&Math.random()>n.sampleRate)return;let r={name:e,ts:Date.now(),seq:++Vl,payload:Wp(t,n.includePayloads)};Lt.push(r),Lt.length>Ni&&(Lt=Lt.slice(-Ni)),Lt.length>=n.maxBatchSize&&$i(!1)}function _i(e,t,n="tab_not_accessible"){let r=Number(t?.logicalTabId)||void 0,o=t?.url||"",i=t?.title||(t?.external?"External Tab (Inaccessible)":"Inactive Tab"),s=String(n||"").trim(),a=s?` Reason: ${s}.`:"",u=t?.external?`This external tab is tracked in virtual mode only. Live DOM control and accessibility-tree access are unavailable here.${a}`:`This tab is currently not attached to an active Rover runtime. Switch to a live tab or reopen it.${a}`;return{url:o,title:i,contentType:"text/html",content:u,metadata:{inaccessible:!0,external:!!t?.external,accessMode:t?.external?"external_placeholder":"inactive_tab",reason:n,logicalTabId:r}}}function xi(e,t,n="tab_not_accessible"){let r=Number(t?.logicalTabId)||0,o=t?.url||"",i=t?.external?`Tab ${r} is external to the active runtime and cannot be controlled directly.`:`Tab ${r} is not attached to an active Rover runtime.`,s=t?.external?"DOMAIN_SCOPE_BLOCKED":"TAB_NOT_ACCESSIBLE";return{success:!1,error:i,allowFallback:!0,output:{success:!1,error:{code:s,message:i,missing:[],next_action:t?.external?"Use open_new_tab for external context or continue on an in-scope tab.":"Switch to an active tab and retry.",retryable:!1},blocked_url:o||void 0,logical_tab_id:r||void 0,external:!!t?.external,policy_action:t?.external?e.externalNavigationPolicy||"open_new_tab_notice":void 0,reason:n},errorDetails:{code:s,message:i,retryable:!1,details:{logicalTabId:r,blockedUrl:o,external:!!t?.external,reason:n}}}}function Yp(e){if(e==="analyze"||e==="route"||e==="execute"||e==="verify"||e==="complete")return e}function jp(e){return e?e==="analyze"?"Analyze":e==="route"?"Route":e==="execute"?"Execute":e==="verify"?"Verify":e==="complete"?"Complete":"Status":"Status"}function Xp(e,t,n){return[String(t||""),String(e||"").trim().toLowerCase(),String(n||"").trim().toLowerCase()].join("|")}function Kp(e,t){if(!e)return!0;let n=e.trim();return!!(t&&n.toLowerCase()===t.trim().toLowerCase()||/^complexity score\b/i.test(n)||/\btool loop$/i.test(n)||/^calling \w[\w\s]*(workflow|sub-agent)$/i.test(n))}function Qp(){return h?.pendingRun?.id}function tn(e){if(e)for(Qn.add(e);Qn.size>80;){let t=Qn.values().next().value;if(!t)break;Qn.delete(t)}}function Jl(e){e&&Qn.delete(e)}function so(){return h?.activeTask?.status==="running"}function Zl(){let e=H?.getState()?.activeRun;return!!(e&&e.runtimeId&&e.runtimeId!==Oe)}function eu(){return!Zl()}function tu(e){if(e==="observer")return Zl()?"Observing active run in another tab...":"Send to take control and run here."}function Jp(e){let t=typeof e?.type=="string"?e.type:"";if(!Op.has(t))return!1;let n=typeof e?.runId=="string"&&e.runId?e.runId:void 0;return Pl({type:t,messageRunId:n,pendingRunId:Qp(),sharedActiveRunId:H?.getState()?.activeRun?.runId,taskStatus:h?.activeTask?.status,ignoredRunIds:Qn})}function Eo(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r=0;r<e.length;r+=1){let o=e[r];if(!o||typeof o!="object")continue;let i=String(o.key||o.id||"").trim()||`clarification_${r+1}`,s=String(o.query||o.question||"").trim();if(!s)continue;let a=typeof o.required=="boolean",u=typeof o.optional=="boolean",m=a?!!o.required:u?!o.optional:!0,p=`${i}::${s}`.toLowerCase();if(n.has(p))continue;n.add(p);let v={key:i,query:s,...typeof o.id=="string"&&o.id.trim()?{id:o.id.trim()}:{},...typeof o.question=="string"&&o.question.trim()?{question:o.question.trim()}:{},...Array.isArray(o.choices)?{choices:o.choices}:{}};m||(v.required=!1),t.push(v)}return t.slice(0,6)}function Zp(e){if(!e||typeof e!="object")return{taskComplete:!1,needsUserInput:!1};let t=e.needsUserInput===!0,n=e.taskComplete===!0&&!t,r=Eo(e.questions);return{taskComplete:n,needsUserInput:t,...r.length?{questions:r}:{}}}function eh(e){if(e&&Pn.has(e))return Pn.get(e);if(h?.uiMessages?.length)for(let t=h.uiMessages.length-1;t>=0;t-=1){let n=h.uiMessages[t];if(n.role==="assistant"){if(n.text)return n.text;let r=ta(n.blocks);if(r)return r}}}function th(e){return br?br.readSync(e):null}function ea(e){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return}}}function er(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n.type;if(r==="text"){let o=String(n.text||"");if(!o)continue;t.push({type:"text",text:o});continue}(r==="tool_output"||r==="json")&&t.push({type:r,data:ea(n.data),label:typeof n.label=="string"?n.label:void 0,toolName:typeof n.toolName=="string"?n.toolName:void 0})}return t.length?t:void 0}function ql(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.entries(e).filter(([,i])=>i!=null);if(t.length!==1)return!1;let[n,r]=t[0];return typeof r!="string"||!r.trim()?!1:new Set(["response","message","summary","text","content","result","description"]).has(n)}function nh(e,t){if(e==null)return!1;if(typeof e=="string"){let n=e.trim();return n?!t||n!==t.trim():!1}if(Array.isArray(e)){let n=e.filter(r=>r!=null);if(n.length===1){let r=n[0];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean"||ql(r))return!1}return!0}return!ql(e)}function ta(e){if(!Array.isArray(e)||!e.length)return;let t=e.filter(r=>r.type==="text").map(r=>String(r.text||"").trim()).filter(Boolean);if(t.length)return t.join(`
|
|
1635
1635
|
|
|
1636
|
-
`);let n=e.find(r=>r.type==="tool_output"||r.type==="json");if(n)return Array.isArray(n.data)?`Received ${n.data.length} item(s).`:n.data&&typeof n.data=="object"?`Received ${Object.keys(n.data).length} field(s).`:typeof n.data=="string"?n.data:String(n.data??"Done.")}function rh(e){if(e==null)return;let t=e?.output??e?.generatedContentRef??e?.schemaHeaderSheetInfo??e,n=ta(er([{type:"tool_output",data:t}]));if(nh(t,n))return er([{type:"tool_output",label:typeof e?.name=="string"?`${e.name} output`:"Tool output",data:t}])}function nu(e){if(!e||typeof e!="object")return null;let t=e.role,n=e.content;return typeof t!="string"||typeof n!="string"||!n?null:{role:t,content:n}}function Pi(e,t){if(!Array.isArray(e))return[];let n=[];for(let r of e.slice(-t)){let o=ea(r);o!==void 0&&n.push(o)}return n}async function oh(e){if(!br)return null;try{return await br.readAsync(e)}catch{return null}}function uo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-qs)){let r=n?.role;r!=="user"&&r!=="assistant"&&r!=="system"||t.push({id:typeof n?.id=="string"&&n.id?n.id:Zn("msg"),role:r,text:String(n?.text||""),blocks:er(n?.blocks),ts:Number(n?.ts)||Date.now(),sourceRuntimeId:typeof n?.sourceRuntimeId=="string"?n.sourceRuntimeId:void 0})}return t.filter(n=>!!n.text||!!n.blocks?.length)}function fo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-$s)){let r=At(String(n?.title||""),400);if(!r)continue;let o=String(n?.kind||"status"),i=n?.status;t.push({id:typeof n?.id=="string"&&n.id?n.id:Zn("timeline"),kind:o,title:r,detail:n?.detail?String(n.detail):void 0,detailBlocks:er(n?.detailBlocks),status:i==="pending"||i==="success"||i==="error"||i==="info"?i:void 0,ts:Number(n?.ts)||Date.now(),sourceRuntimeId:typeof n?.sourceRuntimeId=="string"?n.sourceRuntimeId:void 0})}return t}function yr(e){if(!e||typeof e!="object")return;let t=Array.isArray(e.history)?e.history:[],n=Array.isArray(e.plannerHistory)?e.plannerHistory:[],r=Array.isArray(e.agentPrevSteps)?e.agentPrevSteps:Array.isArray(e.lastToolPreviousSteps)?e.lastToolPreviousSteps:[],o=t.slice(-Wl).map(m=>nu(m)).filter(m=>!!m),i=Pi(n,Ci),s=Pi(r,Ci*2),a=Eo(e?.pendingAskUser?.questions),u=a.length?{questions:a,source:e?.pendingAskUser?.source==="planner"?"planner":"act",askedAt:Number(e?.pendingAskUser?.askedAt)||Date.now()}:void 0;return{trajectoryId:typeof e.trajectoryId=="string"?e.trajectoryId:void 0,history:o,plannerHistory:i,agentPrevSteps:s,lastToolPreviousSteps:s,pendingAskUser:u,updatedAt:Number(e.updatedAt)||Date.now()}}function po(e,t,n){if(!e||typeof e!="object")return Ws(t,n);let r=Fn(),o=yo(e.activeTask,r),i=Bn(e.pendingRun),s=o.status==="running"?i:void 0;return{version:Ys,sessionId:typeof e.sessionId=="string"&&e.sessionId?e.sessionId:t,runtimeId:typeof e.runtimeId=="string"&&e.runtimeId?e.runtimeId:n,uiOpen:!!e.uiOpen,uiHidden:!!e.uiHidden,uiStatus:typeof e.uiStatus=="string"?At(e.uiStatus,300):void 0,uiMessages:uo(e.uiMessages),timeline:fo(e.timeline),executionMode:e.executionMode==="observer"||e.executionMode==="controller"?e.executionMode:"controller",workerState:yr(e.workerState),pendingRun:s,taskEpoch:Math.max(1,Number(e.taskEpoch)||1),activeTask:o,lastRoutingDecision:e.lastRoutingDecision&&(e.lastRoutingDecision.mode==="act"||e.lastRoutingDecision.mode==="planner")?{mode:e.lastRoutingDecision.mode,score:Number(e.lastRoutingDecision.score)||void 0,reason:typeof e.lastRoutingDecision.reason=="string"?At(e.lastRoutingDecision.reason,200):void 0,ts:Number(e.lastRoutingDecision.ts)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function yo(e,t){if(!e||typeof e!="object")return t;let n=typeof e.taskId=="string"&&e.taskId.trim()?e.taskId.trim():t.taskId,r=e.status==="ended"||e.status==="completed"||e.status==="running"?e.status:"running";return{taskId:n,status:r,startedAt:Number(e.startedAt)||t.startedAt,lastUserAt:Number(e.lastUserAt)||void 0,lastAssistantAt:Number(e.lastAssistantAt)||void 0,boundaryReason:typeof e.boundaryReason=="string"?At(e.boundaryReason,120):t.boundaryReason,endedAt:Number(e.endedAt)||void 0}}function ih(e,t){return yo(e,t)}function ru(e){if(!e)return;let t=Eo(e.pendingAskUser?.questions);return{trajectoryId:e.trajectoryId,history:Array.isArray(e.history)?e.history.slice(-Wl).map(n=>nu(n)).filter(n=>!!n):[],plannerHistory:Pi(e.plannerHistory,Ci),agentPrevSteps:Pi(e.agentPrevSteps,Ci*2),pendingAskUser:t.length?{questions:t,source:e.pendingAskUser?.source==="planner"?"planner":"act",askedAt:Number(e.pendingAskUser?.askedAt)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function Bn(e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id.trim()?e.id.trim():void 0,n=typeof e.text=="string"?e.text.trim():"";if(!(!t||!n))return{id:t,text:n,startedAt:Number(e.startedAt)||Date.now(),attempts:Math.max(0,Number(e.attempts)||0),autoResume:e.autoResume!==!1,resumeRequired:e.resumeRequired===!0,resumeReason:e.resumeReason==="cross_host_navigation"||e.resumeReason==="handoff"||e.resumeReason==="page_reload"?e.resumeReason:void 0}}function Ne(){if(!(!h||!Fr))try{h.updatedAt=Date.now(),br?.write(Fr,h),Di||Mt?.markDirty()}catch{}}function sh(){if(Ul)return;Ul=!0;let e=()=>{if(h?.pendingRun?.autoResume){let n=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:h.pendingRun.resumeReason||"page_reload"});h.pendingRun=n,n&&H?.clearActiveRunRuntimeId(n.id)}H?.broadcastClosing(),h?.pendingRun&&H?.releaseWorkflowLock(h.pendingRun.id),Ne(),h?.pendingRun&&Z?.siteId&&Fs(Z.siteId,{sessionId:h.sessionId,pendingRun:{id:h.pendingRun.id,text:h.pendingRun.text,startedAt:h.pendingRun.startedAt,attempts:h.pendingRun.attempts},activeTask:h.activeTask?{taskId:h.activeTask.taskId,status:h.activeTask.status}:void 0,taskEpoch:h.taskEpoch,timestamp:Date.now()}),$i(!0),Js(),Mt?.markDirty(),Mt?.syncNow(),Mt?.stop(),H?.stop()};window.addEventListener("pagehide",e,{capture:!0});let t=n=>{n.persisted&&(H&&(H.reloadFromStorage(),H.registerCurrentTab(window.location.href,document.title||void 0),H.claimLease(!1)),Hn=!1,Z&&Zs(Z))};window.addEventListener("pageshow",t)}function Wi(e="implicit"){if(h)return h.activeTask||(h.activeTask=Fn(e),h.taskEpoch=Math.max(1,Number(h.taskEpoch)||1)),h.activeTask}function ah(e,t=Date.now()){if(!h||e==="system")return;let n=Wi("implicit");n&&n.status==="running"&&(e==="user"&&(n.lastUserAt=t),e==="assistant"&&(n.lastAssistantAt=t))}function Vs(e="worker_task_active",t=Date.now()){if(!h)return;let n=Wi(e);n&&(n.status="running",n.endedAt=void 0,n.boundaryReason=e,!n.lastUserAt&&!n.lastAssistantAt&&(n.lastAssistantAt=t),H?.syncTask({...n},h.taskEpoch),Ne())}function ch(e="worker_task_complete",t=Date.now()){if(!h)return;let n=Wi(e);n&&(n.status="completed",n.endedAt=t,n.boundaryReason=e,H?.syncTask({...n},h.taskEpoch),Ne())}function Un(){qr=null,te?.setTaskSuggestion({visible:!1})}function lh(e){qr={kind:"resume_run",runId:e.id,text:e.text,createdAt:Date.now()},te?.setTaskSuggestion({visible:!0,text:"Previous task was interrupted by navigation. Resume it?",primaryLabel:"Resume",secondaryLabel:"Start fresh"}),Rt("Task paused after navigation. Resume to continue.")}function ou(){te?.clearMessages(),te?.clearTimeline(),te?.setQuestionPrompt(void 0),Un()}function Vi(){let e=Eo(h?.workerState?.pendingAskUser?.questions);if(!e.length){te?.setQuestionPrompt(void 0);return}te?.setQuestionPrompt({questions:e})}function uh(){let e=h?.pendingRun;if(!e)return!1;if(!H)return!0;let t=H?.getState()?.activeRun;if(t?.runId&&t.runId===e.id||t?.runtimeId&&t.runtimeId!==Oe)return!0;let n=Date.now()-Number(e.startedAt||0);return n>=0&&n<=kp}function dh(){if(!h?.pendingRun||uh()||!H)return;let e=h.pendingRun,t=Date.now()-Number(e.startedAt||0);!Number.isFinite(t)||t<Sp||(tn(e.id),wt(void 0),H?.clearActiveRunRuntimeId(e.id),H?.releaseWorkflowLock(e.id),H?.setActiveRun(void 0))}function hn(e,t,n=!0,r){let o=String(t||""),i=er(r?.blocks);if(!o&&(!i||i.length===0))return;let s={id:r?.id||Zn("msg"),role:e,text:o,blocks:i,ts:r?.ts||Date.now(),sourceRuntimeId:r?.sourceRuntimeId};return te?.addMessage(s.role,s.text,{blocks:s.blocks}),h&&n&&(h.uiMessages.push(s),h.uiMessages.length>qs&&(h.uiMessages=h.uiMessages.slice(-qs)),ah(s.role,s.ts),Ne()),H&&r?.publishShared!==!1&&(H.appendMessage({id:s.id,role:s.role,text:s.text,blocks:s.blocks,ts:s.ts}),H.markTaskActivity(s.role,s.ts)),s}function na(e){for(let t of e)hn(t.role,t.text,!1,{id:t.id,ts:t.ts,sourceRuntimeId:t.sourceRuntimeId,publishShared:!1,blocks:t.blocks})}function at(e,t=!0){let n={id:e.id||Zn("timeline"),kind:e.kind,title:At(e.title,400),detail:e.detail?String(e.detail):void 0,detailBlocks:er(e.detailBlocks),status:e.status,ts:e.ts||Date.now(),sourceRuntimeId:e.sourceRuntimeId};return te?.addTimelineEvent(n),h&&t&&(h.timeline.push(n),h.timeline.length>$s&&(h.timeline=h.timeline.slice(-$s)),Ne()),H&&e.publishShared!==!1&&H.appendTimeline({id:n.id,kind:n.kind,title:n.title,detail:n.detail,detailBlocks:n.detailBlocks,status:n.status,ts:n.ts}),n}function ra(e){te?.clearTimeline();for(let t of e)at({id:t.id,kind:t.kind,title:t.title,detail:t.detail,detailBlocks:t.detailBlocks,status:t.status,ts:t.ts,sourceRuntimeId:t.sourceRuntimeId,publishShared:!1},!1)}function Rt(e,t){te?.setStatus(e),h&&(h.uiStatus=At(e,300),Ne()),H&&t?.publishShared!==!1&&H.setStatus(e)}function ho(e,t){lt=e,h&&(h.executionMode=e,Ne()),te?.setExecutionMode(e,{controllerRuntimeId:t?.holderRuntimeId??H?.getCurrentHolderRuntimeId(),localLogicalTabId:t?.localLogicalTabId??H?.getLocalLogicalTabId(),activeLogicalTabId:t?.activeLogicalTabId??H?.getActiveLogicalTabId(),canTakeControl:!0,canComposeInObserver:eu(),note:tu(e)}),Be("mode_change",{mode:e,...t})}function wt(e){h&&(h.pendingRun=e,Ne())}function Hi(e,t){let n=String(e||"").trim();if(!n||!Pe)return;if(lt==="observer"&&!(H?.requestControl()??!1)){hn("system","Unable to take control right now because another tab is still running Rover actions.",!0),at({kind:"info",title:"Observer mode",detail:"Action execution is currently owned by another tab runtime.",status:"info"});return}let r=t?.runId||crypto.randomUUID(),o=!!t?.resume,i=t?.appendUserMessage!==!1;Jl(r),i&&hn("user",n,!0);let s=h?.pendingRun?.id===r?h.pendingRun.attempts:0;wt({id:r,text:n,startedAt:Date.now(),attempts:o?s+1:0,autoResume:t?.autoResume!==!1,resumeRequired:!1,resumeReason:void 0}),Vs(o?"worker_task_resumed":"worker_task_active"),Gl=n,H?.acquireWorkflowLock(r),H?.setActiveRun({runId:r,text:n}),Pe.postMessage({type:"run",text:n,runId:r,resume:o,routing:t?.routing,askUserAnswers:t?.askUserAnswers}),ct&&clearTimeout(ct);let a=r;ct=setTimeout(()=>{h?.pendingRun?.id===a&&(tn(a),wt(void 0),H?.releaseWorkflowLock(a),H?.setActiveRun(void 0),Rt("Task timed out."),hn("system","Task timed out after 5 minutes with no response.",!0),Be("error",{message:"Run safety timeout"})),ct=null},5*6e4)}function ao(e,t){let n=String(e||"").trim();if(!n)return;dh();let r=h?.activeTask?.status,o=!!t?.startNewTask||Ml(r);if(H?.pruneTabs({dropRuntimeDetached:!0,dropAllDetachedExternal:o}),o){let i=t?.reason||(r==="completed"?"auto_after_task_complete":"auto_after_task_end");$r({reason:i,clearUi:!0})}Un(),Hi(n,{appendUserMessage:!0,resume:!1,autoResume:!0,routing:t?.routing,askUserAnswers:t?.askUserAnswers})}function Ui(){if(lt==="observer")return;let e=H?.getState()?.activeRun;if(e?.runtimeId&&e.runtimeId!==Oe&&!(h?.pendingRun?.id===e.runId)||!tr||!Pe||Hn||!h?.pendingRun||!Dl(h.activeTask?.status))return;let t=h.pendingRun;if(!t.autoResume)return;let n=Ks(Z?.task?.autoResumePolicy);if(n==="never"){tn(t.id),wt(void 0),H?.setActiveRun(void 0),Rt("Previous task dismissed after navigation.");return}let r=t.resumeReason==="cross_host_navigation"||t.resumeReason==="agent_navigation",o=Z?.siteId||"";if(!!!sessionStorage.getItem(`rover:tab-alive:${o}`)&&!r&&!(H?.listTabs()||[]).some(m=>m.runtimeId!==Oe&&m.updatedAt>Date.now()-2*2e3)&&h?.pendingRun){tn(h.pendingRun.id),wt(void 0),Rt("Previous task expired.");return}if(Date.now()-t.startedAt>Tp){tn(t.id),wt(void 0),Rt("Previous task expired after navigation.");return}if(t.attempts>=_p){tn(t.id),wt(void 0),hn("system","Auto-resume stopped after too many navigation attempts.",!0);return}if(r){Hn=!0,Rt("Resuming task after navigation..."),Hi(t.text,{runId:t.id,resume:!0,appendUserMessage:!1,autoResume:!0});return}if(n==="confirm"){Hn=!0,lh(t);return}Hn=!0,Rt("Resuming previous task after navigation..."),Hi(t.text,{runId:t.id,resume:!0,appendUserMessage:!1,autoResume:!0})}async function fh(e){if(!h)return;let t=await oh(e);if(!t||!h)return;let n=Number(h.updatedAt)||0,r=po({...t,sessionId:h.sessionId,runtimeId:Oe},h.sessionId,Oe);(Number(r.updatedAt)||0)<=n+200||(h=po({...h,...r,sessionId:h.sessionId,runtimeId:Oe},h.sessionId,Oe),Ne(),te&&(te.clearMessages(),na(h.uiMessages),ra(h.timeline),h.uiStatus&&te.setStatus(h.uiStatus),Vi(),h.uiHidden?te.hide():(te.show(),h.uiOpen?te.open():te.close())),tr&&Pe&&h.workerState&<==="controller"&&(Pe.postMessage({type:"hydrate_state",state:h.workerState}),Be("context_restored",{source:"indexeddb_checkpoint",ts:Date.now()})))}function oa(e,t){if(h){if(t==="remote"){let n=Math.max(1,Number(h.taskEpoch)||1),r=Math.max(1,Number(e.taskEpoch)||1),o=r>n;h.taskEpoch=Math.max(n,r);let i=h.activeTask||Fn("shared_sync");h.activeTask=ih(e.task,i),o&&(h.uiMessages=[],h.timeline=[],ou(),wt(void 0),Un());let s=uo(e.uiMessages),a=new Set(s.map(x=>x.id));if(s.length<h.uiMessages.length||h.uiMessages.some(x=>!a.has(x.id)))h.uiMessages=s,te?.clearMessages(),na(h.uiMessages);else{let x=new Set(h.uiMessages.map(S=>S.id));for(let S of s)x.has(S.id)||(hn(S.role,S.text,!0,{id:S.id,ts:S.ts,sourceRuntimeId:S.sourceRuntimeId,publishShared:!1,blocks:S.blocks}),x.add(S.id))}let m=fo(e.timeline),p=new Set(m.map(x=>x.id));if(m.length<h.timeline.length||h.timeline.some(x=>!p.has(x.id)))h.timeline=m,ra(h.timeline);else{let x=new Set(h.timeline.map(S=>S.id));for(let S of m)x.has(S.id)||(at({id:S.id,kind:S.kind,title:S.title,detail:S.detail,detailBlocks:S.detailBlocks,status:S.status,ts:S.ts,sourceRuntimeId:S.sourceRuntimeId,publishShared:!1},!0),x.add(S.id))}typeof e.uiStatus=="string"&&Rt(e.uiStatus,{publishShared:!1});let I=h.activeTask?.status,A=e.task?.status;if(e.activeRun&&e.activeRun.runtimeId!==Oe&&!Bs({localTaskStatus:I,remoteTaskStatus:A,mode:lt,hasRemoteActiveRun:!0})?wt(Bn({id:e.activeRun.runId,text:e.activeRun.text,startedAt:e.activeRun.startedAt,attempts:h.pendingRun?.attempts||0,autoResume:!0})):Bs({localTaskStatus:I,remoteTaskStatus:A,mode:lt,hasRemoteActiveRun:!!e.activeRun})&&(h.pendingRun?.id&&tn(h.pendingRun.id),wt(void 0)),lt==="observer"&&ho("observer",{localLogicalTabId:H?.getLocalLogicalTabId(),activeLogicalTabId:H?.getActiveLogicalTabId(),holderRuntimeId:H?.getCurrentHolderRuntimeId()}),e.workerContext){let x=yr(e.workerContext),S=Number(h.workerState?.updatedAt)||0,B=Number(x?.updatedAt)||0;x&&B>S+100&&(h.workerState=x,tr&&Pe&<==="controller"&&(Pe.postMessage({type:"hydrate_state",state:x}),Be("context_restored",{source:"shared_session",ts:Date.now()})))}}h.uiMessages=uo(h.uiMessages),h.timeline=fo(h.timeline),h.workerState=yr(h.workerState),Vi(),h.activeTask=yo(h.activeTask,Fn("implicit")),Ne()}}function iu(e){let t=Fn("checkpoint_clone");return{version:Ys,sessionId:e.sessionId,runtimeId:e.runtimeId,uiOpen:!!e.uiOpen,uiHidden:!!e.uiHidden,uiStatus:typeof e.uiStatus=="string"?At(e.uiStatus,300):void 0,uiMessages:uo(e.uiMessages),timeline:fo(e.timeline),executionMode:e.executionMode==="observer"||e.executionMode==="controller"?e.executionMode:"controller",workerState:yr(e.workerState),pendingRun:Bn(e.pendingRun),taskEpoch:Math.max(1,Number(e.taskEpoch)||1),activeTask:yo(e.activeTask,t),lastRoutingDecision:e.lastRoutingDecision&&(e.lastRoutingDecision.mode==="act"||e.lastRoutingDecision.mode==="planner")?{mode:e.lastRoutingDecision.mode,score:Number(e.lastRoutingDecision.score)||void 0,reason:e.lastRoutingDecision.reason,ts:Number(e.lastRoutingDecision.ts)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function ph(e){return!(e.sessionScope==="tab"||e.checkpointing?.enabled!==!0||!(e.apiKey||e.authToken)||!kt)}function hh(){if(!h||!Z||!kt)return null;let e=H?.getState(),t=iu(h),n=Math.max(Number(e?.updatedAt||0),Number(t.updatedAt||0),Date.now());return{version:Rp,siteId:Z.siteId,visitorId:kt,sessionId:h.sessionId,updatedAt:n,sharedState:e,runtimeState:t}}function mh(e){if(!e||typeof e!="object"||!h||!Z||e.siteId&&e.siteId!==Z.siteId||kt&&e.visitorId&&e.visitorId!==kt)return;let t=typeof e.sessionId=="string"&&e.sessionId.trim()?e.sessionId.trim():h.sessionId;Di=!0;try{if(t&&h.sessionId!==t&&(h.sessionId=t,Z={...Z,sessionId:t},Fi(Z),Pe?.postMessage({type:"update_config",config:{sessionId:t}})),e.sharedState&&H&&H.hydrateExternalState(e.sharedState)&&(oa(H.getState(),"remote"),ho(H.getRole(),{localLogicalTabId:H.getLocalLogicalTabId(),activeLogicalTabId:H.getActiveLogicalTabId(),holderRuntimeId:H.getCurrentHolderRuntimeId()})),e.runtimeState&&typeof e.runtimeState=="object"){let n=po({...e.runtimeState,sessionId:t,runtimeId:Oe},t,Oe),r=Number(h.updatedAt)||0;(Number(n.updatedAt)||0)>r+200&&(h=po({...h,...n,sessionId:t,runtimeId:Oe},t,Oe),Ne(),h.uiStatus&&te?.setStatus(h.uiStatus),h.uiHidden?te?.hide():(te?.show(),h.uiOpen?te?.open():te?.close()),tr&&h.workerState&&(Pe?.postMessage({type:"hydrate_state",state:h.workerState}),Be("context_restored",{source:"cloud_checkpoint",ts:Date.now()})),lt==="controller"&&Ui())}}finally{Di=!1}}function su(e){if(Mt?.stop(),Mt=null,!!ph(e)&&kt)try{let t=n=>{Be("checkpoint_state",n),e.checkpointing?.onStateChange?.(n)};Mt=new Ei({apiBase:e.apiBase,apiKey:e.apiKey,authToken:e.authToken,siteId:e.siteId,visitorId:kt,ttlHours:e.checkpointing?.ttlHours??1,flushIntervalMs:e.checkpointing?.flushIntervalMs,pullIntervalMs:e.checkpointing?.pullIntervalMs,minFlushIntervalMs:e.checkpointing?.minFlushIntervalMs,shouldWrite:()=>lt==="controller",buildCheckpoint:()=>hh(),onCheckpoint:n=>{mh(n)},onStateChange:(n,r)=>{t({state:n,reason:r.reason,action:r.action,code:r.code,message:r.message}),n==="paused_auth"&&Be("checkpoint_error",{action:r.action,code:r.code||"INVALID_API_KEY",message:r.message||"Checkpoint sync paused due to auth failure.",disabled:!0,reason:r.reason||"auth_failed"})},onError:(n,r)=>{e.checkpointing?.onError?.(r),r.paused||Be("checkpoint_error",{action:r.action,code:r.code,message:r.message,status:r.status,disabled:!1,reason:"transient_failure"})}}),Mt.start(),Mt.markDirty()}catch{Mt=null}}function Fi(e){if(h){if(H?.stop(),H=null,e.sessionScope==="tab"){ho("controller");return}H=new gi({siteId:e.siteId,sessionId:h.sessionId,runtimeId:Oe,leaseMs:e.tabPolicy?.actionLeaseMs,onRoleChange:(t,n)=>{ho(t,n);let r=t==="controller"&&(Z?.allowActions??!0);if($e?.setAllowActions(r),$e?.setActionGateContext?.({mode:t,controllerRuntimeId:n?.holderRuntimeId??H?.getCurrentHolderRuntimeId(),activeLogicalTabId:n?.activeLogicalTabId??H?.getActiveLogicalTabId(),localLogicalTabId:n?.localLogicalTabId??H?.getLocalLogicalTabId(),reason:Xs(t,r)}),t==="controller"){let o=H?.getWorkerContext();if(o){let i=yr(o),s=Number(h?.workerState?.updatedAt)||0,a=Number(i?.updatedAt)||0;i&&a>s+100&&(h&&(h.workerState=i,Ne()),tr&&Pe&&(Pe.postMessage({type:"hydrate_state",state:i}),Be("context_restored",{source:"controller_handoff",ts:Date.now()})))}Ui()}},onStateChange:(t,n)=>{oa(t,n)},onSwitchRequested:t=>{t>0&&(vo(),at({kind:"status",title:`Switched to tab #${t}`,status:"info"}))}}),H.start(),H.setRpcRequestHandler(async t=>{if(!$e)throw new Error("Bridge not available");if(t.method==="getPageData")return $e.getPageData(t.params);if(t.method==="executeTool")return $e.executeTool(t.params.call,t.params.payload);throw new Error(`Unknown RPC method: ${t.method}`)}),h?.activeTask&&H.syncTask({...h.activeTask,taskId:h.activeTask.taskId},h.taskEpoch),h?.workerState&&H.setWorkerContext(ru(h.workerState))}}function gh(e){let t=At(eh(e)||"Done.",1200);te?.clearTimeline(),h&&(h.timeline=[]),H?.clearTimeline()}function bh(e){if(!(!e||typeof e!="object")&&!Jp(e)){if(e.type==="assistant"){let t=er(e.blocks),n=String(e.text||ta(t)||"");if(typeof e.runId=="string"&&e.runId&&(Pn.set(e.runId,n),Pn.size>80)){let r=Pn.keys().next().value;r&&Pn.delete(r)}hn("assistant",n,!0,{blocks:t}),at({kind:"tool_result",title:"Assistant update",detail:n,detailBlocks:t,status:"success"});return}if(e.type==="status"){let t=Yp(e.stage),n=e.message?String(e.message):void 0,r=e.compactThought?String(e.compactThought):void 0,o=Xp(n,t,r);if(n&&Rt(n),o&&o!==wi&&(wi=o,n)){let i=!!(e.thought||r),s=r||(e.thought?String(e.thought):"");if(i&&t!=="analyze"&&t!=="route"&&t!=="complete"&&!Kp(s,Gl))at({kind:"thought",title:s,detail:e.thought?String(e.thought):r,status:"pending"});else{let u=t?`${jp(t)}: ${n}`:n;at({kind:"status",title:u,detail:r||(e.thought?String(e.thought):void 0),status:t==="complete"?"success":"info"})}}Be("status",e);return}if(e.type==="tool_start"){at({kind:"tool_start",title:`Running ${e.call?.name||"tool"}`,detail:Ai(e.call?.args),status:"pending"}),Be("tool_start",e);return}if(e.type==="tool_result"){let t=er(e.detailBlocks)||rh(e.result);at({kind:"tool_result",title:`${e.call?.name||"tool"} completed`,detail:Ai(e.result),detailBlocks:t,status:e?.result?.success===!1?"error":"success"}),Be("tool_result",e);return}if(e.type==="auth_required"){Be("auth_required",e.error),e.error?.message&&(hn("system",`Auth required: ${e.error.message}`,!0),at({kind:"error",title:"Auth required",detail:String(e.error.message),status:"error"}));return}if(e.type==="navigation_guardrail"){Be("navigation_guardrail",e),at({kind:"status",title:"Navigation guardrail",detail:Ai(e),status:"info"});return}if(e.type==="error"){hn("system",`Error: ${e.message||"unknown"}`,!0),at({kind:"error",title:"Execution error",detail:String(e.message||"unknown"),status:"error"}),Be("error",e);return}if(e.type==="state_snapshot"){if(h){h.workerState=yr({...e.state||{},updatedAt:Date.now()});let t=typeof e?.activeRun?.runId=="string"&&e.activeRun.runId?e.activeRun.runId:void 0,n=typeof e?.activeRun?.text=="string"?e.activeRun.text:void 0,r=Ol({taskStatus:h.activeTask?.status,hasPendingRun:!!h.pendingRun,activeRunId:t,activeRunText:n,ignoredRunIds:Qn});r&&(h.pendingRun=Bn({id:t,text:n,startedAt:e.activeRun.startedAt,attempts:0,autoResume:!0})),t&&n&&r?H?.setActiveRun({runId:t,text:n}):t&&(!so()||Qn.has(t))&&H?.setActiveRun(void 0),!so()&&h.pendingRun&&wt(void 0),h.workerState&&H?.setWorkerContext(ru(h.workerState)),Vi(),Ne()}return}if(e.type==="task_started"){Be("task_started",{taskId:e.taskId,reason:"worker"});return}if(e.type==="run_started"){if(wi="",Un(),typeof e.runId=="string"&&e.runId&&Pn.delete(e.runId),!so()){H?.setActiveRun(void 0);return}let t=h?.pendingRun;typeof e.runId=="string"&&e.runId&&Jl(e.runId),wt(Bn({id:e.runId,text:e.text,startedAt:t?.startedAt||Date.now(),attempts:t?.attempts||0,autoResume:t?.autoResume!==!1})),H?.setActiveRun({runId:e.runId,text:String(e.text||"")}),te?.setRunning(!0),te?.setQuestionPrompt(void 0);let n=`run:${String(e.runId||"")}:start`;h?.timeline.some(r=>r.id===n)||at({id:n,kind:"plan",title:e.resume?"Run resumed":"Run started",detail:String(e.text||""),status:"pending"});return}if(e.type==="run_completed"){wi="",Hn=!1,te?.setRunning(!1),ct&&(clearTimeout(ct),ct=null),h?.pendingRun?.id===e.runId&&wt(void 0),typeof e.runId=="string"&&e.runId&&H?.releaseWorkflowLock(e.runId),h&&e?.route&&(e.route.mode==="act"||e.route.mode==="planner")&&(h.lastRoutingDecision={mode:e.route.mode,score:Number(e.route.score)||void 0,reason:typeof e.route.reason=="string"?At(e.route.reason,200):void 0,ts:Date.now()},Ne()),H?.setActiveRun(void 0);let t=typeof e.runId=="string"&&e.runId?e.runId:void 0;if(t&&tn(t),!e.ok&&e.error){if(t&&Pn.delete(t),!so())return;te?.setQuestionPrompt(void 0),Vs("worker_run_failed"),Rt(`Task failed: ${String(e.error)}`),t&&Pn.delete(t),at({kind:"error",title:"Run failed",detail:String(e.error),status:"error"})}else if(e.ok){if(!so())return;let n=Zp(e),r=n.taskComplete,o=n.needsUserInput,i=n.questions||Eo(e.questions);r?(te?.setQuestionPrompt(void 0),ch("worker_task_complete"),H?.pruneTabs({dropRuntimeDetached:!0,dropAllDetachedExternal:!0}),Rt("Task completed"),gh(typeof e.runId=="string"?e.runId:void 0)):(Vs(o?"worker_waiting_for_input":"worker_continuation"),o&&i.length>0?te?.setQuestionPrompt({questions:i}):te?.setQuestionPrompt(void 0),Rt(o?"Need more input to continue":"Execution finished. Continue when ready."),at({kind:"status",title:o?"Waiting for your input":"Continuation available",detail:o?i.length?`Please answer: ${i.map(s=>`${s.key} (${s.query})`).join("; ")}`:"Planner requested more information before marking the task complete.":"Task is still active and will continue with your next message.",status:"info"}))}return}if(e.type==="ready"){tr=!0,Rt("ready"),Be("ready"),Z&&cu(Z);let t=H?.getWorkerContext(),n=yr(t),r=Number(h?.workerState?.updatedAt)||0,o=Number(n?.updatedAt)||0,i=n&&o>r+100?n:h?.workerState;h&&i&&i!==h.workerState&&(h.workerState=i,Ne()),i?(Pe?.postMessage({type:"hydrate_state",state:i}),Be("context_restored",{source:"runtime_start",ts:Date.now()})):Ui();return}if(e.type==="hydrated"){Ui();return}e.type==="updated"&&Be("updated")}}function Gs(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(t.min,Math.min(t.max,Math.floor(n))):t.fallback}function ia(e){if(!e||typeof e!="object")return;let t=Gs(e.shortcutMaxStored,{min:1,max:Li,fallback:Li}),n=Gs(e.shortcutMaxRendered,{min:1,max:Mi,fallback:Mi});return{shortcutMaxStored:t,shortcutMaxRendered:n}}function wo(){co&&(clearTimeout(co),co=null),lo&&(clearTimeout(lo),lo=null)}function Eh(e){try{let t=localStorage.getItem(`rover:site-config:${e}`);if(t){let n=JSON.parse(t);return!n||typeof n.ts!="number"||typeof n.data!="object"||!n.data||Date.now()-n.ts>Hl?null:{shortcuts:wr(n.data.shortcuts),greeting:mo(n.data.greeting),limits:ia(n.data.limits),version:typeof n.version=="string"?n.version:void 0}}}catch{}try{let t=localStorage.getItem(`rover:shortcuts:${e}`);if(!t)return null;let n=JSON.parse(t);return!n||typeof n.ts!="number"||!Array.isArray(n.data)||Date.now()-n.ts>Hl?null:{shortcuts:wr(n.data)}}catch{return null}}function yh(e,t){try{localStorage.setItem(`rover:site-config:${e}`,JSON.stringify({ts:Date.now(),version:t.version,data:{shortcuts:wr(t.shortcuts),greeting:mo(t.greeting),limits:ia(t.limits)}}))}catch{}}function mo(e){if(!e||typeof e!="object")return;let t={},n=String(e.text||"").trim();n&&(t.text=n.slice(0,Dp));let r=Number(e.delay);Number.isFinite(r)&&(t.delay=Math.max(0,Math.min(6e4,Math.floor(r))));let o=Number(e.duration);return Number.isFinite(o)&&(t.duration=Math.max(1200,Math.min(6e4,Math.floor(o)))),typeof e.disabled=="boolean"&&(t.disabled=e.disabled),Object.keys(t).length?t:void 0}function wh(e){if(!e||typeof e!="object")return null;let t=String(e.id||"").trim().slice(0,80),n=String(e.label||"").trim().slice(0,Cp),r=String(e.prompt||"").trim().slice(0,Lp);if(!t||!n||!r)return null;let o={id:t,label:n,prompt:r,enabled:e.enabled!==!1};e.description&&(o.description=String(e.description).trim().slice(0,Np)),e.icon&&(o.icon=String(e.icon).trim().slice(0,Mp)),(e.routing==="auto"||e.routing==="act"||e.routing==="planner")&&(o.routing=e.routing);let i=Number(e.order);return Number.isFinite(i)&&(o.order=Math.trunc(i)),o}function wr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(t.length>=Li)break;let o=wh(r);!o||n.has(o.id)||(n.add(o.id),t.push(o))}return t}function vh(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{let r=Number.isFinite(t.item.order),o=Number.isFinite(n.item.order);return r&&o?Number(t.item.order)-Number(n.item.order):r?-1:o?1:t.index-n.index}).map(t=>t.item)}function Th(e,t){let n=new Map;for(let r of t)n.set(r.id,r);for(let r of e){let o=n.get(r.id);n.set(r.id,o?{...o,...r}:r)}return vh(Array.from(n.values())).slice(0,Li)}function au(e){let t=Gs(Er?.limits?.shortcutMaxRendered,{min:1,max:Mi,fallback:Mi});return e.filter(n=>n.enabled!==!1).slice(0,t)}function Gi(e){if(!e)return;let t=mo(Er?.greeting),n=mo(e.ui?.greeting);if(!(!t&&!n))return{...t||{},...n||{}}}function sa(e){let t=_n?.name,n=e?.text;return n?n.replace(/\{name\}/g,t||"").trim()||(t?`Hey ${t}! Need any help?`:"Hey! Need any help?"):t?`Hey ${t}! Need any help?`:"Hey! Need any help?"}function go(){if(Jn||!te||!Z||h?.uiOpen)return;let e=Gi(Z);if(e?.disabled===!0)return;let t=`rover:greeting-shown:${Z.siteId}`;try{if(sessionStorage.getItem(t)){gr=!0;return}}catch{}if(gr)return;wo();let n=e?.delay??3e3,r=e?.duration??8e3,o=sa(e);co=setTimeout(()=>{if(co=null,!(Jn||h?.uiOpen)){te?.showGreeting(o),gr=!0;try{sessionStorage.setItem(t,"1")}catch{}lo=setTimeout(()=>{lo=null,te?.dismissGreeting()},r)}},n)}function zs(e){let t=wr(e.ui?.shortcuts||[]),n=wr(Er?.shortcuts||[]),r=Th(t,n);te?.setShortcuts(au(r))}async function _h(e){let t=String(e.authToken||e.apiKey||"").trim();if(!t)return null;let n=await fetch(Ql(e.apiBase),{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({action:"roverGetSiteConfig",data:{siteId:e.siteId,siteKeyId:e.siteKeyId}})});if(!n.ok)return null;let r=await n.json();if(!r?.success)return null;let o=r.data?.siteConfig&&typeof r.data.siteConfig=="object"?r.data.siteConfig:r.data;return{shortcuts:wr(o?.shortcuts),greeting:mo(o?.greeting),limits:ia(o?.limits),version:o?.version!=null?String(o.version):void 0}}function cu(e){let t=Eh(e.siteId);t&&(Er=t),zs(e),go(),_h(e).then(n=>{if(n&&(Er=n,yh(e.siteId,n),zs(e),!Jn)){let r=Gi(e);gr&&!h?.uiOpen?te?.showGreeting(sa(r)):go()}}).catch(()=>{})}function aa(e){if(!Z)return;let t={..._n,...e};t.name&&(t.name=String(t.name).trim().slice(0,120)),t.email&&(t.email=String(t.email).trim().slice(0,240)),_n=t,jl(Z.siteId,_n),te?.setVisitorName(_n.name||""),Jn||(gr&&!h?.uiOpen?te?.showGreeting(sa(Gi(Z))):go())}function xh(e){if(Fi(e),H){let s=H.getRole();lt=s,h&&(h.executionMode=s)}su(e),Zs(e);let t=(e.allowActions??!0)&&(H?H.isController():!0);$e=new di({allowActions:t,runtimeId:Oe,allowedDomains:e.allowedDomains,domainScopeMode:e.domainScopeMode,externalNavigationPolicy:e.externalNavigationPolicy,crossHostPolicy:js(e.navigation?.crossHostPolicy),registerOpenedTab:s=>H?.registerOpenedTab(s),switchToLogicalTab:s=>H?.switchToLogicalTab(s)||{ok:!1,reason:"No session coordinator"},listKnownTabs:()=>(H?.listTabs()||[]).map(s=>({logicalTabId:s.logicalTabId,runtimeId:s.runtimeId,url:s.url,title:s.title,external:!!s.external})),onNavigationGuardrail:s=>{Be("navigation_guardrail",s),at({kind:"status",title:"Navigation guardrail",detail:Ai(s),status:"info"})},onBeforeAgentNavigation:s=>{if(!h?.pendingRun)return;let a=new URL(window.location.href).hostname,u=new URL(s,window.location.href).hostname;a===u&&(h.pendingRun=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:"agent_navigation"}))},onBeforeCrossHostNavigation:s=>{!h||!Z||(h.pendingRun&&(h.pendingRun=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:"cross_host_navigation"})),Fs(Z.siteId,{sessionId:h.sessionId,pendingRun:h.pendingRun?{id:h.pendingRun.id,text:h.pendingRun.text,startedAt:h.pendingRun.startedAt,attempts:h.pendingRun.attempts}:void 0,activeTask:h.activeTask?{taskId:h.activeTask.taskId,status:h.activeTask.status}:void 0,taskEpoch:h.taskEpoch,timestamp:Date.now()}),Ne())},instrumentationOptions:e.mode==="safe"?{observeInlineMutations:!1}:void 0});let n=lt==="observer"?"observer":"controller";$e?.setActionGateContext?.({mode:n,controllerRuntimeId:H?.getCurrentHolderRuntimeId(),activeLogicalTabId:H?.getActiveLogicalTabId(),localLogicalTabId:H?.getLocalLogicalTabId(),reason:Xs(n,t)});let r=new MessageChannel;gl(r.port1,{getSnapshot:()=>$e.getSnapshot(),getPageData:async s=>{let a=Z||e,u=Number(s?.tabId),m=H?.getLocalLogicalTabId();if(!Number.isFinite(u)||u<=0||u===m||!H)return $e.getPageData(s);let v=H.listTabs().find(I=>I.logicalTabId===u);if(!v)return _i(a,{logicalTabId:u,external:!0},"target_tab_missing");if(v.runtimeId===Oe)return $e.getPageData(s);if(v.external&&a.externalNavigationPolicy!=="allow")return _i(a,v,"external_domain_inaccessible");if(!v.runtimeId||!H.isTabAlive(u))return _i(a,v,"target_tab_inactive");try{return await H.sendCrossTabRpc(v.runtimeId,"getPageData",s,15e3)}catch{return _i(a,v,"cross_tab_rpc_failed")}},executeTool:async s=>{let a=Z||e;if(s?.payload?.forceLocal===!0)return $e.executeTool(s.call,s.payload);let m=Number(s?.call?.args?.tab_id),p=H?.getActiveLogicalTabId(),v=Number.isFinite(m)&&m>0?m:p,I=H?.getLocalLogicalTabId();if(!v||v===I||!H)return $e.executeTool(s.call,s.payload);let x=H.listTabs().find(S=>S.logicalTabId===v);if(!x)return xi(a,{logicalTabId:v,external:!0},"target_tab_missing");if(x.external&&a.externalNavigationPolicy!=="allow")return xi(a,x,"external_tab_action_blocked");if(x.runtimeId===Oe)return $e.executeTool(s.call,s.payload);if(!x.runtimeId||!H.isTabAlive(v))return xi(a,x,"target_tab_inactive");try{return await H.sendCrossTabRpc(x.runtimeId,"executeTool",s,2e4)}catch{return xi(a,x,"cross_tab_execute_failed")}},executeClientTool:s=>$e.executeClientTool(s.name,s.args),listClientTools:()=>$e.listClientTools(),getTabContext:()=>{let s=H?.getLocalLogicalTabId(),a=H?.getActiveLogicalTabId();return{id:s||1,logicalTabId:s||1,activeLogicalTabId:a||s||1,runtimeId:Oe,mode:lt,url:window.location.href,title:document.title}},listSessionTabs:()=>H?.listTabs()||[]}),r.port1.start?.();let o=e.workerUrl?e.workerUrl:new URL("./worker/worker.js",__ROVER_SCRIPT_URL__).toString(),i=o;try{let s=window.location.origin,a=new URL(o).origin;if(s!==a){let u=new Blob([`import '${o}';`],{type:"application/javascript"});i=URL.createObjectURL(u)}}catch{}if(Pe=new Worker(i,{type:"module"}),Pe.postMessage({type:"init",config:e,port:r.port2},[r.port2]),te=Tl({shortcuts:au(wr(e.ui?.shortcuts||[])),greeting:Gi(e),visitorName:_n?.name,onShortcutClick:s=>{let a=String(s.prompt||"").trim();a&&ao(a,{routing:s.routing})},onSend:(s,a)=>{ao(s,{askUserAnswers:a?.askUserAnswers})},onRequestControl:()=>{H?.requestControl()??!1?at({kind:"status",title:"Control requested",detail:"This tab is now the active Rover controller.",status:"info"}):hn("system","Unable to acquire control right now. Try again in a moment.",!0)},onCancelRun:()=>{h?.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id),H?.setActiveRun(void 0),wt(void 0),ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Rt("Task cancelled."),hn("system","Task cancelled.",!0),at({kind:"info",title:"Run cancelled",status:"info"}))},onNewTask:()=>{$r({reason:"manual_new_task",clearUi:!0})},onEndTask:()=>{Yi({reason:"manual_end_task"})},onTaskSuggestionPrimary:()=>{let s=qr;if(s){if(s.kind==="resume_run"){Un(),Hi(s.text,{runId:s.runId,resume:!0,appendUserMessage:!1,autoResume:!0});return}ao(s.text,{bypassSuggestion:!0,startNewTask:!0,reason:s.reason})}},onTaskSuggestionSecondary:()=>{let s=qr;if(s){if(s.kind==="resume_run"){h?.pendingRun?.id===s.runId&&(tn(s.runId),H?.releaseWorkflowLock(s.runId),H?.setActiveRun(void 0),wt(void 0)),ct&&(clearTimeout(ct),ct=null),Un(),$r({reason:"resume_declined_start_fresh",clearUi:!0});return}ao(s.text,{bypassSuggestion:!0})}},showTaskControls:e.ui?.showTaskControls!==!1,muted:e.ui?.muted,agent:{name:e.ui?.agent?.name},mascot:{disabled:e.ui?.mascot?.disabled,mp4Url:e.ui?.mascot?.mp4Url,webmUrl:e.ui?.mascot?.webmUrl},onOpen:()=>{Jn=!0,wo(),h&&(h.uiOpen=!0,h.uiHidden=!1,Ne()),Be("open")},onClose:()=>{h&&(h.uiOpen=!1,Ne()),Be("close")}}),Un(),h?.uiMessages?.length&&na(h.uiMessages),h?.timeline?.length&&ra(h.timeline),h?.uiStatus&&te.setStatus(h.uiStatus),Vi(),h?.executionMode&&te.setExecutionMode(h.executionMode,{localLogicalTabId:H?.getLocalLogicalTabId(),activeLogicalTabId:H?.getActiveLogicalTabId(),controllerRuntimeId:H?.getCurrentHolderRuntimeId(),canTakeControl:!0,canComposeInObserver:eu(),note:tu(h.executionMode)}),Pe.onmessage=s=>{bh(s.data||{})},H){let s=()=>{H?.registerCurrentTab(window.location.href,document.title),H?.broadcastNavigation(window.location.href,document.title)},a=history.pushState.bind(history),u=history.replaceState.bind(history);history.pushState=function(...m){let p=a(...m);return setTimeout(s,0),p},history.replaceState=function(...m){let p=u(...m);return setTimeout(s,0),p},window.addEventListener("popstate",s)}h?.uiHidden?te.hide():(te.show(),h?.uiOpen??!!e.openOnInit?te.open():te.close()),h&&(h.uiHidden=!!h.uiHidden,h.uiOpen=!!h.uiOpen,Ne()),H&&(oa(H.getState(),"remote"),ho(H.getRole(),{localLogicalTabId:H.getLocalLogicalTabId(),activeLogicalTabId:H.getActiveLogicalTabId(),holderRuntimeId:H.getCurrentHolderRuntimeId()})),go()}function bo(e){if(Kn)return Bi(e),Kn;br=Al(),Oe=Hp(e.siteId),kt=Xl(e),_n=e.visitor||Bp(e.siteId),Jn=!1,gr=!1,wo(),Er=null,Fr=$p(e.siteId);let t=th(Fr),n=t?null:Nl(e.siteId);n&&Ll(e.siteId);let r=e.sessionId?.trim(),o=!r&&!t?.sessionId&&!n?.sessionId&&e.sessionScope!=="tab"&&kt?qp(e.siteId,kt):void 0,i=r||t?.sessionId||n?.sessionId||o||crypto.randomUUID(),s=t;if(!t&&n){let a=Ws(n.sessionId,Oe);n.pendingRun&&(a.pendingRun=Bn({...n.pendingRun,autoResume:!0,resumeRequired:!0,resumeReason:"cross_host_navigation"})),n.activeTask&&(a.activeTask={...Fn("cross_domain_resume"),taskId:n.activeTask.taskId,status:n.activeTask.status}),a.taskEpoch=n.taskEpoch||1,a.uiOpen=!0,s=a}h=po(s,i,Oe),r&&h.sessionId!==r&&(h=Ws(r,Oe)),Z={...e,visitorId:kt||e.visitorId,sessionId:r||h.sessionId,taskRouting:{mode:e.taskRouting?.mode||"act",actHeuristicThreshold:e.taskRouting?.actHeuristicThreshold,plannerOnActError:e.taskRouting?.plannerOnActError},navigation:{crossHostPolicy:js(e.navigation?.crossHostPolicy)},task:{autoResumePolicy:Ks(e.task?.autoResumePolicy)},taskContext:{...e.taskContext}},h.sessionId=Z.sessionId,h.runtimeId=Oe,h.executionMode=h.executionMode||"controller",h.timeline=fo(h.timeline),h.uiMessages=uo(h.uiMessages),h.activeTask=yo(h.activeTask,Fn("boot")),h.taskEpoch=Math.max(1,Number(h.taskEpoch)||1),lt=h.executionMode,_n&&jl(e.siteId,_n),Ne();try{sessionStorage.setItem(`rover:tab-alive:${e.siteId}`,"1")}catch{}if(tr=!1,Hn=!1,xh(Z),Fr&&fh(Fr),sh(),Kn={boot:bo,init:ca,update:Bi,shutdown:la,open:vo,close:zi,show:ua,hide:da,send:fa,newTask:$r,endTask:Yi,getState:pa,registerTool:ha,identify:aa,on:zl},Si.length){for(let a of Si)Kl(a);Si.length=0}return Kn}function ca(e){return bo(e)}function Bi(e){if(!Kn||!Pe||!Z)return;Z={...Z,...e,taskRouting:{...Z.taskRouting,...e.taskRouting},navigation:{...Z.navigation,...e.navigation,crossHostPolicy:js(e.navigation?.crossHostPolicy??Z.navigation?.crossHostPolicy)},task:{...Z.task,...e.task,autoResumePolicy:Ks(e.task?.autoResumePolicy??Z.task?.autoResumePolicy)},taskContext:{...Z.taskContext,...e.taskContext},ui:{...Z.ui,...e.ui,agent:{...Z.ui?.agent,...e.ui?.agent},panel:{...Z.ui?.panel,...e.ui?.panel}},tools:{...Z.tools,...e.tools,client:e.tools?.client??Z.tools?.client,web:{...Z.tools?.web,...e.tools?.web}}},kt=Xl(Z),kt&&(Z.visitorId=kt),e.sessionId&&h?(h.sessionId=e.sessionId,Ne(),Fi(Z)):(e.sessionScope||e.tabPolicy)&&Fi(Z),su(Z),Zs(Z);let t=e.apiBase!==void 0||e.apiKey!==void 0||e.authToken!==void 0||e.siteId!==void 0||e.siteKeyId!==void 0||e.ui?.shortcuts!==void 0||e.ui?.greeting!==void 0;if($e){typeof e.allowActions=="boolean"&&$e.setAllowActions(e.allowActions&<==="controller");let n=lt==="controller"&&(Z?.allowActions??!0),r=lt==="observer"?"observer":"controller";$e?.setActionGateContext?.({mode:r,controllerRuntimeId:H?.getCurrentHolderRuntimeId(),activeLogicalTabId:H?.getActiveLogicalTabId(),localLogicalTabId:H?.getLocalLogicalTabId(),reason:Xs(r,n)}),(e.allowedDomains||e.domainScopeMode||e.externalNavigationPolicy||e.navigation?.crossHostPolicy)&&$e.setNavigationPolicy({allowedDomains:e.allowedDomains,domainScopeMode:e.domainScopeMode,externalNavigationPolicy:e.externalNavigationPolicy,crossHostPolicy:e.navigation?.crossHostPolicy})}Pe.postMessage({type:"update_config",config:e}),zs(Z),t?cu(Z):go(),e.visitor&&aa(e.visitor),typeof e.openOnInit=="boolean"&&(e.openOnInit?vo():zi())}function la(){Un(),Ne(),$i(!0),Js(),Mt?.markDirty(),Mt?.syncNow(),Mt?.stop(),Mt=null,H?.stop(),H=null,Pe?.terminate(),Pe=null,te?.destroy(),te=null,$e=null,Z=null,tr=!1,Hn=!1,Oe="",kt=void 0,_n=void 0,Jn=!1,gr=!1,wo(),Er=null,Di=!1,ki=!1,Br=!1,Lt=[],Vl=0,lt="controller",qr=null,br=null,Kn=null}function vo(){Jn=!0,wo(),te?.show(),te?.open(),h&&(h.uiHidden=!1,h.uiOpen=!0,Ne())}function zi(){te?.close(),h&&(h.uiOpen=!1,Ne())}function ua(){te?.show(),h&&(h.uiHidden=!1,Ne())}function da(){te?.hide(),h&&(h.uiHidden=!0,h.uiOpen=!1,Ne())}function fa(e){e?.trim()&&ao(e)}function $r(e){if(!h)return;let t=e?.reason||"manual_new_task",n=e?.clearUi!==!1,r=Math.max(1,Number(h.taskEpoch)||1)+1,o=Fn(t);h.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id)),ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Hn=!1,h.taskEpoch=r,h.activeTask=o,wt(void 0),h.workerState=void 0,n&&(h.uiMessages=[],h.timeline=[],h.uiStatus=void 0,ou()),H?.startNewTask({taskId:o.taskId,startedAt:o.startedAt,boundaryReason:t,status:"running",lastUserAt:void 0,lastAssistantAt:void 0}),H?.setActiveRun(void 0),H?.setWorkerContext(void 0),Rt("New task started."),Ne(),Pe?.postMessage({type:"start_new_task",taskId:o.taskId}),Be("task_started",{taskId:o.taskId,reason:t,taskEpoch:r})}function Yi(e){if(!h)return;let t=e?.reason||"manual_end_task",n=Wi("manual_end_task");n&&(n.status="ended",n.endedAt=Date.now(),n.boundaryReason=t,h.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id)),wt(void 0),h.workerState=void 0,ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Un(),Rt("Task ended. Start a new task to continue."),H?.endTask(t),H?.setActiveRun(void 0),H?.setWorkerContext(void 0),Ne(),at({kind:"info",title:"Task ended",detail:"Start a new task when you are ready.",status:"info"}),Be("task_ended",{taskId:n.taskId,reason:t,endedAt:n.endedAt}))}function pa(){return{mode:lt,runtimeId:Oe,runtimeState:h?iu(h):null,sharedState:H?.getState()||null,pendingTaskSuggestion:qr}}function ha(e,t){let n=Pp(e);if(!Kn||!$e||!Pe){Si.push({def:n,handler:t});return}Kl({def:n,handler:t})}function Rh(e){if(!e)return;let t=String(e);if(t==="init")return"init";if(t==="boot")return"boot";if(t==="update")return"update";if(t==="shutdown")return"shutdown";if(t==="open")return"open";if(t==="close")return"close";if(t==="show")return"show";if(t==="hide")return"hide";if(t==="send")return"send";if(t==="newTask")return"newTask";if(t==="endTask")return"endTask";if(t==="getState")return"getState";if(t==="registerTool")return"registerTool";if(t==="on")return"on"}function lu(){let e=window,t=e.rover,n=((r,...o)=>{let i=Rh(r),s=i?n[i]:void 0;if(typeof s=="function")return s(...o)});if(n.boot=bo,n.init=ca,n.update=Bi,n.shutdown=la,n.open=vo,n.close=zi,n.show=ua,n.hide=da,n.send=fa,n.newTask=$r,n.endTask=Yi,n.getState=pa,n.registerTool=ha,n.on=zl,e.rover=n,typeof t=="function"&&Array.isArray(t.q))for(let r of t.q){let[o,...i]=Array.isArray(r)?r:Array.from(r);typeof o=="string"&&n(o,...i)}if(!Kn){let r=typeof globalThis.__ROVER_SCRIPT_EL__<"u"?globalThis.__ROVER_SCRIPT_EL__:null;if(r){let o=r.getAttribute("data-site-id"),i=r.getAttribute("data-api-key");if(o&&i){let s={siteId:o,apiKey:i},a=r.getAttribute("data-allowed-domains");a&&(s.allowedDomains=a.split(",").map(p=>p.trim()).filter(Boolean));let u=r.getAttribute("data-site-key-id");u&&(s.siteKeyId=u);let m=r.getAttribute("data-worker-url");m&&(s.workerUrl=m),bo(s)}}}}lu();return gu(kh);})();
|
|
1636
|
+
`);let n=e.find(r=>r.type==="tool_output"||r.type==="json");if(n)return Array.isArray(n.data)?`Received ${n.data.length} item(s).`:n.data&&typeof n.data=="object"?`Received ${Object.keys(n.data).length} field(s).`:typeof n.data=="string"?n.data:String(n.data??"Done.")}function rh(e){if(e==null)return;let t=e?.output??e?.generatedContentRef??e?.schemaHeaderSheetInfo??e,n=ta(er([{type:"tool_output",data:t}]));if(nh(t,n))return er([{type:"tool_output",label:typeof e?.name=="string"?`${e.name} output`:"Tool output",data:t}])}function nu(e){if(!e||typeof e!="object")return null;let t=e.role,n=e.content;return typeof t!="string"||typeof n!="string"||!n?null:{role:t,content:n}}function Pi(e,t){if(!Array.isArray(e))return[];let n=[];for(let r of e.slice(-t)){let o=ea(r);o!==void 0&&n.push(o)}return n}async function oh(e){if(!br)return null;try{return await br.readAsync(e)}catch{return null}}function uo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-qs)){let r=n?.role;r!=="user"&&r!=="assistant"&&r!=="system"||t.push({id:typeof n?.id=="string"&&n.id?n.id:Zn("msg"),role:r,text:String(n?.text||""),blocks:er(n?.blocks),ts:Number(n?.ts)||Date.now(),sourceRuntimeId:typeof n?.sourceRuntimeId=="string"?n.sourceRuntimeId:void 0})}return t.filter(n=>!!n.text||!!n.blocks?.length)}function fo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e.slice(-$s)){let r=At(String(n?.title||""),400);if(!r)continue;let o=String(n?.kind||"status"),i=n?.status;t.push({id:typeof n?.id=="string"&&n.id?n.id:Zn("timeline"),kind:o,title:r,detail:n?.detail?String(n.detail):void 0,detailBlocks:er(n?.detailBlocks),status:i==="pending"||i==="success"||i==="error"||i==="info"?i:void 0,ts:Number(n?.ts)||Date.now(),sourceRuntimeId:typeof n?.sourceRuntimeId=="string"?n.sourceRuntimeId:void 0})}return t}function yr(e){if(!e||typeof e!="object")return;let t=Array.isArray(e.history)?e.history:[],n=Array.isArray(e.plannerHistory)?e.plannerHistory:[],r=Array.isArray(e.agentPrevSteps)?e.agentPrevSteps:Array.isArray(e.lastToolPreviousSteps)?e.lastToolPreviousSteps:[],o=t.slice(-Wl).map(m=>nu(m)).filter(m=>!!m),i=Pi(n,Ci),s=Pi(r,Ci*2),a=Eo(e?.pendingAskUser?.questions),u=a.length?{questions:a,source:e?.pendingAskUser?.source==="planner"?"planner":"act",askedAt:Number(e?.pendingAskUser?.askedAt)||Date.now()}:void 0;return{trajectoryId:typeof e.trajectoryId=="string"?e.trajectoryId:void 0,history:o,plannerHistory:i,agentPrevSteps:s,lastToolPreviousSteps:s,pendingAskUser:u,updatedAt:Number(e.updatedAt)||Date.now()}}function po(e,t,n){if(!e||typeof e!="object")return Ws(t,n);let r=Fn(),o=yo(e.activeTask,r),i=Bn(e.pendingRun),s=o.status==="running"?i:void 0;return{version:Ys,sessionId:typeof e.sessionId=="string"&&e.sessionId?e.sessionId:t,runtimeId:typeof e.runtimeId=="string"&&e.runtimeId?e.runtimeId:n,uiOpen:!!e.uiOpen,uiHidden:!!e.uiHidden,uiStatus:typeof e.uiStatus=="string"?At(e.uiStatus,300):void 0,uiMessages:uo(e.uiMessages),timeline:fo(e.timeline),executionMode:e.executionMode==="observer"||e.executionMode==="controller"?e.executionMode:"controller",workerState:yr(e.workerState),pendingRun:s,taskEpoch:Math.max(1,Number(e.taskEpoch)||1),activeTask:o,lastRoutingDecision:e.lastRoutingDecision&&(e.lastRoutingDecision.mode==="act"||e.lastRoutingDecision.mode==="planner")?{mode:e.lastRoutingDecision.mode,score:Number(e.lastRoutingDecision.score)||void 0,reason:typeof e.lastRoutingDecision.reason=="string"?At(e.lastRoutingDecision.reason,200):void 0,ts:Number(e.lastRoutingDecision.ts)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function yo(e,t){if(!e||typeof e!="object")return t;let n=typeof e.taskId=="string"&&e.taskId.trim()?e.taskId.trim():t.taskId,r=e.status==="ended"||e.status==="completed"||e.status==="running"?e.status:"running";return{taskId:n,status:r,startedAt:Number(e.startedAt)||t.startedAt,lastUserAt:Number(e.lastUserAt)||void 0,lastAssistantAt:Number(e.lastAssistantAt)||void 0,boundaryReason:typeof e.boundaryReason=="string"?At(e.boundaryReason,120):t.boundaryReason,endedAt:Number(e.endedAt)||void 0}}function ih(e,t){return yo(e,t)}function ru(e){if(!e)return;let t=Eo(e.pendingAskUser?.questions);return{trajectoryId:e.trajectoryId,history:Array.isArray(e.history)?e.history.slice(-Wl).map(n=>nu(n)).filter(n=>!!n):[],plannerHistory:Pi(e.plannerHistory,Ci),agentPrevSteps:Pi(e.agentPrevSteps,Ci*2),pendingAskUser:t.length?{questions:t,source:e.pendingAskUser?.source==="planner"?"planner":"act",askedAt:Number(e.pendingAskUser?.askedAt)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function Bn(e){if(!e||typeof e!="object")return;let t=typeof e.id=="string"&&e.id.trim()?e.id.trim():void 0,n=typeof e.text=="string"?e.text.trim():"";if(!(!t||!n))return{id:t,text:n,startedAt:Number(e.startedAt)||Date.now(),attempts:Math.max(0,Number(e.attempts)||0),autoResume:e.autoResume!==!1,resumeRequired:e.resumeRequired===!0,resumeReason:e.resumeReason==="cross_host_navigation"||e.resumeReason==="agent_navigation"||e.resumeReason==="handoff"||e.resumeReason==="page_reload"?e.resumeReason:void 0}}function Ne(){if(!(!h||!Fr))try{h.updatedAt=Date.now(),br?.write(Fr,h),Di||Mt?.markDirty()}catch{}}function sh(){if(Ul)return;Ul=!0;let e=()=>{if(h?.pendingRun?.autoResume){let n=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:h.pendingRun.resumeReason||"page_reload"});h.pendingRun=n,n&&H?.clearActiveRunRuntimeId(n.id)}H?.broadcastClosing(),h?.pendingRun&&H?.releaseWorkflowLock(h.pendingRun.id),Ne(),h?.pendingRun&&Z?.siteId&&Fs(Z.siteId,{sessionId:h.sessionId,pendingRun:{id:h.pendingRun.id,text:h.pendingRun.text,startedAt:h.pendingRun.startedAt,attempts:h.pendingRun.attempts},activeTask:h.activeTask?{taskId:h.activeTask.taskId,status:h.activeTask.status}:void 0,taskEpoch:h.taskEpoch,timestamp:Date.now()}),$i(!0),Js(),Mt?.markDirty(),Mt?.syncNow(),Mt?.stop(),H?.stop()};window.addEventListener("pagehide",e,{capture:!0});let t=n=>{n.persisted&&(H&&(H.reloadFromStorage(),H.registerCurrentTab(window.location.href,document.title||void 0),H.claimLease(!1)),Hn=!1,Z&&Zs(Z))};window.addEventListener("pageshow",t)}function Wi(e="implicit"){if(h)return h.activeTask||(h.activeTask=Fn(e),h.taskEpoch=Math.max(1,Number(h.taskEpoch)||1)),h.activeTask}function ah(e,t=Date.now()){if(!h||e==="system")return;let n=Wi("implicit");n&&n.status==="running"&&(e==="user"&&(n.lastUserAt=t),e==="assistant"&&(n.lastAssistantAt=t))}function Vs(e="worker_task_active",t=Date.now()){if(!h)return;let n=Wi(e);n&&(n.status="running",n.endedAt=void 0,n.boundaryReason=e,!n.lastUserAt&&!n.lastAssistantAt&&(n.lastAssistantAt=t),H?.syncTask({...n},h.taskEpoch),Ne())}function ch(e="worker_task_complete",t=Date.now()){if(!h)return;let n=Wi(e);n&&(n.status="completed",n.endedAt=t,n.boundaryReason=e,H?.syncTask({...n},h.taskEpoch),Ne())}function Un(){qr=null,te?.setTaskSuggestion({visible:!1})}function lh(e){qr={kind:"resume_run",runId:e.id,text:e.text,createdAt:Date.now()},te?.setTaskSuggestion({visible:!0,text:"Previous task was interrupted by navigation. Resume it?",primaryLabel:"Resume",secondaryLabel:"Start fresh"}),Rt("Task paused after navigation. Resume to continue.")}function ou(){te?.clearMessages(),te?.clearTimeline(),te?.setQuestionPrompt(void 0),Un()}function Vi(){let e=Eo(h?.workerState?.pendingAskUser?.questions);if(!e.length){te?.setQuestionPrompt(void 0);return}te?.setQuestionPrompt({questions:e})}function uh(){let e=h?.pendingRun;if(!e)return!1;if(!H)return!0;let t=H?.getState()?.activeRun;if(t?.runId&&t.runId===e.id||t?.runtimeId&&t.runtimeId!==Oe)return!0;let n=Date.now()-Number(e.startedAt||0);return n>=0&&n<=kp}function dh(){if(!h?.pendingRun||uh()||!H)return;let e=h.pendingRun,t=Date.now()-Number(e.startedAt||0);!Number.isFinite(t)||t<Sp||(tn(e.id),wt(void 0),H?.clearActiveRunRuntimeId(e.id),H?.releaseWorkflowLock(e.id),H?.setActiveRun(void 0))}function hn(e,t,n=!0,r){let o=String(t||""),i=er(r?.blocks);if(!o&&(!i||i.length===0))return;let s={id:r?.id||Zn("msg"),role:e,text:o,blocks:i,ts:r?.ts||Date.now(),sourceRuntimeId:r?.sourceRuntimeId};return te?.addMessage(s.role,s.text,{blocks:s.blocks}),h&&n&&(h.uiMessages.push(s),h.uiMessages.length>qs&&(h.uiMessages=h.uiMessages.slice(-qs)),ah(s.role,s.ts),Ne()),H&&r?.publishShared!==!1&&(H.appendMessage({id:s.id,role:s.role,text:s.text,blocks:s.blocks,ts:s.ts}),H.markTaskActivity(s.role,s.ts)),s}function na(e){for(let t of e)hn(t.role,t.text,!1,{id:t.id,ts:t.ts,sourceRuntimeId:t.sourceRuntimeId,publishShared:!1,blocks:t.blocks})}function at(e,t=!0){let n={id:e.id||Zn("timeline"),kind:e.kind,title:At(e.title,400),detail:e.detail?String(e.detail):void 0,detailBlocks:er(e.detailBlocks),status:e.status,ts:e.ts||Date.now(),sourceRuntimeId:e.sourceRuntimeId};return te?.addTimelineEvent(n),h&&t&&(h.timeline.push(n),h.timeline.length>$s&&(h.timeline=h.timeline.slice(-$s)),Ne()),H&&e.publishShared!==!1&&H.appendTimeline({id:n.id,kind:n.kind,title:n.title,detail:n.detail,detailBlocks:n.detailBlocks,status:n.status,ts:n.ts}),n}function ra(e){te?.clearTimeline();for(let t of e)at({id:t.id,kind:t.kind,title:t.title,detail:t.detail,detailBlocks:t.detailBlocks,status:t.status,ts:t.ts,sourceRuntimeId:t.sourceRuntimeId,publishShared:!1},!1)}function Rt(e,t){te?.setStatus(e),h&&(h.uiStatus=At(e,300),Ne()),H&&t?.publishShared!==!1&&H.setStatus(e)}function ho(e,t){lt=e,h&&(h.executionMode=e,Ne()),te?.setExecutionMode(e,{controllerRuntimeId:t?.holderRuntimeId??H?.getCurrentHolderRuntimeId(),localLogicalTabId:t?.localLogicalTabId??H?.getLocalLogicalTabId(),activeLogicalTabId:t?.activeLogicalTabId??H?.getActiveLogicalTabId(),canTakeControl:!0,canComposeInObserver:eu(),note:tu(e)}),Be("mode_change",{mode:e,...t})}function wt(e){h&&(h.pendingRun=e,Ne())}function Hi(e,t){let n=String(e||"").trim();if(!n||!Pe)return;if(lt==="observer"&&!(H?.requestControl()??!1)){hn("system","Unable to take control right now because another tab is still running Rover actions.",!0),at({kind:"info",title:"Observer mode",detail:"Action execution is currently owned by another tab runtime.",status:"info"});return}let r=t?.runId||crypto.randomUUID(),o=!!t?.resume,i=t?.appendUserMessage!==!1;Jl(r),i&&hn("user",n,!0);let s=h?.pendingRun?.id===r?h.pendingRun.attempts:0;wt({id:r,text:n,startedAt:Date.now(),attempts:o?s+1:0,autoResume:t?.autoResume!==!1,resumeRequired:!1,resumeReason:void 0}),Vs(o?"worker_task_resumed":"worker_task_active"),Gl=n,H?.acquireWorkflowLock(r),H?.setActiveRun({runId:r,text:n}),Pe.postMessage({type:"run",text:n,runId:r,resume:o,routing:t?.routing,askUserAnswers:t?.askUserAnswers}),ct&&clearTimeout(ct);let a=r;ct=setTimeout(()=>{h?.pendingRun?.id===a&&(tn(a),wt(void 0),H?.releaseWorkflowLock(a),H?.setActiveRun(void 0),Rt("Task timed out."),hn("system","Task timed out after 5 minutes with no response.",!0),Be("error",{message:"Run safety timeout"})),ct=null},5*6e4)}function ao(e,t){let n=String(e||"").trim();if(!n)return;dh();let r=h?.activeTask?.status,o=!!t?.startNewTask||Ml(r);if(H?.pruneTabs({dropRuntimeDetached:!0,dropAllDetachedExternal:o}),o){let i=t?.reason||(r==="completed"?"auto_after_task_complete":"auto_after_task_end");$r({reason:i,clearUi:!0})}Un(),Hi(n,{appendUserMessage:!0,resume:!1,autoResume:!0,routing:t?.routing,askUserAnswers:t?.askUserAnswers})}function Ui(){if(lt==="observer")return;let e=H?.getState()?.activeRun;if(e?.runtimeId&&e.runtimeId!==Oe&&!(h?.pendingRun?.id===e.runId)||!tr||!Pe||Hn||!h?.pendingRun||!Dl(h.activeTask?.status))return;let t=h.pendingRun;if(!t.autoResume)return;let n=Ks(Z?.task?.autoResumePolicy);if(n==="never"){tn(t.id),wt(void 0),H?.setActiveRun(void 0),Rt("Previous task dismissed after navigation.");return}let r=t.resumeReason==="cross_host_navigation"||t.resumeReason==="agent_navigation",o=Z?.siteId||"";if(!!!sessionStorage.getItem(`rover:tab-alive:${o}`)&&!r&&!(H?.listTabs()||[]).some(m=>m.runtimeId!==Oe&&m.updatedAt>Date.now()-2*2e3)&&h?.pendingRun){tn(h.pendingRun.id),wt(void 0),Rt("Previous task expired.");return}if(Date.now()-t.startedAt>Tp){tn(t.id),wt(void 0),Rt("Previous task expired after navigation.");return}if(t.attempts>=_p){tn(t.id),wt(void 0),hn("system","Auto-resume stopped after too many navigation attempts.",!0);return}if(r){Hn=!0,Rt("Resuming task after navigation..."),Hi(t.text,{runId:t.id,resume:!0,appendUserMessage:!1,autoResume:!0});return}if(n==="confirm"){Hn=!0,lh(t);return}Hn=!0,Rt("Resuming previous task after navigation..."),Hi(t.text,{runId:t.id,resume:!0,appendUserMessage:!1,autoResume:!0})}async function fh(e){if(!h)return;let t=await oh(e);if(!t||!h)return;let n=Number(h.updatedAt)||0,r=po({...t,sessionId:h.sessionId,runtimeId:Oe},h.sessionId,Oe);(Number(r.updatedAt)||0)<=n+200||(h=po({...h,...r,sessionId:h.sessionId,runtimeId:Oe},h.sessionId,Oe),Ne(),te&&(te.clearMessages(),na(h.uiMessages),ra(h.timeline),h.uiStatus&&te.setStatus(h.uiStatus),Vi(),h.uiHidden?te.hide():(te.show(),h.uiOpen?te.open():te.close())),tr&&Pe&&h.workerState&<==="controller"&&(Pe.postMessage({type:"hydrate_state",state:h.workerState}),Be("context_restored",{source:"indexeddb_checkpoint",ts:Date.now()})))}function oa(e,t){if(h){if(t==="remote"){let n=Math.max(1,Number(h.taskEpoch)||1),r=Math.max(1,Number(e.taskEpoch)||1),o=r>n;h.taskEpoch=Math.max(n,r);let i=h.activeTask||Fn("shared_sync");h.activeTask=ih(e.task,i),o&&(h.uiMessages=[],h.timeline=[],ou(),wt(void 0),Un());let s=uo(e.uiMessages),a=new Set(s.map(x=>x.id));if(s.length<h.uiMessages.length||h.uiMessages.some(x=>!a.has(x.id)))h.uiMessages=s,te?.clearMessages(),na(h.uiMessages);else{let x=new Set(h.uiMessages.map(S=>S.id));for(let S of s)x.has(S.id)||(hn(S.role,S.text,!0,{id:S.id,ts:S.ts,sourceRuntimeId:S.sourceRuntimeId,publishShared:!1,blocks:S.blocks}),x.add(S.id))}let m=fo(e.timeline),p=new Set(m.map(x=>x.id));if(m.length<h.timeline.length||h.timeline.some(x=>!p.has(x.id)))h.timeline=m,ra(h.timeline);else{let x=new Set(h.timeline.map(S=>S.id));for(let S of m)x.has(S.id)||(at({id:S.id,kind:S.kind,title:S.title,detail:S.detail,detailBlocks:S.detailBlocks,status:S.status,ts:S.ts,sourceRuntimeId:S.sourceRuntimeId,publishShared:!1},!0),x.add(S.id))}typeof e.uiStatus=="string"&&Rt(e.uiStatus,{publishShared:!1});let I=h.activeTask?.status,A=e.task?.status;if(e.activeRun&&e.activeRun.runtimeId!==Oe&&!Bs({localTaskStatus:I,remoteTaskStatus:A,mode:lt,hasRemoteActiveRun:!0})?wt(Bn({id:e.activeRun.runId,text:e.activeRun.text,startedAt:e.activeRun.startedAt,attempts:h.pendingRun?.attempts||0,autoResume:!0})):Bs({localTaskStatus:I,remoteTaskStatus:A,mode:lt,hasRemoteActiveRun:!!e.activeRun})&&(h.pendingRun?.id&&tn(h.pendingRun.id),wt(void 0)),lt==="observer"&&ho("observer",{localLogicalTabId:H?.getLocalLogicalTabId(),activeLogicalTabId:H?.getActiveLogicalTabId(),holderRuntimeId:H?.getCurrentHolderRuntimeId()}),e.workerContext){let x=yr(e.workerContext),S=Number(h.workerState?.updatedAt)||0,B=Number(x?.updatedAt)||0;x&&B>S+100&&(h.workerState=x,tr&&Pe&<==="controller"&&(Pe.postMessage({type:"hydrate_state",state:x}),Be("context_restored",{source:"shared_session",ts:Date.now()})))}}h.uiMessages=uo(h.uiMessages),h.timeline=fo(h.timeline),h.workerState=yr(h.workerState),Vi(),h.activeTask=yo(h.activeTask,Fn("implicit")),Ne()}}function iu(e){let t=Fn("checkpoint_clone");return{version:Ys,sessionId:e.sessionId,runtimeId:e.runtimeId,uiOpen:!!e.uiOpen,uiHidden:!!e.uiHidden,uiStatus:typeof e.uiStatus=="string"?At(e.uiStatus,300):void 0,uiMessages:uo(e.uiMessages),timeline:fo(e.timeline),executionMode:e.executionMode==="observer"||e.executionMode==="controller"?e.executionMode:"controller",workerState:yr(e.workerState),pendingRun:Bn(e.pendingRun),taskEpoch:Math.max(1,Number(e.taskEpoch)||1),activeTask:yo(e.activeTask,t),lastRoutingDecision:e.lastRoutingDecision&&(e.lastRoutingDecision.mode==="act"||e.lastRoutingDecision.mode==="planner")?{mode:e.lastRoutingDecision.mode,score:Number(e.lastRoutingDecision.score)||void 0,reason:e.lastRoutingDecision.reason,ts:Number(e.lastRoutingDecision.ts)||Date.now()}:void 0,updatedAt:Number(e.updatedAt)||Date.now()}}function ph(e){return!(e.sessionScope==="tab"||e.checkpointing?.enabled!==!0||!(e.apiKey||e.authToken)||!kt)}function hh(){if(!h||!Z||!kt)return null;let e=H?.getState(),t=iu(h),n=Math.max(Number(e?.updatedAt||0),Number(t.updatedAt||0),Date.now());return{version:Rp,siteId:Z.siteId,visitorId:kt,sessionId:h.sessionId,updatedAt:n,sharedState:e,runtimeState:t}}function mh(e){if(!e||typeof e!="object"||!h||!Z||e.siteId&&e.siteId!==Z.siteId||kt&&e.visitorId&&e.visitorId!==kt)return;let t=typeof e.sessionId=="string"&&e.sessionId.trim()?e.sessionId.trim():h.sessionId;Di=!0;try{if(t&&h.sessionId!==t&&(h.sessionId=t,Z={...Z,sessionId:t},Fi(Z),Pe?.postMessage({type:"update_config",config:{sessionId:t}})),e.sharedState&&H&&H.hydrateExternalState(e.sharedState)&&(oa(H.getState(),"remote"),ho(H.getRole(),{localLogicalTabId:H.getLocalLogicalTabId(),activeLogicalTabId:H.getActiveLogicalTabId(),holderRuntimeId:H.getCurrentHolderRuntimeId()})),e.runtimeState&&typeof e.runtimeState=="object"){let n=po({...e.runtimeState,sessionId:t,runtimeId:Oe},t,Oe),r=Number(h.updatedAt)||0;(Number(n.updatedAt)||0)>r+200&&(h=po({...h,...n,sessionId:t,runtimeId:Oe},t,Oe),Ne(),h.uiStatus&&te?.setStatus(h.uiStatus),h.uiHidden?te?.hide():(te?.show(),h.uiOpen?te?.open():te?.close()),tr&&h.workerState&&(Pe?.postMessage({type:"hydrate_state",state:h.workerState}),Be("context_restored",{source:"cloud_checkpoint",ts:Date.now()})),lt==="controller"&&Ui())}}finally{Di=!1}}function su(e){if(Mt?.stop(),Mt=null,!!ph(e)&&kt)try{let t=n=>{Be("checkpoint_state",n),e.checkpointing?.onStateChange?.(n)};Mt=new Ei({apiBase:e.apiBase,apiKey:e.apiKey,authToken:e.authToken,siteId:e.siteId,visitorId:kt,ttlHours:e.checkpointing?.ttlHours??1,flushIntervalMs:e.checkpointing?.flushIntervalMs,pullIntervalMs:e.checkpointing?.pullIntervalMs,minFlushIntervalMs:e.checkpointing?.minFlushIntervalMs,shouldWrite:()=>lt==="controller",buildCheckpoint:()=>hh(),onCheckpoint:n=>{mh(n)},onStateChange:(n,r)=>{t({state:n,reason:r.reason,action:r.action,code:r.code,message:r.message}),n==="paused_auth"&&Be("checkpoint_error",{action:r.action,code:r.code||"INVALID_API_KEY",message:r.message||"Checkpoint sync paused due to auth failure.",disabled:!0,reason:r.reason||"auth_failed"})},onError:(n,r)=>{e.checkpointing?.onError?.(r),r.paused||Be("checkpoint_error",{action:r.action,code:r.code,message:r.message,status:r.status,disabled:!1,reason:"transient_failure"})}}),Mt.start(),Mt.markDirty()}catch{Mt=null}}function Fi(e){if(h){if(H?.stop(),H=null,e.sessionScope==="tab"){ho("controller");return}H=new gi({siteId:e.siteId,sessionId:h.sessionId,runtimeId:Oe,leaseMs:e.tabPolicy?.actionLeaseMs,onRoleChange:(t,n)=>{ho(t,n);let r=t==="controller"&&(Z?.allowActions??!0);if($e?.setAllowActions(r),$e?.setActionGateContext?.({mode:t,controllerRuntimeId:n?.holderRuntimeId??H?.getCurrentHolderRuntimeId(),activeLogicalTabId:n?.activeLogicalTabId??H?.getActiveLogicalTabId(),localLogicalTabId:n?.localLogicalTabId??H?.getLocalLogicalTabId(),reason:Xs(t,r)}),t==="controller"){let o=H?.getWorkerContext();if(o){let i=yr(o),s=Number(h?.workerState?.updatedAt)||0,a=Number(i?.updatedAt)||0;i&&a>s+100&&(h&&(h.workerState=i,Ne()),tr&&Pe&&(Pe.postMessage({type:"hydrate_state",state:i}),Be("context_restored",{source:"controller_handoff",ts:Date.now()})))}Ui()}},onStateChange:(t,n)=>{oa(t,n)},onSwitchRequested:t=>{t>0&&(vo(),at({kind:"status",title:`Switched to tab #${t}`,status:"info"}))}}),H.start(),H.setRpcRequestHandler(async t=>{if(!$e)throw new Error("Bridge not available");if(t.method==="getPageData")return $e.getPageData(t.params);if(t.method==="executeTool")return $e.executeTool(t.params.call,t.params.payload);throw new Error(`Unknown RPC method: ${t.method}`)}),h?.activeTask&&H.syncTask({...h.activeTask,taskId:h.activeTask.taskId},h.taskEpoch),h?.workerState&&H.setWorkerContext(ru(h.workerState))}}function gh(e){let t=At(eh(e)||"Done.",1200);te?.clearTimeline(),h&&(h.timeline=[]),H?.clearTimeline()}function bh(e){if(!(!e||typeof e!="object")&&!Jp(e)){if(e.type==="assistant"){let t=er(e.blocks),n=String(e.text||ta(t)||"");if(typeof e.runId=="string"&&e.runId&&(Pn.set(e.runId,n),Pn.size>80)){let r=Pn.keys().next().value;r&&Pn.delete(r)}hn("assistant",n,!0,{blocks:t}),at({kind:"tool_result",title:"Assistant update",detail:n,detailBlocks:t,status:"success"});return}if(e.type==="status"){let t=Yp(e.stage),n=e.message?String(e.message):void 0,r=e.compactThought?String(e.compactThought):void 0,o=Xp(n,t,r);if(n&&Rt(n),o&&o!==wi&&(wi=o,n)){let i=!!(e.thought||r),s=r||(e.thought?String(e.thought):"");if(i&&t!=="analyze"&&t!=="route"&&t!=="complete"&&!Kp(s,Gl))at({kind:"thought",title:s,detail:e.thought?String(e.thought):r,status:"pending"});else{let u=t?`${jp(t)}: ${n}`:n;at({kind:"status",title:u,detail:r||(e.thought?String(e.thought):void 0),status:t==="complete"?"success":"info"})}}Be("status",e);return}if(e.type==="tool_start"){at({kind:"tool_start",title:`Running ${e.call?.name||"tool"}`,detail:Ai(e.call?.args),status:"pending"}),Be("tool_start",e);return}if(e.type==="tool_result"){let t=er(e.detailBlocks)||rh(e.result);at({kind:"tool_result",title:`${e.call?.name||"tool"} completed`,detail:Ai(e.result),detailBlocks:t,status:e?.result?.success===!1?"error":"success"}),Be("tool_result",e);return}if(e.type==="auth_required"){Be("auth_required",e.error),e.error?.message&&(hn("system",`Auth required: ${e.error.message}`,!0),at({kind:"error",title:"Auth required",detail:String(e.error.message),status:"error"}));return}if(e.type==="navigation_guardrail"){Be("navigation_guardrail",e),at({kind:"status",title:"Navigation guardrail",detail:Ai(e),status:"info"});return}if(e.type==="error"){hn("system",`Error: ${e.message||"unknown"}`,!0),at({kind:"error",title:"Execution error",detail:String(e.message||"unknown"),status:"error"}),Be("error",e);return}if(e.type==="state_snapshot"){if(h){h.workerState=yr({...e.state||{},updatedAt:Date.now()});let t=typeof e?.activeRun?.runId=="string"&&e.activeRun.runId?e.activeRun.runId:void 0,n=typeof e?.activeRun?.text=="string"?e.activeRun.text:void 0,r=Ol({taskStatus:h.activeTask?.status,hasPendingRun:!!h.pendingRun,activeRunId:t,activeRunText:n,ignoredRunIds:Qn});r&&(h.pendingRun=Bn({id:t,text:n,startedAt:e.activeRun.startedAt,attempts:0,autoResume:!0})),t&&n&&r?H?.setActiveRun({runId:t,text:n}):t&&(!so()||Qn.has(t))&&H?.setActiveRun(void 0),!so()&&h.pendingRun&&wt(void 0),h.workerState&&H?.setWorkerContext(ru(h.workerState)),Vi(),Ne()}return}if(e.type==="task_started"){Be("task_started",{taskId:e.taskId,reason:"worker"});return}if(e.type==="run_started"){if(wi="",Un(),typeof e.runId=="string"&&e.runId&&Pn.delete(e.runId),!so()){H?.setActiveRun(void 0);return}let t=h?.pendingRun;typeof e.runId=="string"&&e.runId&&Jl(e.runId),wt(Bn({id:e.runId,text:e.text,startedAt:t?.startedAt||Date.now(),attempts:t?.attempts||0,autoResume:t?.autoResume!==!1})),H?.setActiveRun({runId:e.runId,text:String(e.text||"")}),te?.setRunning(!0),te?.setQuestionPrompt(void 0);let n=`run:${String(e.runId||"")}:start`;h?.timeline.some(r=>r.id===n)||at({id:n,kind:"plan",title:e.resume?"Run resumed":"Run started",detail:String(e.text||""),status:"pending"});return}if(e.type==="run_completed"){wi="",Hn=!1,te?.setRunning(!1),ct&&(clearTimeout(ct),ct=null),h?.pendingRun?.id===e.runId&&wt(void 0),typeof e.runId=="string"&&e.runId&&H?.releaseWorkflowLock(e.runId),h&&e?.route&&(e.route.mode==="act"||e.route.mode==="planner")&&(h.lastRoutingDecision={mode:e.route.mode,score:Number(e.route.score)||void 0,reason:typeof e.route.reason=="string"?At(e.route.reason,200):void 0,ts:Date.now()},Ne()),H?.setActiveRun(void 0);let t=typeof e.runId=="string"&&e.runId?e.runId:void 0;if(t&&tn(t),!e.ok&&e.error){if(t&&Pn.delete(t),!so())return;te?.setQuestionPrompt(void 0),Vs("worker_run_failed"),Rt(`Task failed: ${String(e.error)}`),t&&Pn.delete(t),at({kind:"error",title:"Run failed",detail:String(e.error),status:"error"})}else if(e.ok){if(!so())return;let n=Zp(e),r=n.taskComplete,o=n.needsUserInput,i=n.questions||Eo(e.questions);r?(te?.setQuestionPrompt(void 0),ch("worker_task_complete"),H?.pruneTabs({dropRuntimeDetached:!0,dropAllDetachedExternal:!0}),Rt("Task completed"),gh(typeof e.runId=="string"?e.runId:void 0)):(Vs(o?"worker_waiting_for_input":"worker_continuation"),o&&i.length>0?te?.setQuestionPrompt({questions:i}):te?.setQuestionPrompt(void 0),Rt(o?"Need more input to continue":"Execution finished. Continue when ready."),at({kind:"status",title:o?"Waiting for your input":"Continuation available",detail:o?i.length?`Please answer: ${i.map(s=>`${s.key} (${s.query})`).join("; ")}`:"Planner requested more information before marking the task complete.":"Task is still active and will continue with your next message.",status:"info"}))}return}if(e.type==="ready"){tr=!0,Rt("ready"),Be("ready"),Z&&cu(Z);let t=H?.getWorkerContext(),n=yr(t),r=Number(h?.workerState?.updatedAt)||0,o=Number(n?.updatedAt)||0,i=n&&o>r+100?n:h?.workerState;h&&i&&i!==h.workerState&&(h.workerState=i,Ne()),i?(Pe?.postMessage({type:"hydrate_state",state:i}),Be("context_restored",{source:"runtime_start",ts:Date.now()})):Ui();return}if(e.type==="hydrated"){Ui();return}e.type==="updated"&&Be("updated")}}function Gs(e,t){let n=Number(e);return Number.isFinite(n)?Math.max(t.min,Math.min(t.max,Math.floor(n))):t.fallback}function ia(e){if(!e||typeof e!="object")return;let t=Gs(e.shortcutMaxStored,{min:1,max:Li,fallback:Li}),n=Gs(e.shortcutMaxRendered,{min:1,max:Mi,fallback:Mi});return{shortcutMaxStored:t,shortcutMaxRendered:n}}function wo(){co&&(clearTimeout(co),co=null),lo&&(clearTimeout(lo),lo=null)}function Eh(e){try{let t=localStorage.getItem(`rover:site-config:${e}`);if(t){let n=JSON.parse(t);return!n||typeof n.ts!="number"||typeof n.data!="object"||!n.data||Date.now()-n.ts>Hl?null:{shortcuts:wr(n.data.shortcuts),greeting:mo(n.data.greeting),limits:ia(n.data.limits),version:typeof n.version=="string"?n.version:void 0}}}catch{}try{let t=localStorage.getItem(`rover:shortcuts:${e}`);if(!t)return null;let n=JSON.parse(t);return!n||typeof n.ts!="number"||!Array.isArray(n.data)||Date.now()-n.ts>Hl?null:{shortcuts:wr(n.data)}}catch{return null}}function yh(e,t){try{localStorage.setItem(`rover:site-config:${e}`,JSON.stringify({ts:Date.now(),version:t.version,data:{shortcuts:wr(t.shortcuts),greeting:mo(t.greeting),limits:ia(t.limits)}}))}catch{}}function mo(e){if(!e||typeof e!="object")return;let t={},n=String(e.text||"").trim();n&&(t.text=n.slice(0,Dp));let r=Number(e.delay);Number.isFinite(r)&&(t.delay=Math.max(0,Math.min(6e4,Math.floor(r))));let o=Number(e.duration);return Number.isFinite(o)&&(t.duration=Math.max(1200,Math.min(6e4,Math.floor(o)))),typeof e.disabled=="boolean"&&(t.disabled=e.disabled),Object.keys(t).length?t:void 0}function wh(e){if(!e||typeof e!="object")return null;let t=String(e.id||"").trim().slice(0,80),n=String(e.label||"").trim().slice(0,Cp),r=String(e.prompt||"").trim().slice(0,Lp);if(!t||!n||!r)return null;let o={id:t,label:n,prompt:r,enabled:e.enabled!==!1};e.description&&(o.description=String(e.description).trim().slice(0,Np)),e.icon&&(o.icon=String(e.icon).trim().slice(0,Mp)),(e.routing==="auto"||e.routing==="act"||e.routing==="planner")&&(o.routing=e.routing);let i=Number(e.order);return Number.isFinite(i)&&(o.order=Math.trunc(i)),o}function wr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(t.length>=Li)break;let o=wh(r);!o||n.has(o.id)||(n.add(o.id),t.push(o))}return t}function vh(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{let r=Number.isFinite(t.item.order),o=Number.isFinite(n.item.order);return r&&o?Number(t.item.order)-Number(n.item.order):r?-1:o?1:t.index-n.index}).map(t=>t.item)}function Th(e,t){let n=new Map;for(let r of t)n.set(r.id,r);for(let r of e){let o=n.get(r.id);n.set(r.id,o?{...o,...r}:r)}return vh(Array.from(n.values())).slice(0,Li)}function au(e){let t=Gs(Er?.limits?.shortcutMaxRendered,{min:1,max:Mi,fallback:Mi});return e.filter(n=>n.enabled!==!1).slice(0,t)}function Gi(e){if(!e)return;let t=mo(Er?.greeting),n=mo(e.ui?.greeting);if(!(!t&&!n))return{...t||{},...n||{}}}function sa(e){let t=_n?.name,n=e?.text;return n?n.replace(/\{name\}/g,t||"").trim()||(t?`Hey ${t}! Need any help?`:"Hey! Need any help?"):t?`Hey ${t}! Need any help?`:"Hey! Need any help?"}function go(){if(Jn||!te||!Z||h?.uiOpen)return;let e=Gi(Z);if(e?.disabled===!0)return;let t=`rover:greeting-shown:${Z.siteId}`;try{if(sessionStorage.getItem(t)){gr=!0;return}}catch{}if(gr)return;wo();let n=e?.delay??3e3,r=e?.duration??8e3,o=sa(e);co=setTimeout(()=>{if(co=null,!(Jn||h?.uiOpen)){te?.showGreeting(o),gr=!0;try{sessionStorage.setItem(t,"1")}catch{}lo=setTimeout(()=>{lo=null,te?.dismissGreeting()},r)}},n)}function zs(e){let t=wr(e.ui?.shortcuts||[]),n=wr(Er?.shortcuts||[]),r=Th(t,n);te?.setShortcuts(au(r))}async function _h(e){let t=String(e.authToken||e.apiKey||"").trim();if(!t)return null;let n=await fetch(Ql(e.apiBase),{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({action:"roverGetSiteConfig",data:{siteId:e.siteId,siteKeyId:e.siteKeyId}})});if(!n.ok)return null;let r=await n.json();if(!r?.success)return null;let o=r.data?.siteConfig&&typeof r.data.siteConfig=="object"?r.data.siteConfig:r.data;return{shortcuts:wr(o?.shortcuts),greeting:mo(o?.greeting),limits:ia(o?.limits),version:o?.version!=null?String(o.version):void 0}}function cu(e){let t=Eh(e.siteId);t&&(Er=t),zs(e),go(),_h(e).then(n=>{if(n&&(Er=n,yh(e.siteId,n),zs(e),!Jn)){let r=Gi(e);gr&&!h?.uiOpen?te?.showGreeting(sa(r)):go()}}).catch(()=>{})}function aa(e){if(!Z)return;let t={..._n,...e};t.name&&(t.name=String(t.name).trim().slice(0,120)),t.email&&(t.email=String(t.email).trim().slice(0,240)),_n=t,jl(Z.siteId,_n),te?.setVisitorName(_n.name||""),Jn||(gr&&!h?.uiOpen?te?.showGreeting(sa(Gi(Z))):go())}function xh(e){if(Fi(e),H){let s=H.getRole();lt=s,h&&(h.executionMode=s)}su(e),Zs(e);let t=(e.allowActions??!0)&&(H?H.isController():!0);$e=new di({allowActions:t,runtimeId:Oe,allowedDomains:e.allowedDomains,domainScopeMode:e.domainScopeMode,externalNavigationPolicy:e.externalNavigationPolicy,crossHostPolicy:js(e.navigation?.crossHostPolicy),registerOpenedTab:s=>H?.registerOpenedTab(s),switchToLogicalTab:s=>H?.switchToLogicalTab(s)||{ok:!1,reason:"No session coordinator"},listKnownTabs:()=>(H?.listTabs()||[]).map(s=>({logicalTabId:s.logicalTabId,runtimeId:s.runtimeId,url:s.url,title:s.title,external:!!s.external})),onNavigationGuardrail:s=>{Be("navigation_guardrail",s),at({kind:"status",title:"Navigation guardrail",detail:Ai(s),status:"info"})},onBeforeAgentNavigation:s=>{if(!h?.pendingRun)return;let a=new URL(window.location.href).hostname,u=new URL(s,window.location.href).hostname;a===u&&(h.pendingRun=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:"agent_navigation"}),Ne())},onBeforeCrossHostNavigation:s=>{!h||!Z||(h.pendingRun&&(h.pendingRun=Bn({...h.pendingRun,resumeRequired:!0,resumeReason:"cross_host_navigation"})),Fs(Z.siteId,{sessionId:h.sessionId,pendingRun:h.pendingRun?{id:h.pendingRun.id,text:h.pendingRun.text,startedAt:h.pendingRun.startedAt,attempts:h.pendingRun.attempts}:void 0,activeTask:h.activeTask?{taskId:h.activeTask.taskId,status:h.activeTask.status}:void 0,taskEpoch:h.taskEpoch,timestamp:Date.now()}),Ne())},instrumentationOptions:e.mode==="safe"?{observeInlineMutations:!1}:void 0});let n=lt==="observer"?"observer":"controller";$e?.setActionGateContext?.({mode:n,controllerRuntimeId:H?.getCurrentHolderRuntimeId(),activeLogicalTabId:H?.getActiveLogicalTabId(),localLogicalTabId:H?.getLocalLogicalTabId(),reason:Xs(n,t)});let r=new MessageChannel;gl(r.port1,{getSnapshot:()=>$e.getSnapshot(),getPageData:async s=>{let a=Z||e,u=Number(s?.tabId),m=H?.getLocalLogicalTabId();if(!Number.isFinite(u)||u<=0||u===m||!H)return $e.getPageData(s);let v=H.listTabs().find(I=>I.logicalTabId===u);if(!v)return _i(a,{logicalTabId:u,external:!0},"target_tab_missing");if(v.runtimeId===Oe)return $e.getPageData(s);if(v.external&&a.externalNavigationPolicy!=="allow")return _i(a,v,"external_domain_inaccessible");if(!v.runtimeId||!H.isTabAlive(u))return _i(a,v,"target_tab_inactive");try{return await H.sendCrossTabRpc(v.runtimeId,"getPageData",s,15e3)}catch{return _i(a,v,"cross_tab_rpc_failed")}},executeTool:async s=>{let a=Z||e;if(s?.payload?.forceLocal===!0)return $e.executeTool(s.call,s.payload);let m=Number(s?.call?.args?.tab_id),p=H?.getActiveLogicalTabId(),v=Number.isFinite(m)&&m>0?m:p,I=H?.getLocalLogicalTabId();if(!v||v===I||!H)return $e.executeTool(s.call,s.payload);let x=H.listTabs().find(S=>S.logicalTabId===v);if(!x)return xi(a,{logicalTabId:v,external:!0},"target_tab_missing");if(x.external&&a.externalNavigationPolicy!=="allow")return xi(a,x,"external_tab_action_blocked");if(x.runtimeId===Oe)return $e.executeTool(s.call,s.payload);if(!x.runtimeId||!H.isTabAlive(v))return xi(a,x,"target_tab_inactive");try{return await H.sendCrossTabRpc(x.runtimeId,"executeTool",s,2e4)}catch{return xi(a,x,"cross_tab_execute_failed")}},executeClientTool:s=>$e.executeClientTool(s.name,s.args),listClientTools:()=>$e.listClientTools(),getTabContext:()=>{let s=H?.getLocalLogicalTabId(),a=H?.getActiveLogicalTabId();return{id:s||1,logicalTabId:s||1,activeLogicalTabId:a||s||1,runtimeId:Oe,mode:lt,url:window.location.href,title:document.title}},listSessionTabs:()=>H?.listTabs()||[]}),r.port1.start?.();let o=e.workerUrl?e.workerUrl:new URL("./worker/worker.js",__ROVER_SCRIPT_URL__).toString(),i=o;try{let s=window.location.origin,a=new URL(o).origin;if(s!==a){let u=new Blob([`import '${o}';`],{type:"application/javascript"});i=URL.createObjectURL(u)}}catch{}if(Pe=new Worker(i,{type:"module"}),Pe.postMessage({type:"init",config:e,port:r.port2},[r.port2]),te=Tl({shortcuts:au(wr(e.ui?.shortcuts||[])),greeting:Gi(e),visitorName:_n?.name,onShortcutClick:s=>{let a=String(s.prompt||"").trim();a&&ao(a,{routing:s.routing})},onSend:(s,a)=>{ao(s,{askUserAnswers:a?.askUserAnswers})},onRequestControl:()=>{H?.requestControl()??!1?at({kind:"status",title:"Control requested",detail:"This tab is now the active Rover controller.",status:"info"}):hn("system","Unable to acquire control right now. Try again in a moment.",!0)},onCancelRun:()=>{h?.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id),H?.setActiveRun(void 0),wt(void 0),ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Rt("Task cancelled."),hn("system","Task cancelled.",!0),at({kind:"info",title:"Run cancelled",status:"info"}))},onNewTask:()=>{$r({reason:"manual_new_task",clearUi:!0})},onEndTask:()=>{Yi({reason:"manual_end_task"})},onTaskSuggestionPrimary:()=>{let s=qr;if(s){if(s.kind==="resume_run"){Un(),Hi(s.text,{runId:s.runId,resume:!0,appendUserMessage:!1,autoResume:!0});return}ao(s.text,{bypassSuggestion:!0,startNewTask:!0,reason:s.reason})}},onTaskSuggestionSecondary:()=>{let s=qr;if(s){if(s.kind==="resume_run"){h?.pendingRun?.id===s.runId&&(tn(s.runId),H?.releaseWorkflowLock(s.runId),H?.setActiveRun(void 0),wt(void 0)),ct&&(clearTimeout(ct),ct=null),Un(),$r({reason:"resume_declined_start_fresh",clearUi:!0});return}ao(s.text,{bypassSuggestion:!0})}},showTaskControls:e.ui?.showTaskControls!==!1,muted:e.ui?.muted,agent:{name:e.ui?.agent?.name},mascot:{disabled:e.ui?.mascot?.disabled,mp4Url:e.ui?.mascot?.mp4Url,webmUrl:e.ui?.mascot?.webmUrl},onOpen:()=>{Jn=!0,wo(),h&&(h.uiOpen=!0,h.uiHidden=!1,Ne()),Be("open")},onClose:()=>{h&&(h.uiOpen=!1,Ne()),Be("close")}}),Un(),h?.uiMessages?.length&&na(h.uiMessages),h?.timeline?.length&&ra(h.timeline),h?.uiStatus&&te.setStatus(h.uiStatus),Vi(),h?.executionMode&&te.setExecutionMode(h.executionMode,{localLogicalTabId:H?.getLocalLogicalTabId(),activeLogicalTabId:H?.getActiveLogicalTabId(),controllerRuntimeId:H?.getCurrentHolderRuntimeId(),canTakeControl:!0,canComposeInObserver:eu(),note:tu(h.executionMode)}),Pe.onmessage=s=>{bh(s.data||{})},H){let s=()=>{H?.registerCurrentTab(window.location.href,document.title),H?.broadcastNavigation(window.location.href,document.title)},a=history.pushState.bind(history),u=history.replaceState.bind(history);history.pushState=function(...m){let p=a(...m);return setTimeout(s,0),p},history.replaceState=function(...m){let p=u(...m);return setTimeout(s,0),p},window.addEventListener("popstate",s)}h?.uiHidden?te.hide():(te.show(),h?.uiOpen??!!e.openOnInit?te.open():te.close()),h&&(h.uiHidden=!!h.uiHidden,h.uiOpen=!!h.uiOpen,Ne()),H&&(oa(H.getState(),"remote"),ho(H.getRole(),{localLogicalTabId:H.getLocalLogicalTabId(),activeLogicalTabId:H.getActiveLogicalTabId(),holderRuntimeId:H.getCurrentHolderRuntimeId()})),go()}function bo(e){if(Kn)return Bi(e),Kn;br=Al(),Oe=Hp(e.siteId),kt=Xl(e),_n=e.visitor||Bp(e.siteId),Jn=!1,gr=!1,wo(),Er=null,Fr=$p(e.siteId);let t=th(Fr),n=t?null:Nl(e.siteId);n&&Ll(e.siteId);let r=e.sessionId?.trim(),o=!r&&!t?.sessionId&&!n?.sessionId&&e.sessionScope!=="tab"&&kt?qp(e.siteId,kt):void 0,i=r||t?.sessionId||n?.sessionId||o||crypto.randomUUID(),s=t;if(!t&&n){let a=Ws(n.sessionId,Oe);n.pendingRun&&(a.pendingRun=Bn({...n.pendingRun,autoResume:!0,resumeRequired:!0,resumeReason:"cross_host_navigation"})),n.activeTask&&(a.activeTask={...Fn("cross_domain_resume"),taskId:n.activeTask.taskId,status:n.activeTask.status}),a.taskEpoch=n.taskEpoch||1,a.uiOpen=!0,s=a}h=po(s,i,Oe),r&&h.sessionId!==r&&(h=Ws(r,Oe)),Z={...e,visitorId:kt||e.visitorId,sessionId:r||h.sessionId,taskRouting:{mode:e.taskRouting?.mode||"act",actHeuristicThreshold:e.taskRouting?.actHeuristicThreshold,plannerOnActError:e.taskRouting?.plannerOnActError},navigation:{crossHostPolicy:js(e.navigation?.crossHostPolicy)},task:{autoResumePolicy:Ks(e.task?.autoResumePolicy)},taskContext:{...e.taskContext}},h.sessionId=Z.sessionId,h.runtimeId=Oe,h.executionMode=h.executionMode||"controller",h.timeline=fo(h.timeline),h.uiMessages=uo(h.uiMessages),h.activeTask=yo(h.activeTask,Fn("boot")),h.taskEpoch=Math.max(1,Number(h.taskEpoch)||1),lt=h.executionMode,_n&&jl(e.siteId,_n),Ne();try{sessionStorage.setItem(`rover:tab-alive:${e.siteId}`,"1")}catch{}if(tr=!1,Hn=!1,xh(Z),Fr&&fh(Fr),sh(),Kn={boot:bo,init:ca,update:Bi,shutdown:la,open:vo,close:zi,show:ua,hide:da,send:fa,newTask:$r,endTask:Yi,getState:pa,registerTool:ha,identify:aa,on:zl},Si.length){for(let a of Si)Kl(a);Si.length=0}return Kn}function ca(e){return bo(e)}function Bi(e){if(!Kn||!Pe||!Z)return;Z={...Z,...e,taskRouting:{...Z.taskRouting,...e.taskRouting},navigation:{...Z.navigation,...e.navigation,crossHostPolicy:js(e.navigation?.crossHostPolicy??Z.navigation?.crossHostPolicy)},task:{...Z.task,...e.task,autoResumePolicy:Ks(e.task?.autoResumePolicy??Z.task?.autoResumePolicy)},taskContext:{...Z.taskContext,...e.taskContext},ui:{...Z.ui,...e.ui,agent:{...Z.ui?.agent,...e.ui?.agent},panel:{...Z.ui?.panel,...e.ui?.panel}},tools:{...Z.tools,...e.tools,client:e.tools?.client??Z.tools?.client,web:{...Z.tools?.web,...e.tools?.web}}},kt=Xl(Z),kt&&(Z.visitorId=kt),e.sessionId&&h?(h.sessionId=e.sessionId,Ne(),Fi(Z)):(e.sessionScope||e.tabPolicy)&&Fi(Z),su(Z),Zs(Z);let t=e.apiBase!==void 0||e.apiKey!==void 0||e.authToken!==void 0||e.siteId!==void 0||e.siteKeyId!==void 0||e.ui?.shortcuts!==void 0||e.ui?.greeting!==void 0;if($e){typeof e.allowActions=="boolean"&&$e.setAllowActions(e.allowActions&<==="controller");let n=lt==="controller"&&(Z?.allowActions??!0),r=lt==="observer"?"observer":"controller";$e?.setActionGateContext?.({mode:r,controllerRuntimeId:H?.getCurrentHolderRuntimeId(),activeLogicalTabId:H?.getActiveLogicalTabId(),localLogicalTabId:H?.getLocalLogicalTabId(),reason:Xs(r,n)}),(e.allowedDomains||e.domainScopeMode||e.externalNavigationPolicy||e.navigation?.crossHostPolicy)&&$e.setNavigationPolicy({allowedDomains:e.allowedDomains,domainScopeMode:e.domainScopeMode,externalNavigationPolicy:e.externalNavigationPolicy,crossHostPolicy:e.navigation?.crossHostPolicy})}Pe.postMessage({type:"update_config",config:e}),zs(Z),t?cu(Z):go(),e.visitor&&aa(e.visitor),typeof e.openOnInit=="boolean"&&(e.openOnInit?vo():zi())}function la(){Un(),Ne(),$i(!0),Js(),Mt?.markDirty(),Mt?.syncNow(),Mt?.stop(),Mt=null,H?.stop(),H=null,Pe?.terminate(),Pe=null,te?.destroy(),te=null,$e=null,Z=null,tr=!1,Hn=!1,Oe="",kt=void 0,_n=void 0,Jn=!1,gr=!1,wo(),Er=null,Di=!1,ki=!1,Br=!1,Lt=[],Vl=0,lt="controller",qr=null,br=null,Kn=null}function vo(){Jn=!0,wo(),te?.show(),te?.open(),h&&(h.uiHidden=!1,h.uiOpen=!0,Ne())}function zi(){te?.close(),h&&(h.uiOpen=!1,Ne())}function ua(){te?.show(),h&&(h.uiHidden=!1,Ne())}function da(){te?.hide(),h&&(h.uiHidden=!0,h.uiOpen=!1,Ne())}function fa(e){e?.trim()&&ao(e)}function $r(e){if(!h)return;let t=e?.reason||"manual_new_task",n=e?.clearUi!==!1,r=Math.max(1,Number(h.taskEpoch)||1)+1,o=Fn(t);h.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id)),ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Hn=!1,h.taskEpoch=r,h.activeTask=o,wt(void 0),h.workerState=void 0,n&&(h.uiMessages=[],h.timeline=[],h.uiStatus=void 0,ou()),H?.startNewTask({taskId:o.taskId,startedAt:o.startedAt,boundaryReason:t,status:"running",lastUserAt:void 0,lastAssistantAt:void 0}),H?.setActiveRun(void 0),H?.setWorkerContext(void 0),Rt("New task started."),Ne(),Pe?.postMessage({type:"start_new_task",taskId:o.taskId}),Be("task_started",{taskId:o.taskId,reason:t,taskEpoch:r})}function Yi(e){if(!h)return;let t=e?.reason||"manual_end_task",n=Wi("manual_end_task");n&&(n.status="ended",n.endedAt=Date.now(),n.boundaryReason=t,h.pendingRun&&(tn(h.pendingRun.id),Pe?.postMessage({type:"cancel_run",runId:h.pendingRun.id}),H?.releaseWorkflowLock(h.pendingRun.id)),wt(void 0),h.workerState=void 0,ct&&(clearTimeout(ct),ct=null),te?.setRunning(!1),te?.setQuestionPrompt(void 0),Un(),Rt("Task ended. Start a new task to continue."),H?.endTask(t),H?.setActiveRun(void 0),H?.setWorkerContext(void 0),Ne(),at({kind:"info",title:"Task ended",detail:"Start a new task when you are ready.",status:"info"}),Be("task_ended",{taskId:n.taskId,reason:t,endedAt:n.endedAt}))}function pa(){return{mode:lt,runtimeId:Oe,runtimeState:h?iu(h):null,sharedState:H?.getState()||null,pendingTaskSuggestion:qr}}function ha(e,t){let n=Pp(e);if(!Kn||!$e||!Pe){Si.push({def:n,handler:t});return}Kl({def:n,handler:t})}function Rh(e){if(!e)return;let t=String(e);if(t==="init")return"init";if(t==="boot")return"boot";if(t==="update")return"update";if(t==="shutdown")return"shutdown";if(t==="open")return"open";if(t==="close")return"close";if(t==="show")return"show";if(t==="hide")return"hide";if(t==="send")return"send";if(t==="newTask")return"newTask";if(t==="endTask")return"endTask";if(t==="getState")return"getState";if(t==="registerTool")return"registerTool";if(t==="on")return"on"}function lu(){let e=window,t=e.rover,n=((r,...o)=>{let i=Rh(r),s=i?n[i]:void 0;if(typeof s=="function")return s(...o)});if(n.boot=bo,n.init=ca,n.update=Bi,n.shutdown=la,n.open=vo,n.close=zi,n.show=ua,n.hide=da,n.send=fa,n.newTask=$r,n.endTask=Yi,n.getState=pa,n.registerTool=ha,n.on=zl,e.rover=n,typeof t=="function"&&Array.isArray(t.q))for(let r of t.q){let[o,...i]=Array.isArray(r)?r:Array.from(r);typeof o=="string"&&n(o,...i)}if(!Kn){let r=typeof globalThis.__ROVER_SCRIPT_EL__<"u"?globalThis.__ROVER_SCRIPT_EL__:null;if(r){let o=r.getAttribute("data-site-id"),i=r.getAttribute("data-api-key");if(o&&i){let s={siteId:o,apiKey:i},a=r.getAttribute("data-allowed-domains");a&&(s.allowedDomains=a.split(",").map(p=>p.trim()).filter(Boolean));let u=r.getAttribute("data-site-key-id");u&&(s.siteKeyId=u);let m=r.getAttribute("data-worker-url");m&&(s.workerUrl=m),bo(s)}}}}lu();return gu(kh);})();
|
package/dist/rover.js
CHANGED
|
@@ -18420,7 +18420,7 @@ function sanitizePendingRun(input) {
|
|
|
18420
18420
|
attempts: Math.max(0, Number(input.attempts) || 0),
|
|
18421
18421
|
autoResume: input.autoResume !== false,
|
|
18422
18422
|
resumeRequired: input.resumeRequired === true,
|
|
18423
|
-
resumeReason: input.resumeReason === "cross_host_navigation" || input.resumeReason === "handoff" || input.resumeReason === "page_reload" ? input.resumeReason : void 0
|
|
18423
|
+
resumeReason: input.resumeReason === "cross_host_navigation" || input.resumeReason === "agent_navigation" || input.resumeReason === "handoff" || input.resumeReason === "page_reload" ? input.resumeReason : void 0
|
|
18424
18424
|
};
|
|
18425
18425
|
}
|
|
18426
18426
|
function persistRuntimeState() {
|
|
@@ -20019,6 +20019,7 @@ function createRuntime(cfg) {
|
|
|
20019
20019
|
resumeRequired: true,
|
|
20020
20020
|
resumeReason: "agent_navigation"
|
|
20021
20021
|
});
|
|
20022
|
+
persistRuntimeState();
|
|
20022
20023
|
}
|
|
20023
20024
|
},
|
|
20024
20025
|
onBeforeCrossHostNavigation: (_targetUrl) => {
|