@pluno/product-agent-web 0.1.269 → 0.1.270

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.
@@ -43,6 +43,7 @@ export declare class ProductAgentBackendTransport extends EventTarget {
43
43
  get connectionId(): string | null;
44
44
  restoreExecutor(connectionId: string): Promise<void>;
45
45
  get connectionAttempt(): import("./socketIOTransport").ProductAgentConnectionAttempt | null;
46
+ get connectionActivity(): import("./socketIOTransport").ProductAgentSocketActivity;
46
47
  retryReadiness(): void;
47
48
  private startInitialReadinessBudget;
48
49
  private resetBootstrap;
@@ -17,6 +17,19 @@ export type ProductAgentConnectionAttempt = {
17
17
  reconnectAttempt: number;
18
18
  startedAt: number;
19
19
  };
20
+ export type ProductAgentSocketActivity = {
21
+ lastPacketReceivedAt: number | null;
22
+ lastHeartbeatReceivedAt: number | null;
23
+ lastHeartbeatQueuedAt: number | null;
24
+ lastDisconnect: {
25
+ occurredAt: number;
26
+ reason: string;
27
+ connectionAttemptId: string | null;
28
+ lastPacketReceivedAt: number | null;
29
+ lastHeartbeatReceivedAt: number | null;
30
+ lastHeartbeatQueuedAt: number | null;
31
+ } | null;
32
+ };
20
33
  type Ready = {
21
34
  protocol: number;
22
35
  role: string;
@@ -67,6 +80,8 @@ export declare class ProductAgentSocketIOTransport {
67
80
  private readinessTimer;
68
81
  private attemptCount;
69
82
  private attempt;
83
+ private activity;
84
+ get connectionActivity(): ProductAgentSocketActivity;
70
85
  constructor(options: Options);
71
86
  connect(): void;
72
87
  get connectionId(): string | null;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Y(s,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"]}:s??{allowed:!0,reason:"allowed",actions:[]}}function m(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class w{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=m(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=m(e),this.trailingLoad=null,this.publish())}reset(){this.state=m(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,i=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:i},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||i!==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||i!==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 y(s){const e={},t=[];for(const i of s.entities)e[i.id]||t.push(i.id),e[i.id]=i;return{entitiesById:e,ids:t,nextCursor:s.nextCursor}}function j(s,e,t){if(t==="replace"||s===null)return e;const i={...s.entitiesById,...e.entitiesById},n=[...s.ids];for(const r of e.ids)s.entitiesById[r]||n.push(r);return{entitiesById:i,ids:n,nextCursor:e.nextCursor}}function z(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function X(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function ee(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function te(s){return s?s.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(s.submissionGate.reason)?{state:"action_required",reason:s.submissionGate.reason}:{state:"hidden"}:s.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:s.creditLimit!==null&&s.creditLimit>0&&s.creditsRemaining!==null&&s.creditsRemaining>0&&s.creditsRemaining/s.creditLimit<=.2?{state:"low_credits"}:s.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function se(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function ie(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const $="Pluno is reconnecting. Try again in a moment.";function K(s){return(s instanceof Error?s.message:s)===$}class ne{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new w(`${e}:recent`,async({cursor:n})=>y(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),j),this.pinnedQuery=new w(`${e}:pinned`,async()=>y({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(),i=[...v(t.data),...v(e.data)],n=new Map(i.map(d=>[d.id,d])),r=Array.from(n.values()).map(d=>this.applyOverrides(d,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(d=>!n.has(d.id)).reverse(),a=e.data||t.data||o.length>0?y({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:a,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,i=>({...i,isActive:t}))}setPinned(e,t){const i={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,i),this.updateEntity(e,n=>({...n,isPinned:t})),i}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,i){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:i})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,i=>({...i,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...v(this.pinnedQuery.getState().data),...v(this.recentQuery.getState().data)],t=new Set(e.map(i=>i.id));for(const i of this.optimisticEntities.keys())t.has(i)&&this.optimisticEntities.delete(i);for(const i of e)this.applyOverrides(i,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const i=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...i.sessions),t=i.nextCursor}while(t);return e}applyOverrides(e,t){let i=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):i={...i,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):i={...i,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(i={...i,customTitle:this.titleOverrides.get(e.id)??null}),i}updateProjection(){this.publish()}updateEntity(e,t){const i=this.optimisticEntities.get(e);i&&this.optimisticEntities.set(e,t(i)),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 v(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function re(s,e){return s.status==="error"||e.status==="error"?"error":s.status==="loading"||e.status==="loading"?"loading":s.status==="refreshing"||e.status==="refreshing"?"refreshing":s.status==="loading_more"?"loading_more":s.status==="ready"||e.status==="ready"?"ready":"not_requested"}function O(s){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(s);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function b(s){if(s===null||typeof s=="string"||typeof s=="boolean")return!0;if(typeof s=="number")return Number.isFinite(s);if(Array.isArray(s))return s.every(b);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(b)}function U(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(U),Object.freeze(s)),s}function oe(s){if(!b(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function ae(s,e){if(!e)return!1;const t=s.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const i=Object.values(s.items).sort((r,o)=>O(r.created_at).localeCompare(O(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of i)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&s.streams[r.id]?.state==="finished"&&s.streams[r.id].revision>=r.data.revision))return!0;return!1}class de{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(P).map(i=>[this.getDecisionKey(i),i])),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 i=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(i);if(n&&n.version>=t.version)continue;if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");const r=n?.payload.kind==="personal_channel"&&n.lifecycle==="completed"?"completed":t.lifecycle,o=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,U(oe({...t,lifecycle:r,payload:o}))),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={share:null,integrations:[],channel:null},i=e?this.conversationReader(e):null;if(!i)return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,o)=>r.version-o.version||r.id.localeCompare(o.id));for(const r of n){const o=r.payload;if(o.kind==="sharing"){if(t.share=null,!o.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const a=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:o.variant,userPrompt:a?.type==="user_message"?a.data.content:"",assistantAnswer:""},terminal:!o.wait_for_terminal||ae(i,r.user_message_id)}}else o.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:o.request_id,appSlug:o.app_slug,appName:o.app_name,appLogo:o.app_logo??void 0,expiresAt:o.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(o.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:o.request_id,channel:o.channel,managementUrl:o.management_url},lifecycle: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(P).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));return i!==void 0&&i>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 i=this.scheduledEligibility.get(this.getExactKey(e));if(i!==void 0&&i>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 i=this.getExactKey(e),n=this.scheduledEligibility.get(i);return n!==void 0?n:(this.scheduledEligibility.set(i,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(i=>i>e),...Array.from(this.decisions.values()).map(i=>i.nextEligibleAt?Date.parse(i.nextEligibleAt):Number.NaN).filter(i=>Number.isFinite(i)&&i>e)];return t.length>0?Math.min(...t):null}act(e,t,i={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,i));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,i){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!G(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=i.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,i.snoozeUntil)},o=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),a=new Map(this.decisions);return a.set(o,r),await this.storage.save([...a.values()]),this.decisions=a,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,i,n){if(t==="later")return new Date(i.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=i.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=I(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${I(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${I(e.scope)}:category:${e.category}`}}function ce(s,e){return{load:async()=>L(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function L(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(P):[]}function I(s){return`${s.level}:${s.key}`}function G(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function P(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&G(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const le={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},ue=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function F(s,e){if(!e)return _(s);const t=_(s),i=`${le[e]} Pluno`;return t?`${i}: ${t}`:i}class pe{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,i=await e();i===void 0||t!==this.liveStatusVersion||(i?this.applyStatus(i):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=_(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,i=this.lastAppliedTitle===null?_(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):i!==e&&this.titleDocument.setTitle(i)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=F(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function he(s){return{getTitle:()=>s.title,setTitle:e=>{s.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(s.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function _(s){return s.replace(ue,"")}const ge="0.1.269",fe={version:ge},p=s=>typeof s=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(s)?s:null;function me(s){if(!s||typeof s!="object")return!1;const e=s,t=n=>Number.isSafeInteger(n)&&n>=0,i=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)&&p(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||p(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&p(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||i(e.lastIntent))&&(e.lastSelection===null||i(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(i)}function B(s){if(!s||typeof s!="object")return!1;const e=s;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 q=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],T=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),h=s=>s===null||T(s),ye=s=>typeof s=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(s)&&Number.isFinite(Date.parse(s));function Q(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&h(e.sessionId)&&T(e.itemId)&&h(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&h(e.runId)&&(e.createdAt===null||ye(e.createdAt))}function ve(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(i))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(i=>i===null||t(i))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(i=>i===null||p(i)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(i=>typeof i=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||me(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(i=>i===void 0||t(i))}function H(s){if(!s||typeof s!="object"||Object.keys(s).some(i=>i!=="before"&&i!=="current"))return!1;const e=i=>{if(!i||typeof i!="object")return!1;const n=i;return Object.keys(i).every(r=>[...q,"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(o=>["key","count","rows","truncated"].includes(o))&&h(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(o=>o&&Object.keys(o).every(a=>["itemId","groupId"].includes(a))&&h(o.itemId)&&h(o.groupId))))&&(n.context===void 0||ve(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&h(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&q.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(T))},t=s;return(t.before===null||e(t.before))&&e(t.current)}const R=500;function V(s){const e=s.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>R?`${e.slice(0,R-1)}…`:e}function be(s){let e=2166136261;for(let t=0;t<s.length;t+=1)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function E(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).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 _e(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||p(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||p(t)!==null)&&(e.normalization===void 0||E(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,i])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof i=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(i))}function Ie(s,e,t,i,n={}){const r=!i&&e==="conversation_error"&&t!==void 0&&s.conversationDiagnostics?.errorMessageFingerprint===be(V(t))?s.conversationDiagnostics:void 0;return{sessionId:p(s.sessionId),requestId:p(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...p(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?p(s.lastErrorCode):null,...E(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:fe.version,...n}}}function Se(s){if(s.details!==void 0&&!b(s.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:s.code,message:s.message,retryable:s.retryable,...s.details===void 0?{}:{details:s.details}}}function g(s,e="runtime_error",t="runtime"){const i=s!==null&&typeof s=="object"?s:null,n=typeof s=="string"?s:i&&"message"in i&&typeof i.message=="string"?i.message:"",r=i&&"code"in i&&typeof i.code=="string"&&i.code.trim()?i.code:e,o=i&&"details"in i?i.details:null,a=o&&typeof o=="object"?o:{},d={...typeof a.httpStatus=="number"&&Number.isInteger(a.httpStatus)&&a.httpStatus>=100&&a.httpStatus<=599?{httpStatus:a.httpStatus}:{},errorNormalization:E(a.errorNormalization)?a.errorNormalization:{boundary:t,category:s instanceof Error?"error":s===null?"null":Array.isArray(s)?"array":typeof s,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof s=="string"||i&&"message"in i&&typeof i.message=="string"?"blank":"non_text"},...a.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(a.acceptance))?{acceptance:String(a.acceptance)}:{},...typeof a.securitySettingsUrl=="string"?{securitySettingsUrl:a.securitySettingsUrl}:{},...typeof a.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(a.transportCode)?{transportCode:a.transportCode}:{},...typeof a.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(a.requestId)?{requestId:a.requestId}:{},...typeof a.durationMs=="number"&&Number.isFinite(a.durationMs)&&a.durationMs>=0?{durationMs:a.durationMs}:{},...typeof a.successfulRequests=="number"&&Number.isSafeInteger(a.successfulRequests)&&a.successfulRequests>=0?{successfulRequests:a.successfulRequests}:{}};return Se({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(i&&"retryable"in i&&i.retryable===!0),...Object.keys(d).length?{details:d}:{}})}function Z(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(i))&&p(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(i=>i==null||t(i))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(i=>i===null||p(i)!==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(i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(i))}const Ae=["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","warmup_checkpoint","warmup_http","warmup_wait","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],J=["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 we(s){const e=s,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&J.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const W=Math.random().toString(36).slice(2);let Pe=0;const C=()=>`timing:${W}:${++Pe}`,f=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function M(s){if(!s||typeof s!="object")return!1;const e=s;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||f(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&J.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)&&Ae.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&f(e.spanId)&&f(e.requestId)&&(e.clientMessageId===null||f(e.clientMessageId))&&(e.sessionId===null||f(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function x(s,e){if(e={workerId:W,...e},!s)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,o,a,d)=>{const c={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o)),...r==="failed"?{failureCategory:we(d)}:{}};s&&M(c)&&Promise.resolve().then(()=>s(c)).catch(()=>{})};return{identity:e,mark:n=>i(n,"observed",t,C()),measure(n,r){const o=performance.now(),a=C();return i(n,"started",o,a),r().then(d=>(i(n,"completed",o,a),d),d=>{throw i(n,"failed",o,a,d),d})}}}const S=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function Te(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&S(e.sessionId)&&S(e.responseItemId)&&S(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Ee(s,e,t="stopped",i,n="Run stopped by user."){const r=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d)),o=s.messages.filter(d=>!(d.dataType==="run_status"&&d.loading&&r.has(d.respondsToUserMessageId??""))).map(d=>r.has(d.respondsToUserMessageId??"")?{...d,loading:!1}:d);for(const d of r)o.some(c=>c.respondsToUserMessageId===d&&(c.dataType==="run_status"||c.dataType==="run_error"||c.role==="assistant"&&c.phase!=="commentary"))||o.some(c=>c.role==="user"&&c.id===d)&&o.push({id:`local-interrupted:${d}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:d});const a=s.segments?.map(d=>({...d,outcomeIds:[...d.outcomeIds,...o.filter(c=>c.id===`local-interrupted:${d.userMessageId}`&&!d.outcomeIds.includes(c.id)).map(c=>c.id)]}));return{...s,messages:o,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&o.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Me={"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 ke(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Me,s.slice(13))}function D(s){return{...s.id===void 0?{}:{id:s.id},name:s.name,mimeType:s.mimeType,sizeBytes:s.sizeBytes,...s.sandboxPath===void 0?{}:{sandboxPath:s.sandboxPath},...s.storageKey===void 0?{}:{storageKey:s.storageKey},...s.fileUrl===void 0?{}:{fileUrl:s.fileUrl}}}function Oe(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;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 Te(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return M(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||_e(e.errorDiagnostic))&&(e.httpRequest===void 0||Z(e.httpRequest))&&(e.historyRefreshFailure===void 0||B(e.historyRefreshFailure))&&(e.renderedError===void 0||Q(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||H(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||ke(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 typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return 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 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 qe{constructor(e,t,i){this.adapter=t,this.state=A(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=m("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;operationQueue=Promise.resolve();destroyed=!1;on(e,t){const i=this.listeners[e]??new Set;return i.add(t),this.listeners[e]=i,()=>i.delete(t)}getState(){const e=A(this.state);for(const[n,r]of this.submissionPreviews)e.messages.some(o=>o.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(o=>({...o}))}),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"].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 i=Ee(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:i.messages,segments:i.segments}:i}updateProjection(e,t,i,n,r){if(this.destroyed)return;const o=this.getState();(o.user?.id!==e.user?.id||o.selectionKey!==void 0&&o.selectionKey!==e.selectionKey||o.selectionKey===void 0&&o.sessionId!==null&&o.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const a of e.messages)a.role==="user"&&this.submissionPreviews.delete(a.id);this.state=A(e);for(const[a,d]of this.stopPreviews){const c=e.activity?.executionKey;(d!==void 0&&d!=="[]"&&c!==void 0&&c!=="[]"&&(c!==d||["completed","failed","stopped"].includes(e.activity.phase))||(d===void 0||d==="[]")&&e.messages.some(u=>u.respondsToUserMessageId===a&&!u.provisional&&u.loading!==!0&&(u.dataType==="run_status"||u.dataType==="run_error"||u.role==="assistant"&&u.phase!=="commentary"&&(u.streamState===void 0||["finished","stopped","failed"].includes(u.streamState)))))&&this.stopPreviews.delete(a)}if(this.pendingStop?.userMessageIds.every(a=>!this.stopPreviews.has(a))&&(this.pendingStop=null),o.user?.id===e.user?.id)for(const a of this.state.messages){if(a.role!=="user"||!a.attachments?.length)continue;const d=o.messages.find(c=>c.role==="user"&&c.id===a.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&d)||(a.attachments=Re(d?.attachments,a.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=N(i);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const a of this.accountListeners)a(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0,this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionPreviews.clear(),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?.()}}warmup(e="panel_open"){return this.adapter.dispatch({type:"runtime.warmup",reason:e}).then(()=>{})}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&&M(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,i){i!==void 0&&!H(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!Q(n)||r!==void 0&&!B(r))return;const a=Ie(this.getState(),e,i,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:a,...a.clientMessageId?{clientMessageId:a.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...Z(o)?{httpRequest:o}:{},...i?{displayedMessage:V(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim();t={...t,attachments:t.attachments?.map(c=>({...c}))};const n=t.attachments??[];if(!i&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(c=>c.id?[c.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(c=>({...c}))}});const d=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:o},a);return this.emit("state",this.getState()),d.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,o=x(c=>{i===this.submissionGeneration&&this.reportOperationTiming(c)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],d=!1;if(i!==this.submissionGeneration)return null;try{if(!await o.measure("staging_ipc",async()=>{const l=await this.enqueueOperation(async()=>this.destroyed||i!==this.submissionGeneration?null:{result:this.adapter.dispatch({type:"conversation.stage",initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(D):void 0,submittedAt:t.submittedAt})});return l?(await l.result,l):null})||i!==this.submissionGeneration)return null;if(d=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of a){if(u.sandboxPath||u.storageKey){l.push(u);continue}const k=u.id?this.attachmentFiles.get(u.id):void 0;if(!k)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(k,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}a=l}if(i!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(D):void 0}),i!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),r}catch(c){if(i!==this.submissionGeneration)return null;if(K(c))for(const u of t.attachments??[])u.id&&this.attachmentFiles.delete(u.id);const l=this.submissionPreviews.get(r);throw l&&(l.pending=!1,l.error=g(c),l.retry=!d&&g(c).code==="command_not_received"?()=>this.sendMessageNow(e,t,i):void 0,this.emit("state",this.getState())),d&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:g(c).message}),c}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}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 i=this.submissionPreviews.get(t);if(i?.pending)return!1;const n=i?.retry,r=this.submissionGeneration;try{return i&&n?(i.pending=!0,i.error=void 0,i.retry=void 0,this.pendingTransfers.set(t,(i.message.attachments??[]).flatMap(o=>o.id?[o.id]:[])),this.emit("state",this.getState()),await n()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!i)throw o;return r===this.submissionGeneration&&this.submissionPreviews.get(t)===i&&(i.error=g(o),this.emit("state",this.getState())),!1}finally{n&&this.pendingTransfers.delete(t),i&&r===this.submissionGeneration&&this.submissionPreviews.get(t)===i&&(i.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),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c))],n=x(c=>this.reportOperationTiming(c),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:i[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:i,promise:Promise.resolve()};this.pendingStop=r;const o=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const c of i)this.stopPreviews.set(c,t.includes(c)?void 0:o);const a=this.submissionGeneration;r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},c=>{if(!(a!==this.submissionGeneration||i.every(l=>!this.stopPreviews.has(l)))){for(const l of i)this.stopPreviews.delete(l);this.stopError=g(c).message}}).finally(()=>{this.destroyed||a!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState());const d=r.promise;return this.operationQueue=d.then(()=>{},()=>{}),d.then(()=>{})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const i of this.pendingTransfers.values())for(const n of i)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const i of this.submissionPreviews.values()){i.pending=!1,i.retry=void 0;for(const n of i.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return this.operationQueue=Promise.resolve(),t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const i=this.getSessionHistoryState().data;return{sessions:i?i.ids.map(n=>i.entitiesById[n]):[],nextCursor:i?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return N(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,i,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(o=>o.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n,expectedSourceVersion:r}).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.emit("state",this.getState()),this.dispatch({type:"session.load",sessionId:e}).then(()=>{}))}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const i=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=i,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:i}).then(()=>{})}dispatch(e){return e.type==="session.list"?this.adapter.dispatch(e):this.enqueueOperation(()=>this.adapter.dispatch(e))}enqueueOperation(e){const t=this.operationQueue.then(e);return this.operationQueue=t.then(()=>{},()=>{}),t}emit(e,t){const i=this.listeners[e];for(const n of i??[])n(t)}}function Re(s,e){if(!e||!s)return e;const t=new Map;for(const i of s){const n=i.previewUrl;i.id&&n&&t.set(i.id,n)}return e.map(i=>{const n=i.id?t.get(i.id):void 0;return n?{...i,previewUrl:n}:i})}function A(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},i=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),i&&Object.defineProperty(t,"assistantDraftItemId",{value:i,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:s.activeScheduledFollowUps?.map(e=>({...e}))??null}}function N(s){return{...s,data:s.data?y({entities:z(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=$;exports.ProductAgentInteractionManager=de;exports.ProductAgentQueryController=w;exports.ProductAgentRemoteRuntimeClient=qe;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=pe;exports.canSubmitPersonalProductAgentMessage=se;exports.createLocalStorageInteractionDecisionStorage=ce;exports.createProductAgentQueryState=m;exports.createProductAgentTaskPageTitleDocument=he;exports.formatProductAgentTaskPageTitle=F;exports.hasProductAgentPaidCreditFallback=ee;exports.isProductAgentAuthReconnectError=K;exports.isProductAgentRuntimeCommand=Oe;exports.mergeProductAgentEntityPages=j;exports.normalizeProductAgentEntityPage=y;exports.readLocalStorageInteractionDecisions=L;exports.reconcileProductAgentSubmissionGate=Y;exports.resolveProductAgentBillingPresentation=te;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=X;exports.selectProductAgentQueryEntities=z;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Y(s,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"]}:s??{allowed:!0,reason:"allowed",actions:[]}}function m(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class w{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=m(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=m(e),this.trailingLoad=null,this.publish())}reset(){this.state=m(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,i=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:i},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||i!==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||i!==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 y(s){const e={},t=[];for(const i of s.entities)e[i.id]||t.push(i.id),e[i.id]=i;return{entitiesById:e,ids:t,nextCursor:s.nextCursor}}function j(s,e,t){if(t==="replace"||s===null)return e;const i={...s.entitiesById,...e.entitiesById},n=[...s.ids];for(const r of e.ids)s.entitiesById[r]||n.push(r);return{entitiesById:i,ids:n,nextCursor:e.nextCursor}}function z(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function X(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function ee(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function te(s){return s?s.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(s.submissionGate.reason)?{state:"action_required",reason:s.submissionGate.reason}:{state:"hidden"}:s.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:s.creditLimit!==null&&s.creditLimit>0&&s.creditsRemaining!==null&&s.creditsRemaining>0&&s.creditsRemaining/s.creditLimit<=.2?{state:"low_credits"}:s.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function se(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function ie(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const $="Pluno is reconnecting. Try again in a moment.";function K(s){return(s instanceof Error?s.message:s)===$}class ne{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new w(`${e}:recent`,async({cursor:n})=>y(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),j),this.pinnedQuery=new w(`${e}:pinned`,async()=>y({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(),i=[...v(t.data),...v(e.data)],n=new Map(i.map(d=>[d.id,d])),r=Array.from(n.values()).map(d=>this.applyOverrides(d,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(d=>!n.has(d.id)).reverse(),a=e.data||t.data||o.length>0?y({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:a,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,i=>({...i,isActive:t}))}setPinned(e,t){const i={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,i),this.updateEntity(e,n=>({...n,isPinned:t})),i}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,i){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:i})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,i=>({...i,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...v(this.pinnedQuery.getState().data),...v(this.recentQuery.getState().data)],t=new Set(e.map(i=>i.id));for(const i of this.optimisticEntities.keys())t.has(i)&&this.optimisticEntities.delete(i);for(const i of e)this.applyOverrides(i,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const i=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...i.sessions),t=i.nextCursor}while(t);return e}applyOverrides(e,t){let i=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):i={...i,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):i={...i,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(i={...i,customTitle:this.titleOverrides.get(e.id)??null}),i}updateProjection(){this.publish()}updateEntity(e,t){const i=this.optimisticEntities.get(e);i&&this.optimisticEntities.set(e,t(i)),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 v(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function re(s,e){return s.status==="error"||e.status==="error"?"error":s.status==="loading"||e.status==="loading"?"loading":s.status==="refreshing"||e.status==="refreshing"?"refreshing":s.status==="loading_more"?"loading_more":s.status==="ready"||e.status==="ready"?"ready":"not_requested"}function O(s){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(s);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function b(s){if(s===null||typeof s=="string"||typeof s=="boolean")return!0;if(typeof s=="number")return Number.isFinite(s);if(Array.isArray(s))return s.every(b);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(b)}function U(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(U),Object.freeze(s)),s}function oe(s){if(!b(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function ae(s,e){if(!e)return!1;const t=s.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const i=Object.values(s.items).sort((r,o)=>O(r.created_at).localeCompare(O(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of i)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&s.streams[r.id]?.state==="finished"&&s.streams[r.id].revision>=r.data.revision))return!0;return!1}class de{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(P).map(i=>[this.getDecisionKey(i),i])),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 i=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(i);if(n&&n.version>=t.version)continue;if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");const r=n?.payload.kind==="personal_channel"&&n.lifecycle==="completed"?"completed":t.lifecycle,o=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,U(oe({...t,lifecycle:r,payload:o}))),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={share:null,integrations:[],channel:null},i=e?this.conversationReader(e):null;if(!i)return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,o)=>r.version-o.version||r.id.localeCompare(o.id));for(const r of n){const o=r.payload;if(o.kind==="sharing"){if(t.share=null,!o.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const a=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:o.variant,userPrompt:a?.type==="user_message"?a.data.content:"",assistantAnswer:""},terminal:!o.wait_for_terminal||ae(i,r.user_message_id)}}else o.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:o.request_id,appSlug:o.app_slug,appName:o.app_name,appLogo:o.app_logo??void 0,expiresAt:o.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(o.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:o.request_id,channel:o.channel,managementUrl:o.management_url},lifecycle: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(P).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));return i!==void 0&&i>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 i=this.scheduledEligibility.get(this.getExactKey(e));if(i!==void 0&&i>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 i=this.getExactKey(e),n=this.scheduledEligibility.get(i);return n!==void 0?n:(this.scheduledEligibility.set(i,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(i=>i>e),...Array.from(this.decisions.values()).map(i=>i.nextEligibleAt?Date.parse(i.nextEligibleAt):Number.NaN).filter(i=>Number.isFinite(i)&&i>e)];return t.length>0?Math.min(...t):null}act(e,t,i={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,i));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,i){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!G(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=i.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,i.snoozeUntil)},o=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),a=new Map(this.decisions);return a.set(o,r),await this.storage.save([...a.values()]),this.decisions=a,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,i,n){if(t==="later")return new Date(i.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=i.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=I(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${I(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${I(e.scope)}:category:${e.category}`}}function ce(s,e){return{load:async()=>L(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function L(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(P):[]}function I(s){return`${s.level}:${s.key}`}function G(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function P(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&G(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const le={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},ue=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function F(s,e){if(!e)return _(s);const t=_(s),i=`${le[e]} Pluno`;return t?`${i}: ${t}`:i}class pe{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,i=await e();i===void 0||t!==this.liveStatusVersion||(i?this.applyStatus(i):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=_(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,i=this.lastAppliedTitle===null?_(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):i!==e&&this.titleDocument.setTitle(i)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=F(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function he(s){return{getTitle:()=>s.title,setTitle:e=>{s.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(s.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function _(s){return s.replace(ue,"")}const ge="0.1.270",fe={version:ge},p=s=>typeof s=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(s)?s:null;function me(s){if(!s||typeof s!="object")return!1;const e=s,t=n=>Number.isSafeInteger(n)&&n>=0,i=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)&&p(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||p(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&p(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||i(e.lastIntent))&&(e.lastSelection===null||i(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(i)}function B(s){if(!s||typeof s!="object")return!1;const e=s;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 q=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],T=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),h=s=>s===null||T(s),ye=s=>typeof s=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(s)&&Number.isFinite(Date.parse(s));function Q(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&h(e.sessionId)&&T(e.itemId)&&h(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&h(e.runId)&&(e.createdAt===null||ye(e.createdAt))}function ve(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(i))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(i=>i===null||t(i))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(i=>i===null||p(i)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(i=>typeof i=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||me(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(i=>i===void 0||t(i))}function H(s){if(!s||typeof s!="object"||Object.keys(s).some(i=>i!=="before"&&i!=="current"))return!1;const e=i=>{if(!i||typeof i!="object")return!1;const n=i;return Object.keys(i).every(r=>[...q,"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(o=>["key","count","rows","truncated"].includes(o))&&h(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(o=>o&&Object.keys(o).every(a=>["itemId","groupId"].includes(a))&&h(o.itemId)&&h(o.groupId))))&&(n.context===void 0||ve(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&h(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&q.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(T))},t=s;return(t.before===null||e(t.before))&&e(t.current)}const R=500;function V(s){const e=s.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>R?`${e.slice(0,R-1)}…`:e}function be(s){let e=2166136261;for(let t=0;t<s.length;t+=1)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function E(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).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 _e(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||p(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||p(t)!==null)&&(e.normalization===void 0||E(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,i])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof i=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(i))}function Ie(s,e,t,i,n={}){const r=!i&&e==="conversation_error"&&t!==void 0&&s.conversationDiagnostics?.errorMessageFingerprint===be(V(t))?s.conversationDiagnostics:void 0;return{sessionId:p(s.sessionId),requestId:p(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...p(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?p(s.lastErrorCode):null,...E(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:fe.version,...n}}}function Se(s){if(s.details!==void 0&&!b(s.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:s.code,message:s.message,retryable:s.retryable,...s.details===void 0?{}:{details:s.details}}}function g(s,e="runtime_error",t="runtime"){const i=s!==null&&typeof s=="object"?s:null,n=typeof s=="string"?s:i&&"message"in i&&typeof i.message=="string"?i.message:"",r=i&&"code"in i&&typeof i.code=="string"&&i.code.trim()?i.code:e,o=i&&"details"in i?i.details:null,a=o&&typeof o=="object"?o:{},d={...typeof a.httpStatus=="number"&&Number.isInteger(a.httpStatus)&&a.httpStatus>=100&&a.httpStatus<=599?{httpStatus:a.httpStatus}:{},errorNormalization:E(a.errorNormalization)?a.errorNormalization:{boundary:t,category:s instanceof Error?"error":s===null?"null":Array.isArray(s)?"array":typeof s,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof s=="string"||i&&"message"in i&&typeof i.message=="string"?"blank":"non_text"},...a.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(a.acceptance))?{acceptance:String(a.acceptance)}:{},...typeof a.securitySettingsUrl=="string"?{securitySettingsUrl:a.securitySettingsUrl}:{},...typeof a.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(a.transportCode)?{transportCode:a.transportCode}:{},...typeof a.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(a.requestId)?{requestId:a.requestId}:{},...typeof a.durationMs=="number"&&Number.isFinite(a.durationMs)&&a.durationMs>=0?{durationMs:a.durationMs}:{},...typeof a.successfulRequests=="number"&&Number.isSafeInteger(a.successfulRequests)&&a.successfulRequests>=0?{successfulRequests:a.successfulRequests}:{}};return Se({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(i&&"retryable"in i&&i.retryable===!0),...Object.keys(d).length?{details:d}:{}})}function Z(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(i))&&p(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(i=>i==null||t(i))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(i=>i===null||p(i)!==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(i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(i))}const Ae=["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","warmup_checkpoint","warmup_http","warmup_wait","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],J=["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 we(s){const e=s,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&J.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const W=Math.random().toString(36).slice(2);let Pe=0;const C=()=>`timing:${W}:${++Pe}`,f=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function M(s){if(!s||typeof s!="object")return!1;const e=s;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||f(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&J.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)&&Ae.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&f(e.spanId)&&f(e.requestId)&&(e.clientMessageId===null||f(e.clientMessageId))&&(e.sessionId===null||f(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function x(s,e){if(e={workerId:W,...e},!s)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,o,a,d)=>{const c={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o)),...r==="failed"?{failureCategory:we(d)}:{}};s&&M(c)&&Promise.resolve().then(()=>s(c)).catch(()=>{})};return{identity:e,mark:n=>i(n,"observed",t,C()),measure(n,r){const o=performance.now(),a=C();return i(n,"started",o,a),r().then(d=>(i(n,"completed",o,a),d),d=>{throw i(n,"failed",o,a,d),d})}}}const S=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function Te(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&S(e.sessionId)&&S(e.responseItemId)&&S(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Ee(s,e,t="stopped",i,n="Run stopped by user."){const r=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d)),o=s.messages.filter(d=>!(d.dataType==="run_status"&&d.loading&&r.has(d.respondsToUserMessageId??""))).map(d=>r.has(d.respondsToUserMessageId??"")?{...d,loading:!1}:d);for(const d of r)o.some(c=>c.respondsToUserMessageId===d&&(c.dataType==="run_status"||c.dataType==="run_error"||c.role==="assistant"&&c.phase!=="commentary"))||o.some(c=>c.role==="user"&&c.id===d)&&o.push({id:`local-interrupted:${d}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:d});const a=s.segments?.map(d=>({...d,outcomeIds:[...d.outcomeIds,...o.filter(c=>c.id===`local-interrupted:${d.userMessageId}`&&!d.outcomeIds.includes(c.id)).map(c=>c.id)]}));return{...s,messages:o,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&o.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Me={"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 ke(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Me,s.slice(13))}function D(s){return{...s.id===void 0?{}:{id:s.id},name:s.name,mimeType:s.mimeType,sizeBytes:s.sizeBytes,...s.sandboxPath===void 0?{}:{sandboxPath:s.sandboxPath},...s.storageKey===void 0?{}:{storageKey:s.storageKey},...s.fileUrl===void 0?{}:{fileUrl:s.fileUrl}}}function Oe(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;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 Te(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return M(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||_e(e.errorDiagnostic))&&(e.httpRequest===void 0||Z(e.httpRequest))&&(e.historyRefreshFailure===void 0||B(e.historyRefreshFailure))&&(e.renderedError===void 0||Q(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||H(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||ke(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 typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return 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 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 qe{constructor(e,t,i){this.adapter=t,this.state=A(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=m("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;operationQueue=Promise.resolve();destroyed=!1;on(e,t){const i=this.listeners[e]??new Set;return i.add(t),this.listeners[e]=i,()=>i.delete(t)}getState(){const e=A(this.state);for(const[n,r]of this.submissionPreviews)e.messages.some(o=>o.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(o=>({...o}))}),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"].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 i=Ee(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:i.messages,segments:i.segments}:i}updateProjection(e,t,i,n,r){if(this.destroyed)return;const o=this.getState();(o.user?.id!==e.user?.id||o.selectionKey!==void 0&&o.selectionKey!==e.selectionKey||o.selectionKey===void 0&&o.sessionId!==null&&o.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const a of e.messages)a.role==="user"&&this.submissionPreviews.delete(a.id);this.state=A(e);for(const[a,d]of this.stopPreviews){const c=e.activity?.executionKey;(d!==void 0&&d!=="[]"&&c!==void 0&&c!=="[]"&&(c!==d||["completed","failed","stopped"].includes(e.activity.phase))||(d===void 0||d==="[]")&&e.messages.some(u=>u.respondsToUserMessageId===a&&!u.provisional&&u.loading!==!0&&(u.dataType==="run_status"||u.dataType==="run_error"||u.role==="assistant"&&u.phase!=="commentary"&&(u.streamState===void 0||["finished","stopped","failed"].includes(u.streamState)))))&&this.stopPreviews.delete(a)}if(this.pendingStop?.userMessageIds.every(a=>!this.stopPreviews.has(a))&&(this.pendingStop=null),o.user?.id===e.user?.id)for(const a of this.state.messages){if(a.role!=="user"||!a.attachments?.length)continue;const d=o.messages.find(c=>c.role==="user"&&c.id===a.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&d)||(a.attachments=Re(d?.attachments,a.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=N(i);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const a of this.accountListeners)a(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0,this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionPreviews.clear(),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?.()}}warmup(e="panel_open"){return this.adapter.dispatch({type:"runtime.warmup",reason:e}).then(()=>{})}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&&M(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,i){i!==void 0&&!H(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!Q(n)||r!==void 0&&!B(r))return;const a=Ie(this.getState(),e,i,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:a,...a.clientMessageId?{clientMessageId:a.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...Z(o)?{httpRequest:o}:{},...i?{displayedMessage:V(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim();t={...t,attachments:t.attachments?.map(c=>({...c}))};const n=t.attachments??[];if(!i&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(c=>c.id?[c.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(c=>({...c}))}});const d=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:o},a);return this.emit("state",this.getState()),d.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,o=x(c=>{i===this.submissionGeneration&&this.reportOperationTiming(c)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],d=!1;if(i!==this.submissionGeneration)return null;try{if(!await o.measure("staging_ipc",async()=>{const l=await this.enqueueOperation(async()=>this.destroyed||i!==this.submissionGeneration?null:{result:this.adapter.dispatch({type:"conversation.stage",initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(D):void 0,submittedAt:t.submittedAt})});return l?(await l.result,l):null})||i!==this.submissionGeneration)return null;if(d=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of a){if(u.sandboxPath||u.storageKey){l.push(u);continue}const k=u.id?this.attachmentFiles.get(u.id):void 0;if(!k)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(k,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}a=l}if(i!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(D):void 0}),i!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),r}catch(c){if(i!==this.submissionGeneration)return null;if(K(c))for(const u of t.attachments??[])u.id&&this.attachmentFiles.delete(u.id);const l=this.submissionPreviews.get(r);throw l&&(l.pending=!1,l.error=g(c),l.retry=!d&&g(c).code==="command_not_received"?()=>this.sendMessageNow(e,t,i):void 0,this.emit("state",this.getState())),d&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:g(c).message}),c}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}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 i=this.submissionPreviews.get(t);if(i?.pending)return!1;const n=i?.retry,r=this.submissionGeneration;try{return i&&n?(i.pending=!0,i.error=void 0,i.retry=void 0,this.pendingTransfers.set(t,(i.message.attachments??[]).flatMap(o=>o.id?[o.id]:[])),this.emit("state",this.getState()),await n()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!i)throw o;return r===this.submissionGeneration&&this.submissionPreviews.get(t)===i&&(i.error=g(o),this.emit("state",this.getState())),!1}finally{n&&this.pendingTransfers.delete(t),i&&r===this.submissionGeneration&&this.submissionPreviews.get(t)===i&&(i.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),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c))],n=x(c=>this.reportOperationTiming(c),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:i[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:i,promise:Promise.resolve()};this.pendingStop=r;const o=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const c of i)this.stopPreviews.set(c,t.includes(c)?void 0:o);const a=this.submissionGeneration;r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},c=>{if(!(a!==this.submissionGeneration||i.every(l=>!this.stopPreviews.has(l)))){for(const l of i)this.stopPreviews.delete(l);this.stopError=g(c).message}}).finally(()=>{this.destroyed||a!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState());const d=r.promise;return this.operationQueue=d.then(()=>{},()=>{}),d.then(()=>{})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const i of this.pendingTransfers.values())for(const n of i)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const i of this.submissionPreviews.values()){i.pending=!1,i.retry=void 0;for(const n of i.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return this.operationQueue=Promise.resolve(),t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const i=this.getSessionHistoryState().data;return{sessions:i?i.ids.map(n=>i.entitiesById[n]):[],nextCursor:i?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return N(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,i,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(o=>o.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n,expectedSourceVersion:r}).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.emit("state",this.getState()),this.dispatch({type:"session.load",sessionId:e}).then(()=>{}))}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const i=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=i,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:i}).then(()=>{})}dispatch(e){return e.type==="session.list"?this.adapter.dispatch(e):this.enqueueOperation(()=>this.adapter.dispatch(e))}enqueueOperation(e){const t=this.operationQueue.then(e);return this.operationQueue=t.then(()=>{},()=>{}),t}emit(e,t){const i=this.listeners[e];for(const n of i??[])n(t)}}function Re(s,e){if(!e||!s)return e;const t=new Map;for(const i of s){const n=i.previewUrl;i.id&&n&&t.set(i.id,n)}return e.map(i=>{const n=i.id?t.get(i.id):void 0;return n?{...i,previewUrl:n}:i})}function A(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},i=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),i&&Object.defineProperty(t,"assistantDraftItemId",{value:i,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:s.activeScheduledFollowUps?.map(e=>({...e}))??null}}function N(s){return{...s,data:s.data?y({entities:z(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=$;exports.ProductAgentInteractionManager=de;exports.ProductAgentQueryController=w;exports.ProductAgentRemoteRuntimeClient=qe;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=pe;exports.canSubmitPersonalProductAgentMessage=se;exports.createLocalStorageInteractionDecisionStorage=ce;exports.createProductAgentQueryState=m;exports.createProductAgentTaskPageTitleDocument=he;exports.formatProductAgentTaskPageTitle=F;exports.hasProductAgentPaidCreditFallback=ee;exports.isProductAgentAuthReconnectError=K;exports.isProductAgentRuntimeCommand=Oe;exports.mergeProductAgentEntityPages=j;exports.normalizeProductAgentEntityPage=y;exports.readLocalStorageInteractionDecisions=L;exports.reconcileProductAgentSubmissionGate=Y;exports.resolveProductAgentBillingPresentation=te;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=X;exports.selectProductAgentQueryEntities=z;
@@ -564,7 +564,7 @@ function ke(s) {
564
564
  function _(s) {
565
565
  return s.replace(te, "");
566
566
  }
567
- const ie = "0.1.269", ne = {
567
+ const ie = "0.1.270", ne = {
568
568
  version: ie
569
569
  }, p = (s) => typeof s == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(s) ? s : null;
570
570
  function re(s) {
@@ -762,7 +762,7 @@ function Gr(t, e, s, n) {
762
762
  function Ns(t = null) {
763
763
  return { authority: t, refusal: null, paidFallbackBySession: {}, query: ye("account"), preferences: null };
764
764
  }
765
- function Jr(t, e) {
765
+ function Qr(t, e) {
766
766
  return t.preferences && e.preferencesVersion <= t.preferences.preferencesVersion ? t : { ...t, preferences: e };
767
767
  }
768
768
  function js() {
@@ -811,7 +811,7 @@ function ie(t, e) {
811
811
  function Xe(t, e) {
812
812
  return t.account.preferences?.[e === "notifications" ? "taskNotificationsEnabled" : "tabGroupingEnabled"] ?? null;
813
813
  }
814
- const Qr = {
814
+ const Jr = {
815
815
  account: "read_account",
816
816
  preferences: "manage_preferences",
817
817
  preferencePrompts: "manage_preferences",
@@ -844,7 +844,7 @@ const Qr = {
844
844
  blockedOrigins: "manage_origin_access"
845
845
  };
846
846
  function tt(t, e) {
847
- if (!X(t.profile, xi[Qr[e.kind]])) throw new Error("Feature capability unavailable.");
847
+ if (!X(t.profile, xi[Jr[e.kind]])) throw new Error("Feature capability unavailable.");
848
848
  if (["decisions", "decision", "preferencePrompts"].includes(e.kind) && !X(t.profile, "canShowPersonalFeatures")) throw new Error("Personal feature unavailable.");
849
849
  if (t.profile.startsWith("embedded_") && e.kind === "targetFeedback") throw new Error("Embedded target feedback has no supported contract.");
850
850
  if (e.kind === "proactiveFeedback" && !X(t.profile, "canManageProactiveSuggestions")) throw new Error("Proactive feedback unavailable.");
@@ -929,7 +929,7 @@ function Ls(t, e, s) {
929
929
  const w = h.kind === "preferencePrompts" ? h.value[y] : h.feature === y ? h.value : null;
930
930
  w && w.revision > n.interactions.preferencePrompts[y].revision && u(y, w.requestId);
931
931
  }
932
- h.kind === "preferences" && (n = { ...n, account: Jr(n.account, h.value) }), h.kind === "preferencePrompts" && (n = { ...n, interactions: Bn(n.interactions, h.value) }), h.kind === "preferencePrompt" && (n = { ...n, interactions: Bn(n.interactions, { ...n.interactions.preferencePrompts, [h.feature]: h.value }) }), h.kind === "decisions" && (n = { ...n, interactions: ss(n.interactions, h.decisions) }), h.kind === "decision" && (n = { ...n, interactions: ss(n.interactions, [h.value]) });
932
+ h.kind === "preferences" && (n = { ...n, account: Qr(n.account, h.value) }), h.kind === "preferencePrompts" && (n = { ...n, interactions: Bn(n.interactions, h.value) }), h.kind === "preferencePrompt" && (n = { ...n, interactions: Bn(n.interactions, { ...n.interactions.preferencePrompts, [h.feature]: h.value }) }), h.kind === "decisions" && (n = { ...n, interactions: ss(n.interactions, h.decisions) }), h.kind === "decision" && (n = { ...n, interactions: ss(n.interactions, [h.value]) });
933
933
  }, g = (h, b) => {
934
934
  const y = n.interactions.deviceFacts[h];
935
935
  b.revision <= y.revision || (Xe(n, h) === !0 && (b.permission === "granted" && y.permission !== "granted" || b.snoozedUntil && b.snoozedUntil !== y.snoozedUntil) && u(h, null), a({ deviceFacts: { ...n.interactions.deviceFacts, [h]: b } }));
@@ -1862,7 +1862,7 @@ function lo(t, e = null) {
1862
1862
  } : void 0);
1863
1863
  return { ...n, ...o ? { auth: o } : {}, submissionGate: a, usingPaidCreditFallback: e ? t.paidFallbackBySession[e] ?? !1 : !1 };
1864
1864
  }
1865
- const uo = "0.1.269", Lt = {
1865
+ const uo = "0.1.270", Lt = {
1866
1866
  version: uo
1867
1867
  }, ln = (t) => t.selectedModel ?? t.historyModel ?? t.defaultModel, po = (t, e) => t.scopes[e];
1868
1868
  function Ft(t) {
@@ -2692,7 +2692,7 @@ function rt(t) {
2692
2692
  const e = t;
2693
2693
  return Object.keys(e).every((s) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs", "failureCategory", "tabId", "queueDepth", "workerId"].includes(s)) && (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 || Ve(e.workerId)) && (e.failureCategory === void 0 || e.status === "failed" && Vi.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) && yo.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && Ve(e.spanId) && Ve(e.requestId) && (e.clientMessageId === null || Ve(e.clientMessageId)) && (e.sessionId === null || Ve(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
2694
2694
  }
2695
- function Q(t, e) {
2695
+ function J(t, e) {
2696
2696
  if (e = { workerId: Ki, ...e }, !t) return {
2697
2697
  identity: e,
2698
2698
  mark: (i) => {
@@ -2745,7 +2745,7 @@ function wo(t) {
2745
2745
  }), r = (a, o) => {
2746
2746
  const c = Object.entries(a.operations).filter(([, m]) => m.command.type === "run.stop"), d = Object.entries(a.submissions).filter(([, m]) => m.cancelled);
2747
2747
  if (!o && !d.length && !c.some(([, m]) => m.phase !== "done" && m.phase !== "failed")) return Promise.resolve();
2748
- const l = c[c.length - 1]?.[1].command, u = Q(l ? t.onTiming : void 0, {
2748
+ const l = c[c.length - 1]?.[1].command, u = J(l ? t.onTiming : void 0, {
2749
2749
  operation: "stop",
2750
2750
  layer: "http",
2751
2751
  requestId: l?.request_id ?? "cancellation",
@@ -2806,7 +2806,7 @@ function wo(t) {
2806
2806
  function _o(t, e, s, n) {
2807
2807
  if (t !== e)
2808
2808
  for (const i of Object.values(e.submissions))
2809
- i.delivery !== "accepted" || t.submissions[i.userMessageId]?.delivery === "accepted" || Q(s, {
2809
+ i.delivery !== "accepted" || t.submissions[i.userMessageId]?.delivery === "accepted" || J(s, {
2810
2810
  operation: "send",
2811
2811
  layer: n,
2812
2812
  entrySurface: i.entrySurface,
@@ -3085,12 +3085,12 @@ class wt {
3085
3085
  this.schedule(r, e);
3086
3086
  }
3087
3087
  }
3088
- function J(t) {
3088
+ function Q(t) {
3089
3089
  const e = t.runtime(), s = e.engine.getState().slices.directory;
3090
3090
  return !e.isDisposed && (t.isCurrent?.() ?? !0) && s.authorityId === t.authority.authorityId && s.generation === t.authority.generation;
3091
3091
  }
3092
3092
  function ee(t, e) {
3093
- if (!J(t) || e.authorityId !== t.authority.authorityId || e.generation !== t.authority.generation)
3093
+ if (!Q(t) || e.authorityId !== t.authority.authorityId || e.generation !== t.authority.generation)
3094
3094
  throw Object.assign(new Error("Conversation authority was retired."), { code: "authority_retired", retryable: !0 });
3095
3095
  }
3096
3096
  function ke(t, e) {
@@ -3114,7 +3114,7 @@ function ke(t, e) {
3114
3114
  function Do(t) {
3115
3115
  let e = Promise.resolve();
3116
3116
  const s = (o = un(t.runtime().engine.getState().slices.conversation, t.runtime().engine.getState().slices.directory), c = Promise.resolve()) => {
3117
- const d = c.then(() => ({ ok: !0 }), (m) => ({ ok: !1, error: m })), l = o ? Object.values(o.submissions).filter((m) => m.delivery !== "accepted").slice(-8).map((m) => ({ submission: m, timer: Q(t.onTiming, {
3117
+ const d = c.then(() => ({ ok: !0 }), (m) => ({ ok: !1, error: m })), l = o ? Object.values(o.submissions).filter((m) => m.delivery !== "accepted").slice(-8).map((m) => ({ submission: m, timer: J(t.onTiming, {
3118
3118
  operation: "send",
3119
3119
  layer: "http",
3120
3120
  requestId: m.requestId,
@@ -3132,7 +3132,7 @@ function Do(t) {
3132
3132
  };
3133
3133
  return e = e.then(g, g), e;
3134
3134
  }, n = (o, c) => {
3135
- throw J(t) && !(o instanceof Error && "code" in o && ["executor_not_ready", "request_timed_out"].includes(String(o.code))) && t.onError?.(o, c), ke(o, c);
3135
+ throw Q(t) && !(o instanceof Error && "code" in o && ["executor_not_ready", "request_timed_out"].includes(String(o.code))) && t.onError?.(o, c), ke(o, c);
3136
3136
  }, i = () => {
3137
3137
  const { token: o, protocol: c, ...d } = t.http.auth;
3138
3138
  return { ...d, ...t.connectionId() ? { connection_id: t.connectionId() } : {} };
@@ -3143,7 +3143,7 @@ function Do(t) {
3143
3143
  if (!t.onTiming || o.submission.sessionId !== null) return;
3144
3144
  const c = t.runtime(), d = Object.values(c.engine.getState().slices.conversation.operations).find((g) => g.command.type === "runtime.warmup" && g.conversationScopeId === o.submission.conversationScopeId && ["waiting", "running", "uncertain"].includes(g.phase));
3145
3145
  if (!d) return;
3146
- const l = Q(t.onTiming, {
3146
+ const l = J(t.onTiming, {
3147
3147
  operation: "send",
3148
3148
  layer: "http",
3149
3149
  requestId: d.command.request_id,
@@ -3157,7 +3157,7 @@ function Do(t) {
3157
3157
  l.measure("warmup_wait", () => new Promise((g, m) => {
3158
3158
  const f = () => {
3159
3159
  const v = c.engine.getState().slices, I = v.conversation.submissions[o.submission.userMessageId], _ = v.conversation.operations[d.command.request_id];
3160
- !J(t) || !I || I.cancelled || v.directory.clients[I.clientScopeId] !== I.conversationScopeId ? m(new Error("Warmup wait was retired.")) : (I.sessionId !== null || !_ || !["waiting", "running", "uncertain"].includes(_.phase)) && g();
3160
+ !Q(t) || !I || I.cancelled || v.directory.clients[I.clientScopeId] !== I.conversationScopeId ? m(new Error("Warmup wait was retired.")) : (I.sessionId !== null || !_ || !["waiting", "running", "uncertain"].includes(_.phase)) && g();
3161
3161
  };
3162
3162
  u = c.engine.subscribe(f), p = c.onDispose(() => m(new Error("Warmup wait was retired."))), f();
3163
3163
  })).catch(() => {
@@ -3168,7 +3168,7 @@ function Do(t) {
3168
3168
  return {
3169
3169
  "conversation.prepare": async (o) => {
3170
3170
  r(o.submission.userMessageId);
3171
- const c = new AbortController(), d = Q(t.onTiming, {
3171
+ const c = new AbortController(), d = J(t.onTiming, {
3172
3172
  operation: "send",
3173
3173
  layer: "http",
3174
3174
  requestId: o.submission.requestId,
@@ -3184,7 +3184,7 @@ function Do(t) {
3184
3184
  ));
3185
3185
  }, 18e4), p = t.runtime(), g = () => {
3186
3186
  const v = p.engine.getState().slices, I = v.conversation.submissions[o.submission.userMessageId];
3187
- (!J(t) || !I || I.cancelled || I.requestId !== o.submission.requestId || v.directory.clients[I.clientScopeId] !== I.conversationScopeId) && l(Object.assign(new Error("Submission preparation was retired."), { code: "aborted", retryable: !1 }));
3187
+ (!Q(t) || !I || I.cancelled || I.requestId !== o.submission.requestId || v.directory.clients[I.clientScopeId] !== I.conversationScopeId) && l(Object.assign(new Error("Submission preparation was retired."), { code: "aborted", retryable: !1 }));
3188
3188
  }, m = p.engine.subscribe(g), f = p.onDispose(() => l(Object.assign(new Error("Submission runtime was disposed."), { code: "aborted" })));
3189
3189
  return g(), bt(c.signal, () => t.prepareSubmission(o, c.signal).then((v) => (c.signal.aborted && d.mark("context_discarded"), v), (v) => {
3190
3190
  throw c.signal.aborted && d.mark("context_discarded"), v;
@@ -3193,7 +3193,7 @@ function Do(t) {
3193
3193
  });
3194
3194
  },
3195
3195
  "conversation.checkpoint": async (o) => (ee(t, o), await s(o.checkpoint, t.saveCancellation(o.checkpoint)).catch((c) => n(c, { operation: "conversation.checkpoint" })), ee(t, o), null),
3196
- "conversation.receipt": (o) => Q(t.onTiming, {
3196
+ "conversation.receipt": (o) => J(t.onTiming, {
3197
3197
  operation: "send",
3198
3198
  layer: "http",
3199
3199
  requestId: o.userMessageId,
@@ -3207,7 +3207,7 @@ function Do(t) {
3207
3207
  client_message_id: o.userMessageId
3208
3208
  }, "POST", "conversations", { readOnly: !0 });
3209
3209
  if (ee(t, o), c !== null && (typeof c.sessionId != "string" || !c.sessionId || c.clientMessageId !== o.userMessageId || o.sessionId !== null && c.sessionId !== o.sessionId)) throw Object.assign(new Error("Conversation receipt identity mismatch."), { code: "acceptance_identity_mismatch" });
3210
- return c !== null && Q(t.onTiming, {
3210
+ return c !== null && J(t.onTiming, {
3211
3211
  operation: "send",
3212
3212
  layer: "http",
3213
3213
  requestId: o.userMessageId,
@@ -3219,7 +3219,7 @@ function Do(t) {
3219
3219
  let c = !1;
3220
3220
  return Promise.resolve().then(async () => {
3221
3221
  ee(t, o), (o.command.type === "chat.user_message" || o.command.type === "attachment.upload_completed") && r(String(o.command.payload.clientMessageId));
3222
- const d = o.command.payload, l = o.command.type === "runtime.warmup", u = Q(["runtime.warmup", "chat.user_message", "chat.retry_last_user_message", "run.stop", "attachment.upload_completed"].includes(o.command.type) ? t.onTiming : void 0, {
3222
+ const d = o.command.payload, l = o.command.type === "runtime.warmup", u = J(["runtime.warmup", "chat.user_message", "chat.retry_last_user_message", "run.stop", "attachment.upload_completed"].includes(o.command.type) ? t.onTiming : void 0, {
3223
3223
  operation: o.command.type === "run.stop" ? "stop" : "send",
3224
3224
  layer: "http",
3225
3225
  requestId: o.command.request_id,
@@ -3239,7 +3239,7 @@ function Do(t) {
3239
3239
  if (o.command.type.startsWith("chat.")) {
3240
3240
  const g = p.result;
3241
3241
  if (typeof g?.sessionId != "string" || !g.sessionId || g.clientMessageId !== o.command.payload.clientMessageId || o.command.payload.sessionId && g.sessionId !== o.command.payload.sessionId) throw Object.assign(new Error("Conversation acceptance identity mismatch."), { code: "acceptance_identity_mismatch" });
3242
- Q(t.onTiming, {
3242
+ J(t.onTiming, {
3243
3243
  operation: "send",
3244
3244
  layer: "http",
3245
3245
  requestId: o.command.request_id,
@@ -3251,7 +3251,7 @@ function Do(t) {
3251
3251
  });
3252
3252
  }).catch((d) => {
3253
3253
  if (o.previousAcceptance === "unissued" && d instanceof Error && "backendRefusal" in d && d.backendRefusal === !0) {
3254
- J(t) && t.onError?.(d, { operation: o.command.type, requestId: o.command.request_id });
3254
+ Q(t) && t.onError?.(d, { operation: o.command.type, requestId: o.command.request_id });
3255
3255
  const l = ke(d);
3256
3256
  throw Object.assign(l, { details: { ...l.details, acceptance: "rejected" } });
3257
3257
  }
@@ -3265,7 +3265,7 @@ function Do(t) {
3265
3265
  },
3266
3266
  "conversation.upload": (o) => {
3267
3267
  let c = !1;
3268
- return Q(t.onTiming, {
3268
+ return J(t.onTiming, {
3269
3269
  operation: "send",
3270
3270
  layer: "http",
3271
3271
  requestId: o.submission.userMessageId,
@@ -3326,7 +3326,7 @@ function Do(t) {
3326
3326
  ee(t, o);
3327
3327
  const c = t.runtime(), d = new AbortController(), l = () => {
3328
3328
  const g = c.engine.getState().slices;
3329
- J(t) ? g.directory.memberships[o.sessionId]?.members.length ? g.conversation.sessions[o.sessionId]?.queries[o.lane].requestId !== o.requestId && d.abort("request_replaced") : d.abort("observation_released") : d.abort("authority_retired");
3329
+ Q(t) ? g.directory.memberships[o.sessionId]?.members.length ? g.conversation.sessions[o.sessionId]?.queries[o.lane].requestId !== o.requestId && d.abort("request_replaced") : d.abort("observation_released") : d.abort("authority_retired");
3330
3330
  }, u = c.engine.subscribe(l), p = c.onDispose(() => d.abort("owner_disposed"));
3331
3331
  l();
3332
3332
  try {
@@ -3388,7 +3388,7 @@ class Uo {
3388
3388
  maxFailureIntervalMs: 3e4,
3389
3389
  isActiveTurn: () => !0,
3390
3390
  poll: async () => {
3391
- if (!(this.disposed || !J(e)) && (await e.runtime().engine.dispatch({ ...e.authority, type: "conversation.recover", now: e.now() }), await this.waitForDelivery(), this.hasUncertainDelivery()))
3391
+ if (!(this.disposed || !Q(e)) && (await e.runtime().engine.dispatch({ ...e.authority, type: "conversation.recover", now: e.now() }), await this.waitForDelivery(), this.hasUncertainDelivery()))
3392
3392
  throw new Error("Submission receipt recovery is still pending.");
3393
3393
  }
3394
3394
  }), e.runtime().engine.dispatch({ ...e.authority, type: "conversation.enable_effects" }), this.unsubscribe = e.runtime().engine.subscribe(() => this.reconcile()), this.unsubscribeDispose = e.runtime().onDispose(() => this.dispose());
@@ -3402,7 +3402,7 @@ class Uo {
3402
3402
  owner;
3403
3403
  deliveryRecovery;
3404
3404
  reconcile() {
3405
- const e = this.options.runtime(), s = !this.disposed && J(this.options) && (this.options.enabled?.() ?? !0), n = e.engine.getProjection().directory.intents;
3405
+ const e = this.options.runtime(), s = !this.disposed && Q(this.options) && (this.options.enabled?.() ?? !0), n = e.engine.getProjection().directory.intents;
3406
3406
  for (const [r, a] of this.observations)
3407
3407
  s && n[r]?.observe || (a.current.stop(), a.history.stop(), this.observations.delete(r), e.engine.dispatch({ ...this.options.authority, type: "conversation.observation_released", sessionId: r }), a.roomRequested && this.options.socket.release(r, this.owner).catch((o) => this.report(o)));
3408
3408
  if (s) for (const [r, a] of Object.entries(n)) {
@@ -3413,7 +3413,7 @@ class Uo {
3413
3413
  maxFailureIntervalMs: 6e4,
3414
3414
  isActiveTurn: () => !1,
3415
3415
  poll: async () => {
3416
- for (; !this.disposed && J(this.options) && this.observations.get(r)?.history === o; ) {
3416
+ for (; !this.disposed && Q(this.options) && this.observations.get(r)?.history === o; ) {
3417
3417
  const d = e.engine.getState().slices.conversation.sessions[r]?.queries.history;
3418
3418
  if (!d || d.cursor === null || d.error && !d.error.retryable) return;
3419
3419
  const l = d.cursor;
@@ -3449,31 +3449,31 @@ class Uo {
3449
3449
  }
3450
3450
  refresh(e, s = "current") {
3451
3451
  const n = this.options.runtime(), i = n.engine.getState().slices.conversation.sessions[e]?.queries[s].requestId;
3452
- if (!J(this.options) || !this.observations.has(e)) return Promise.resolve();
3452
+ if (!Q(this.options) || !this.observations.has(e)) return Promise.resolve();
3453
3453
  const r = i ?? this.options.nextRequestId();
3454
3454
  return n.engine.dispatch({ ...this.options.authority, type: "conversation.snapshot", sessionId: e, requestId: r, lane: s }).then(() => new Promise((o, c) => {
3455
3455
  let d = null;
3456
3456
  const l = () => {
3457
- const u = n.engine.getState().slices.conversation.sessions[e]?.queries[s], p = !this.disposed && J(this.options) && this.observations.has(e);
3457
+ const u = n.engine.getState().slices.conversation.sessions[e]?.queries[s], p = !this.disposed && Q(this.options) && this.observations.has(e);
3458
3458
  return p && u?.requestId === r ? !1 : (d?.(), this.waiters.delete(l), p && u?.status === "error" ? c(u.error) : o(), !0);
3459
3459
  };
3460
3460
  l() || (this.waiters.add(l), d = n.engine.subscribe(l));
3461
3461
  }));
3462
3462
  }
3463
3463
  receive(e) {
3464
- if (this.disposed || !J(this.options) || !(this.options.enabled?.() ?? !0)) return;
3464
+ if (this.disposed || !Q(this.options) || !(this.options.enabled?.() ?? !0)) return;
3465
3465
  const s = e.type === "conversation.item.updated" ? e.item.conversation_id : e.type === "conversation.execution.updated" ? e.execution.conversation_id : e.type === "conversation.interaction.updated" ? e.interaction.conversation_id : e.conversation_id;
3466
3466
  this.observations.has(s) && this.options.runtime().engine.accept({ ...this.options.authority, type: "conversation.display_received", event: e });
3467
3467
  }
3468
3468
  wake() {
3469
- if (!(this.disposed || !J(this.options)) && (this.reconcile(), !!(this.options.enabled?.() ?? !0))) {
3469
+ if (!(this.disposed || !Q(this.options)) && (this.reconcile(), !!(this.options.enabled?.() ?? !0))) {
3470
3470
  this.deliveryRecovery.refresh();
3471
3471
  for (const [e, s] of this.observations)
3472
3472
  s.roomRequested && this.options.socket.retain(e, this.owner).catch((n) => this.report(n)), s.current.refresh(), s.history.refresh();
3473
3473
  }
3474
3474
  }
3475
3475
  report(e) {
3476
- !this.disposed && J(this.options) && this.options.onError(e);
3476
+ !this.disposed && Q(this.options) && this.options.onError(e);
3477
3477
  }
3478
3478
  hasUncertainDelivery() {
3479
3479
  const e = this.options.runtime().engine.getState().slices.conversation;
@@ -3486,7 +3486,7 @@ class Uo {
3486
3486
  waitForDelivery() {
3487
3487
  return new Promise((e) => {
3488
3488
  let s = null;
3489
- const n = () => !this.disposed && J(this.options) && this.hasRunningDelivery() ? !1 : (s?.(), this.waiters.delete(n), e(), !0);
3489
+ const n = () => !this.disposed && Q(this.options) && this.hasRunningDelivery() ? !1 : (s?.(), this.waiters.delete(n), e(), !0);
3490
3490
  n() || (this.waiters.add(n), s = this.options.runtime().engine.subscribe(n));
3491
3491
  });
3492
3492
  }
@@ -3504,7 +3504,7 @@ function Pe(t, e) {
3504
3504
  (s, n, i, r) => `${n}${new URL(i, e).toString()}${r}`
3505
3505
  ) : t;
3506
3506
  }
3507
- function Js(t, e, s = "stopped", n, i = "Run stopped by user.") {
3507
+ function Qs(t, e, s = "stopped", n, i = "Run stopped by user.") {
3508
3508
  const r = new Set(n ?? [
3509
3509
  t.assistantDraftRespondsToUserMessageId,
3510
3510
  t.activeResponseUserMessageId,
@@ -3671,20 +3671,20 @@ function ds(t, e, s, n) {
3671
3671
  };
3672
3672
  let h = S;
3673
3673
  for (const y of t.optimistic.filter((w) => w.cancelled && !t.stop?.userMessageIds.includes(w.userMessageId))) {
3674
- const w = Js(h, "", "stopped", [y.userMessageId], Jn(y.cancellationReason));
3674
+ const w = Qs(h, "", "stopped", [y.userMessageId], Qn(y.cancellationReason));
3675
3675
  h = { ...h, messages: w.messages, segments: w.segments };
3676
3676
  }
3677
3677
  if (!t.stop) return h;
3678
- const b = Js(
3678
+ const b = Qs(
3679
3679
  h,
3680
3680
  "",
3681
3681
  t.stop.pending ? "stopping" : "stopped",
3682
3682
  t.stop.userMessageIds,
3683
- Jn(t.stop.reason ?? "user_requested")
3683
+ Qn(t.stop.reason ?? "user_requested")
3684
3684
  );
3685
3685
  return { ...S, messages: b.messages, segments: b.segments };
3686
3686
  }
3687
- function Jn(t) {
3687
+ function Qn(t) {
3688
3688
  switch (t) {
3689
3689
  case "user_requested":
3690
3690
  return "Run stopped by user.";
@@ -3733,7 +3733,7 @@ function _t(t) {
3733
3733
  updatedAt: null
3734
3734
  };
3735
3735
  }
3736
- class Qn {
3736
+ class Jn {
3737
3737
  constructor(e, s, n = (i, r) => r) {
3738
3738
  this.loader = s, this.merge = n, this.state = _t(e);
3739
3739
  }
@@ -3828,7 +3828,7 @@ function Lo(t, e, s) {
3828
3828
  function Fo(t) {
3829
3829
  return t ? t.ids.map((e) => t.entitiesById[e]).filter((e) => !!e) : [];
3830
3830
  }
3831
- function Ql(t) {
3831
+ function Jl(t) {
3832
3832
  return t.visible ? t.minimized ? { state: "minimized" } : { state: t.open ? "visible_open" : "visible_closed" } : { state: "hidden" };
3833
3833
  }
3834
3834
  function $o(t) {
@@ -3865,7 +3865,7 @@ const kt = /* @__PURE__ */ Object.create(null);
3865
3865
  Object.keys(he).forEach((t) => {
3866
3866
  kt[he[t]] = t;
3867
3867
  });
3868
- const Qs = { type: "error", data: "parser error" }, Ji = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", Qi = typeof ArrayBuffer == "function", Xi = (t) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(t) : t && t.buffer instanceof ArrayBuffer, mn = ({ type: t, data: e }, s, n) => Ji && e instanceof Blob ? s ? n(e) : Xn(e, n) : Qi && (e instanceof ArrayBuffer || Xi(e)) ? s ? n(e) : Xn(new Blob([e]), n) : n(he[t] + (e || "")), Xn = (t, e) => {
3868
+ const Js = { type: "error", data: "parser error" }, Qi = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", Ji = typeof ArrayBuffer == "function", Xi = (t) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(t) : t && t.buffer instanceof ArrayBuffer, mn = ({ type: t, data: e }, s, n) => Qi && e instanceof Blob ? s ? n(e) : Xn(e, n) : Ji && (e instanceof ArrayBuffer || Xi(e)) ? s ? n(e) : Xn(new Blob([e]), n) : n(he[t] + (e || "")), Xn = (t, e) => {
3869
3869
  const s = new FileReader();
3870
3870
  return s.onload = function() {
3871
3871
  const n = s.result.split(",")[1];
@@ -3877,9 +3877,9 @@ function Yn(t) {
3877
3877
  }
3878
3878
  let ls;
3879
3879
  function Vo(t, e) {
3880
- if (Ji && t.data instanceof Blob)
3880
+ if (Qi && t.data instanceof Blob)
3881
3881
  return t.data.arrayBuffer().then(Yn).then(e);
3882
- if (Qi && (t.data instanceof ArrayBuffer || Xi(t.data)))
3882
+ if (Ji && (t.data instanceof ArrayBuffer || Xi(t.data)))
3883
3883
  return e(Yn(t.data));
3884
3884
  mn(t, !1, (s) => {
3885
3885
  ls || (ls = new TextEncoder()), e(ls.encode(s));
@@ -3910,14 +3910,14 @@ const Ko = (t) => {
3910
3910
  data: t.substring(1)
3911
3911
  } : {
3912
3912
  type: kt[s]
3913
- } : Qs;
3913
+ } : Js;
3914
3914
  }, Go = (t, e) => {
3915
3915
  if (Wo) {
3916
3916
  const s = Ko(t);
3917
3917
  return Yi(s, e);
3918
3918
  } else
3919
3919
  return { base64: !0, data: t };
3920
- }, Yi = (t, e) => e === "blob" ? t instanceof Blob ? t : new Blob([t]) : t instanceof ArrayBuffer ? t : t.buffer, Zi = "", Jo = (t, e) => {
3920
+ }, Yi = (t, e) => e === "blob" ? t instanceof Blob ? t : new Blob([t]) : t instanceof ArrayBuffer ? t : t.buffer, Zi = "", Qo = (t, e) => {
3921
3921
  const s = t.length, n = new Array(s);
3922
3922
  let i = 0;
3923
3923
  t.forEach((r, a) => {
@@ -3925,7 +3925,7 @@ const Ko = (t) => {
3925
3925
  n[a] = o, ++i === s && e(n.join(Zi));
3926
3926
  });
3927
3927
  });
3928
- }, Qo = (t, e) => {
3928
+ }, Jo = (t, e) => {
3929
3929
  const s = t.split(Zi), n = [];
3930
3930
  for (let i = 0; i < s.length; i++) {
3931
3931
  const r = yn(s[i], e);
@@ -3991,7 +3991,7 @@ function Yo(t, e) {
3991
3991
  break;
3992
3992
  const c = ft(s, 8), d = new DataView(c.buffer, c.byteOffset, c.length), l = d.getUint32(0);
3993
3993
  if (l > Math.pow(2, 21) - 1) {
3994
- o.enqueue(Qs);
3994
+ o.enqueue(Js);
3995
3995
  break;
3996
3996
  }
3997
3997
  i = l * Math.pow(2, 32) + d.getUint32(4), n = 3;
@@ -4002,7 +4002,7 @@ function Yo(t, e) {
4002
4002
  o.enqueue(yn(r ? c : us.decode(c), e)), n = 0;
4003
4003
  }
4004
4004
  if (i === 0 || i > t) {
4005
- o.enqueue(Qs);
4005
+ o.enqueue(Js);
4006
4006
  break;
4007
4007
  }
4008
4008
  }
@@ -4253,7 +4253,7 @@ class da extends vn {
4253
4253
  return this.onClose({ description: "transport closed by the server" }), !1;
4254
4254
  this.onPacket(n);
4255
4255
  };
4256
- Qo(e, this.socket.binaryType).forEach(s), this.readyState !== "closed" && (this._polling = !1, this.emitReserved("pollComplete"), this.readyState === "open" && this._poll());
4256
+ Jo(e, this.socket.binaryType).forEach(s), this.readyState !== "closed" && (this._polling = !1, this.emitReserved("pollComplete"), this.readyState === "open" && this._poll());
4257
4257
  }
4258
4258
  /**
4259
4259
  * For polling, send a close packet.
@@ -4273,7 +4273,7 @@ class da extends vn {
4273
4273
  * @protected
4274
4274
  */
4275
4275
  write(e) {
4276
- this.writable = !1, Jo(e, (s) => {
4276
+ this.writable = !1, Qo(e, (s) => {
4277
4277
  this.doWrite(s, () => {
4278
4278
  this.writable = !0, this.emitReserved("drain");
4279
4279
  });
@@ -6189,6 +6189,13 @@ class La {
6189
6189
  forceNew: !0,
6190
6190
  auth: { ...e.auth },
6191
6191
  reconnection: e.reconnect ?? !0
6192
+ }), this.socket.io.on("open", () => {
6193
+ const s = this.socket.io.engine, n = this.attempt;
6194
+ s.on("packet", (i) => {
6195
+ this.socket.io.engine !== s || this.attempt !== n || (this.activity.lastPacketReceivedAt = Date.now(), i.type === "ping" && (this.activity.lastHeartbeatReceivedAt = this.activity.lastPacketReceivedAt));
6196
+ }), s.on("packetCreate", (i) => {
6197
+ this.socket.io.engine === s && this.attempt === n && i.type === "pong" && (this.activity.lastHeartbeatQueuedAt = Date.now());
6198
+ });
6192
6199
  }), this.socket.io.on("reconnect_attempt", () => this.beginAttempt()), this.socket.io.on("close", (s) => {
6193
6200
  const n = this.generation, i = this.attempt;
6194
6201
  s === "forced close" ? queueMicrotask(() => {
@@ -6271,6 +6278,15 @@ class La {
6271
6278
  readinessTimer = null;
6272
6279
  attemptCount = 0;
6273
6280
  attempt = null;
6281
+ activity = {
6282
+ lastPacketReceivedAt: null,
6283
+ lastHeartbeatReceivedAt: null,
6284
+ lastHeartbeatQueuedAt: null,
6285
+ lastDisconnect: null
6286
+ };
6287
+ get connectionActivity() {
6288
+ return { ...this.activity, lastDisconnect: this.activity.lastDisconnect ? { ...this.activity.lastDisconnect } : null };
6289
+ }
6274
6290
  connect() {
6275
6291
  if (!this.retired && this.rejectedToken !== this.options.auth.token) {
6276
6292
  if (this.active) return;
@@ -6320,7 +6336,7 @@ class La {
6320
6336
  !this.active || this.retired || (this.invalidate(!1, e), this.socket.io.engine.close());
6321
6337
  }
6322
6338
  beginAttempt() {
6323
- this.clearReadinessTimers(), this.active = !0, this.attempt = { connectionAttemptId: crypto.randomUUID(), reconnectAttempt: this.attemptCount++, startedAt: Date.now() }, this.socket.auth = { ...this.options.auth, connection_attempt_id: this.attempt.connectionAttemptId }, this.options.onAttempt?.(this.attempt);
6339
+ this.clearReadinessTimers(), this.activity = { ...this.activity, lastPacketReceivedAt: null, lastHeartbeatReceivedAt: null, lastHeartbeatQueuedAt: null }, this.active = !0, this.attempt = { connectionAttemptId: crypto.randomUUID(), reconnectAttempt: this.attemptCount++, startedAt: Date.now() }, this.socket.auth = { ...this.options.auth, connection_attempt_id: this.attempt.connectionAttemptId }, this.options.onAttempt?.(this.attempt);
6324
6340
  const e = this.generation, s = (n) => {
6325
6341
  e !== this.generation || !this.active || (this.options.onError(new A("Product Agent readiness timed out", n, !1, {
6326
6342
  retryable: !0,
@@ -6485,7 +6501,14 @@ class La {
6485
6501
  }
6486
6502
  invalidate(e = !1, s = "local_invalidation") {
6487
6503
  if (this.clearReadinessTimers(), !!this.active) {
6488
- this.active = !1, this.generation++, this.ready = null, this.admitted = null, this.activating = !1;
6504
+ this.activity.lastDisconnect = {
6505
+ occurredAt: Date.now(),
6506
+ reason: s,
6507
+ connectionAttemptId: this.attempt?.connectionAttemptId ?? null,
6508
+ lastPacketReceivedAt: this.activity.lastPacketReceivedAt,
6509
+ lastHeartbeatReceivedAt: this.activity.lastHeartbeatReceivedAt,
6510
+ lastHeartbeatQueuedAt: this.activity.lastHeartbeatQueuedAt
6511
+ }, this.active = !1, this.generation++, this.ready = null, this.admitted = null, this.activating = !1;
6489
6512
  for (const n of [...this.pending]) n(new A("Connection lost before acknowledgement", "delivery_unknown", !0));
6490
6513
  this.options.onDisconnect(e, s);
6491
6514
  }
@@ -7046,7 +7069,7 @@ function Ga(t, e, s, n = () => crypto.randomUUID()) {
7046
7069
  };
7047
7070
  }
7048
7071
  const oi = /* @__PURE__ */ new Map(), ai = /* @__PURE__ */ new Map();
7049
- function Ja(t, e, s = () => crypto.randomUUID()) {
7072
+ function Qa(t, e, s = () => crypto.randomUUID()) {
7050
7073
  try {
7051
7074
  return Ga(window.sessionStorage, t, e, s);
7052
7075
  } catch (n) {
@@ -7147,6 +7170,9 @@ class L extends EventTarget {
7147
7170
  get connectionAttempt() {
7148
7171
  return this.transport.connectionAttempt;
7149
7172
  }
7173
+ get connectionActivity() {
7174
+ return this.transport.connectionActivity;
7175
+ }
7150
7176
  retryReadiness() {
7151
7177
  this.initialReadinessExpired = !1, this.startInitialReadinessBudget(), this.transport.replaceCredentials(this.options.auth, !1);
7152
7178
  }
@@ -7436,7 +7462,7 @@ function ur(t) {
7436
7462
  const e = t;
7437
7463
  return typeof e.observedAt == "string" && e.observedAt.length <= 40 && Number.isFinite(Date.parse(e.observedAt)) && Te(e.sessionId) && Te(e.responseItemId) && Te(e.respondsToUserMessageId) && typeof e.panelVisible == "boolean" && typeof e.documentVisible == "boolean" && typeof e.loading == "boolean";
7438
7464
  }
7439
- function Qa(t, e, s) {
7465
+ function Ja(t, e, s) {
7440
7466
  if (!ur(s)) return;
7441
7467
  const n = tn.get(t) ?? /* @__PURE__ */ new Map();
7442
7468
  n.set(e, {
@@ -8615,7 +8641,7 @@ function Is(t, e, s, n) {
8615
8641
  }
8616
8642
  class eu {
8617
8643
  constructor(e, s, n = 20) {
8618
- this.loadPage = s, this.limit = n, this.recentQuery = new Qn(
8644
+ this.loadPage = s, this.limit = n, this.recentQuery = new Jn(
8619
8645
  `${e}:recent`,
8620
8646
  async ({ cursor: i }) => St(
8621
8647
  await this.loadPage({ cursor: i, limit: this.limit, pinned: !1 }).then((r) => ({
@@ -8624,7 +8650,7 @@ class eu {
8624
8650
  }))
8625
8651
  ),
8626
8652
  Lo
8627
- ), this.pinnedQuery = new Qn(
8653
+ ), this.pinnedQuery = new Jn(
8628
8654
  `${e}:pinned`,
8629
8655
  async () => St({
8630
8656
  entities: await this.loadAllPinned(),
@@ -9128,7 +9154,7 @@ class ou {
9128
9154
  this.stopError && (e.lastError = this.stopError, e.lastErrorCode = "stop_failed");
9129
9155
  const s = [...this.stopPreviews.keys()];
9130
9156
  if (!s.length) return e;
9131
- const n = Js(e, "", "stopping", s);
9157
+ const n = Qs(e, "", "stopping", s);
9132
9158
  return e.activeResponseUserMessageId && !this.stopPreviews.has(e.activeResponseUserMessageId) ? { ...e, messages: n.messages, segments: n.segments } : n;
9133
9159
  }
9134
9160
  updateProjection(e, s, n, i, r) {
@@ -9237,7 +9263,7 @@ class ou {
9237
9263
  });
9238
9264
  }
9239
9265
  async sendMessageNow(e, s, n) {
9240
- const i = e, r = s.clientMessageId, a = Q((d) => {
9266
+ const i = e, r = s.clientMessageId, a = J((d) => {
9241
9267
  n === this.submissionGeneration && this.reportOperationTiming(d);
9242
9268
  }, {
9243
9269
  operation: "send",
@@ -9343,7 +9369,7 @@ class ou {
9343
9369
  ...s,
9344
9370
  e.activeResponseUserMessageId,
9345
9371
  e.messages.filter((d) => d.role === "user").slice(-1)[0]?.id
9346
- ].filter((d) => !!d))], i = Q((d) => this.reportOperationTiming(d), {
9372
+ ].filter((d) => !!d))], i = J((d) => this.reportOperationTiming(d), {
9347
9373
  operation: "stop",
9348
9374
  layer: "renderer",
9349
9375
  requestId: crypto.randomUUID(),
@@ -9527,7 +9553,7 @@ function mi(t) {
9527
9553
  }) : null
9528
9554
  };
9529
9555
  }
9530
- const Jc = globalThis.fetch.bind(globalThis), yi = '.pluno-pa-widget-host[data-pluno-product-agent-ui="widget"]', Qc = '.pluno-pa-widget[data-pluno-product-agent-ui-root="widget"]', Xc = ".pluno-pa-widget__panel", Yc = ".pluno-pa-widget__timeline", Zc = "__plunoExtensionWidgetOwner";
9556
+ const Qc = globalThis.fetch.bind(globalThis), yi = '.pluno-pa-widget-host[data-pluno-product-agent-ui="widget"]', Jc = '.pluno-pa-widget[data-pluno-product-agent-ui-root="widget"]', Xc = ".pluno-pa-widget__panel", Yc = ".pluno-pa-widget__timeline", Zc = "__plunoExtensionWidgetOwner";
9531
9557
  class ue extends Error {
9532
9558
  constructor(e, s, n, i) {
9533
9559
  super(e), this.retryable = s, this.status = n, this.retryAfterMs = i, this.name = "ProductAgentTokenProviderError";
@@ -9656,7 +9682,7 @@ function Es(t) {
9656
9682
  }
9657
9683
  return !0;
9658
9684
  }
9659
- function Je(t) {
9685
+ function Qe(t) {
9660
9686
  const e = Z(t, "connection_failed", "web_transport");
9661
9687
  if (t instanceof Error && t.message === e.message) return t;
9662
9688
  if (t && typeof t == "object" && !("message" in t)) {
@@ -9857,7 +9883,7 @@ class Kt {
9857
9883
  runtime: this.clientRuntime,
9858
9884
  authority: this.directoryAuthority,
9859
9885
  random: Math.random,
9860
- persistence: Ja(
9886
+ persistence: Qa(
9861
9887
  this.modelClientScopeId,
9862
9888
  this.directoryAuthority.authorityId
9863
9889
  )
@@ -9868,7 +9894,7 @@ class Kt {
9868
9894
  isActiveTurn: (s) => this.clientRuntime.engine.getProjection().directory.activityBySessionId[s] === !0,
9869
9895
  nextRequestId: z,
9870
9896
  onError: (s) => {
9871
- this.handleDirectoryTransportError(s), this.emit("error", Je(s));
9897
+ this.handleDirectoryTransportError(s), this.emit("error", Qe(s));
9872
9898
  },
9873
9899
  wakeup: { start: () => {
9874
9900
  }, stop: () => {
@@ -9912,7 +9938,7 @@ class Kt {
9912
9938
  http: this.directoryHttp,
9913
9939
  now: () => Date.now(),
9914
9940
  prepareSubmission: async ({ submission: f, sources: v }, I) => {
9915
- const _ = Q(this.operationTimingReporter, {
9941
+ const _ = J(this.operationTimingReporter, {
9916
9942
  operation: "send",
9917
9943
  layer: "sdk",
9918
9944
  requestId: f.requestId,
@@ -10324,7 +10350,7 @@ class Kt {
10324
10350
  this.handleDirectoryTransportError(r);
10325
10351
  return;
10326
10352
  }
10327
- const a = Je(r);
10353
+ const a = Qe(r);
10328
10354
  if (Es(r)) {
10329
10355
  V("web-sdk.agent", "Pluno connection attempt failed; retrying", {
10330
10356
  message: a.message,
@@ -10370,7 +10396,7 @@ class Kt {
10370
10396
  this.authenticatingWarmupHints.delete(o), !(this.clientRuntime.isDisposed || r !== this.submissionIntentRevision || a && a !== this.authenticatedUserId) && this.warmup(e);
10371
10397
  }, (c) => {
10372
10398
  this.authenticatingWarmupHints.delete(o), this.clientRuntime.isDisposed || V("web-sdk.warmup", "Authentication did not admit the warm-up hint", {
10373
- message: Je(c).message
10399
+ message: Qe(c).message
10374
10400
  });
10375
10401
  });
10376
10402
  return;
@@ -10437,7 +10463,7 @@ class Kt {
10437
10463
  if (!n && !i.length) return null;
10438
10464
  if (this.options.productVariant === "customer_embedded" && (i.forEach(Cr), i.reduce((v, I) => v + I.sizeBytes, 0) > Ir))
10439
10465
  throw new Error("Embedded attachments must total at most 50 MB per message");
10440
- const r = s.clientMessageId ?? z(), a = Q(this.operationTimingReporter, {
10466
+ const r = s.clientMessageId ?? z(), a = J(this.operationTimingReporter, {
10441
10467
  operation: "send",
10442
10468
  layer: "sdk",
10443
10469
  requestId: r,
@@ -10505,7 +10531,7 @@ class Kt {
10505
10531
  });
10506
10532
  }
10507
10533
  reportResponseVisibility(e) {
10508
- Qa(this, this.options.entrySurface, e);
10534
+ Ja(this, this.options.entrySurface, e);
10509
10535
  }
10510
10536
  reportInvalidStateTransition(e, s, n) {
10511
10537
  n !== void 0 && !gn(n) || this.reportHealthSignal("invalid_state_transition", {
@@ -10544,7 +10570,7 @@ class Kt {
10544
10570
  if (!r) return !1;
10545
10571
  if (r.type === "preparation") {
10546
10572
  const a = z(), o = Bo(r.submission);
10547
- return bs(this.clientRuntime, this.modelClientScopeId, a, r.submission.requestedModel), this.sendMessage(o.content, { clientMessageId: a, attachments: o.attachments, proactiveSuggestionQuestion: o.proactiveSuggestionQuestion }).catch((c) => this.emit("error", Je(c))), !0;
10573
+ return bs(this.clientRuntime, this.modelClientScopeId, a, r.submission.requestedModel), this.sendMessage(o.content, { clientMessageId: a, attachments: o.attachments, proactiveSuggestionQuestion: o.proactiveSuggestionQuestion }).catch((c) => this.emit("error", Qe(c))), !0;
10548
10574
  }
10549
10575
  return r.type === "delivery" ? (this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.submit", userMessageId: r.userMessageId, now: Date.now(), manualRetry: !0 }), !0) : (this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.operation", command: {
10550
10576
  request_id: z(),
@@ -10645,7 +10671,7 @@ class Kt {
10645
10671
  }
10646
10672
  stop() {
10647
10673
  const e = this.getState();
10648
- Q((s) => this.reportOperationTiming(s), {
10674
+ J((s) => this.reportOperationTiming(s), {
10649
10675
  operation: "stop",
10650
10676
  layer: "sdk",
10651
10677
  requestId: z(),
@@ -10932,7 +10958,7 @@ class Kt {
10932
10958
  },
10933
10959
  embedded: {
10934
10960
  appearance: async (l) => {
10935
- const u = await this.directoryHttp.request("/bootstrap", { page_url: l.pageUrl }, void 0, "GET", "embed"), p = Jd(u);
10961
+ const u = await this.directoryHttp.request("/bootstrap", { page_url: l.pageUrl }, void 0, "GET", "embed"), p = Qd(u);
10936
10962
  return { kind: "appearance", origin: l.origin, value: p ? { accent: p.accentColor ?? "#7c3aed", colorScheme: p.colorScheme ?? "light", fontFamily: p.fontFamily ?? "inherit", scribbleStyle: p.scribbleStyle ?? !1 } : null };
10937
10963
  },
10938
10964
  feedback: async (l) => (await this.directoryHttp.request("/feedback", {}, { message: l }, "POST", "embed")).success
@@ -11383,7 +11409,7 @@ class Kt {
11383
11409
  this.clearSocketAuthTimer(), this.clearEmbeddedRecoveryBudget(), this.rejectedDiagnosticsToken = null, this.clientDiagnosticsRetryTimer !== null && window.clearTimeout(this.clientDiagnosticsRetryTimer), this.clientDiagnosticsRetryTimer = null, this.options.productVariant === "customer_embedded" && (this.pendingTransportDiagnostics.length > 0 || this.state.lastErrorCode === "connection_failed") && this.reportTransportDiagnostic("ready_applied", { recoveryOutcome: "recovered", stage: "bootstrap" }), this.reconnectAttempts = 0, this.transportDiagnosticEpisodes.clear(), this.flushClientDiagnostics();
11384
11410
  const s = Ri(e.user);
11385
11411
  this.applyAuthenticatedDirectoryIdentity(e.user), this.authenticatedSocket = this.socket, this.directoryObservation.reconnect().catch(() => {
11386
- }), this.conversationObservation?.wake(), this.flushPendingWidgetLifecycleEvents(), this.flushQueuedClientEvents(), this.startHeartbeat(), this.runtimeHelperJavascript = Qd(e.runtimeHelpers)?.javascript ?? null;
11412
+ }), this.conversationObservation?.wake(), this.flushPendingWidgetLifecycleEvents(), this.flushQueuedClientEvents(), this.startHeartbeat(), this.runtimeHelperJavascript = Jd(e.runtimeHelpers)?.javascript ?? null;
11387
11413
  const n = {
11388
11414
  user: s,
11389
11415
  status: "connected",
@@ -11751,7 +11777,7 @@ class Kt {
11751
11777
  this.directoryHttp.auth.token = c, a = "bootstrap", this.lastRecoveryStage = a, await this.replaceDefaultTransportCredentials(e), this.reportTransportDiagnostic("auth_refresh_validated", r);
11752
11778
  })().catch((c) => {
11753
11779
  if (this.socket !== e || this.state.status === "closed") throw c;
11754
- if (this.reportTransportDiagnostic("auth_refresh_failed", { ...r, ...this.connectionFailureDiagnostic(c, a) }), this.credentialRecoveryFailure = Je(c), c instanceof A && ["unauthorized", "403", "update_required"].includes(c.code) || !Es(c)) {
11780
+ if (this.reportTransportDiagnostic("auth_refresh_failed", { ...r, ...this.connectionFailureDiagnostic(c, a) }), this.credentialRecoveryFailure = Qe(c), c instanceof A && ["unauthorized", "403", "update_required"].includes(c.code) || !Es(c)) {
11755
11781
  const d = c instanceof A ? c : new A(c instanceof ue ? c.message : "Your session could not be refreshed. Try again.", this.options.productVariant === "customer_embedded" ? "connection_failed" : "unauthorized", !1);
11756
11782
  throw this.stopAuthentication(d), d;
11757
11783
  }
@@ -12145,7 +12171,7 @@ function Md(t, e) {
12145
12171
  const i = () => {
12146
12172
  if (!n)
12147
12173
  throw new Error("sandboxFiles is only available during browser-code execution");
12148
- }, r = async (o, c) => await Jc(`${e.replace(/\/$/, "")}${o}`, c);
12174
+ }, r = async (o, c) => await Qc(`${e.replace(/\/$/, "")}${o}`, c);
12149
12175
  return {
12150
12176
  value: Object.freeze({
12151
12177
  upload: async (o) => {
@@ -12406,20 +12432,20 @@ function $d(t, e) {
12406
12432
  const Dn = y(D, R);
12407
12433
  On.push(Dn), Gt.push(Dn.lines);
12408
12434
  }
12409
- const Jt = [];
12435
+ const Qt = [];
12410
12436
  if (w.shadowRoot)
12411
12437
  for (const D of Array.from(w.shadowRoot.children))
12412
- D instanceof HTMLElement && Jt.push(y(D, R + 1));
12413
- const ct = [...On, ...Jt], Qt = O.length > 0 || k || ct.some((D) => D.hasUsefulContent), xn = Be(
12438
+ D instanceof HTMLElement && Qt.push(y(D, R + 1));
12439
+ const ct = [...On, ...Qt], Jt = O.length > 0 || k || ct.some((D) => D.hasUsefulContent), xn = Be(
12414
12440
  [O, ...ct.map((D) => D.textPreview)].filter(Boolean).join(" ")
12415
- ).slice(0, 180), Lr = w.hasAttribute("contenteditable") && (O.length > 0 || !w.querySelector("[contenteditable]")), Mn = d.some((D) => w.hasAttribute(D)) || !!q || Lr, Xt = (w.getClientRects().length > 0 || C.display === "contents") && (s.has(T) || Mn || E) && (Qt || E) && (!i.has(T) || Qt || Mn || E), Yt = Xt ? 1 : 0, $e = [];
12441
+ ).slice(0, 180), Lr = w.hasAttribute("contenteditable") && (O.length > 0 || !w.querySelector("[contenteditable]")), Mn = d.some((D) => w.hasAttribute(D)) || !!q || Lr, Xt = (w.getClientRects().length > 0 || C.display === "contents") && (s.has(T) || Mn || E) && (Jt || E) && (!i.has(T) || Jt || Mn || E), Yt = Xt ? 1 : 0, $e = [];
12416
12442
  if (Xt) {
12417
12443
  const D = ct.some((ve) => ve.containsTextElement), $ = n.has(T) && !D ? xn : O;
12418
12444
  $e.push(Sr(w, c, a, $.slice(0, 180)));
12419
12445
  }
12420
12446
  for (const D of Gt)
12421
12447
  $e.push(...yt(D, Yt));
12422
- const Zt = Jt.flatMap((D) => D.lines);
12448
+ const Zt = Qt.flatMap((D) => D.lines);
12423
12449
  if (Zt.length > 0) {
12424
12450
  const D = Zt.slice(0, 20);
12425
12451
  Zt.length > D.length && D.push("… shadow DOM omitted");
@@ -12432,7 +12458,7 @@ function $d(t, e) {
12432
12458
  }
12433
12459
  return {
12434
12460
  lines: $e,
12435
- hasUsefulContent: Qt,
12461
+ hasUsefulContent: Jt,
12436
12462
  textPreview: xn,
12437
12463
  containsTextElement: n.has(T) || ct.some((D) => D.containsTextElement)
12438
12464
  };
@@ -12569,7 +12595,7 @@ function Kd() {
12569
12595
  },
12570
12596
  {
12571
12597
  name: "widget_root",
12572
- selector: Qc,
12598
+ selector: Jc,
12573
12599
  description: "Finds Pluno's widget root inside the widget host shadow root."
12574
12600
  },
12575
12601
  {
@@ -12610,7 +12636,7 @@ function ki(t) {
12610
12636
  function Gd(t) {
12611
12637
  return Array.isArray(t) ? t.filter((e) => typeof e == "string" && e.trim().length > 0) : [];
12612
12638
  }
12613
- function Jd(t) {
12639
+ function Qd(t) {
12614
12640
  if (!t || typeof t != "object")
12615
12641
  return null;
12616
12642
  const e = t, s = e.appearance, n = s && typeof s == "object" ? s : e, i = typeof n.accentColor == "string" ? n.accentColor : null, r = n.colorScheme === "dark" ? "dark" : n.colorScheme === "light" ? "light" : null, a = typeof n.fontFamily == "string" && n.fontFamily.trim() ? n.fontFamily : null, o = typeof n.scribbleStyle == "boolean" ? n.scribbleStyle : null;
@@ -12621,7 +12647,7 @@ function Jd(t) {
12621
12647
  ...o !== null ? { scribbleStyle: o } : {}
12622
12648
  };
12623
12649
  }
12624
- function Qd(t) {
12650
+ function Jd(t) {
12625
12651
  if (!t || typeof t != "object")
12626
12652
  return null;
12627
12653
  const e = t.javascript;
@@ -12736,7 +12762,7 @@ function Rr(t, e) {
12736
12762
  ...W(i) ? { runId: W(i) } : {},
12737
12763
  dataType: "function_call_output",
12738
12764
  toolName: mr,
12739
- callId: Qe(i) ?? void 0,
12765
+ callId: Je(i) ?? void 0,
12740
12766
  sharePromptAllowed: r
12741
12767
  };
12742
12768
  const a = Pc(i.output);
@@ -12751,7 +12777,7 @@ function Rr(t, e) {
12751
12777
  ...W(i) ? { runId: W(i) } : {},
12752
12778
  dataType: "scheduled_check_in",
12753
12779
  toolName: vr,
12754
- callId: Qe(i) ?? void 0,
12780
+ callId: Je(i) ?? void 0,
12755
12781
  scheduledCheckInId: a.id ?? void 0,
12756
12782
  scheduledCheckInAt: a.dueAt
12757
12783
  };
@@ -12767,7 +12793,7 @@ function Rr(t, e) {
12767
12793
  ...W(i) ? { runId: W(i) } : {},
12768
12794
  dataType: "function_call_output",
12769
12795
  toolName: "authenticate_pipedream_app",
12770
- callId: Qe(i) ?? void 0,
12796
+ callId: Je(i) ?? void 0,
12771
12797
  integrationAuthRequest: o
12772
12798
  } : c ? {
12773
12799
  id: String(s.id ?? crypto.randomUUID()),
@@ -12780,7 +12806,7 @@ function Rr(t, e) {
12780
12806
  ...W(i) ? { runId: W(i) } : {},
12781
12807
  dataType: "function_call_output",
12782
12808
  toolName: "request_personal_channel_connection",
12783
- callId: Qe(i) ?? void 0,
12809
+ callId: Je(i) ?? void 0,
12784
12810
  personalChannelConnectionRequest: c
12785
12811
  } : null;
12786
12812
  }
@@ -12795,7 +12821,7 @@ function Rr(t, e) {
12795
12821
  ...W(i) ? { runId: W(i) } : {},
12796
12822
  dataType: String(i.type),
12797
12823
  toolName: i.type === "tab_lifecycle_decision" ? "tab_lifecycle_decision" : typeof i.name == "string" ? i.name : void 0,
12798
- callId: Qe(i) ?? void 0,
12824
+ callId: Je(i) ?? void 0,
12799
12825
  loading: i.steered === !0 ? !1 : i.localExecutionStatus === "queued" || i.localExecutionStatus === "running" ? !0 : typeof i.localExecutionStatus == "string" ? !1 : void 0,
12800
12826
  ...i.steered === !0 ? { steered: !0 } : {}
12801
12827
  } : i.type === "run_status" || i.type === "run_error" ? i.type === "run_error" && i.stage === "tool_execution" ? null : {
@@ -12884,7 +12910,7 @@ function et(t) {
12884
12910
  const e = t.trim() || "Run tool", s = e.codePointAt(0) ?? 0;
12885
12911
  return s >= 126976 && s <= 129791 || s >= 9728 && s <= 10175 || s >= 127462 && s <= 127487 ? e : `🛠️ ${e}`;
12886
12912
  }
12887
- function Qe(t) {
12913
+ function Je(t) {
12888
12914
  const e = t.callId ?? t.call_id;
12889
12915
  return typeof e == "string" && e ? e : null;
12890
12916
  }
@@ -13414,12 +13440,12 @@ function Br(t) {
13414
13440
  }
13415
13441
  }
13416
13442
  function Bt(t) {
13417
- return t.replace(Hl, Fl).replace(Vl, Jl).replace(Pr, `Bearer ${me}`).replace(Dr, `Basic ${me}`).replace(Ur, me).replace(Nr, (e, s) => `${s}: ${Wt}`);
13443
+ return t.replace(Hl, Fl).replace(Vl, Ql).replace(Pr, `Bearer ${me}`).replace(Dr, `Basic ${me}`).replace(Ur, me).replace(Nr, (e, s) => `${s}: ${Wt}`);
13418
13444
  }
13419
13445
  function Gl(t) {
13420
13446
  return t.replace(Pr, `Bearer ${me}`).replace(Dr, `Basic ${me}`).replace(Ur, me).replace(Nr, (e, s) => `${s}: ${Wt}`);
13421
13447
  }
13422
- function Jl(t) {
13448
+ function Ql(t) {
13423
13449
  const e = t.match(Kl)?.[0] ?? "", s = e ? t.slice(0, -e.length) : t;
13424
13450
  return `${Br(s)}${e}`;
13425
13451
  }
@@ -13432,13 +13458,13 @@ function uu(t) {
13432
13458
  export {
13433
13459
  yi as PLUNO_PRODUCT_AGENT_WIDGET_HOST_SELECTOR,
13434
13460
  Xc as PLUNO_PRODUCT_AGENT_WIDGET_PANEL_SELECTOR,
13435
- Qc as PLUNO_PRODUCT_AGENT_WIDGET_ROOT_SELECTOR,
13461
+ Jc as PLUNO_PRODUCT_AGENT_WIDGET_ROOT_SELECTOR,
13436
13462
  Yc as PLUNO_PRODUCT_AGENT_WIDGET_TIMELINE_SELECTOR,
13437
13463
  zo as PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE,
13438
13464
  au as PRODUCT_AGENT_PROVIDER_INPUT_ATTACHMENT_ACCEPT,
13439
13465
  lu as PlunoProductAgent,
13440
13466
  tu as ProductAgentInteractionManager,
13441
- Qn as ProductAgentQueryController,
13467
+ Jn as ProductAgentQueryController,
13442
13468
  ou as ProductAgentRemoteRuntimeClient,
13443
13469
  Kt as ProductAgentSessionEngine,
13444
13470
  eu as ProductAgentSessionHistoryManager,
@@ -13460,7 +13486,7 @@ export {
13460
13486
  du as normalizeProductAgentSessionItems,
13461
13487
  $c as readLocalStorageInteractionDecisions,
13462
13488
  Yl as resolveProductAgentComposerAction,
13463
- Ql as resolveProductAgentWidgetPresentation,
13489
+ Jl as resolveProductAgentWidgetPresentation,
13464
13490
  Fo as selectProductAgentQueryEntities,
13465
13491
  _l as validateProductAgentProviderInputFile
13466
13492
  };
@@ -37,7 +37,7 @@ function Hp(t, e, n, i) {
37
37
  function Kp(t) {
38
38
  return Ur(t) > 0.5 ? [24, 24, 27] : [250, 250, 249];
39
39
  }
40
- const Wp = "0.1.269", ri = {
40
+ const Wp = "0.1.270", ri = {
41
41
  version: Wp
42
42
  }, ye = (t) => typeof t == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(t) ? t : null;
43
43
  function Rd(t) {
@@ -6386,6 +6386,13 @@ class sf {
6386
6386
  forceNew: !0,
6387
6387
  auth: { ...e.auth },
6388
6388
  reconnection: e.reconnect ?? !0
6389
+ }), this.socket.io.on("open", () => {
6390
+ const n = this.socket.io.engine, i = this.attempt;
6391
+ n.on("packet", (s) => {
6392
+ this.socket.io.engine !== n || this.attempt !== i || (this.activity.lastPacketReceivedAt = Date.now(), s.type === "ping" && (this.activity.lastHeartbeatReceivedAt = this.activity.lastPacketReceivedAt));
6393
+ }), n.on("packetCreate", (s) => {
6394
+ this.socket.io.engine === n && this.attempt === i && s.type === "pong" && (this.activity.lastHeartbeatQueuedAt = Date.now());
6395
+ });
6389
6396
  }), this.socket.io.on("reconnect_attempt", () => this.beginAttempt()), this.socket.io.on("close", (n) => {
6390
6397
  const i = this.generation, s = this.attempt;
6391
6398
  n === "forced close" ? queueMicrotask(() => {
@@ -6468,6 +6475,15 @@ class sf {
6468
6475
  readinessTimer = null;
6469
6476
  attemptCount = 0;
6470
6477
  attempt = null;
6478
+ activity = {
6479
+ lastPacketReceivedAt: null,
6480
+ lastHeartbeatReceivedAt: null,
6481
+ lastHeartbeatQueuedAt: null,
6482
+ lastDisconnect: null
6483
+ };
6484
+ get connectionActivity() {
6485
+ return { ...this.activity, lastDisconnect: this.activity.lastDisconnect ? { ...this.activity.lastDisconnect } : null };
6486
+ }
6471
6487
  connect() {
6472
6488
  if (!this.retired && this.rejectedToken !== this.options.auth.token) {
6473
6489
  if (this.active) return;
@@ -6517,7 +6533,7 @@ class sf {
6517
6533
  !this.active || this.retired || (this.invalidate(!1, e), this.socket.io.engine.close());
6518
6534
  }
6519
6535
  beginAttempt() {
6520
- this.clearReadinessTimers(), this.active = !0, this.attempt = { connectionAttemptId: crypto.randomUUID(), reconnectAttempt: this.attemptCount++, startedAt: Date.now() }, this.socket.auth = { ...this.options.auth, connection_attempt_id: this.attempt.connectionAttemptId }, this.options.onAttempt?.(this.attempt);
6536
+ this.clearReadinessTimers(), this.activity = { ...this.activity, lastPacketReceivedAt: null, lastHeartbeatReceivedAt: null, lastHeartbeatQueuedAt: null }, this.active = !0, this.attempt = { connectionAttemptId: crypto.randomUUID(), reconnectAttempt: this.attemptCount++, startedAt: Date.now() }, this.socket.auth = { ...this.options.auth, connection_attempt_id: this.attempt.connectionAttemptId }, this.options.onAttempt?.(this.attempt);
6521
6537
  const e = this.generation, n = (i) => {
6522
6538
  e !== this.generation || !this.active || (this.options.onError(new L("Product Agent readiness timed out", i, !1, {
6523
6539
  retryable: !0,
@@ -6682,7 +6698,14 @@ class sf {
6682
6698
  }
6683
6699
  invalidate(e = !1, n = "local_invalidation") {
6684
6700
  if (this.clearReadinessTimers(), !!this.active) {
6685
- this.active = !1, this.generation++, this.ready = null, this.admitted = null, this.activating = !1;
6701
+ this.activity.lastDisconnect = {
6702
+ occurredAt: Date.now(),
6703
+ reason: n,
6704
+ connectionAttemptId: this.attempt?.connectionAttemptId ?? null,
6705
+ lastPacketReceivedAt: this.activity.lastPacketReceivedAt,
6706
+ lastHeartbeatReceivedAt: this.activity.lastHeartbeatReceivedAt,
6707
+ lastHeartbeatQueuedAt: this.activity.lastHeartbeatQueuedAt
6708
+ }, this.active = !1, this.generation++, this.ready = null, this.admitted = null, this.activating = !1;
6686
6709
  for (const i of [...this.pending]) i(new L("Connection lost before acknowledgement", "delivery_unknown", !0));
6687
6710
  this.options.onDisconnect(e, n);
6688
6711
  }
@@ -7344,6 +7367,9 @@ class Ae extends EventTarget {
7344
7367
  get connectionAttempt() {
7345
7368
  return this.transport.connectionAttempt;
7346
7369
  }
7370
+ get connectionActivity() {
7371
+ return this.transport.connectionActivity;
7372
+ }
7347
7373
  retryReadiness() {
7348
7374
  this.initialReadinessExpired = !1, this.startInitialReadinessBudget(), this.transport.replaceCredentials(this.options.auth, !1);
7349
7375
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluno/product-agent-web",
3
- "version": "0.1.269",
3
+ "version": "0.1.270",
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",