@pluno/product-agent-web 0.1.295 → 0.1.296

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function te(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function _(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class E{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=_(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=_(e),this.trailingLoad=null,this.publish())}reset(){this.state=_(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function I(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function $(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function U(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function se(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function ie(i){if(!i||typeof i!="object")return!1;const e=i.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function ne(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function re(i){return i.submissionAllowed&&i.isAuthenticated&&i.hasWorkspace&&!i.isWebsiteBlocked&&i.isCurrentPageResolved&&!i.isSubmitting&&!i.hasPendingMessage}function oe(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const F="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===F}class ae{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new E(`${e}:recent`,async({cursor:n})=>I(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),$),this.pinnedQuery=new E(`${e}:pinned`,async()=>I({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),a=e.data||t.data||o.length>0?I({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:de(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,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function de(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function x(i){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(i);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function G(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(G),Object.freeze(i)),i}function ce(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}function le(i,e){if(!e)return!1;const t=i.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const s=Object.values(i.items).sort((r,o)=>x(r.created_at).localeCompare(x(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of s)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&i.streams[r.id]?.state==="finished"&&i.streams[r.id].revision>=r.data.revision))return!0;return!1}class ue{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(n&&n.version>=t.version)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(s,G(ce({...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},s=e?this.conversationReader(e):null;if(!s)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?s.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||le(s,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(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!Q(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},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,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=M(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${M(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${M(e.scope)}:category:${e.category}`}}function pe(i,e){return{load:async()=>B(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function B(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function M(i){return`${i.level}:${i.key}`}function Q(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&Q(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const he={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},ge=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function H(i,e){if(!e)return P(i);const t=P(i),s=`${he[e]} Pluno`;return t?`${s}: ${t}`:s}class fe{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=P(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,s=this.lastAppliedTitle===null?P(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function me(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function P(i){return i.replace(ge,"")}const ye="0.1.295",be={version:ye},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function ve(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),_e=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function Z(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||_e(e.createdAt))}function Ie(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||ve(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function J(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(o=>["key","count","rows","truncated"].includes(o))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(o=>o&&Object.keys(o).every(a=>["itemId","groupId"].includes(a))&&y(o.itemId)&&y(o.groupId))))&&(n.context===void 0||Ie(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const N=500;function W(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>N?`${e.slice(0,N-1)}…`:e}function Se(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function Ae(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function we(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===Se(W(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:be.version,...n}}}function Pe(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,o=s&&"details"in s?s.details:null,a=o&&typeof o=="object"?o:{},c={...typeof a.httpStatus=="number"&&Number.isInteger(a.httpStatus)&&a.httpStatus>=100&&a.httpStatus<=599?{httpStatus:a.httpStatus}:{},errorNormalization:O(a.errorNormalization)?a.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...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 Pe({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function Y(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Me=["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","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],X=["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 Te(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&X.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const ee=Math.random().toString(36).slice(2);let Ee=0;const j=()=>`timing:${ee}:${++Ee}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&X.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)&&Me.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function K(i,e){if(e={workerId:ee,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,o,a,c)=>{const d={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o)),...r==="failed"?{failureCategory:Te(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,j()),measure(n,r){const o=performance.now(),a=j();return s(n,"started",o,a),r().then(c=>(s(n,"completed",o,a),c),c=>{throw s(n,"failed",o,a,c),c})}}}const T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Re(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function ke(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),o=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)o.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||o.some(d=>d.role==="user"&&d.id===c)&&o.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const a=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...o.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:o,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&o.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const qe={"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 Oe(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(qe,i.slice(13))}function z(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Ce(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Re(e.observation);case"runtime.warmup":return(e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input")&&(e.requestedModel===void 0||typeof e.requestedModel=="string");case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||Ae(e.errorDiagnostic))&&(e.httpRequest===void 0||Y(e.httpRequest))&&(e.historyRefreshFailure===void 0||V(e.historyRefreshFailure))&&(e.renderedError===void 0||Z(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||J(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Oe(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.prompt_presented":return(e.feature==="notifications"||e.feature==="tab_grouping")&&typeof e.openingGeneration=="number"&&Number.isSafeInteger(e.openingGeneration)&&e.openingGeneration>0;case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return(e.requestedModel===void 0||typeof e.requestedModel=="string")&&typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return(e.reconcileAcceptance===void 0||typeof e.reconcileAcceptance=="boolean")&&(e.selectionKey===void 0||typeof e.selectionKey=="string")&&(e.reconcileAcceptance!==!0||typeof e.selectionKey=="string"&&e.selectionKey.length>0)&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return(e.selectionKey===void 0||typeof e.selectionKey=="string")&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class xe{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-5.6-terra",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=_("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;readinessPendingSubmissions=new Set;pendingTransfers=new Map;submissionPreviews=new Map;submissionRetries=new Map;retainedTranscript=null;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;durabilityWaiters=new Set;navigationRevision=0;pendingNavigation=!1;destroyed=!1;hasBeenReady;on(e,t){const s=this.listeners[e]??new Set;return s.add(t),this.listeners[e]=s,()=>s.delete(t)}getState(){const e=A(this.state);if(this.pendingNavigation&&(e.isLoadingSession=!0),this.retainedTranscript){const n=A({...e,...this.retainedTranscript}),r=new Set(n.messages.map(a=>a.id)),o=new Set(n.segments?.map(a=>a.id));e.messages=[...n.messages,...e.messages.filter(a=>!r.has(a.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(a=>({...a})),...(e.segments??[]).filter(a=>!o.has(a.id))]),e.removedItems={...n.removedItems,...e.removedItems}}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","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=ke(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const o=this.getState(),a=!this.hasBeenReady&&(!o.user||o.user.id===e.user?.id),c=o.stableSelectionKey!==void 0&&o.stableSelectionKey===e.stableSelectionKey&&o.user?.id===e.user?.id&&o.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!a&&!d&&(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)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const p=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=p?this.retainedTranscript??(this.state.isLoadingSession||this.state.messages.length===0?null:{messages:this.state.messages,segments:this.state.segments,removedItems:this.state.removedItems}):null,this.state=A(e),t!==void 0&&!this.modelExplicit&&(this.model=t),e.status==="connected"&&e.submissionReady!==!1&&(this.hasBeenReady=!0);for(const[l,u]of this.stopPreviews){const h=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&h!==void 0&&h!=="[]"&&(h!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),o.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=o.messages.find(h=>h.role==="user"&&h.id===l.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&u)||(l.attachments=De(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=L(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}warmup(e="panel_open",t=this.model){return this.adapter.dispatch({type:"runtime.warmup",reason:e,requestedModel:t}).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&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!J(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!Z(n)||r!==void 0&&!V(r))return;const a=we(this.getState(),e,s,!!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}:{},...Y(o)?{httpRequest:o}:{},...s?{displayedMessage:W(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){const s=e.trim();if(this.pendingNavigation)return Promise.reject(new Error("Wait for the conversation to finish loading."));t={...t,requestedModel:t.requestedModel??this.getModel(),attachments:t.attachments?.map(d=>({...d}))};const n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:o,selectionKey:this.state.selectionKey},a);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,o=K(p=>{s===this.submissionGeneration&&this.reportOperationTiming(p)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const p=await o.measure("staging_ipc",async()=>{if(d){if(!await o.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(z):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const h=b(u);if(h.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=h),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!p||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),p.result?.submissionAccepted){r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null);for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(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 h=u.id?this.attachmentFiles.get(u.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(h,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}a=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(z):void 0}),s!==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(p){if(s!==this.submissionGeneration)return null;if(R(p))for(const f of t.attachments??[])f.id&&this.attachmentFiles.delete(f.id);const u=b(p).code==="command_not_received";!c&&!R(p)&&(d||u||t.selectionKey!==void 0)&&this.submissionRetries.set(r,{retry:async()=>(d&&await this.connect(),this.sendMessageNow(e,{...t,reconcileAcceptance:!d&&!u},s)),attachmentIds:(t.attachments??[]).flatMap(f=>f.id?[f.id]:[])});const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=b(p),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:b(p).message}),p}finally{this.readinessPendingSubmissions.delete(r)}}getModel(){return this.model}setModel(e){return this.modelExplicit=!0,this.model===e||(this.model=e,this.emit("state",this.getState())),Promise.resolve()}async retryLastMessage(e){const t=e??[...this.submissionPreviews].reverse().find(([,a])=>a.error)?.[0]??this.state.messages.filter(a=>a.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,o=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(a){if(!s&&!r)throw a;return s&&o===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(a),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&o===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=K(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const o=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:o);const a=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(a!==this.submissionGeneration||s.every(p=>!this.stopPreviews.has(p)))){for(const p of s)this.stopPreviews.delete(p);this.stopError=b(d).message}}).finally(()=>{this.destroyed||a!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,o)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const a=this.state;if(a.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(a.conversationDiagnostics?.failedClientMessageId===e&&a.lastError&&a.lastErrorCode!=="submission_checkpoint_pending"){o(Object.assign(new Error(a.lastError),{code:a.lastErrorCode}));return}const c=a.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){o(new Error(c.content));return}a.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return L(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(o=>o.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const s=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=s,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:s}).then(()=>{})}dispatch(e){return this.adapter.dispatch(e)}async navigate(e){const t=++this.navigationRevision;this.pendingNavigation=!0,this.model=this.initialModel,this.emit("state",this.getState());try{await this.dispatch(e)}finally{t===this.navigationRevision&&(this.pendingNavigation=!1,this.emit("state",this.getState()))}}emit(e,t){const s=this.listeners[e];for(const n of s??[])n(t)}}function De(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function L(i){return{...i,data:i.data?I({entities:U(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=F;exports.ProductAgentInteractionManager=ue;exports.ProductAgentQueryController=E;exports.ProductAgentRemoteRuntimeClient=xe;exports.ProductAgentSessionHistoryManager=ae;exports.ProductAgentTaskPageTitleController=fe;exports.canSubmitPersonalProductAgentMessage=re;exports.createLocalStorageInteractionDecisionStorage=pe;exports.createProductAgentQueryState=_;exports.createProductAgentTaskPageTitleDocument=me;exports.formatProductAgentTaskPageTitle=H;exports.hasProductAgentPaidCreditFallback=ie;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Ce;exports.mergeProductAgentEntityPages=$;exports.normalizeProductAgentEntityPage=I;exports.readLocalStorageInteractionDecisions=B;exports.reconcileProductAgentSubmissionGate=te;exports.resolveProductAgentBillingPresentation=ne;exports.resolveProductAgentComposerAction=oe;exports.resolveProductAgentWidgetPresentation=se;exports.selectProductAgentQueryEntities=U;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function te(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function _(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class E{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=_(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=_(e),this.trailingLoad=null,this.publish())}reset(){this.state=_(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function I(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function $(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function U(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function se(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function ie(i){if(!i||typeof i!="object")return!1;const e=i.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function ne(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function re(i){return i.submissionAllowed&&i.isAuthenticated&&i.hasWorkspace&&!i.isWebsiteBlocked&&i.isCurrentPageResolved&&!i.isSubmitting&&!i.hasPendingMessage}function oe(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const F="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===F}class ae{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new E(`${e}:recent`,async({cursor:n})=>I(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),$),this.pinnedQuery=new E(`${e}:pinned`,async()=>I({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),a=e.data||t.data||o.length>0?I({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:de(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,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function de(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function x(i){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(i);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function G(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(G),Object.freeze(i)),i}function ce(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}function le(i,e){if(!e)return!1;const t=i.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const s=Object.values(i.items).sort((r,o)=>x(r.created_at).localeCompare(x(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of s)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&i.streams[r.id]?.state==="finished"&&i.streams[r.id].revision>=r.data.revision))return!0;return!1}class ue{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(n&&n.version>=t.version)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(s,G(ce({...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},s=e?this.conversationReader(e):null;if(!s)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?s.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||le(s,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(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!Q(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},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,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=M(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${M(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${M(e.scope)}:category:${e.category}`}}function pe(i,e){return{load:async()=>B(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function B(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function M(i){return`${i.level}:${i.key}`}function Q(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&Q(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const he={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},ge=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function H(i,e){if(!e)return P(i);const t=P(i),s=`${he[e]} Pluno`;return t?`${s}: ${t}`:s}class fe{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=P(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,s=this.lastAppliedTitle===null?P(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function me(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function P(i){return i.replace(ge,"")}const ye="0.1.296",be={version:ye},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function ve(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),_e=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function Z(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||_e(e.createdAt))}function Ie(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||ve(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function J(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(o=>["key","count","rows","truncated"].includes(o))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(o=>o&&Object.keys(o).every(a=>["itemId","groupId"].includes(a))&&y(o.itemId)&&y(o.groupId))))&&(n.context===void 0||Ie(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const N=500;function W(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>N?`${e.slice(0,N-1)}…`:e}function Se(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function Ae(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function we(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===Se(W(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:be.version,...n}}}function Pe(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,o=s&&"details"in s?s.details:null,a=o&&typeof o=="object"?o:{},c={...typeof a.httpStatus=="number"&&Number.isInteger(a.httpStatus)&&a.httpStatus>=100&&a.httpStatus<=599?{httpStatus:a.httpStatus}:{},errorNormalization:O(a.errorNormalization)?a.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...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 Pe({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function Y(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Me=["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","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],X=["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 Te(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&X.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const ee=Math.random().toString(36).slice(2);let Ee=0;const j=()=>`timing:${ee}:${++Ee}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&X.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)&&Me.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function K(i,e){if(e={workerId:ee,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,o,a,c)=>{const d={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o)),...r==="failed"?{failureCategory:Te(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,j()),measure(n,r){const o=performance.now(),a=j();return s(n,"started",o,a),r().then(c=>(s(n,"completed",o,a),c),c=>{throw s(n,"failed",o,a,c),c})}}}const T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Re(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function ke(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),o=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)o.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||o.some(d=>d.role==="user"&&d.id===c)&&o.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const a=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...o.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:o,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:a,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&o.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const qe={"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 Oe(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(qe,i.slice(13))}function z(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Ce(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Re(e.observation);case"runtime.warmup":return(e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input")&&(e.requestedModel===void 0||typeof e.requestedModel=="string");case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||Ae(e.errorDiagnostic))&&(e.httpRequest===void 0||Y(e.httpRequest))&&(e.historyRefreshFailure===void 0||V(e.historyRefreshFailure))&&(e.renderedError===void 0||Z(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||J(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Oe(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.prompt_presented":return(e.feature==="notifications"||e.feature==="tab_grouping")&&typeof e.openingGeneration=="number"&&Number.isSafeInteger(e.openingGeneration)&&e.openingGeneration>0;case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return(e.requestedModel===void 0||typeof e.requestedModel=="string")&&typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return(e.reconcileAcceptance===void 0||typeof e.reconcileAcceptance=="boolean")&&(e.selectionKey===void 0||typeof e.selectionKey=="string")&&(e.reconcileAcceptance!==!0||typeof e.selectionKey=="string"&&e.selectionKey.length>0)&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return(e.selectionKey===void 0||typeof e.selectionKey=="string")&&typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class xe{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-5.6-terra",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=_("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;readinessPendingSubmissions=new Set;pendingTransfers=new Map;submissionPreviews=new Map;submissionRetries=new Map;retainedTranscript=null;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Map;durabilityWaiters=new Set;navigationRevision=0;pendingNavigation=!1;destroyed=!1;hasBeenReady;on(e,t){const s=this.listeners[e]??new Set;return s.add(t),this.listeners[e]=s,()=>s.delete(t)}getState(){const e=A(this.state);if(this.pendingNavigation&&(e.isLoadingSession=!0),this.retainedTranscript){const n=A({...e,...this.retainedTranscript}),r=new Set(n.messages.map(a=>a.id)),o=new Set(n.segments?.map(a=>a.id));e.messages=[...n.messages,...e.messages.filter(a=>!r.has(a.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(a=>({...a})),...(e.segments??[]).filter(a=>!o.has(a.id))]),e.removedItems={...n.removedItems,...e.removedItems}}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","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=ke(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const o=this.getState(),a=!this.hasBeenReady&&(!o.user||o.user.id===e.user?.id),c=o.stableSelectionKey!==void 0&&o.stableSelectionKey===e.stableSelectionKey&&o.user?.id===e.user?.id&&o.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!a&&!d&&(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)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const p=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=p?this.retainedTranscript??(this.state.isLoadingSession||this.state.messages.length===0?null:{messages:this.state.messages,segments:this.state.segments,removedItems:this.state.removedItems}):null,this.state=A(e),t!==void 0&&!this.modelExplicit&&(this.model=t),e.status==="connected"&&e.submissionReady!==!1&&(this.hasBeenReady=!0);for(const[l,u]of this.stopPreviews){const h=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&h!==void 0&&h!=="[]"&&(h!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),o.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=o.messages.find(h=>h.role==="user"&&h.id===l.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&u)||(l.attachments=De(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=L(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}warmup(e="panel_open",t=this.model){return this.adapter.dispatch({type:"runtime.warmup",reason:e,requestedModel:t}).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&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!J(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!Z(n)||r!==void 0&&!V(r))return;const a=we(this.getState(),e,s,!!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}:{},...Y(o)?{httpRequest:o}:{},...s?{displayedMessage:W(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){const s=e.trim();if(this.pendingNavigation)return Promise.reject(new Error("Wait for the conversation to finish loading."));t={...t,requestedModel:t.requestedModel??this.getModel(),attachments:t.attachments?.map(d=>({...d}))};const n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:o,selectionKey:this.state.selectionKey},a);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,o=K(p=>{s===this.submissionGeneration&&this.reportOperationTiming(p)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const p=await o.measure("staging_ipc",async()=>{if(d){if(!await o.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(z):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const h=b(u);if(h.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=h),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!p||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),p.result?.submissionAccepted){r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null);for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(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 h=u.id?this.attachmentFiles.get(u.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(h,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}a=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(z):void 0}),s!==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(p){if(s!==this.submissionGeneration)return null;if(R(p))for(const f of t.attachments??[])f.id&&this.attachmentFiles.delete(f.id);const u=b(p).code==="command_not_received";!c&&!R(p)&&(d||u||t.selectionKey!==void 0)&&this.submissionRetries.set(r,{retry:async()=>(d&&await this.connect(),this.sendMessageNow(e,{...t,reconcileAcceptance:!d&&!u},s)),attachmentIds:(t.attachments??[]).flatMap(f=>f.id?[f.id]:[])});const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=b(p),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:b(p).message}),p}finally{this.readinessPendingSubmissions.delete(r)}}getModel(){return this.model}setModel(e){return this.modelExplicit=!0,this.model===e||(this.model=e,this.emit("state",this.getState())),Promise.resolve()}async retryLastMessage(e){const t=e??[...this.submissionPreviews].reverse().find(([,a])=>a.error)?.[0]??this.state.messages.filter(a=>a.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,o=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(a){if(!s&&!r)throw a;return s&&o===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(a),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&o===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=K(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const o=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:o);const a=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(a!==this.submissionGeneration||s.every(p=>!this.stopPreviews.has(p)))){for(const p of s)this.stopPreviews.delete(p);this.stopError=b(d).message}}).finally(()=>{this.destroyed||a!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,o)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const a=this.state;if(a.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(a.conversationDiagnostics?.failedClientMessageId===e&&a.lastError&&a.lastErrorCode!=="submission_checkpoint_pending"){o(Object.assign(new Error(a.lastError),{code:a.lastErrorCode}));return}const c=a.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){o(new Error(c.content));return}a.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return L(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(o=>o.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const s=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=s,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:s}).then(()=>{})}dispatch(e){return this.adapter.dispatch(e)}async navigate(e){const t=++this.navigationRevision;this.pendingNavigation=!0,this.model=this.initialModel,this.emit("state",this.getState());try{await this.dispatch(e)}finally{t===this.navigationRevision&&(this.pendingNavigation=!1,this.emit("state",this.getState()))}}emit(e,t){const s=this.listeners[e];for(const n of s??[])n(t)}}function De(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function L(i){return{...i,data:i.data?I({entities:U(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=F;exports.ProductAgentInteractionManager=ue;exports.ProductAgentQueryController=E;exports.ProductAgentRemoteRuntimeClient=xe;exports.ProductAgentSessionHistoryManager=ae;exports.ProductAgentTaskPageTitleController=fe;exports.canSubmitPersonalProductAgentMessage=re;exports.createLocalStorageInteractionDecisionStorage=pe;exports.createProductAgentQueryState=_;exports.createProductAgentTaskPageTitleDocument=me;exports.formatProductAgentTaskPageTitle=H;exports.hasProductAgentPaidCreditFallback=ie;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Ce;exports.mergeProductAgentEntityPages=$;exports.normalizeProductAgentEntityPage=I;exports.readLocalStorageInteractionDecisions=B;exports.reconcileProductAgentSubmissionGate=te;exports.resolveProductAgentBillingPresentation=ne;exports.resolveProductAgentComposerAction=oe;exports.resolveProductAgentWidgetPresentation=se;exports.selectProductAgentQueryEntities=U;
@@ -564,7 +564,7 @@ function Ce(i) {
564
564
  function M(i) {
565
565
  return i.replace(ne, "");
566
566
  }
567
- const oe = "0.1.295", ae = {
567
+ const oe = "0.1.296", ae = {
568
568
  version: oe
569
569
  }, g = (i) => typeof i == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(i) ? i : null;
570
570
  function de(i) {
@@ -1987,7 +1987,7 @@ function Io(t, e = null) {
1987
1987
  } : void 0);
1988
1988
  return { ...n, ...o ? { auth: o } : {}, submissionGate: a, usingPaidCreditFallback: e ? t.paidFallbackBySession[e] ?? !1 : !1 };
1989
1989
  }
1990
- const wo = "0.1.295", zt = {
1990
+ const wo = "0.1.296", zt = {
1991
1991
  version: wo
1992
1992
  }, Ki = (t) => t.selectedModel ?? t.historyModel ?? t.defaultModel, _o = (t, e) => t.scopes[e];
1993
1993
  function Ht(t) {
@@ -76,7 +76,7 @@ function ih(t, e, n, i) {
76
76
  function sh(t) {
77
77
  return Vr(t) > 0.5 ? [24, 24, 27] : [250, 250, 249];
78
78
  }
79
- const oh = "0.1.295", ci = {
79
+ const oh = "0.1.296", ci = {
80
80
  version: oh
81
81
  }, fe = (t) => typeof t == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(t) ? t : null;
82
82
  function Ld(t) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluno/product-agent-web",
3
- "version": "0.1.295",
3
+ "version": "0.1.296",
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",