@pluno/product-agent-web 0.1.321 → 0.1.323

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function ee(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function I(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class M{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=I(e)}loader;merge;state;listeners=new Set;inFlight=null;trailingLoad=null;getState(){return this.state}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}setKey(e){e!==this.state.key&&(this.state=I(e),this.trailingLoad=null,this.publish())}reset(){this.state=I(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function _(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function L(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function $(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function te(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function se(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function ie(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const G="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===G}class ne{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new M(`${e}:recent`,async({cursor:n})=>_(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),L),this.pinnedQuery=new M(`${e}:pinned`,async()=>_({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?_({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function re(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function F(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(F),Object.freeze(i)),i}function oe(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}class ae{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(!(n&&n.version>=t.version)){if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");t.payload.kind==="integration_auth"&&(this.sources.set(s,F(oe(t))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id))}}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={integrations:[]};if(!(e?this.conversationReader(e):null))return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;a.kind==="integration_auth"&&t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle})}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!B(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=P(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${P(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${P(e.scope)}:category:${e.category}`}}function de(i,e){return{load:async()=>U(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function U(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function P(i){return`${i.level}:${i.key}`}function B(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&B(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ce={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},le=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function H(i,e){if(!e)return E(i);const t=E(i),s=`${ce[e]} Pluno`;return t?`${s}: ${t}`:s}class ue{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=E(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,s=this.lastAppliedTitle===null?E(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function pe(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function E(i){return i.replace(le,"")}const he="0.1.321",ge={version:he},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function fe(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function Q(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),me=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||me(e.createdAt))}function ye(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||fe(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function Z(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(a=>["key","count","rows","truncated"].includes(a))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(a=>a&&Object.keys(a).every(o=>["itemId","groupId"].includes(o))&&y(a.itemId)&&y(a.groupId))))&&(n.context===void 0||ye(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const x=500;function J(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>x?`${e.slice(0,x-1)}…`:e}function be(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function ve(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function Ie(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===be(J(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:ge.version,...n}}}function _e(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,a=s&&"details"in s?s.details:null,o=a&&typeof a=="object"?a:{},c={...typeof o.httpStatus=="number"&&Number.isInteger(o.httpStatus)&&o.httpStatus>=100&&o.httpStatus<=599?{httpStatus:o.httpStatus}:{},errorNormalization:O(o.errorNormalization)?o.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...o.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(o.acceptance))?{acceptance:String(o.acceptance)}:{},...typeof o.securitySettingsUrl=="string"?{securitySettingsUrl:o.securitySettingsUrl}:{},...typeof o.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(o.transportCode)?{transportCode:o.transportCode}:{},...typeof o.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(o.requestId)?{requestId:o.requestId}:{},...typeof o.durationMs=="number"&&Number.isFinite(o.durationMs)&&o.durationMs>=0?{durationMs:o.durationMs}:{},...typeof o.successfulRequests=="number"&&Number.isSafeInteger(o.successfulRequests)&&o.successfulRequests>=0?{successfulRequests:o.successfulRequests}:{}};return _e({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function W(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Se=["submit","stop","staging_ipc","send_ipc","stop_ipc","attachment_transfer","tab_lookup","tab_recovery","session_recovery","conversation_scope","local_stage","view_publication","page_access","authentication","community","preferences","page_capture","session_tabs","context_ready","first_frame","checkpoint","command_http","http_authentication","http_request","receipt_http","attachment_upload","runtime_reading","runtime_stopping","runtime_progress","runtime_stopped","message_painted","reading_painted","stopping_painted","progress_painted","stopped_painted","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],Y=["request_timed_out","delivery_unknown","invalid_ack","acceptance_identity_mismatch","disconnected","executor_not_ready","unauthorized","connection_failed","invalid_response","network_error","type_error","aborted","backend_refusal","unknown"];function Ae(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&Y.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const X=Math.random().toString(36).slice(2);let we=0;const N=()=>`timing:${X}:${++we}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&Y.includes(e.failureCategory))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp","email"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&Se.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function j(i,e){if(e={workerId:X,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,a,o,c)=>{const d={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a)),...r==="failed"?{failureCategory:Ae(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,N()),measure(n,r){const a=performance.now(),o=N();return s(n,"started",a,o),r().then(c=>(s(n,"completed",a,o),c),c=>{throw s(n,"failed",a,o,c),c})}}}const T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Ee(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Pe(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),a=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)a.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||a.some(d=>d.role==="user"&&d.id===c)&&a.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const o=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...a.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:a,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&a.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Te={"stop-without-rendered-message":"Stop is enabled while no message is rendered or the welcome screen is still visible.","in-progress-stop-unavailable":"An in-progress response has no visible enabled interrupt control.","stop-did-not-interrupt":"The stopped response remained in progress after an interrupt click.","duplicate-message-item":"A canonical message rendered more than once.","duplicate-canonical-item":"A canonical session item rendered more than once.","duplicate-tool-call":"A tool call rendered more than once.","duplicate-attachment":"An attachment rendered more than once.","duplicate-terminal-outcome":"A response rendered more than one terminal outcome.","foreign-session-item-visible":"The visible transcript contains state owned by another session.","terminal-response-reactivated":"A terminal response became active again.","terminal-history-not-append-only":"An established terminal outcome disappeared or changed order.","runtime-transcript-not-rendered":"A nonempty runtime transcript is displaying starter prompts.","thinking-groups-without-user-message":"Multiple thinking groups appeared without a user message between them.","thinking-without-progress":"Thinking remained visible without progress for five minutes."};function Me(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Te,i.slice(13))}function K(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Re(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Ee(e.observation);case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||ve(e.errorDiagnostic))&&(e.httpRequest===void 0||W(e.httpRequest))&&(e.historyRefreshFailure===void 0||Q(e.historyRefreshFailure))&&(e.renderedError===void 0||V(e.renderedError))&&(e.reason==="conversation_error"||e.reason==="attachment_error"||e.reason==="history_error"||e.reason==="action_error")&&typeof e.errorFingerprint=="string"&&/^fnv1a-[0-9a-f]{8}$/.test(e.errorFingerprint)&&(e.displayedMessage===void 0||typeof e.displayedMessage=="string"&&e.displayedMessage.length<=500);case"runtime.report_invalid_state_transition":return(e.uiInvariant===void 0||Z(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Me(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.prompt_presented":return(e.feature==="notifications"||e.feature==="tab_grouping")&&typeof e.openingGeneration=="number"&&Number.isSafeInteger(e.openingGeneration)&&e.openingGeneration>0;case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return(e.requestedModel===void 0||typeof e.requestedModel=="string")&&typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return!1;case"conversation.stage":return(e.reconcileAcceptance===void 0||typeof e.reconcileAcceptance=="boolean")&&(e.selectionKey===void 0||typeof e.selectionKey=="string")&&(e.reconcileAcceptance!==!0||typeof e.selectionKey=="string"&&e.selectionKey.length>0)&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return(e.selectionKey===void 0||typeof e.selectionKey=="string")&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class ke{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-6.1-sol",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=I("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;readinessPendingSubmissions=new Set;pendingTransfers=new Map;submissionPreviews=new Map;submissionRetries=new Map;retainedTranscript=null;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;durabilityWaiters=new Set;navigationRevision=0;pendingNavigation=!1;destroyed=!1;hasBeenReady;on(e,t){const s=this.listeners[e]??new Set;return s.add(t),this.listeners[e]=s,()=>s.delete(t)}getState(){const e=A(this.state);if(this.pendingNavigation&&(e.isLoadingSession=!0),this.retainedTranscript){const n=A({...e,...this.retainedTranscript}),r=new Set(n.messages.map(o=>o.id)),a=new Set(n.segments?.map(o=>o.id));e.messages=[...n.messages,...e.messages.filter(o=>!r.has(o.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(o=>({...o})),...(e.segments??[]).filter(o=>!a.has(o.id))]),e.removedItems={...n.removedItems,...e.removedItems}}for(const[n,r]of this.submissionPreviews)e.messages.some(a=>a.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(a=>({...a}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error.message,e.lastErrorCode=["unauthorized","401","auth_reconnecting","submission_not_available","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=Pe(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const a=this.getState(),o=!this.hasBeenReady&&(!a.user||a.user.id===e.user?.id),c=a.stableSelectionKey!==void 0&&a.stableSelectionKey===e.stableSelectionKey&&a.user?.id===e.user?.id&&a.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!o&&!d&&(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const p=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=p?this.retainedTranscript??(this.state.isLoadingSession||this.state.messages.length===0?null:{messages:this.state.messages,segments:this.state.segments,removedItems:this.state.removedItems}):null,this.state=A(e),t!==void 0&&!this.modelExplicit&&(this.model=t),e.status==="connected"&&e.submissionReady!==!1&&(this.hasBeenReady=!0);for(const[l,u]of this.stopPreviews){const h=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&h!==void 0&&h!=="[]"&&(h!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),a.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=a.messages.find(h=>h.role==="user"&&h.id===l.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&u)||(l.attachments=qe(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=z(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}recordPromptPresented(e,t){this.dispatch({type:"runtime.prompt_presented",feature:e,openingGeneration:t})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!Z(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const a=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!V(n)||r!==void 0&&!Q(r))return;const o=Ie(this.getState(),e,s,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:o,...o.clientMessageId?{clientMessageId:o.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...W(a)?{httpRequest:a}:{},...s?{displayedMessage:J(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){if(t.proactiveSuggestionQuestion!==void 0)return Promise.reject(new Error("Personal Product Agent has retired."));const s=e.trim();if(this.pendingNavigation)return Promise.reject(new Error("Wait for the conversation to finish loading."));t={...t,requestedModel:t.requestedModel??this.getModel(),attachments:t.attachments?.map(d=>({...d}))};const n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??crypto.randomUUID(),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:a,selectionKey:this.state.selectionKey},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,a=j(p=>{s===this.submissionGeneration&&this.reportOperationTiming(p)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const p=await a.measure("staging_ipc",async()=>{if(d){if(!await a.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,content:n,clientMessageId:r,attachments:o.length>0?o.map(K):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const h=b(u);if(h.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=h),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!p||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),p.result?.submissionAccepted){for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of o){if(u.sandboxPath||u.storageKey){l.push(u);continue}const h=u.id?this.attachmentFiles.get(u.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(h,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}o=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,attachments:o.length>0?o.map(K):void 0}),s!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}catch(p){if(s!==this.submissionGeneration)return null;if(R(p))for(const f of t.attachments??[])f.id&&this.attachmentFiles.delete(f.id);const u=b(p).code==="command_not_received";!c&&!R(p)&&(d||u||t.selectionKey!==void 0)&&this.submissionRetries.set(r,{retry:async()=>(d&&await this.connect(),this.sendMessageNow(e,{...t,reconcileAcceptance:!d&&!u},s)),attachmentIds:(t.attachments??[]).flatMap(f=>f.id?[f.id]:[])});const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=b(p),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:b(p).message}),p}finally{this.readinessPendingSubmissions.delete(r)}}getModel(){return this.model}setModel(e){return this.modelExplicit=!0,this.model===e||(this.model=e,this.emit("state",this.getState())),Promise.resolve()}async retryLastMessage(e){const t=e??[...this.submissionPreviews].reverse().find(([,o])=>o.error)?.[0]??this.state.messages.filter(o=>o.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,a=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!s&&!r)throw o;return s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(o),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=j(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const a=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:a);const o=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(o!==this.submissionGeneration||s.every(p=>!this.stopPreviews.has(p)))){for(const p of s)this.stopPreviews.delete(p);this.stopError=b(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,a)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const o=this.state;if(o.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(o.conversationDiagnostics?.failedClientMessageId===e&&o.lastError&&o.lastErrorCode!=="submission_checkpoint_pending"){a(Object.assign(new Error(o.lastError),{code:o.lastErrorCode}));return}const c=o.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){a(new Error(c.content));return}o.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return z(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(a=>a.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){return Promise.resolve()}dispatch(e){return this.adapter.dispatch(e)}async navigate(e){const t=++this.navigationRevision;this.pendingNavigation=!0,this.model=this.initialModel,this.emit("state",this.getState());try{await this.dispatch(e)}finally{t===this.navigationRevision&&(this.pendingNavigation=!1,this.emit("state",this.getState()))}}emit(e,t){const s=this.listeners[e];for(const n of s??[])n(t)}}function qe(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function z(i){return{...i,data:i.data?_({entities:$(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=G;exports.ProductAgentInteractionManager=ae;exports.ProductAgentQueryController=M;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=pe;exports.formatProductAgentTaskPageTitle=H;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=U;exports.reconcileProductAgentSubmissionGate=ee;exports.resolveProductAgentBillingPresentation=se;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=te;exports.selectProductAgentQueryEntities=$;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function ee(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function I(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class M{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=I(e)}loader;merge;state;listeners=new Set;inFlight=null;trailingLoad=null;getState(){return this.state}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}setKey(e){e!==this.state.key&&(this.state=I(e),this.trailingLoad=null,this.publish())}reset(){this.state=I(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function _(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function L(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function $(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function te(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function se(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function ie(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const G="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===G}class ne{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new M(`${e}:recent`,async({cursor:n})=>_(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),L),this.pinnedQuery=new M(`${e}:pinned`,async()=>_({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?_({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function re(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function F(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(F),Object.freeze(i)),i}function oe(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}class ae{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(!(n&&n.version>=t.version)){if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");t.payload.kind==="integration_auth"&&(this.sources.set(s,F(oe(t))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id))}}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={integrations:[]};if(!(e?this.conversationReader(e):null))return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;a.kind==="integration_auth"&&t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle})}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!B(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=P(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${P(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${P(e.scope)}:category:${e.category}`}}function de(i,e){return{load:async()=>U(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function U(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function P(i){return`${i.level}:${i.key}`}function B(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&B(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ce={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},le=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function H(i,e){if(!e)return E(i);const t=E(i),s=`${ce[e]} Pluno`;return t?`${s}: ${t}`:s}class ue{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=E(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,s=this.lastAppliedTitle===null?E(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function pe(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function E(i){return i.replace(le,"")}const he="0.1.323",ge={version:he},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function fe(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function Q(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),me=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||me(e.createdAt))}function ye(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||fe(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function Z(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(a=>["key","count","rows","truncated"].includes(a))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(a=>a&&Object.keys(a).every(o=>["itemId","groupId"].includes(o))&&y(a.itemId)&&y(a.groupId))))&&(n.context===void 0||ye(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const x=500;function J(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>x?`${e.slice(0,x-1)}…`:e}function be(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function ve(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function Ie(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===be(J(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:ge.version,...n}}}function _e(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,a=s&&"details"in s?s.details:null,o=a&&typeof a=="object"?a:{},c={...typeof o.httpStatus=="number"&&Number.isInteger(o.httpStatus)&&o.httpStatus>=100&&o.httpStatus<=599?{httpStatus:o.httpStatus}:{},errorNormalization:O(o.errorNormalization)?o.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...o.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(o.acceptance))?{acceptance:String(o.acceptance)}:{},...typeof o.securitySettingsUrl=="string"?{securitySettingsUrl:o.securitySettingsUrl}:{},...typeof o.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(o.transportCode)?{transportCode:o.transportCode}:{},...typeof o.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(o.requestId)?{requestId:o.requestId}:{},...typeof o.durationMs=="number"&&Number.isFinite(o.durationMs)&&o.durationMs>=0?{durationMs:o.durationMs}:{},...typeof o.successfulRequests=="number"&&Number.isSafeInteger(o.successfulRequests)&&o.successfulRequests>=0?{successfulRequests:o.successfulRequests}:{}};return _e({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function W(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Se=["submit","stop","staging_ipc","send_ipc","stop_ipc","attachment_transfer","tab_lookup","tab_recovery","session_recovery","conversation_scope","local_stage","view_publication","page_access","authentication","community","preferences","page_capture","session_tabs","context_ready","first_frame","checkpoint","command_http","http_authentication","http_request","receipt_http","attachment_upload","runtime_reading","runtime_stopping","runtime_progress","runtime_stopped","message_painted","reading_painted","stopping_painted","progress_painted","stopped_painted","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],Y=["request_timed_out","delivery_unknown","invalid_ack","acceptance_identity_mismatch","disconnected","executor_not_ready","unauthorized","connection_failed","invalid_response","network_error","type_error","aborted","backend_refusal","unknown"];function Ae(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&Y.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const X=Math.random().toString(36).slice(2);let we=0;const N=()=>`timing:${X}:${++we}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&Y.includes(e.failureCategory))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp","email"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&Se.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function j(i,e){if(e={workerId:X,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,a,o,c)=>{const d={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a)),...r==="failed"?{failureCategory:Ae(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,N()),measure(n,r){const a=performance.now(),o=N();return s(n,"started",a,o),r().then(c=>(s(n,"completed",a,o),c),c=>{throw s(n,"failed",a,o,c),c})}}}const T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Ee(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Pe(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),a=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)a.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||a.some(d=>d.role==="user"&&d.id===c)&&a.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const o=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...a.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:a,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&a.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Te={"stop-without-rendered-message":"Stop is enabled while no message is rendered or the welcome screen is still visible.","in-progress-stop-unavailable":"An in-progress response has no visible enabled interrupt control.","stop-did-not-interrupt":"The stopped response remained in progress after an interrupt click.","duplicate-message-item":"A canonical message rendered more than once.","duplicate-canonical-item":"A canonical session item rendered more than once.","duplicate-tool-call":"A tool call rendered more than once.","duplicate-attachment":"An attachment rendered more than once.","duplicate-terminal-outcome":"A response rendered more than one terminal outcome.","foreign-session-item-visible":"The visible transcript contains state owned by another session.","terminal-response-reactivated":"A terminal response became active again.","terminal-history-not-append-only":"An established terminal outcome disappeared or changed order.","runtime-transcript-not-rendered":"A nonempty runtime transcript is displaying starter prompts.","thinking-groups-without-user-message":"Multiple thinking groups appeared without a user message between them.","thinking-without-progress":"Thinking remained visible without progress for five minutes."};function Me(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Te,i.slice(13))}function K(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Re(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Ee(e.observation);case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||ve(e.errorDiagnostic))&&(e.httpRequest===void 0||W(e.httpRequest))&&(e.historyRefreshFailure===void 0||Q(e.historyRefreshFailure))&&(e.renderedError===void 0||V(e.renderedError))&&(e.reason==="conversation_error"||e.reason==="attachment_error"||e.reason==="history_error"||e.reason==="action_error")&&typeof e.errorFingerprint=="string"&&/^fnv1a-[0-9a-f]{8}$/.test(e.errorFingerprint)&&(e.displayedMessage===void 0||typeof e.displayedMessage=="string"&&e.displayedMessage.length<=500);case"runtime.report_invalid_state_transition":return(e.uiInvariant===void 0||Z(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Me(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.prompt_presented":return(e.feature==="notifications"||e.feature==="tab_grouping")&&typeof e.openingGeneration=="number"&&Number.isSafeInteger(e.openingGeneration)&&e.openingGeneration>0;case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return(e.requestedModel===void 0||typeof e.requestedModel=="string")&&typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return!1;case"conversation.stage":return(e.reconcileAcceptance===void 0||typeof e.reconcileAcceptance=="boolean")&&(e.selectionKey===void 0||typeof e.selectionKey=="string")&&(e.reconcileAcceptance!==!0||typeof e.selectionKey=="string"&&e.selectionKey.length>0)&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return(e.selectionKey===void 0||typeof e.selectionKey=="string")&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class ke{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-6.1-sol",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=I("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;readinessPendingSubmissions=new Set;pendingTransfers=new Map;submissionPreviews=new Map;submissionRetries=new Map;retainedTranscript=null;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;durabilityWaiters=new Set;navigationRevision=0;pendingNavigation=!1;destroyed=!1;hasBeenReady;on(e,t){const s=this.listeners[e]??new Set;return s.add(t),this.listeners[e]=s,()=>s.delete(t)}getState(){const e=A(this.state);if(this.pendingNavigation&&(e.isLoadingSession=!0),this.retainedTranscript){const n=A({...e,...this.retainedTranscript}),r=new Set(n.messages.map(o=>o.id)),a=new Set(n.segments?.map(o=>o.id));e.messages=[...n.messages,...e.messages.filter(o=>!r.has(o.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(o=>({...o})),...(e.segments??[]).filter(o=>!a.has(o.id))]),e.removedItems={...n.removedItems,...e.removedItems}}for(const[n,r]of this.submissionPreviews)e.messages.some(a=>a.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(a=>({...a}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error.message,e.lastErrorCode=["unauthorized","401","auth_reconnecting","submission_not_available","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=Pe(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const a=this.getState(),o=!this.hasBeenReady&&(!a.user||a.user.id===e.user?.id),c=a.stableSelectionKey!==void 0&&a.stableSelectionKey===e.stableSelectionKey&&a.user?.id===e.user?.id&&a.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!o&&!d&&(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const p=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=p?this.retainedTranscript??(this.state.isLoadingSession||this.state.messages.length===0?null:{messages:this.state.messages,segments:this.state.segments,removedItems:this.state.removedItems}):null,this.state=A(e),t!==void 0&&!this.modelExplicit&&(this.model=t),e.status==="connected"&&e.submissionReady!==!1&&(this.hasBeenReady=!0);for(const[l,u]of this.stopPreviews){const h=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&h!==void 0&&h!=="[]"&&(h!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),a.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=a.messages.find(h=>h.role==="user"&&h.id===l.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&u)||(l.attachments=qe(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=z(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}recordPromptPresented(e,t){this.dispatch({type:"runtime.prompt_presented",feature:e,openingGeneration:t})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!Z(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const a=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!V(n)||r!==void 0&&!Q(r))return;const o=Ie(this.getState(),e,s,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:o,...o.clientMessageId?{clientMessageId:o.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...W(a)?{httpRequest:a}:{},...s?{displayedMessage:J(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){if(t.proactiveSuggestionQuestion!==void 0)return Promise.reject(new Error("Personal Product Agent has retired."));const s=e.trim();if(this.pendingNavigation)return Promise.reject(new Error("Wait for the conversation to finish loading."));t={...t,requestedModel:t.requestedModel??this.getModel(),attachments:t.attachments?.map(d=>({...d}))};const n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??crypto.randomUUID(),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:a,selectionKey:this.state.selectionKey},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,a=j(p=>{s===this.submissionGeneration&&this.reportOperationTiming(p)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const p=await a.measure("staging_ipc",async()=>{if(d){if(!await a.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,content:n,clientMessageId:r,attachments:o.length>0?o.map(K):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const h=b(u);if(h.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=h),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!p||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),p.result?.submissionAccepted){for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of o){if(u.sandboxPath||u.storageKey){l.push(u);continue}const h=u.id?this.attachmentFiles.get(u.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(h,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}o=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,attachments:o.length>0?o.map(K):void 0}),s!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}catch(p){if(s!==this.submissionGeneration)return null;if(R(p))for(const f of t.attachments??[])f.id&&this.attachmentFiles.delete(f.id);const u=b(p).code==="command_not_received";!c&&!R(p)&&(d||u||t.selectionKey!==void 0)&&this.submissionRetries.set(r,{retry:async()=>(d&&await this.connect(),this.sendMessageNow(e,{...t,reconcileAcceptance:!d&&!u},s)),attachmentIds:(t.attachments??[]).flatMap(f=>f.id?[f.id]:[])});const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=b(p),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:b(p).message}),p}finally{this.readinessPendingSubmissions.delete(r)}}getModel(){return this.model}setModel(e){return this.modelExplicit=!0,this.model===e||(this.model=e,this.emit("state",this.getState())),Promise.resolve()}async retryLastMessage(e){const t=e??[...this.submissionPreviews].reverse().find(([,o])=>o.error)?.[0]??this.state.messages.filter(o=>o.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,a=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!s&&!r)throw o;return s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(o),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=j(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const a=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:a);const o=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(o!==this.submissionGeneration||s.every(p=>!this.stopPreviews.has(p)))){for(const p of s)this.stopPreviews.delete(p);this.stopError=b(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,a)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const o=this.state;if(o.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(o.conversationDiagnostics?.failedClientMessageId===e&&o.lastError&&o.lastErrorCode!=="submission_checkpoint_pending"){a(Object.assign(new Error(o.lastError),{code:o.lastErrorCode}));return}const c=o.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){a(new Error(c.content));return}o.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return z(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(a=>a.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){return Promise.resolve()}dispatch(e){return this.adapter.dispatch(e)}async navigate(e){const t=++this.navigationRevision;this.pendingNavigation=!0,this.model=this.initialModel,this.emit("state",this.getState());try{await this.dispatch(e)}finally{t===this.navigationRevision&&(this.pendingNavigation=!1,this.emit("state",this.getState()))}}emit(e,t){const s=this.listeners[e];for(const n of s??[])n(t)}}function qe(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function z(i){return{...i,data:i.data?_({entities:$(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=G;exports.ProductAgentInteractionManager=ae;exports.ProductAgentQueryController=M;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=pe;exports.formatProductAgentTaskPageTitle=H;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=U;exports.reconcileProductAgentSubmissionGate=ee;exports.resolveProductAgentBillingPresentation=se;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=te;exports.selectProductAgentQueryEntities=$;
@@ -522,7 +522,7 @@ function Re(i) {
522
522
  function E(i) {
523
523
  return i.replace(se, "");
524
524
  }
525
- const ne = "0.1.321", re = {
525
+ const ne = "0.1.323", re = {
526
526
  version: ne
527
527
  }, g = (i) => typeof i == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(i) ? i : null;
528
528
  function oe(i) {
@@ -846,7 +846,7 @@ function wr(t, e = null) {
846
846
  } : void 0);
847
847
  return { ...i, ...a ? { auth: a } : {}, submissionGate: o };
848
848
  }
849
- const _r = "0.1.321", Tt = {
849
+ const _r = "0.1.323", Tt = {
850
850
  version: _r
851
851
  };
852
852
  function We(t) {
@@ -940,7 +940,7 @@ function vs(t) {
940
940
  function nn(t) {
941
941
  return ["history_load_failed", "request_timed_out", "connection_interrupted", "408", "425", "429"].includes(t) || /^5\d\d$/.test(t);
942
942
  }
943
- const kr = "Message storage has not confirmed this submission. Reconnect to check its status.";
943
+ const Er = "Message storage has not confirmed this submission. Reconnect to check its status.";
944
944
  function qt(t) {
945
945
  if (!Number.isSafeInteger(t) || t < 0) throw new Error("Invalid conversation revision.");
946
946
  }
@@ -979,7 +979,7 @@ function Is(t, e) {
979
979
  };
980
980
  return { ...t, execution: e, executionByUserMessage: s };
981
981
  }
982
- function Er(t) {
982
+ function kr(t) {
983
983
  const e = /* @__PURE__ */ new Set();
984
984
  for (const s of Object.values(t.items)) {
985
985
  const i = Rt(s), n = t.streams[s.id];
@@ -1106,7 +1106,7 @@ function Tr(t, e, s, i) {
1106
1106
  for (const y of m.removed_items) c = $t(c, y);
1107
1107
  for (const y of m.items) c = bs(c, y);
1108
1108
  for (const y of m.streams) c = rn(c, y);
1109
- if (c = Is(c, m.execution), c = $t(c, {
1109
+ if (c = Is(c, m.execution), m.follow_ups_version === 0 && m.follow_ups.length === 0 ? c = { ...c, followUps: [], followUpsVersion: Number.MAX_SAFE_INTEGER } : c = $t(c, {
1110
1110
  type: "conversation.follow_ups.updated",
1111
1111
  conversation_id: m.conversation_id,
1112
1112
  version: m.follow_ups_version,
@@ -1159,7 +1159,7 @@ function Tr(t, e, s, i) {
1159
1159
  if (s.clients[e.clientScopeId] !== e.conversationScopeId) throw new Error("Submission selection has changed.");
1160
1160
  const { type: a, authorityId: c, generation: d, prepareContext: u, reconcileAcceptance: l, waitForAuthentication: h, ...f } = e, m = t.submissions[e.userMessageId];
1161
1161
  if (m) {
1162
- const { contextPreparation: b, requestedModel: I, sessionId: w, delivery: k, cancelled: E, cancellationReason: D, error: S, executionVersion: q, ...A } = m;
1162
+ const { contextPreparation: b, requestedModel: I, sessionId: w, delivery: E, cancelled: k, cancellationReason: D, error: S, executionVersion: q, ...A } = m;
1163
1163
  if (Ze(A) !== Ze(f)) throw new Error("User-message identity cannot be reused with different input.");
1164
1164
  return { state: t, effects: r };
1165
1165
  }
@@ -1241,7 +1241,7 @@ function Tr(t, e, s, i) {
1241
1241
  requestId: e.requestId,
1242
1242
  lane: e.lane,
1243
1243
  before: e.lane === "history" ? c.cursor : null,
1244
- refreshItemIds: Er(a),
1244
+ refreshItemIds: kr(a),
1245
1245
  retryPreparation: c.error?.code === "history_preparation_failed"
1246
1246
  }, u = Object.values(t.submissions).filter((f) => f.sessionId === e.sessionId && f.delivery === "accepted" && f.executionVersion === null).map((f) => f.userMessageId), l = t.requestSequence + 1, h = `conversation:${t.generation}:${l}`;
1247
1247
  n = {
@@ -1340,7 +1340,7 @@ function pi(t, e) {
1340
1340
  return { sessionId: t.sessionId, clientMessageId: e };
1341
1341
  }
1342
1342
  const dt = { code: "personal_product_agent_retired", message: "Personal Product Agent has retired.", retryable: !1 };
1343
- function ks(t) {
1343
+ function Es(t) {
1344
1344
  let e = t;
1345
1345
  const s = [];
1346
1346
  if (!t.effectsEnabled || !t.authorityId) return { state: t, effects: s };
@@ -1589,20 +1589,20 @@ function Mr(t, e, s, i) {
1589
1589
  delivery: (w.contextPreparation === null && !m.deliveries[I]?.handoffRecovery || !m.deliveries[I]) && !w.cancelled && w.delivery !== "accepted" ? "failed" : w.delivery === "sending" ? "uncertain" : w.delivery,
1590
1590
  error: w.delivery !== "accepted" && F(w, m.deliveries[I]) ? dt : w.contextPreparation === null && !m.deliveries[I]?.handoffRecovery && !w.cancelled && !["unauthorized", "auth_reconnecting"].includes(w.error?.code ?? "") ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : !m.deliveries[I] && w.delivery !== "accepted" && !w.cancelled ? { code: "submission_interrupted", message: "Message preparation was interrupted. Retry this message.", retryable: !0 } : w.error
1591
1591
  }])),
1592
- deliveries: Object.fromEntries(Object.entries(m.submissions).map(([I, w], k) => {
1593
- const E = m.deliveries[I], D = w.contextPreparation === null && !E?.handoffRecovery, S = w.delivery === "accepted" ? "accepted" : E?.acceptance ?? (E && (E.step === "send" || E.step === "receipt") ? "uncertain" : "unissued");
1592
+ deliveries: Object.fromEntries(Object.entries(m.submissions).map(([I, w], E) => {
1593
+ const k = m.deliveries[I], D = w.contextPreparation === null && !k?.handoffRecovery, S = w.delivery === "accepted" ? "accepted" : k?.acceptance ?? (k && (k.step === "send" || k.step === "receipt") ? "uncertain" : "unissued");
1594
1594
  return [I, {
1595
- ...hi(w, k),
1596
- ...E,
1595
+ ...hi(w, E),
1596
+ ...k,
1597
1597
  acceptance: S,
1598
- allocation: w.sessionId !== null ? "resolved" : E?.allocation ?? (E?.step === "upload" ? "uncertain" : "unissued"),
1598
+ allocation: w.sessionId !== null ? "resolved" : k?.allocation ?? (k?.step === "upload" ? "uncertain" : "unissued"),
1599
1599
  effectId: null,
1600
1600
  // Readiness is authority-local and must be re-established after restart. Captured input stays immutable.
1601
- step: S === "uncertain" && (E?.step === "send" || E?.handoffRecovery) && E.phase !== "done" ? "receipt" : E?.step ?? null,
1601
+ step: S === "uncertain" && (k?.step === "send" || k?.handoffRecovery) && k.phase !== "done" ? "receipt" : k?.step ?? null,
1602
1602
  prepared: S === "accepted",
1603
- queuePosition: E?.queuePosition ?? k,
1603
+ queuePosition: k?.queuePosition ?? E,
1604
1604
  // Retired inputs can only reconcile their original receipt, including interrupted preparation.
1605
- phase: S === "accepted" ? "done" : S === "uncertain" && F(w, E) ? "uncertain" : D || !E ? "failed" : ["running", "waiting"].includes(E.phase) ? "uncertain" : E.phase
1605
+ phase: S === "accepted" ? "done" : S === "uncertain" && F(w, k) ? "uncertain" : D || !k ? "failed" : ["running", "waiting"].includes(k.phase) ? "uncertain" : k.phase
1606
1606
  }];
1607
1607
  })),
1608
1608
  // Retired warmup hints must never replay; other durable commands retain their recovery state.
@@ -1730,7 +1730,7 @@ function Mr(t, e, s, i) {
1730
1730
  return h && !h.cancelled && !["accepted", "failed"].includes(h.delivery) && !a.durableSubmissionIds.includes(l);
1731
1731
  });
1732
1732
  c.length !== a.pendingDurabilityIds.length && (a = { ...a, pendingDurabilityIds: c });
1733
- const d = ks(a), u = Rs(t, d.state, s, e.type === "conversation.recover" && t.checkpointError !== null);
1733
+ const d = Es(a), u = Rs(t, d.state, s, e.type === "conversation.recover" && t.checkpointError !== null);
1734
1734
  return { state: u.state, effects: [...u.effects, ...o.effects, ...d.effects], interactionSources: o.interactionSources };
1735
1735
  }
1736
1736
  const Cr = [
@@ -2211,7 +2211,7 @@ const lt = /* @__PURE__ */ Object.create(null);
2211
2211
  Object.keys(ae).forEach((t) => {
2212
2212
  lt[ae[t]] = t;
2213
2213
  });
2214
- const Es = { type: "error", data: "parser error" }, un = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", hn = typeof ArrayBuffer == "function", pn = (t) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(t) : t && t.buffer instanceof ArrayBuffer, Hs = ({ type: t, data: e }, s, i) => un && e instanceof Blob ? s ? i(e) : yi(e, i) : hn && (e instanceof ArrayBuffer || pn(e)) ? s ? i(e) : yi(new Blob([e]), i) : i(ae[t] + (e || "")), yi = (t, e) => {
2214
+ const ks = { type: "error", data: "parser error" }, un = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", hn = typeof ArrayBuffer == "function", pn = (t) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(t) : t && t.buffer instanceof ArrayBuffer, Hs = ({ type: t, data: e }, s, i) => un && e instanceof Blob ? s ? i(e) : yi(e, i) : hn && (e instanceof ArrayBuffer || pn(e)) ? s ? i(e) : yi(new Blob([e]), i) : i(ae[t] + (e || "")), yi = (t, e) => {
2215
2215
  const s = new FileReader();
2216
2216
  return s.onload = function() {
2217
2217
  const i = s.result.split(",")[1];
@@ -2256,7 +2256,7 @@ const Gr = (t) => {
2256
2256
  data: t.substring(1)
2257
2257
  } : {
2258
2258
  type: lt[s]
2259
- } : Es;
2259
+ } : ks;
2260
2260
  }, Qr = (t, e) => {
2261
2261
  if (Jr) {
2262
2262
  const s = Gr(t);
@@ -2337,7 +2337,7 @@ function eo(t, e) {
2337
2337
  break;
2338
2338
  const c = tt(s, 8), d = new DataView(c.buffer, c.byteOffset, c.length), u = d.getUint32(0);
2339
2339
  if (u > Math.pow(2, 21) - 1) {
2340
- a.enqueue(Es);
2340
+ a.enqueue(ks);
2341
2341
  break;
2342
2342
  }
2343
2343
  n = u * Math.pow(2, 32) + d.getUint32(4), i = 3;
@@ -2348,7 +2348,7 @@ function eo(t, e) {
2348
2348
  a.enqueue(Ks(r ? c : Kt.decode(c), e)), i = 0;
2349
2349
  }
2350
2350
  if (n === 0 || n > t) {
2351
- a.enqueue(Es);
2351
+ a.enqueue(ks);
2352
2352
  break;
2353
2353
  }
2354
2354
  }
@@ -3252,7 +3252,7 @@ class me extends j {
3252
3252
  }
3253
3253
  }
3254
3254
  me.protocol = gn;
3255
- class ko extends me {
3255
+ class Eo extends me {
3256
3256
  constructor() {
3257
3257
  super(...arguments), this._upgrades = [];
3258
3258
  }
@@ -3324,7 +3324,7 @@ class ko extends me {
3324
3324
  return s;
3325
3325
  }
3326
3326
  }
3327
- let Eo = class extends ko {
3327
+ let ko = class extends Eo {
3328
3328
  constructor(e, s = {}) {
3329
3329
  const i = typeof e == "object", n = i ? { ...e } : { ...s };
3330
3330
  (!n.transports || n.transports && typeof n.transports[0] == "string") && (n.transports = (n.transports || ["polling", "websocket", "webtransport"]).map((r) => wo[r]).filter((r) => !!r)), super(i ? n : e, n);
@@ -4297,7 +4297,7 @@ class Cs extends j {
4297
4297
  open(e) {
4298
4298
  if (~this._readyState.indexOf("open"))
4299
4299
  return this;
4300
- this.engine = new Eo(this.uri, this.opts);
4300
+ this.engine = new ko(this.uri, this.opts);
4301
4301
  const s = this.engine, i = this;
4302
4302
  this._readyState = "opening", this.skipReconnect = !1;
4303
4303
  const n = ie(s, "open", function() {
@@ -5107,7 +5107,7 @@ function Ho(t) {
5107
5107
  const f = h[0];
5108
5108
  if (o.before !== null && f.next_cursor === o.before)
5109
5109
  throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
5110
- const m = h.reduce((g, y) => y.execution.version > g.version ? y.execution : g, f.execution), p = h.reduce((g, y) => y.follow_ups_version > g.follow_ups_version ? y : g, f);
5110
+ const m = h.reduce((g, y) => y.execution.version > g.version ? y.execution : g, f.execution), p = h.find((g) => g.follow_ups_version === 0 && g.follow_ups.length === 0) ?? h.reduce((g, y) => y.follow_ups_version > g.follow_ups_version ? y : g, f);
5111
5111
  return { snapshot: {
5112
5112
  ...f,
5113
5113
  execution: m,
@@ -5313,7 +5313,7 @@ function pe(t, e, s) {
5313
5313
  let _ = g ? "submitting" : y ? "awaiting_execution" : l?.phase ?? "idle";
5314
5314
  const b = Object.entries(t.stops).filter(([v]) => v === s || n !== null && e.selections[v]?.sessionId === n).map(([, v]) => v).find((v) => (!o.length || v.userMessageIds.includes(o[o.length - 1].userMessageId) || !g && !y && ne(l).some((C) => v.userMessageIds.includes(C))) && (!l || l.version <= v.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(l.phase) || o.some((C) => C.cancelled && C.executionVersion === null && v.userMessageIds.includes(C.userMessageId)))), I = l && ["thinking", "steering", "queued", "stopping"].includes(l.phase) || o.some((v) => v.delivery === "accepted" && v.executionVersion === null && b?.userMessageIds.includes(v.userMessageId));
5315
5315
  b && I && !g && (!l || !["thinking", "steering", "queued", "stopping"].includes(l.phase) || ne(l).every((v) => b.userMessageIds.includes(v))) && (_ = "stopping"), b && !I && !g && o.some((v) => v.cancelled && v.executionVersion === null && b.userMessageIds.includes(v.userMessageId)) && (_ = o.some((v) => b.userMessageIds.includes(v.userMessageId) && ["sending", "uncertain"].includes(v.delivery)) ? "stopping" : "stopped");
5316
- const w = ["thinking", "steering", "queued"].includes(_), k = t.stops[s] ?? b, E = k?.userMessageIds.filter((v) => !["completed", "failed"].includes(r?.executionByUserMessage[v]?.phase ?? "")) ?? [], D = E.some((v) => {
5316
+ const w = ["thinking", "steering", "queued"].includes(_), E = t.stops[s] ?? b, k = E?.userMessageIds.filter((v) => !["completed", "failed"].includes(r?.executionByUserMessage[v]?.phase ?? "")) ?? [], D = k.some((v) => {
5317
5317
  const C = o.find(($) => $.userMessageId === v);
5318
5318
  return !Object.values(t.operations).some(($) => $.command.type === "run.stop" && $.command.payload.expectedUserMessageId === v && $.phase === "done") && (C?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(C.delivery) || !!(l && ne(l).includes(v) && ["thinking", "steering", "queued", "stopping"].includes(l.phase)));
5319
5319
  }), S = l?.user_message_ids ?? [], q = g || y ? p?.userMessageId ?? null : S[S.length - 1] ?? null, A = u.find((v) => v.userMessageId === q), P = w ? [...A?.activityIds ?? []].reverse().find((v) => d[v] === "open") ?? null : null, T = n !== null && !!e.selections[s]?.provisionalId && a.length === 0 && o.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
@@ -5334,7 +5334,7 @@ function pe(t, e, s) {
5334
5334
  removedItems: r?.removedItems ?? {},
5335
5335
  streamStates: d,
5336
5336
  preparation: r?.preparation ?? null,
5337
- stop: k ? { ...k, userMessageIds: E, pending: D } : null,
5337
+ stop: E ? { ...E, userMessageIds: k, pending: D } : null,
5338
5338
  segments: u.map((v, C) => ({ ...v, collapsed: w ? v.userMessageId !== q : C < u.length - 1 || v.activityIds.length > 0 })),
5339
5339
  activity: { phase: _, activeItemId: P, userMessageId: q, executionKey: JSON.stringify([...ne(l)].sort()) },
5340
5340
  // Staging transfers the immutable input to the core. Waiting for backend acceptance leaves
@@ -5360,7 +5360,7 @@ function Wo(t, e) {
5360
5360
  return K({ scopes: Object.fromEntries([...new Set(Object.values(e.clients))].map((s) => [s, pe(t, e, s)])) });
5361
5361
  }
5362
5362
  const Go = /(\]\()(\/api\/product-agent\/attachments\/download\?[^)\s]+)(\))/g;
5363
- function Ee(t, e) {
5363
+ function ke(t, e) {
5364
5364
  return e ? t.replace(
5365
5365
  Go,
5366
5366
  (s, i, n, r) => `${i}${new URL(n, e).toString()}${r}`
@@ -5411,21 +5411,21 @@ function Jo(t, e, s, i) {
5411
5411
  };
5412
5412
  switch (t.type) {
5413
5413
  case "user_message":
5414
- return { ...r, role: "user", content: Ee(t.data.content, i), attachments: t.data.attachments.map((o) => Si(o, i)) };
5414
+ return { ...r, role: "user", content: ke(t.data.content, i), attachments: t.data.attachments.map((o) => Si(o, i)) };
5415
5415
  case "final_response":
5416
5416
  return {
5417
5417
  ...r,
5418
5418
  role: "assistant",
5419
5419
  phase: "final_answer",
5420
- content: Ee(t.data.content, i),
5420
+ content: ke(t.data.content, i),
5421
5421
  attachments: t.data.attachments.map((o) => Si(o, i)),
5422
5422
  loading: n,
5423
5423
  streamState: s
5424
5424
  };
5425
5425
  case "commentary":
5426
- return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content: Ee(t.data.content, i), loading: n };
5426
+ return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content: ke(t.data.content, i), loading: n };
5427
5427
  case "tool_summary":
5428
- return { ...r, role: "tool", dataType: "tool_summary", content: Ee(t.data.content, i), loading: n };
5428
+ return { ...r, role: "tool", dataType: "tool_summary", content: ke(t.data.content, i), loading: n };
5429
5429
  // The supported public renderer recognizes run_error; a bare error system row is silently omitted.
5430
5430
  case "error":
5431
5431
  return {
@@ -5484,10 +5484,10 @@ function Wt(t, e, s, i) {
5484
5484
  }] : [S];
5485
5485
  }), g = e?.error != null && t.historyRefreshFailure != null && t.historyRefreshFailure.consecutiveFailures < 4, y = g ? null : e?.error ?? null, _ = [...t.submissions].reverse().find((S) => t.pendingDurabilityIds?.includes(S.userMessageId)), b = _ ? {
5486
5486
  code: "submission_checkpoint_pending",
5487
- message: kr,
5487
+ message: Er,
5488
5488
  details: { requestId: _.requestId }
5489
5489
  } : null, I = u?.delivery === "failed" && !u.cancelled && !f ? u.error : y ?? b;
5490
- let k = {
5490
+ let E = {
5491
5491
  isRetrying: t.isRetrying ?? !1,
5492
5492
  historyRefreshFailure: I === e?.error ? t.historyRefreshFailure ?? null : null,
5493
5493
  conversationDiagnostics: {
@@ -5530,21 +5530,21 @@ function Wt(t, e, s, i) {
5530
5530
  lastErrorSecuritySettingsUrl: typeof I?.details?.securitySettingsUrl == "string" ? I.details.securitySettingsUrl : null
5531
5531
  };
5532
5532
  for (const S of t.optimistic.filter((q) => q.cancelled && !t.stop?.userMessageIds.includes(q.userMessageId))) {
5533
- const q = Os(k, "", "stopped", [S.userMessageId], Ri(S.cancellationReason));
5534
- k = { ...k, messages: q.messages, segments: q.segments };
5533
+ const q = Os(E, "", "stopped", [S.userMessageId], Ri(S.cancellationReason));
5534
+ E = { ...E, messages: q.messages, segments: q.segments };
5535
5535
  }
5536
5536
  if (t.stop) {
5537
5537
  const S = Os(
5538
- k,
5538
+ E,
5539
5539
  "",
5540
5540
  t.stop.pending ? "stopping" : "stopped",
5541
5541
  t.stop.userMessageIds,
5542
5542
  Ri(t.stop.reason ?? "user_requested")
5543
5543
  );
5544
- k = { ...k, messages: S.messages, segments: S.segments };
5544
+ E = { ...E, messages: S.messages, segments: S.segments };
5545
5545
  }
5546
- const E = new Map(k.segments.flatMap((S, q) => [S.userMessageId, ...S.activityIds, ...S.outcomeIds].filter((A) => A !== null).map((A) => [A, q]))), D = (S) => E.get(S.id) ?? E.get(S.respondsToUserMessageId ?? "") ?? 1 / 0;
5547
- return { ...k, messages: [...k.messages].sort((S, q) => D(S) - D(q)) };
5546
+ const k = new Map(E.segments.flatMap((S, q) => [S.userMessageId, ...S.activityIds, ...S.outcomeIds].filter((A) => A !== null).map((A) => [A, q]))), D = (S) => k.get(S.id) ?? k.get(S.respondsToUserMessageId ?? "") ?? 1 / 0;
5547
+ return { ...E, messages: [...E.messages].sort((S, q) => D(S) - D(q)) };
5548
5548
  }
5549
5549
  function Ri(t) {
5550
5550
  switch (t) {
@@ -5703,7 +5703,7 @@ function il(t) {
5703
5703
  };
5704
5704
  }
5705
5705
  const Zo = "Pluno is reconnecting. Try again in a moment.";
5706
- function ki(t) {
5706
+ function Ei(t) {
5707
5707
  return (t instanceof Error ? t.message : t) === Zo;
5708
5708
  }
5709
5709
  function ea() {
@@ -5712,7 +5712,7 @@ function ea() {
5712
5712
  const e = Array.from(t, (s) => s.toString(16).padStart(2, "0")).join("");
5713
5713
  return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
5714
5714
  }
5715
- const Ei = (t) => t && /^[a-zA-Z0-9_:;=./-]{1,160}$/.test(t) ? t : null;
5715
+ const ki = (t) => t && /^[a-zA-Z0-9_:;=./-]{1,160}$/.test(t) ? t : null;
5716
5716
  class An {
5717
5717
  constructor(e) {
5718
5718
  this.options = e, this.auth = e.auth;
@@ -5771,7 +5771,7 @@ class An {
5771
5771
  }, p = () => m("transport_disposed"), g = () => m(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(o?.reason) ? o.reason : "caller_cancelled");
5772
5772
  this.requests.signal.addEventListener("abort", p, { once: !0 }), o?.addEventListener("abort", g, { once: !0 });
5773
5773
  const y = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && n === "POST", _ = /^\/conversations(?:\/[^/]+)?$/.test(e) && (n ?? (i === void 0 ? "GET" : "POST")) === "GET", b = setTimeout(() => m("deadline"), _ ? 6e4 : y ? 3e4 : 15e3), I = ea(), w = Date.now();
5774
- let k = null, E = !1, D = null, S = null, q = null;
5774
+ let E = null, k = !1, D = null, S = null, q = null;
5775
5775
  try {
5776
5776
  const A = await Promise.resolve(fetch(u, {
5777
5777
  method: n ?? (i === void 0 ? "GET" : "POST"),
@@ -5780,9 +5780,9 @@ class An {
5780
5780
  headers: { "x-product-agent-auth-request-id": I, authorization: d || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...y ? { "x-request-id": I } : {} },
5781
5781
  ...i === void 0 ? {} : { body: JSON.stringify(i) }
5782
5782
  })).catch((P) => {
5783
- throw E = !0, P;
5783
+ throw k = !0, P;
5784
5784
  });
5785
- if (k = Date.now(), D = A.status, S = Ei(A.headers.get("x-request-id")), q = Ei(A.headers.get("x-cloud-trace-context")), !A.ok) {
5785
+ if (E = Date.now(), D = A.status, S = ki(A.headers.get("x-request-id")), q = ki(A.headers.get("x-cloud-trace-context")), !A.ok) {
5786
5786
  const P = A.status === 401 ? "unauthorized" : A.status === 426 ? "update_required" : String(A.status), T = (await A.json().catch(() => null))?.detail;
5787
5787
  if (A.status === 410 && T?.code === "personal_product_agent_retired" && typeof T.message == "string")
5788
5788
  throw new R(
@@ -5816,9 +5816,9 @@ class An {
5816
5816
  route: y ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
5817
5817
  status: D,
5818
5818
  abortTrigger: P,
5819
- category: P === "deadline" ? "request_timed_out" : P === "unexpected_abort" ? "connection_interrupted" : P ? "request_cancelled" : A instanceof R ? A.code : E ? "connection_interrupted" : "invalid_response",
5820
- responseHeadersMs: k === null ? null : Math.max(0, k - w),
5821
- responseBodyMs: k === null ? null : Math.max(0, Date.now() - k),
5819
+ category: P === "deadline" ? "request_timed_out" : P === "unexpected_abort" ? "connection_interrupted" : P ? "request_cancelled" : A instanceof R ? A.code : k ? "connection_interrupted" : "invalid_response",
5820
+ responseHeadersMs: E === null ? null : Math.max(0, E - w),
5821
+ responseBodyMs: E === null ? null : Math.max(0, Date.now() - E),
5822
5822
  owner: P === "deadline" ? "http_deadline" : P === "transport_disposed" ? "http_transport" : P && P !== "unexpected_abort" ? "conversation_query" : D === null ? "browser" : "http_response",
5823
5823
  elapsedMs: Math.max(0, Date.now() - w),
5824
5824
  attempt: c,
@@ -5843,7 +5843,7 @@ class An {
5843
5843
  );
5844
5844
  }
5845
5845
  throw A instanceof R && v ? new R(A.message, A.code, A.outcomeUnknown, { ...A.detail, ...v }, A.backendRefusal) : v ? new R(
5846
- E ? "The connection was interrupted. Please try again." : y ? "The conversation response could not be read. Please try again." : "The response could not be read. Please try again.",
5846
+ k ? "The connection was interrupted. Please try again." : y ? "The conversation response could not be read. Please try again." : "The response could not be read. Please try again.",
5847
5847
  "connection_interrupted",
5848
5848
  !0,
5849
5849
  v
@@ -5860,7 +5860,7 @@ function Ve(t) {
5860
5860
  }
5861
5861
  return t;
5862
5862
  }
5863
- function kn() {
5863
+ function En() {
5864
5864
  return Ve({
5865
5865
  authorityId: null,
5866
5866
  generation: 0,
@@ -5910,7 +5910,7 @@ function ve(t) {
5910
5910
  const e = t.origin.trim();
5911
5911
  return { ...t, origin: e.includes("://") ? new URL(e).origin : e.toLowerCase() };
5912
5912
  }
5913
- function En(t, e) {
5913
+ function kn(t, e) {
5914
5914
  return t.request(`/conversations/${encodeURIComponent(e)}`, {}, void 0, "GET", t.auth.client_kind === "extension" ? "extension" : void 0);
5915
5915
  }
5916
5916
  function Ti(t) {
@@ -5942,7 +5942,7 @@ function ia(t) {
5942
5942
  if (t.http.auth.client_kind === "embed") {
5943
5943
  const a = await t.http.request("/conversations", { ...r, page_url: n.origin ?? t.pageUrl() });
5944
5944
  Ue(t, i), o = { entries: await Promise.all(a.sessions.map(async (d) => ({
5945
- ...await En(t.http, d.id),
5945
+ ...await kn(t.http, d.id),
5946
5946
  ...typeof d.isActive == "boolean" ? { is_active: d.isActive } : {}
5947
5947
  }))), next_cursor: a.nextCursor };
5948
5948
  } else
@@ -5996,7 +5996,7 @@ class na {
5996
5996
  isActiveTurn: () => this.options.isActiveTurn(n),
5997
5997
  poll: async () => {
5998
5998
  try {
5999
- return await En(this.options.http, n);
5999
+ return await kn(this.options.http, n);
6000
6000
  } catch (c) {
6001
6001
  throw this.options.onError(c), c;
6002
6002
  }
@@ -6879,7 +6879,7 @@ function _e(t, e, s) {
6879
6879
  if (e.expectedGeneration !== t.generation || e.generation <= t.generation) return { state: t, effects: n };
6880
6880
  const r = e.adoptLocalSubmissions && !t.authorityId ? Object.fromEntries(Object.entries(t.clients).filter(([, o]) => t.selections[o]?.sessionId === null)) : {};
6881
6881
  i = {
6882
- ...kn(),
6882
+ ...En(),
6883
6883
  authorityId: e.authorityId,
6884
6884
  generation: e.generation,
6885
6885
  clients: r,
@@ -7321,7 +7321,7 @@ class Ra {
7321
7321
  features: K(ms()),
7322
7322
  interactions: K(fs()),
7323
7323
  modelSelection: ha(),
7324
- directory: kn(),
7324
+ directory: En(),
7325
7325
  conversation: sn()
7326
7326
  }) }),
7327
7327
  reducer: (n, r) => {
@@ -7333,7 +7333,7 @@ class Ra {
7333
7333
  return { state: Object.freeze({ revision: n.revision + 1, slices: Object.freeze({ ...n.slices, ...d }) }), effects: c.effects };
7334
7334
  }
7335
7335
  if (Ia(o)) {
7336
- const c = _e(n.slices.directory, o, n.slices.conversation), d = ks(Ss(n.slices.conversation, c.state, o.type === "directory.authority_replace" && o.adoptLocalSubmissions === !0)), u = Rs(n.slices.conversation, d.state, c.state, c.state.clients !== n.slices.directory.clients), l = u.state, h = Di(n.slices.conversation, l, c.state);
7336
+ const c = _e(n.slices.directory, o, n.slices.conversation), d = Es(Ss(n.slices.conversation, c.state, o.type === "directory.authority_replace" && o.adoptLocalSubmissions === !0)), u = Rs(n.slices.conversation, d.state, c.state, c.state.clients !== n.slices.directory.clients), l = u.state, h = Di(n.slices.conversation, l, c.state);
7337
7337
  return { state: h === n.slices.directory && l === n.slices.conversation ? n : Object.freeze({
7338
7338
  revision: n.revision + 1,
7339
7339
  slices: Object.freeze({ ...n.slices, directory: h, conversation: l })
@@ -7370,7 +7370,7 @@ class Ra {
7370
7370
  }).state);
7371
7371
  }
7372
7372
  d = Di(n.slices.conversation, c.state, d);
7373
- const l = ks(Ss(c.state, d)), h = Rs(c.state, l.state, d);
7373
+ const l = Es(Ss(c.state, d)), h = Rs(c.state, l.state, d);
7374
7374
  let f = n.slices;
7375
7375
  const m = [], p = c.interactionSources, g = f.account.authority;
7376
7376
  if (p && g && g.authorityId === p.authorityId && g.generation === p.generation) {
@@ -7455,7 +7455,7 @@ class Ra {
7455
7455
  }
7456
7456
  }
7457
7457
  }
7458
- const Aa = "pluno-product-agent-attachments", ka = 1, Ds = "files", Ea = 1440 * 60 * 1e3;
7458
+ const Aa = "pluno-product-agent-attachments", Ea = 1, Ds = "files", ka = 1440 * 60 * 1e3;
7459
7459
  async function Ta(t) {
7460
7460
  const e = await Ot();
7461
7461
  await Mn(e, "readwrite", (s) => s.put(t));
@@ -7483,7 +7483,7 @@ async function qn(t, e) {
7483
7483
  });
7484
7484
  });
7485
7485
  }
7486
- async function qa(t = Ea) {
7486
+ async function qa(t = ka) {
7487
7487
  const e = await Ot(), s = Date.now() - t;
7488
7488
  await Js(e, "readwrite", async (i) => {
7489
7489
  const n = i.index("lastUsedAt");
@@ -7492,7 +7492,7 @@ async function qa(t = Ea) {
7492
7492
  }
7493
7493
  function Ot() {
7494
7494
  return typeof indexedDB > "u" ? Promise.reject(new Error("Product Agent attachment storage is unavailable")) : new Promise((t, e) => {
7495
- const s = indexedDB.open(Aa, ka);
7495
+ const s = indexedDB.open(Aa, Ea);
7496
7496
  s.onupgradeneeded = () => {
7497
7497
  const n = s.result.createObjectStore(Ds, { keyPath: "attachmentId" });
7498
7498
  n.createIndex("lastUsedAt", "lastUsedAt", { unique: !1 }), n.createIndex("sessionId", "sessionId", { unique: !1 }), n.createIndex("origin", "origin", { unique: !1 });
@@ -8484,11 +8484,11 @@ class ll {
8484
8484
  return r;
8485
8485
  } catch (u) {
8486
8486
  if (i !== this.submissionGeneration) return null;
8487
- if (ki(u))
8487
+ if (Ei(u))
8488
8488
  for (const m of s.attachments ?? [])
8489
8489
  m.id && this.attachmentFiles.delete(m.id);
8490
8490
  const h = Q(u).code === "command_not_received";
8491
- !c && !ki(u) && (d || h || s.selectionKey !== void 0) && this.submissionRetries.set(r, {
8491
+ !c && !Ei(u) && (d || h || s.selectionKey !== void 0) && this.submissionRetries.set(r, {
8492
8492
  retry: async () => (d && await this.connect(), this.sendMessageNow(e, { ...s, reconcileAcceptance: !d && !h }, i)),
8493
8493
  attachmentIds: (s.attachments ?? []).flatMap((m) => m.id ? [m.id] : [])
8494
8494
  });
@@ -8791,8 +8791,7 @@ function is(t) {
8791
8791
  "status",
8792
8792
  "reason",
8793
8793
  "phase",
8794
- "elapsedMs",
8795
- "e2bEventSequence"
8794
+ "elapsedMs"
8796
8795
  ]) {
8797
8796
  const d = t[c];
8798
8797
  (typeof d == "string" || typeof d == "number" || typeof d == "boolean" || d === null) && (e[c] = d);
@@ -8865,7 +8864,7 @@ function Ac(t, e = Math.random) {
8865
8864
  const s = Math.min(Ns, gc * 2 ** t), i = 1 - Li + e() * Li * 2;
8866
8865
  return Math.min(Ns, Math.round(s * i));
8867
8866
  }
8868
- function kc(t) {
8867
+ function Ec(t) {
8869
8868
  const e = t.split(".")[1];
8870
8869
  if (!e)
8871
8870
  return null;
@@ -9141,19 +9140,19 @@ class xt {
9141
9140
  requestId: p.requestId,
9142
9141
  clientMessageId: p.userMessageId,
9143
9142
  sessionId: p.sessionId
9144
- }), b = (w, k) => _.measure(w, () => at(y, k));
9143
+ }), b = (w, E) => _.measure(w, () => at(y, E));
9145
9144
  let I = p.contextPreparation ?? { pageContent: "", sessionTabs: [] };
9146
9145
  if (p.contextPreparation === null) {
9147
- await b("first_frame", () => new Promise((k) => {
9146
+ await b("first_frame", () => new Promise((E) => {
9148
9147
  if (document.visibilityState !== "visible") {
9149
- setTimeout(k, 0);
9148
+ setTimeout(E, 0);
9150
9149
  return;
9151
9150
  }
9152
- const E = () => {
9153
- cancelAnimationFrame(S), document.removeEventListener("visibilitychange", D), setTimeout(k, 0);
9151
+ const k = () => {
9152
+ cancelAnimationFrame(S), document.removeEventListener("visibilitychange", D), setTimeout(E, 0);
9154
9153
  }, D = () => {
9155
- document.visibilityState !== "visible" && E();
9156
- }, S = requestAnimationFrame(E);
9154
+ document.visibilityState !== "visible" && k();
9155
+ }, S = requestAnimationFrame(k);
9157
9156
  document.addEventListener("visibilitychange", D);
9158
9157
  }));
9159
9158
  const w = p.context.page;
@@ -9209,14 +9208,14 @@ class xt {
9209
9208
  const c = this.clientRuntime.engine.getState().slices.conversation, d = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : zt(n);
9210
9209
  if (this.authenticatedUserId && !c.submissionOrder.length && !Object.keys(c.operations).length) {
9211
9210
  const p = this.queuedClientEvents.filter((_) => _.type === "chat.user_message"), g = d ? JSON.parse(d) : p.length ? Kr(c, p.map((_) => {
9212
- const { type: b, ...I } = _, w = this.clientRuntime.engine.getState().slices.directory, k = w.clients[this.modelClientScopeId];
9211
+ const { type: b, ...I } = _, w = this.clientRuntime.engine.getState().slices.directory, E = w.clients[this.modelClientScopeId];
9213
9212
  return {
9214
9213
  command: { type: b, request_id: _.clientMessageId, payload: JSON.parse(JSON.stringify(I)) },
9215
9214
  requestedModel: _.model ?? null,
9216
9215
  clientScopeId: this.modelClientScopeId,
9217
- conversationScopeId: k,
9216
+ conversationScopeId: E,
9218
9217
  viewId: `sdk:${this.modelClientScopeId}`,
9219
- sessionId: _.sessionId ?? w.selections[k]?.sessionId ?? null,
9218
+ sessionId: _.sessionId ?? w.selections[E]?.sessionId ?? null,
9220
9219
  entrySurface: this.options.entrySurface,
9221
9220
  submittedAt: Date.now()
9222
9221
  };
@@ -9277,21 +9276,21 @@ class xt {
9277
9276
  const I = this.firstResponseTimersByClientMessageId.get(b.userMessageId);
9278
9277
  I && (I.sessionId = b.sessionId), this.emit("ack", { clientMessageId: b.userMessageId, sessionId: b.sessionId });
9279
9278
  const w = b.sessionId;
9280
- w && this.getState().sessionId === w && this.directoryHttp.request(`/sessions/${encodeURIComponent(w)}/history`, { limit: 200 }).then((k) => {
9281
- i() && this.getState().sessionId === w && this.state.status !== "closed" && ts(this.clientRuntime, this.modelClientScopeId, w, k.turns);
9282
- }).catch((k) => {
9283
- i() && this.getState().sessionId === w && this.handleDirectoryTransportError(k);
9279
+ w && this.getState().sessionId === w && this.directoryHttp.request(`/sessions/${encodeURIComponent(w)}/history`, { limit: 200 }).then((E) => {
9280
+ i() && this.getState().sessionId === w && this.state.status !== "closed" && ts(this.clientRuntime, this.modelClientScopeId, w, E.turns);
9281
+ }).catch((E) => {
9282
+ i() && this.getState().sessionId === w && this.handleDirectoryTransportError(E);
9284
9283
  });
9285
9284
  }
9286
9285
  (b.cancelled || b.delivery === "failed") && this.clearFirstResponseTimer(b.userMessageId);
9287
9286
  }
9288
9287
  for (const [b, I] of Object.entries(p.directory.clients)) {
9289
9288
  if (!b.startsWith(`background:${this.modelClientScopeId}:`)) continue;
9290
- const w = pe(p.conversation, p.directory, I), k = w.sessionId ? p.conversation.sessions[w.sessionId] : void 0;
9291
- if (this.firstResponseTimersByClientMessageId.size && (u(Wt(w, k?.queries.current, this.options.backendUrl).messages, w.sessionId), ["failed", "stopped"].includes(w.activity.phase)))
9292
- for (const D of ne(k?.execution)) this.clearFirstResponseTimer(D);
9293
- const E = w.activity.phase === "completed" && ne(k?.execution).some((D) => this.firstResponseTimersByClientMessageId.has(D));
9294
- (y && w.sessionId === this.getState().sessionId || !E && ["completed", "failed", "stopped"].includes(w.activity.phase)) && this.directoryScope.detach(b);
9289
+ const w = pe(p.conversation, p.directory, I), E = w.sessionId ? p.conversation.sessions[w.sessionId] : void 0;
9290
+ if (this.firstResponseTimersByClientMessageId.size && (u(Wt(w, E?.queries.current, this.options.backendUrl).messages, w.sessionId), ["failed", "stopped"].includes(w.activity.phase)))
9291
+ for (const D of ne(E?.execution)) this.clearFirstResponseTimer(D);
9292
+ const k = w.activity.phase === "completed" && ne(E?.execution).some((D) => this.firstResponseTimersByClientMessageId.has(D));
9293
+ (y && w.sessionId === this.getState().sessionId || !k && ["completed", "failed", "stopped"].includes(w.activity.phase)) && this.directoryScope.detach(b);
9295
9294
  }
9296
9295
  const _ = this.getState();
9297
9296
  u(_.messages, _.sessionId);
@@ -9408,7 +9407,7 @@ class xt {
9408
9407
  throw new ce("Pluno token request was cancelled", !0);
9409
9408
  if (typeof d != "string" || !d.trim())
9410
9409
  throw new ce("Chat setup did not return a session. Contact your app administrator, then try again.", !1);
9411
- return this.token = d, this.tokenExpiresAtMs = kc(d), d;
9410
+ return this.token = d, this.tokenExpiresAtMs = Ec(d), d;
9412
9411
  } finally {
9413
9412
  a !== null && window.clearTimeout(a);
9414
9413
  }
@@ -9570,7 +9569,7 @@ class xt {
9570
9569
  }
9571
9570
  destroy() {
9572
9571
  if (!this.clientRuntime.isDisposed) {
9573
- this.disconnect(), this.clearAllFirstResponseTimers(), this.locationChangeCleanup?.(), this.locationChangeCleanup = null, this.cleanupSessionBrowserApis(), this.pageLifecycleCleanup?.(), this.pageLifecycleCleanup = null, this.activeBrowserToolCalls.clear(), kd(this.options.clientId), this.transportIdentity.release(), this.networkCaptureCleanup?.(), this.networkCaptureCleanup = null, this.networkBatchTimer !== null && (window.clearTimeout(this.networkBatchTimer), this.networkBatchTimer = null), this.queuedNetworkEvents = [];
9572
+ this.disconnect(), this.clearAllFirstResponseTimers(), this.locationChangeCleanup?.(), this.locationChangeCleanup = null, this.cleanupSessionBrowserApis(), this.pageLifecycleCleanup?.(), this.pageLifecycleCleanup = null, this.activeBrowserToolCalls.clear(), Ed(this.options.clientId), this.transportIdentity.release(), this.networkCaptureCleanup?.(), this.networkCaptureCleanup = null, this.networkBatchTimer !== null && (window.clearTimeout(this.networkBatchTimer), this.networkBatchTimer = null), this.queuedNetworkEvents = [];
9574
9573
  for (const e of Object.values(this.listeners))
9575
9574
  e?.clear();
9576
9575
  this.accountListeners.clear(), this.interactionListeners.clear(), this.conversationAdapterGeneration++, this.conversationObservation?.dispose(), this.conversationUnsubscribe?.(), this.directoryObservation.dispose(), this.directoryHttp.dispose(), this.clientRuntime.dispose();
@@ -9662,8 +9661,8 @@ class xt {
9662
9661
  if (!(w && !w.cancelled && w.delivery !== "accepted" && w.delivery !== "failed"))
9663
9662
  if (_?.(), b?.(), w?.delivery === "failed" && !w.cancelled) y(new Error(w.error?.message ?? "Message delivery failed."));
9664
9663
  else {
9665
- const k = w?.invocation === "user" && w.contextPreparation?.pageContent ? w.context.page?.url : null;
9666
- w?.delivery === "accepted" && !w.cancelled && typeof k == "string" && c === this.submissionIntentRevision && p === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = k), g(w?.delivery === "accepted" && !w.cancelled ? r : null);
9664
+ const E = w?.invocation === "user" && w.contextPreparation?.pageContent ? w.context.page?.url : null;
9665
+ w?.delivery === "accepted" && !w.cancelled && typeof E == "string" && c === this.submissionIntentRevision && p === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = E), g(w?.delivery === "accepted" && !w.cancelled ? r : null);
9667
9666
  }
9668
9667
  };
9669
9668
  _ = this.clientRuntime.engine.subscribe(I), b = this.clientRuntime.onDispose(() => {
@@ -9722,7 +9721,7 @@ class xt {
9722
9721
  } }), !0);
9723
9722
  }
9724
9723
  createLocalAttachment(e) {
9725
- this.options.productVariant === "customer_embedded" && Ed(e);
9724
+ this.options.productVariant === "customer_embedded" && kd(e);
9726
9725
  const s = W(), i = {
9727
9726
  id: s,
9728
9727
  name: e.name || "attachment",
@@ -10793,12 +10792,12 @@ class xt {
10793
10792
  }
10794
10793
  const ds = /* @__PURE__ */ new WeakMap();
10795
10794
  function Bn(t) {
10796
- const e = window.__plunoProductAgentNetworkCapture ?? Ec();
10795
+ const e = window.__plunoProductAgentNetworkCapture ?? kc();
10797
10796
  return e.subscribers.add(t), () => {
10798
10797
  e.subscribers.delete(t), !(e.subscribers.size > 0) && (e.destroy(), window.__plunoProductAgentNetworkCapture === e && delete window.__plunoProductAgentNetworkCapture);
10799
10798
  };
10800
10799
  }
10801
- function Ec() {
10800
+ function kc() {
10802
10801
  const t = /* @__PURE__ */ new Set(), e = (h) => {
10803
10802
  t.forEach((f) => {
10804
10803
  try {
@@ -10816,7 +10815,7 @@ function Ec() {
10816
10815
  }
10817
10816
  try {
10818
10817
  const y = f instanceof Request ? f : null, _ = Pd(f, y), b = Qn(m?.headers ?? y?.headers);
10819
- if (!ke(_, b, m?.body)) {
10818
+ if (!Ee(_, b, m?.body)) {
10820
10819
  const w = {
10821
10820
  requestId: hs("fetch"),
10822
10821
  url: de(_, os),
@@ -10827,19 +10826,19 @@ function Ec() {
10827
10826
  startedAt: new Date(p).toISOString()
10828
10827
  };
10829
10828
  g.then(
10830
- (k) => {
10831
- xd(k, w, p, e).catch(() => {
10829
+ (E) => {
10830
+ xd(E, w, p, e).catch(() => {
10832
10831
  e({
10833
10832
  ...w,
10834
- responseStatus: k.status,
10833
+ responseStatus: E.status,
10835
10834
  durationMs: Date.now() - p
10836
10835
  });
10837
10836
  });
10838
10837
  },
10839
- (k) => {
10838
+ (E) => {
10840
10839
  e({
10841
10840
  ...w,
10842
- errorText: de(k instanceof Error ? k.message : String(k)),
10841
+ errorText: de(E instanceof Error ? E.message : String(E)),
10843
10842
  durationMs: Date.now() - p
10844
10843
  });
10845
10844
  }
@@ -10857,15 +10856,15 @@ function Ec() {
10857
10856
  requestHeaders: {},
10858
10857
  startedAtMs: Date.now(),
10859
10858
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
10860
- excluded: ke(b)
10859
+ excluded: Ee(b)
10861
10860
  }), _;
10862
10861
  }, c = function(f, m) {
10863
10862
  const p = n.call(this, f, m), g = ds.get(this);
10864
- return g && Object.keys(g.requestHeaders).length < Ys && (g.requestHeaders[f] = si(f, m), g.excluded = g.excluded || ke(g.url, g.requestHeaders)), p;
10863
+ return g && Object.keys(g.requestHeaders).length < Ys && (g.requestHeaders[f] = si(f, m), g.excluded = g.excluded || Ee(g.url, g.requestHeaders)), p;
10865
10864
  }, d = function(f) {
10866
10865
  try {
10867
10866
  const m = ds.get(this);
10868
- m && (m.excluded = m.excluded || ke(m.url, m.requestHeaders, f), m.requestBody = Xi(f), m.excluded || this.addEventListener(
10867
+ m && (m.excluded = m.excluded || Ee(m.url, m.requestHeaders, f), m.requestBody = Xi(f), m.excluded || this.addEventListener(
10869
10868
  "loadend",
10870
10869
  () => {
10871
10870
  queueMicrotask(() => {
@@ -10917,7 +10916,7 @@ function Ec() {
10917
10916
  u = new PerformanceObserver((h) => {
10918
10917
  for (const f of h.getEntries()) {
10919
10918
  const m = f;
10920
- if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || ke(m.name))
10919
+ if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || Ee(m.name))
10921
10920
  continue;
10922
10921
  const p = performance.timeOrigin + m.startTime;
10923
10922
  e({
@@ -11325,12 +11324,12 @@ function Wc(t, e) {
11325
11324
  const I = b.getAttribute("data-testid") || b.getAttribute("data-test") || b.getAttribute("data-qa") || b.getAttribute("data-cy") || "";
11326
11325
  return `${b.tagName.toLowerCase()}|${m(b)}|${I}`;
11327
11326
  }, g = (b, I, w) => {
11328
- const k = (E, D) => {
11329
- const S = E.tagName.toLowerCase(), q = window.getComputedStyle(E), A = u.has(E);
11330
- if (f >= 1e3 && !A || w.has(E) || r.has(S) || E.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || q.display === "none" || q.visibility === "hidden")
11327
+ const E = (k, D) => {
11328
+ const S = k.tagName.toLowerCase(), q = window.getComputedStyle(k), A = u.has(k);
11329
+ if (f >= 1e3 && !A || w.has(k) || r.has(S) || k.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || q.display === "none" || q.visibility === "hidden")
11331
11330
  return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
11332
11331
  f += 1;
11333
- const P = m(E), T = zn(E), v = a.has(P) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(S) || S === "a" && E.hasAttribute("href"), C = Array.from(E.children).filter((O) => O instanceof HTMLElement), U = /* @__PURE__ */ new Map();
11332
+ const P = m(k), T = zn(k), v = a.has(P) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(S) || S === "a" && k.hasAttribute("href"), C = Array.from(k.children).filter((O) => O instanceof HTMLElement), U = /* @__PURE__ */ new Map();
11334
11333
  for (const O of C) {
11335
11334
  const B = p(O);
11336
11335
  U.set(B, (U.get(B) ?? 0) + 1);
@@ -11347,19 +11346,19 @@ function Wc(t, e) {
11347
11346
  ii.has(B) || (Ut.push([`… ${$.get(B) ?? 0} similar siblings omitted`]), ii.add(B));
11348
11347
  continue;
11349
11348
  }
11350
- const ci = k(O, D);
11349
+ const ci = E(O, D);
11351
11350
  ni.push(ci), Ut.push(ci.lines);
11352
11351
  }
11353
11352
  const Nt = [];
11354
- if (E.shadowRoot)
11355
- for (const O of Array.from(E.shadowRoot.children))
11356
- O instanceof HTMLElement && Nt.push(k(O, D + 1));
11353
+ if (k.shadowRoot)
11354
+ for (const O of Array.from(k.shadowRoot.children))
11355
+ O instanceof HTMLElement && Nt.push(E(O, D + 1));
11357
11356
  const Xe = [...ni, ...Nt], jt = T.length > 0 || v || Xe.some((O) => O.hasUsefulContent), ri = qe(
11358
11357
  [T, ...Xe.map((O) => O.textPreview)].filter(Boolean).join(" ")
11359
- ).slice(0, 180), rr = E.hasAttribute("contenteditable") && (T.length > 0 || !E.querySelector("[contenteditable]")), oi = d.some((O) => E.hasAttribute(O)) || !!P || rr, Bt = (E.getClientRects().length > 0 || q.display === "contents") && (s.has(S) || oi || A) && (jt || A) && (!n.has(S) || jt || oi || A), Lt = Bt ? 1 : 0, Oe = [];
11358
+ ).slice(0, 180), rr = k.hasAttribute("contenteditable") && (T.length > 0 || !k.querySelector("[contenteditable]")), oi = d.some((O) => k.hasAttribute(O)) || !!P || rr, Bt = (k.getClientRects().length > 0 || q.display === "contents") && (s.has(S) || oi || A) && (jt || A) && (!n.has(S) || jt || oi || A), Lt = Bt ? 1 : 0, Oe = [];
11360
11359
  if (Bt) {
11361
11360
  const O = Xe.some((ue) => ue.containsTextElement), B = i.has(S) && !O ? ri : T;
11362
- Oe.push($n(E, c, o, B.slice(0, 180)));
11361
+ Oe.push($n(k, c, o, B.slice(0, 180)));
11363
11362
  }
11364
11363
  for (const O of Ut)
11365
11364
  Oe.push(...ot(O, Lt));
@@ -11381,7 +11380,7 @@ function Wc(t, e) {
11381
11380
  containsTextElement: i.has(S) || Xe.some((O) => O.containsTextElement)
11382
11381
  };
11383
11382
  };
11384
- return [`--- ${I} ---`, ...k(b, 0).lines].join(`
11383
+ return [`--- ${I} ---`, ...E(b, 0).lines].join(`
11385
11384
  `);
11386
11385
  }, y = [], _ = qe(window.getSelection()?.toString() ?? "");
11387
11386
  _ && y.push(`--- selected text ---
@@ -11627,7 +11626,7 @@ function Hn(t, e) {
11627
11626
  id: typeof n.id == "string" ? n.id : String(s.id ?? crypto.randomUUID()),
11628
11627
  role: "assistant",
11629
11628
  ...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
11630
- content: Ee(
11629
+ content: ke(
11631
11630
  Gi(n.content),
11632
11631
  e
11633
11632
  ),
@@ -11644,7 +11643,7 @@ function Hn(t, e) {
11644
11643
  id: String(s.id ?? crypto.randomUUID()),
11645
11644
  role: r,
11646
11645
  ...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
11647
- content: Ee(
11646
+ content: ke(
11648
11647
  Gi(n.content),
11649
11648
  e
11650
11649
  ),
@@ -12038,7 +12037,7 @@ function Ad(t, e) {
12038
12037
  ...e.filter((i) => !s.has(i.callId))
12039
12038
  ];
12040
12039
  }
12041
- function kd(t) {
12040
+ function Ed(t) {
12042
12041
  try {
12043
12042
  window.sessionStorage.removeItem(`${Pt}${t}`);
12044
12043
  } catch {
@@ -12077,7 +12076,7 @@ function Wn(t, e) {
12077
12076
  function Gn(t) {
12078
12077
  return t.type || qd(t.name) || "application/octet-stream";
12079
12078
  }
12080
- function Ed(t) {
12079
+ function kd(t) {
12081
12080
  Jn({
12082
12081
  name: t.name,
12083
12082
  mimeType: Gn(t),
@@ -12155,7 +12154,7 @@ function Qn(t) {
12155
12154
  return e;
12156
12155
  }
12157
12156
  function si(t, e) {
12158
- return ir(t) ? Dt : de(Et(e), wc);
12157
+ return ir(t) ? Dt : de(kt(e), wc);
12159
12158
  }
12160
12159
  function Pd(t, e) {
12161
12160
  return typeof t == "string" ? t : t instanceof URL ? t.toString() : e?.url ?? "";
@@ -12226,11 +12225,11 @@ function Yi(t) {
12226
12225
  return t;
12227
12226
  const e = t.trim();
12228
12227
  if (!e.startsWith("{") && !e.startsWith("["))
12229
- return Et(t);
12228
+ return kt(t);
12230
12229
  try {
12231
12230
  return JSON.stringify(te(JSON.parse(t)));
12232
12231
  } catch {
12233
- return Et(t);
12232
+ return kt(t);
12234
12233
  }
12235
12234
  }
12236
12235
  function Xn(t) {
@@ -12239,7 +12238,7 @@ function Xn(t) {
12239
12238
  const e = t.get("content-type")?.toLowerCase() ?? "", s = t.get("content-length"), i = Number(s);
12240
12239
  return s !== null && Number.isInteger(i) && i >= 0 && i <= Xs && (e.startsWith("text/") || e.includes("json") || e.includes("javascript"));
12241
12240
  }
12242
- function ke(t, e = {}, s) {
12241
+ function Ee(t, e = {}, s) {
12243
12242
  if (Bd(s))
12244
12243
  return !0;
12245
12244
  const i = Object.entries(e).find(([n]) => n.toLowerCase() === "content-type")?.[1]?.toLowerCase();
@@ -12256,7 +12255,7 @@ function ke(t, e = {}, s) {
12256
12255
  }
12257
12256
  }
12258
12257
  function jd(t, e) {
12259
- if (ke(t))
12258
+ if (Ee(t))
12260
12259
  return !0;
12261
12260
  try {
12262
12261
  const s = new URL(t, location.href), i = new URL(e);
@@ -12322,11 +12321,11 @@ function Kd(t) {
12322
12321
  }
12323
12322
  const Dt = "[REDACTED_SECRET]", le = "[REDACTED_TOKEN]", Vd = "[REDACTED_SIGNED_URL]", Wd = 20, Gd = /^(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|token|api_key|apiKey|apikey|key|secret|signature|sig|password|passwd|pwd|code|state|session|jwt|csrf|csrfToken|xsrf|xsrfToken)$/i, Zn = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, er = /\bBasic\s+[A-Za-z0-9+/=-]{12,}/gi, tr = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, sr = /\b(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|api_key|apiKey|apikey|client_secret|clientSecret|password|secret|token|jwt|csrf|csrfToken|xsrf|xsrfToken)\b\s*[:=]\s*["']?[^"',&\s}]+/gi, Jd = /\bhttps?:\/\/[^\s"'<>]+(?:X-Amz-Signature|X-Goog-Signature|Signature|sig=)[^\s"'<>]*/gi, Qd = /\bhttps?:\/\/[^\s"'<>]+/gi, Xd = /[),.;\]]+$/;
12324
12323
  function te(t) {
12325
- return kt(t, 0, /* @__PURE__ */ new WeakSet());
12324
+ return Et(t, 0, /* @__PURE__ */ new WeakSet());
12326
12325
  }
12327
- function kt(t, e, s) {
12326
+ function Et(t, e, s) {
12328
12327
  if (typeof t == "string")
12329
- return t.startsWith("data:image/") || t.startsWith("data:application/pdf;") ? t : Et(t);
12328
+ return t.startsWith("data:image/") || t.startsWith("data:application/pdf;") ? t : kt(t);
12330
12329
  if (t === null || typeof t != "object")
12331
12330
  return t;
12332
12331
  if (e >= Wd)
@@ -12334,10 +12333,10 @@ function kt(t, e, s) {
12334
12333
  if (s.has(t))
12335
12334
  return "[REDACTED_CIRCULAR]";
12336
12335
  if (s.add(t), Array.isArray(t))
12337
- return t.map((n) => kt(n, e + 1, s));
12336
+ return t.map((n) => Et(n, e + 1, s));
12338
12337
  const i = {};
12339
12338
  for (const [n, r] of Object.entries(t))
12340
- n === "pageContent" ? i[n] = r : ir(n) ? i[n] = Dt : i[n] = n.toLowerCase() === "url" ? Yd(r) : kt(r, e + 1, s);
12339
+ n === "pageContent" ? i[n] = r : ir(n) ? i[n] = Dt : i[n] = n.toLowerCase() === "url" ? Yd(r) : Et(r, e + 1, s);
12341
12340
  return i;
12342
12341
  }
12343
12342
  function ir(t) {
@@ -12345,7 +12344,7 @@ function ir(t) {
12345
12344
  return e.includes("authorization") || e.includes("cookie") || e.includes("password") || e.includes("passwd") || e === "pwd" || e.includes("secret") || e === "token" || e.endsWith("token") || e.includes("apikey") || e.includes("csrf") || e.includes("xsrf") || e === "jwt" || e === "session" || e === "signature" || e.includes("privatekey");
12346
12345
  }
12347
12346
  function Yd(t) {
12348
- return typeof t == "string" ? nr(t) : kt(t, 0, /* @__PURE__ */ new WeakSet());
12347
+ return typeof t == "string" ? nr(t) : Et(t, 0, /* @__PURE__ */ new WeakSet());
12349
12348
  }
12350
12349
  function nr(t) {
12351
12350
  try {
@@ -12357,7 +12356,7 @@ function nr(t) {
12357
12356
  return Zd(t);
12358
12357
  }
12359
12358
  }
12360
- function Et(t) {
12359
+ function kt(t) {
12361
12360
  return t.replace(Jd, Vd).replace(Qd, el).replace(Zn, `Bearer ${le}`).replace(er, `Basic ${le}`).replace(tr, le).replace(sr, (e, s) => `${s}: ${Dt}`);
12362
12361
  }
12363
12362
  function Zd(t) {
@@ -12397,7 +12396,7 @@ export {
12397
12396
  ec as formatProductAgentTaskPageTitle,
12398
12397
  pl as getProductAgentOriginAccessErrorMessage,
12399
12398
  hl as installProductAgentPageEnvironment,
12400
- ki as isProductAgentAuthReconnectError,
12399
+ Ei as isProductAgentAuthReconnectError,
12401
12400
  dl as isProductAgentRuntimeCommand,
12402
12401
  Xo as mergeProductAgentEntityPages,
12403
12402
  yt as normalizeProductAgentEntityPage,
@@ -12406,5 +12405,5 @@ export {
12406
12405
  il as resolveProductAgentComposerAction,
12407
12406
  sl as resolveProductAgentWidgetPresentation,
12408
12407
  Yo as selectProductAgentQueryEntities,
12409
- Ed as validateProductAgentProviderInputFile
12408
+ kd as validateProductAgentProviderInputFile
12410
12409
  };
@@ -846,7 +846,7 @@ function au(t, e = null) {
846
846
  } : void 0);
847
847
  return { ...s, ...a ? { auth: a } : {}, submissionGate: r };
848
848
  }
849
- const cu = "0.1.321", Cn = {
849
+ const cu = "0.1.323", Cn = {
850
850
  version: cu
851
851
  };
852
852
  function pi(t) {
@@ -1106,7 +1106,7 @@ function gu(t, e, n, s) {
1106
1106
  for (const b of m.removed_items) c = Gi(c, b);
1107
1107
  for (const b of m.items) c = No(c, b);
1108
1108
  for (const b of m.streams) c = Wc(c, b);
1109
- if (c = Uo(c, m.execution), c = Gi(c, {
1109
+ if (c = Uo(c, m.execution), m.follow_ups_version === 0 && m.follow_ups.length === 0 ? c = { ...c, followUps: [], followUpsVersion: Number.MAX_SAFE_INTEGER } : c = Gi(c, {
1110
1110
  type: "conversation.follow_ups.updated",
1111
1111
  conversation_id: m.conversation_id,
1112
1112
  version: m.follow_ups_version,
@@ -5280,7 +5280,7 @@ function Dp(t) {
5280
5280
  const f = h[0];
5281
5281
  if (r.before !== null && f.next_cursor === r.before)
5282
5282
  throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
5283
- const m = h.reduce((y, b) => b.execution.version > y.version ? b.execution : y, f.execution), g = h.reduce((y, b) => b.follow_ups_version > y.follow_ups_version ? b : y, f);
5283
+ const m = h.reduce((y, b) => b.execution.version > y.version ? b.execution : y, f.execution), g = h.find((y) => y.follow_ups_version === 0 && y.follow_ups.length === 0) ?? h.reduce((y, b) => b.follow_ups_version > y.follow_ups_version ? b : y, f);
5284
5284
  return { snapshot: {
5285
5285
  ...f,
5286
5286
  execution: m,
@@ -7995,8 +7995,7 @@ function co(t) {
7995
7995
  "status",
7996
7996
  "reason",
7997
7997
  "phase",
7998
- "elapsedMs",
7999
- "e2bEventSequence"
7998
+ "elapsedMs"
8000
7999
  ]) {
8001
8000
  const l = t[c];
8002
8001
  (typeof l == "string" || typeof l == "number" || typeof l == "boolean" || l === null) && (e[c] = l);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluno/product-agent-web",
3
- "version": "0.1.321",
3
+ "version": "0.1.323",
4
4
  "description": "Browser SDK and default widget for embedding Pluno Product Agent into customer web apps.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1,10 +0,0 @@
1
- export declare class AssistantDeltaReplayGuard {
2
- private readonly receivedBySession;
3
- accept(event: {
4
- sessionId?: unknown;
5
- runId?: unknown;
6
- e2bEventSequence?: unknown;
7
- }): boolean;
8
- forget(sessionId: string): void;
9
- clear(): void;
10
- }