@pluno/product-agent-web 0.1.232 → 0.1.234

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
+ import type { OwnerDiagnostics } from "../../runtime/transitionDiagnostics";
1
2
  import type { ProductAgentState } from "../../index";
2
3
  import type { PAConversationProjection, PAConversationRecord } from "../../core/conversation/contracts";
3
- export type PAConversationPresentation = Pick<ProductAgentState, "historyPreparation" | "selectionKey" | "isDraftSession" | "sessionId" | "messages" | "removedItems" | "activeScheduledFollowUps" | "isLoadingSession" | "assistantDraft" | "assistantDraftItemId" | "assistantDraftPhase" | "assistantDraftRespondsToUserMessageId" | "assistantDraftRunId" | "activeResponseUserMessageId" | "pendingMessageStatus" | "turnPhase" | "isThinking" | "taskStatus" | "lastError" | "lastErrorCode" | "lastErrorSecuritySettingsUrl"> & Required<Pick<ProductAgentState, "segments" | "activity" | "receipts">>;
4
- export declare function projectConversationPresentation(projection: PAConversationProjection, query: PAConversationRecord["queries"]["current"] | undefined, backendUrl: string): PAConversationPresentation;
4
+ export type PAConversationPresentation = Pick<ProductAgentState, "conversationDiagnostics" | "historyPreparation" | "selectionKey" | "isDraftSession" | "sessionId" | "messages" | "removedItems" | "activeScheduledFollowUps" | "isLoadingSession" | "assistantDraft" | "assistantDraftItemId" | "assistantDraftPhase" | "assistantDraftRespondsToUserMessageId" | "assistantDraftRunId" | "activeResponseUserMessageId" | "pendingMessageStatus" | "turnPhase" | "isThinking" | "taskStatus" | "lastError" | "lastErrorCode" | "lastErrorSecuritySettingsUrl"> & Required<Pick<ProductAgentState, "segments" | "activity" | "receipts">>;
5
+ export declare function projectConversationPresentation(projection: PAConversationProjection, query: PAConversationRecord["queries"]["current"] | undefined, backendUrl: string, owner?: OwnerDiagnostics): PAConversationPresentation;
@@ -189,6 +189,7 @@ export type PAConversationProjection = Readonly<{
189
189
  }>) | null;
190
190
  segments: readonly PAConversationSegment[];
191
191
  activity: Readonly<{
192
+ executionKey?: string;
192
193
  phase: PAExecutionState["phase"] | "submitting" | "awaiting_execution";
193
194
  activeItemId: string | null;
194
195
  userMessageId?: string | null;
@@ -39,6 +39,7 @@ export declare function selectConversation(state: PAConversationState, directory
39
39
  }>) | null;
40
40
  segments: readonly PAConversationSegment[];
41
41
  activity: Readonly<{
42
+ executionKey?: string;
42
43
  phase: import("./display").PAExecutionState["phase"] | "submitting" | "awaiting_execution";
43
44
  activeItemId: string | null;
44
45
  userMessageId?: string | null;
package/dist/index.d.ts CHANGED
@@ -133,6 +133,7 @@ export type ProductAgentAppearance = {
133
133
  };
134
134
  export type ProductAgentTurnPhase = "sending" | "starting" | "thinking";
135
135
  export type ProductAgentState = {
136
+ conversationDiagnostics?: import("./runtime/transitionDiagnostics").ConversationDiagnostics;
136
137
  selectionKey?: string;
137
138
  isDraftSession?: boolean;
138
139
  submissionContext?: ProductAgentSubmissionContext;
@@ -153,6 +154,7 @@ export type ProductAgentState = {
153
154
  collapsed: boolean;
154
155
  }>[];
155
156
  activity?: Readonly<{
157
+ executionKey?: string;
156
158
  phase: "idle" | "queued" | "thinking" | "steering" | "stopping" | "completed" | "failed" | "stopped" | "submitting" | "awaiting_execution";
157
159
  activeItemId: string | null;
158
160
  }>;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function h(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class A{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=h(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=h(e),this.trailingLoad=null,this.publish())}reset(){this.state=h(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 g(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 q(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 N(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function z(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function G(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 H(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function V(s){return s?s.submissionGate?.allowed===!1?{state:"action_required",reason:s.submissionGate.reason}: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 Z(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function J(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const L="Pluno is reconnecting. Try again in a moment.";function U(s){return(s instanceof Error?s.message:s)===L}class W{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new A(`${e}:recent`,async({cursor:n})=>g(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),q),this.pinnedQuery=new A(`${e}:pinned`,async()=>g({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=[...f(t.data),...f(e.data)],n=new Map(i.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?g({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:Y(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,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=[...f(this.pinnedQuery.getState().data),...f(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 f(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function Y(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 M(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 I(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(I);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(I)}function K(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(K),Object.freeze(s)),s}function X(s){if(!I(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function ee(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,a)=>M(r.created_at).localeCompare(M(a.created_at))||r.id.localeCompare(a.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 te{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(w).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,a=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,K(X({...t,lifecycle:r,payload:a}))),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,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;if(a.kind==="sharing"){if(t.share=null,!a.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const o=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:a.variant,userPrompt:o?.type==="user_message"?o.data.content:"",assistantAnswer:""},terminal:!a.wait_for_terminal||ee(i,r.user_message_id)}}else a.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:a.request_id,channel:a.channel,managementUrl:a.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(w).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(!Q(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)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,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=b(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${b(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${b(e.scope)}:category:${e.category}`}}function se(s,e){return{load:async()=>$(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function $(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(w):[]}function b(s){return`${s.level}:${s.key}`}function Q(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function w(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")&&Q(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ie={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},ne=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function j(s,e){if(!e)return v(s);const t=v(s),i=`${ie[e]} Pluno`;return t?`${i}: ${t}`:i}class re{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=v(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?v(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=j(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function oe(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 v(s){return s.replace(ne,"")}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"],ce=Math.random().toString(36).slice(2);let le=0;const O=()=>`timing:${ce}:${++le}`,m=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function P(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"].includes(t))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp"].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)&&m(e.spanId)&&m(e.requestId)&&(e.clientMessageId===null||m(e.clientMessageId))&&(e.sessionId===null||m(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function R(s,e){if(!s)return{mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,a,o)=>{const c={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a))};s&&P(c)&&Promise.resolve().then(()=>s(c)).catch(()=>{})};return{mark:n=>i(n,"observed",t,O()),measure(n,r){const a=performance.now(),o=O();return i(n,"started",a,o),r().then(c=>(i(n,"completed",a,o),c),c=>{throw i(n,"failed",a,o),c})}}}const C=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],E=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),y=s=>s===null||E(s),de=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 B(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))&&y(e.sessionId)&&E(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||de(e.createdAt))}function F(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=>[...C,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence"].includes(r))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&C.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(E))},t=s;return(t.before===null||e(t.before))&&e(t.current)}const S=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function ue(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"}const D=500;function pe(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>D?`${e.slice(0,D-1)}…`:e}function he(s,e,t="stopped",i){const n=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(o=>o.role==="user").slice(-1)[0]?.id].filter(o=>!!o)),r=s.messages.filter(o=>!(o.dataType==="run_status"&&o.loading&&n.has(o.respondsToUserMessageId??""))).map(o=>n.has(o.respondsToUserMessageId??"")?{...o,loading:!1}:o);for(const o of n)r.some(c=>c.respondsToUserMessageId===o&&(c.dataType==="run_status"||c.dataType==="run_error"||c.role==="assistant"&&c.phase!=="commentary"))||r.some(c=>c.role==="user"&&c.id===o)&&r.push({id:`local-interrupted:${o}`,role:"system",dataType:"run_status",content:t==="stopping"?"Stopping…":"Run stopped by user.",createdAt:e,respondsToUserMessageId:o});const a=s.segments?.map(o=>({...o,outcomeIds:[...o.outcomeIds,...r.filter(c=>c.id===`local-interrupted:${o.userMessageId}`&&!o.outcomeIds.includes(c.id)).map(c=>c.id)]}));return{...s,messages:r,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&r.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const ge={"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 fe(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(ge,s.slice(13))}function k(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 me(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;switch(e.type){case"runtime.connect":case"session.new":case"run.retry":return!0;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 ue(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return P(e.timing);case"runtime.report_displayed_error":return(e.renderedError===void 0||B(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||F(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||fe(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");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 ye{constructor(e,t,i){this.adapter=t,this.state=_(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=h("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;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=_(this.state);for(const[t,i]of this.submissionPreviews)e.messages.some(n=>n.id===t)||(e.messages.push({...i.message,attachments:i.message.attachments?.map(n=>({...n}))}),e.segments&&(e.segments=[...e.segments,{id:t,userMessageId:t,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,i.pending&&(e.activeResponseUserMessageId=t,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),i.error&&(e.lastError=i.error,e.lastErrorCode="message_delivery_failed"));return this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed"),this.pendingStop?he(e,"","stopping",this.pendingStop.userMessageIds):e}updateProjection(e,t,i,n,r){if(this.destroyed)return;const a=this.getState();(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const o of e.messages)o.role==="user"&&this.submissionPreviews.delete(o.id);if(this.state=_(e),a.user?.id===e.user?.id)for(const o of this.state.messages){if(o.role!=="user"||!o.attachments?.length)continue;const c=a.messages.find(l=>l.role==="user"&&l.id===o.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&c)||(o.attachments=ve(c?.attachments,o.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=x(i);for(const o of this.sessionHistoryListeners)o(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(o=>({...o}));for(const o of this.interactionListeners)o(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const o of this.accountListeners)o(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.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(()=>{})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&P(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&&!F(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n){n!==void 0&&!B(n)||this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...i?{displayedMessage:pe(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim(),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()),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(l=>l.id?[l.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(l=>({...l}))}});const c=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:a},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,a=R(l=>{i===this.submissionGeneration&&this.reportOperationTiming(l)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1;if(i!==this.submissionGeneration)return null;try{if(!await a.measure("staging_ipc",async()=>{const d=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:o.length>0?o.map(k):void 0,submittedAt:t.submittedAt})});return d?(await d.result,d):null})||i!==this.submissionGeneration)return null;if(c=!0,o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const d=[];for(const u of o){if(u.sandboxPath||u.storageKey){d.push(u);continue}const T=u.id?this.attachmentFiles.get(u.id):void 0;if(!T)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(d.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(T,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}o=d}const p=await a.measure("send_ipc",()=>this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,...t.automationOnboarding?{automationOnboarding:!0}:{},attachments:o.length>0?o.map(k):void 0}));if(i!==this.submissionGeneration)return null;for(const d of t.attachments??[])d.id&&this.attachmentFiles.delete(d.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),p?.clientMessageId??r}catch(l){if(i!==this.submissionGeneration)return null;if(U(l))for(const d of t.attachments??[])d.id&&this.attachmentFiles.delete(d.id);const p=this.submissionPreviews.get(r);throw p&&(p.pending=!1,p.error=l instanceof Error?l.message:String(l),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:l instanceof Error?l.message:String(l)}),l}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}retryLastMessage(){return this.dispatch({type:"run.retry"}),!0}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(),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(o=>o.role==="user").slice(-1)[0]?.id].filter(o=>!!o))],n=R(o=>this.reportOperationTiming(o),{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,r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},o=>{this.pendingStop===r&&(this.stopError=o instanceof Error?o.message:String(o))}).finally(()=>{this.pendingStop===r&&(this.pendingStop=null,this.emit("state",this.getState()))}),this.emit("state",this.getState());const a=r.promise;return this.operationQueue=a.then(()=>{},()=>{}),a.then(()=>{})}cancelPendingSubmissions(){this.pendingStop=null,this.stopError=null;const e=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const t of this.pendingTransfers.values())for(const i of t)this.attachmentFiles.delete(i);this.pendingTransfers.clear();for(const t of this.submissionPreviews.values())t.pending=!1;return this.operationQueue=Promise.resolve(),e}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 x(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={}){return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n}).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 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 ve(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 _(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},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 x(s){return{...s,data:s.data?g({entities:N(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=L;exports.ProductAgentInteractionManager=te;exports.ProductAgentQueryController=A;exports.ProductAgentRemoteRuntimeClient=ye;exports.ProductAgentSessionHistoryManager=W;exports.ProductAgentTaskPageTitleController=re;exports.canSubmitPersonalProductAgentMessage=Z;exports.createLocalStorageInteractionDecisionStorage=se;exports.createProductAgentQueryState=h;exports.createProductAgentTaskPageTitleDocument=oe;exports.formatProductAgentTaskPageTitle=j;exports.hasProductAgentPaidCreditFallback=H;exports.isProductAgentAuthReconnectError=U;exports.isProductAgentRuntimeCommand=me;exports.mergeProductAgentEntityPages=q;exports.normalizeProductAgentEntityPage=g;exports.readLocalStorageInteractionDecisions=$;exports.reconcileProductAgentSubmissionGate=G;exports.resolveProductAgentBillingPresentation=V;exports.resolveProductAgentComposerAction=J;exports.resolveProductAgentWidgetPresentation=z;exports.selectProductAgentQueryEntities=N;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function h(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class I{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=h(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=h(e),this.trailingLoad=null,this.publish())}reset(){this.state=h(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 g(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 N(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 L(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function G(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function H(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 V(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function Z(s){return s?s.submissionGate?.allowed===!1?{state:"action_required",reason:s.submissionGate.reason}: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 J(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function W(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const j="Pluno is reconnecting. Try again in a moment.";function K(s){return(s instanceof Error?s.message:s)===j}class Y{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new I(`${e}:recent`,async({cursor:n})=>g(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),N),this.pinnedQuery=new I(`${e}:pinned`,async()=>g({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=[...f(t.data),...f(e.data)],n=new Map(i.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?g({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:X(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,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=[...f(this.pinnedQuery.getState().data),...f(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 f(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function X(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 w(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(w);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(w)}function U(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(U),Object.freeze(s)),s}function ee(s){if(!w(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function te(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,a)=>O(r.created_at).localeCompare(O(a.created_at))||r.id.localeCompare(a.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 se{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,a=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,U(ee({...t,lifecycle:r,payload:a}))),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,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;if(a.kind==="sharing"){if(t.share=null,!a.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const o=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:a.variant,userPrompt:o?.type==="user_message"?o.data.content:"",assistantAnswer:""},terminal:!a.wait_for_terminal||te(i,r.user_message_id)}}else a.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:a.request_id,channel:a.channel,managementUrl:a.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(!Q(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)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,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=S(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${S(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${S(e.scope)}:category:${e.category}`}}function ie(s,e){return{load:async()=>$(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function $(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(P):[]}function S(s){return`${s.level}:${s.key}`}function Q(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")&&Q(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ne={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},re=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function F(s,e){if(!e)return b(s);const t=b(s),i=`${ne[e]} Pluno`;return t?`${i}: ${t}`:i}class oe{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=b(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?b(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 ae(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 b(s){return s.replace(re,"")}const ce=["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"],de=Math.random().toString(36).slice(2);let le=0;const R=()=>`timing:${de}:${++le}`,m=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function E(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"].includes(t))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&ce.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&m(e.spanId)&&m(e.requestId)&&(e.clientMessageId===null||m(e.clientMessageId))&&(e.sessionId===null||m(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function C(s,e){if(!s)return{mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,a,o)=>{const c={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a))};s&&E(c)&&Promise.resolve().then(()=>s(c)).catch(()=>{})};return{mark:n=>i(n,"observed",t,R()),measure(n,r){const a=performance.now(),o=R();return i(n,"started",a,o),r().then(c=>(i(n,"completed",a,o),c),c=>{throw i(n,"failed",a,o),c})}}}const y=s=>typeof s=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(s)?s:null;function ue(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)&&y(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||y(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&y(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)}const k=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],T=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),v=s=>s===null||T(s),pe=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 B(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))&&v(e.sessionId)&&T(e.itemId)&&v(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&v(e.runId)&&(e.createdAt===null||pe(e.createdAt))}function he(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"].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||y(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"].includes(e.renderSource)&&(e.owner===void 0||ue(e.owner))}function z(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=>[...k,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context"].includes(r))&&(n.context===void 0||he(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&v(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&k.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 A=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function ge(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))&&A(e.sessionId)&&A(e.responseItemId)&&A(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}const D=500;function fe(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>D?`${e.slice(0,D-1)}…`:e}function me(s,e,t="stopped",i){const n=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(o=>o.role==="user").slice(-1)[0]?.id].filter(o=>!!o)),r=s.messages.filter(o=>!(o.dataType==="run_status"&&o.loading&&n.has(o.respondsToUserMessageId??""))).map(o=>n.has(o.respondsToUserMessageId??"")?{...o,loading:!1}:o);for(const o of n)r.some(c=>c.respondsToUserMessageId===o&&(c.dataType==="run_status"||c.dataType==="run_error"||c.role==="assistant"&&c.phase!=="commentary"))||r.some(c=>c.role==="user"&&c.id===o)&&r.push({id:`local-interrupted:${o}`,role:"system",dataType:"run_status",content:t==="stopping"?"Stopping…":"Run stopped by user.",createdAt:e,respondsToUserMessageId:o});const a=s.segments?.map(o=>({...o,outcomeIds:[...o.outcomeIds,...r.filter(c=>c.id===`local-interrupted:${o.userMessageId}`&&!o.outcomeIds.includes(c.id)).map(c=>c.id)]}));return{...s,messages:r,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&r.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const ye={"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 ve(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(ye,s.slice(13))}function q(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 be(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;switch(e.type){case"runtime.connect":case"session.new":case"run.retry":return!0;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 ge(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return E(e.timing);case"runtime.report_displayed_error":return(e.renderedError===void 0||B(e.renderedError))&&(e.reason==="conversation_error"||e.reason==="attachment_error"||e.reason==="history_error"||e.reason==="action_error")&&typeof e.errorFingerprint=="string"&&/^fnv1a-[0-9a-f]{8}$/.test(e.errorFingerprint)&&(e.displayedMessage===void 0||typeof e.displayedMessage=="string"&&e.displayedMessage.length<=500);case"runtime.report_invalid_state_transition":return(e.uiInvariant===void 0||z(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||ve(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");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 Se{constructor(e,t,i){this.adapter=t,this.state=_(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=h("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;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=_(this.state);for(const[t,i]of this.submissionPreviews)e.messages.some(n=>n.id===t)||(e.messages.push({...i.message,attachments:i.message.attachments?.map(n=>({...n}))}),e.segments&&(e.segments=[...e.segments,{id:t,userMessageId:t,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,i.pending&&(e.activeResponseUserMessageId=t,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),i.error&&(e.lastError=i.error,e.lastErrorCode="message_delivery_failed"));return this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed"),this.pendingStop?me(e,"","stopping",this.pendingStop.userMessageIds):e}updateProjection(e,t,i,n,r){if(this.destroyed)return;const a=this.getState();(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const o of e.messages)o.role==="user"&&this.submissionPreviews.delete(o.id);if(this.state=_(e),a.user?.id===e.user?.id)for(const o of this.state.messages){if(o.role!=="user"||!o.attachments?.length)continue;const c=a.messages.find(d=>d.role==="user"&&d.id===o.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&c)||(o.attachments=Ae(c?.attachments,o.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=x(i);for(const o of this.sessionHistoryListeners)o(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(o=>({...o}));for(const o of this.interactionListeners)o(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const o of this.accountListeners)o(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.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(()=>{})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&E(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&&!z(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n){n!==void 0&&!B(n)||this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...i?{displayedMessage:fe(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim(),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()),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:a},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,a=C(d=>{i===this.submissionGeneration&&this.reportOperationTiming(d)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1;if(i!==this.submissionGeneration)return null;try{if(!await a.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:o.length>0?o.map(q):void 0,submittedAt:t.submittedAt})});return l?(await l.result,l):null})||i!==this.submissionGeneration)return null;if(c=!0,o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of o){if(u.sandboxPath||u.storageKey){l.push(u);continue}const M=u.id?this.attachmentFiles.get(u.id):void 0;if(!M)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(M,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}o=l}const p=await a.measure("send_ipc",()=>this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,...t.automationOnboarding?{automationOnboarding:!0}:{},attachments:o.length>0?o.map(q):void 0}));if(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),p?.clientMessageId??r}catch(d){if(i!==this.submissionGeneration)return null;if(K(d))for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);const p=this.submissionPreviews.get(r);throw p&&(p.pending=!1,p.error=d instanceof Error?d.message:String(d),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:d instanceof Error?d.message:String(d)}),d}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}retryLastMessage(){return this.dispatch({type:"run.retry"}),!0}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(),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(o=>o.role==="user").slice(-1)[0]?.id].filter(o=>!!o))],n=C(o=>this.reportOperationTiming(o),{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,r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},o=>{this.pendingStop===r&&(this.stopError=o instanceof Error?o.message:String(o))}).finally(()=>{this.pendingStop===r&&(this.pendingStop=null,this.emit("state",this.getState()))}),this.emit("state",this.getState());const a=r.promise;return this.operationQueue=a.then(()=>{},()=>{}),a.then(()=>{})}cancelPendingSubmissions(){this.pendingStop=null,this.stopError=null;const e=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const t of this.pendingTransfers.values())for(const i of t)this.attachmentFiles.delete(i);this.pendingTransfers.clear();for(const t of this.submissionPreviews.values())t.pending=!1;return this.operationQueue=Promise.resolve(),e}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 x(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={}){return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n}).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 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 Ae(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 _(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},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 x(s){return{...s,data:s.data?g({entities:L(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=j;exports.ProductAgentInteractionManager=se;exports.ProductAgentQueryController=I;exports.ProductAgentRemoteRuntimeClient=Se;exports.ProductAgentSessionHistoryManager=Y;exports.ProductAgentTaskPageTitleController=oe;exports.canSubmitPersonalProductAgentMessage=J;exports.createLocalStorageInteractionDecisionStorage=ie;exports.createProductAgentQueryState=h;exports.createProductAgentTaskPageTitleDocument=ae;exports.formatProductAgentTaskPageTitle=F;exports.hasProductAgentPaidCreditFallback=V;exports.isProductAgentAuthReconnectError=K;exports.isProductAgentRuntimeCommand=be;exports.mergeProductAgentEntityPages=N;exports.normalizeProductAgentEntityPage=g;exports.readLocalStorageInteractionDecisions=$;exports.reconcileProductAgentSubmissionGate=H;exports.resolveProductAgentBillingPresentation=Z;exports.resolveProductAgentComposerAction=W;exports.resolveProductAgentWidgetPresentation=G;exports.selectProductAgentQueryEntities=L;