@pluno/product-agent-web 0.1.312 → 0.1.313
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts
CHANGED
|
@@ -348,6 +348,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
348
348
|
private socketAuthTimer;
|
|
349
349
|
private reconnectAttempts;
|
|
350
350
|
private embeddedRecoveryTimer;
|
|
351
|
+
private embeddedRecoveryTokenExpired;
|
|
351
352
|
private recoveryDiagnosticId;
|
|
352
353
|
private rejectedDiagnosticsToken;
|
|
353
354
|
private lastRecoveryStage;
|
|
@@ -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.312",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-6.1-sol",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.313",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-6.1-sol",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.
|
|
567
|
+
const oe = "0.1.313", 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) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const xi = [
|
|
2
2
|
{ value: "gpt-6-sol", label: "gpt-6-sol", price: "$$" },
|
|
3
3
|
{ value: "gpt-6-luna", label: "gpt-6-luna", price: "$" },
|
|
4
4
|
{ value: "deepseek/deepseek-v4-flash", label: "DeepSeek V4 Flash", price: "$" },
|
|
@@ -7,9 +7,9 @@ const Oi = [
|
|
|
7
7
|
function Gr(t) {
|
|
8
8
|
return t.length <= 4 ? { primary: t, more: [] } : { primary: t.slice(0, 3), more: t.slice(3) };
|
|
9
9
|
}
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
const Jr = (t) =>
|
|
10
|
+
const Oi = Gr(xi), ns = Oi.primary;
|
|
11
|
+
Oi.more;
|
|
12
|
+
const Jr = (t) => xi.some((e) => e.value === t), Oe = (t) => t === "gpt-5.6-sol" || t === "gpt-5.6-terra" || t === "anthropic/claude-sonnet-5" ? "gpt-6-sol" : t === "anthropic/claude-opus-5" ? "anthropic/claude-opus-5.5" : Jr(t) ? t : void 0;
|
|
13
13
|
function wt(t, e, s) {
|
|
14
14
|
t.throwIfAborted();
|
|
15
15
|
let n, i = () => {
|
|
@@ -327,15 +327,15 @@ function eo(t, e) {
|
|
|
327
327
|
return s && n >= 0 ? s.slice(0, n + 1) : [e];
|
|
328
328
|
}
|
|
329
329
|
function ge(t, e, s) {
|
|
330
|
-
const n = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => S.conversationScopeId === s), i = e.selections[s]?.sessionId ?? n.find((S) => !S.cancelled && S.sessionId !== null)?.sessionId ?? null, r = i ? t.sessions[i] : void 0, a = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => i ? S.sessionId === i || S.sessionId === null && S.conversationScopeId === s : S.conversationScopeId === s), o = Object.values(r?.items ?? {}).sort((S,
|
|
331
|
-
const U = fe(S.created_at), H = fe(
|
|
332
|
-
return U < H ? -1 : U > H ? 1 : S.id <
|
|
330
|
+
const n = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => S.conversationScopeId === s), i = e.selections[s]?.sessionId ?? n.find((S) => !S.cancelled && S.sessionId !== null)?.sessionId ?? null, r = i ? t.sessions[i] : void 0, a = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => i ? S.sessionId === i || S.sessionId === null && S.conversationScopeId === s : S.conversationScopeId === s), o = Object.values(r?.items ?? {}).sort((S, x) => {
|
|
331
|
+
const U = fe(S.created_at), H = fe(x.created_at);
|
|
332
|
+
return U < H ? -1 : U > H ? 1 : S.id < x.id ? -1 : S.id > x.id ? 1 : 0;
|
|
333
333
|
}), c = a.filter((S) => (!S.cancelled || S.conversationScopeId === s && (S.sessionId === null || S.sessionId === i || i === null && S === a[a.length - 1])) && !r?.items[S.userMessageId] && !r?.removedItems[S.userMessageId]), d = {};
|
|
334
334
|
for (const S of o) {
|
|
335
|
-
const
|
|
336
|
-
if (
|
|
335
|
+
const x = Dt(S);
|
|
336
|
+
if (x === null) continue;
|
|
337
337
|
const U = r?.streams[S.id];
|
|
338
|
-
d[S.id] = U ? U.state === "open" ? "open" :
|
|
338
|
+
d[S.id] = U ? U.state === "open" ? "open" : x < U.revision ? "awaiting_content" : U.state : "open";
|
|
339
339
|
}
|
|
340
340
|
const u = [];
|
|
341
341
|
for (const S of o)
|
|
@@ -343,15 +343,15 @@ function ge(t, e, s) {
|
|
|
343
343
|
u.push({ id: S.id, userMessageId: S.id, activityIds: [], outcomeIds: [], collapsed: !1 });
|
|
344
344
|
else {
|
|
345
345
|
u.length || u.push({ id: `leading:${S.id}`, userMessageId: null, activityIds: [], outcomeIds: [], collapsed: !1 });
|
|
346
|
-
const
|
|
347
|
-
u[
|
|
346
|
+
const x = u.length - 1, U = u[x], H = S.type === "commentary" || S.type === "tool_summary" ? "activityIds" : "outcomeIds";
|
|
347
|
+
u[x] = { ...U, [H]: [...U[H], S.id] };
|
|
348
348
|
}
|
|
349
349
|
for (const S of c) {
|
|
350
|
-
const
|
|
350
|
+
const x = u.findIndex((U) => {
|
|
351
351
|
const H = a.find((ct) => ct.userMessageId === U.userMessageId), ze = r?.items[U.userMessageId ?? U.activityIds[0] ?? U.outcomeIds[0]];
|
|
352
352
|
return (H?.submittedAt ?? (ze ? Date.parse(ze.created_at) : 1 / 0)) > S.submittedAt;
|
|
353
353
|
});
|
|
354
|
-
u.splice(
|
|
354
|
+
u.splice(x < 0 ? u.length : x, 0, {
|
|
355
355
|
id: S.userMessageId,
|
|
356
356
|
userMessageId: S.userMessageId,
|
|
357
357
|
activityIds: [],
|
|
@@ -361,11 +361,11 @@ function ge(t, e, s) {
|
|
|
361
361
|
}
|
|
362
362
|
const l = r?.execution, h = a.filter((S) => !S.cancelled && S.delivery !== "failed"), p = h.filter((S) => S.delivery !== "accepted" && S.executionVersion === null), m = h.filter((S) => S.delivery === "accepted" && S.executionVersion === null), f = h[h.length - 1], y = p.length > 0, b = f !== void 0 && m.includes(f);
|
|
363
363
|
let k = y ? "submitting" : b ? "awaiting_execution" : l?.phase ?? "idle";
|
|
364
|
-
const R = Object.entries(t.stops).filter(([S]) => S === s || i !== null && e.selections[S]?.sessionId === i).map(([, S]) => S).find((S) => (!a.length || S.userMessageIds.includes(a[a.length - 1].userMessageId) || !y && !b && le(l).some((
|
|
364
|
+
const R = Object.entries(t.stops).filter(([S]) => S === s || i !== null && e.selections[S]?.sessionId === i).map(([, S]) => S).find((S) => (!a.length || S.userMessageIds.includes(a[a.length - 1].userMessageId) || !y && !b && le(l).some((x) => S.userMessageIds.includes(x))) && (!l || l.version <= S.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(l.phase) || a.some((x) => x.cancelled && x.executionVersion === null && S.userMessageIds.includes(x.userMessageId)))), g = l && ["thinking", "steering", "queued", "stopping"].includes(l.phase) || a.some((S) => S.delivery === "accepted" && S.executionVersion === null && R?.userMessageIds.includes(S.userMessageId));
|
|
365
365
|
R && g && !y && (!l || !["thinking", "steering", "queued", "stopping"].includes(l.phase) || le(l).every((S) => R.userMessageIds.includes(S))) && (k = "stopping"), R && !g && !y && a.some((S) => S.cancelled && S.executionVersion === null && R.userMessageIds.includes(S.userMessageId)) && (k = a.some((S) => R.userMessageIds.includes(S.userMessageId) && ["sending", "uncertain"].includes(S.delivery)) ? "stopping" : "stopped");
|
|
366
366
|
const v = ["thinking", "steering", "queued"].includes(k), I = t.stops[s] ?? R, w = I?.userMessageIds.filter((S) => !["completed", "failed"].includes(r?.executionByUserMessage[S]?.phase ?? "")) ?? [], A = w.some((S) => {
|
|
367
|
-
const
|
|
368
|
-
return !Object.values(t.operations).some((H) => H.command.type === "run.stop" && H.command.payload.expectedUserMessageId === S && H.phase === "done") && (
|
|
367
|
+
const x = a.find((H) => H.userMessageId === S);
|
|
368
|
+
return !Object.values(t.operations).some((H) => H.command.type === "run.stop" && H.command.payload.expectedUserMessageId === S && H.phase === "done") && (x?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(x.delivery) || !!(l && le(l).includes(S) && ["thinking", "steering", "queued", "stopping"].includes(l.phase)));
|
|
369
369
|
}), _ = l?.user_message_ids ?? [], q = y || b ? f?.userMessageId ?? null : _[_.length - 1] ?? null, E = u.find((S) => S.userMessageId === q), C = v ? [...E?.activityIds ?? []].reverse().find((S) => d[S] === "open") ?? null : null, M = i !== null && !!e.selections[s]?.provisionalId && o.length === 0 && a.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
|
|
370
370
|
(!r?.execution || r.execution.phase === "idle" && r.execution.user_message_ids.length === 0) && Object.values(t.operations).some((S) => S.conversationScopeId === s && S.phase === "done" && ["runtime.warmup", "attachment.prepare"].includes(S.command.type) && !S.command.payload.sessionId && S.result?.sessionId === i);
|
|
371
371
|
return G({
|
|
@@ -386,7 +386,7 @@ function ge(t, e, s) {
|
|
|
386
386
|
streamStates: d,
|
|
387
387
|
preparation: r?.preparation ?? null,
|
|
388
388
|
stop: I ? { ...I, userMessageIds: w, pending: A } : null,
|
|
389
|
-
segments: u.map((S,
|
|
389
|
+
segments: u.map((S, x) => ({ ...S, collapsed: v ? S.userMessageId !== q : x < u.length - 1 || S.activityIds.length > 0 })),
|
|
390
390
|
activity: { phase: k, activeItemId: C, userMessageId: q, executionKey: JSON.stringify([...le(l)].sort()) },
|
|
391
391
|
// Staging transfers the immutable input to the core. Waiting for backend acceptance leaves
|
|
392
392
|
// the same submitted text in the optimistic transcript and composer during delivery.
|
|
@@ -896,9 +896,9 @@ function zs(t, e, s) {
|
|
|
896
896
|
const I = { ...n.features.contextObservers }, w = I[g];
|
|
897
897
|
if (v === null ? delete I[g] : I[g] = ie(o, { kind: "originContext", clientScopeId: g, origin: v, pageUrl: "" }), r({ contextObservers: I }), !w || Object.values(I).includes(w)) return;
|
|
898
898
|
const A = { ...n.features.queries }, _ = { ...n.features.polls }, q = { ...n.features.contextReads }, E = { ...n.features.originContextQueries }, C = { ...n.features.pending }, M = E[w]?.origin, S = { ...n.features.contextRunOrigins };
|
|
899
|
-
for (const [
|
|
899
|
+
for (const [x, U] of Object.entries(S)) U === M && delete S[x];
|
|
900
900
|
delete A[w], delete _[w], delete q[w], delete E[w];
|
|
901
|
-
for (const [
|
|
901
|
+
for (const [x, U] of Object.entries(C)) U.mode === "query" && U.key === w && delete C[x];
|
|
902
902
|
r({ queries: A, polls: _, contextReads: q, originContextQueries: E, contextRunOrigins: S, pending: C });
|
|
903
903
|
};
|
|
904
904
|
if (e.type === "stage7.account_fallback") return { state: { ...n, account: {
|
|
@@ -1292,7 +1292,7 @@ function zs(t, e, s) {
|
|
|
1292
1292
|
for (const [C, M] of Object.entries(n.features.originContextQueries))
|
|
1293
1293
|
if (M.origin === w) {
|
|
1294
1294
|
A[C] = { ...A[C], data: I, status: "ready", error: null, requestId: null, updatedAt: e.output.completedAt }, q[C] = { settledAt: e.output.completedAt, failures: 0 }, delete E[C];
|
|
1295
|
-
for (const [S,
|
|
1295
|
+
for (const [S, x] of Object.entries(_)) x.mode === "query" && x.key === C && delete _[S];
|
|
1296
1296
|
["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(I.value.status) && (E[C] = { query: { ...M, kind: "originContext", trigger: "poll" }, deadline: n.features.now + 5e3 });
|
|
1297
1297
|
}
|
|
1298
1298
|
r({ queries: A, pending: _, contextReads: q, polls: E });
|
|
@@ -1527,7 +1527,7 @@ function P(t) {
|
|
|
1527
1527
|
function de(t) {
|
|
1528
1528
|
return t == null ? null : P(t);
|
|
1529
1529
|
}
|
|
1530
|
-
function
|
|
1530
|
+
function xe(t) {
|
|
1531
1531
|
if (typeof t != "number" || !Number.isSafeInteger(t) || t < 0) throw new Error("Invalid feature revision.");
|
|
1532
1532
|
return t;
|
|
1533
1533
|
}
|
|
@@ -1552,23 +1552,23 @@ function Ve(t) {
|
|
|
1552
1552
|
return {
|
|
1553
1553
|
taskNotificationsEnabled: as(e.taskNotificationsEnabled),
|
|
1554
1554
|
tabGroupingEnabled: as(e.tabGroupingEnabled),
|
|
1555
|
-
preferencesVersion:
|
|
1555
|
+
preferencesVersion: xe(e.preferencesVersion),
|
|
1556
1556
|
scribbleStyleEnabled: as(e.scribbleStyleEnabled),
|
|
1557
1557
|
blockedOrigins: St(e.blockedServiceOrigins),
|
|
1558
1558
|
personalInstructions: de(e.personalInstructions),
|
|
1559
|
-
securityPolicyVersion:
|
|
1559
|
+
securityPolicyVersion: xe(e.securityPolicyVersion)
|
|
1560
1560
|
};
|
|
1561
1561
|
}
|
|
1562
1562
|
function jt(t) {
|
|
1563
1563
|
const e = N(t);
|
|
1564
|
-
return { eligibleSince: Nt(e.eligibleSince), revision:
|
|
1564
|
+
return { eligibleSince: Nt(e.eligibleSince), revision: xe(e.revision), requestId: de(e.requestId), snoozedUntil: Nt(e.snoozedUntil) };
|
|
1565
1565
|
}
|
|
1566
1566
|
function ho(t) {
|
|
1567
1567
|
const e = N(t);
|
|
1568
1568
|
return { notifications: jt(e.notifications), tab_grouping: jt(e.tabGrouping) };
|
|
1569
1569
|
}
|
|
1570
1570
|
function $n(t) {
|
|
1571
|
-
const e = N(t), s = N(e.request), n = P(s.category), i = P(s.action), r = { category: n, action: i, promptKey: P(s.promptKey), expectedRevision:
|
|
1571
|
+
const e = N(t), s = N(e.request), n = P(s.category), i = P(s.action), r = { category: n, action: i, promptKey: P(s.promptKey), expectedRevision: xe(s.expectedRevision) };
|
|
1572
1572
|
un(r);
|
|
1573
1573
|
const a = P(e.outcome);
|
|
1574
1574
|
if (!["resolved", "snoozed", "suppressed"].includes(a)) throw new Error("Invalid decision outcome.");
|
|
@@ -1578,7 +1578,7 @@ function $n(t) {
|
|
|
1578
1578
|
if (a === "snoozed" && c === null) throw new Error("Missing decision deadline.");
|
|
1579
1579
|
return {
|
|
1580
1580
|
decisionKey: P(e.decisionKey),
|
|
1581
|
-
revision:
|
|
1581
|
+
revision: xe(e.revision),
|
|
1582
1582
|
decidedAt: o,
|
|
1583
1583
|
request: { ...r, requestId: P(s.requestId) },
|
|
1584
1584
|
outcome: a,
|
|
@@ -1601,11 +1601,11 @@ function po(t) {
|
|
|
1601
1601
|
if (s.template === "semantic_interaction") return { ...n, condition: { template: s.template, event: cs(s.event) } };
|
|
1602
1602
|
if (s.template === "event_sequence") {
|
|
1603
1603
|
if (!Array.isArray(s.steps)) throw new Error("Invalid proactive sequence.");
|
|
1604
|
-
return { ...n, condition: { template: s.template, steps: s.steps.map(cs), withinSeconds:
|
|
1604
|
+
return { ...n, condition: { template: s.template, steps: s.steps.map(cs), withinSeconds: xe(s.withinSeconds) } };
|
|
1605
1605
|
}
|
|
1606
1606
|
if (s.template === "page_state_after_event") {
|
|
1607
1607
|
const i = N(s.state);
|
|
1608
|
-
return { ...n, condition: { template: s.template, event: cs(s.event), withinSeconds:
|
|
1608
|
+
return { ...n, condition: { template: s.template, event: cs(s.event), withinSeconds: xe(s.withinSeconds), state: {
|
|
1609
1609
|
urlRegex: P(i.urlRegex),
|
|
1610
1610
|
...i.textRegex == null ? {} : { textRegex: P(i.textRegex) },
|
|
1611
1611
|
...i.roleRegex == null ? {} : { roleRegex: P(i.roleRegex) },
|
|
@@ -1987,7 +1987,7 @@ function _o(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 So = "0.1.
|
|
1990
|
+
const So = "0.1.313", zt = {
|
|
1991
1991
|
version: So
|
|
1992
1992
|
}, Ki = (t) => t.selectedModel ?? t.historyModel ?? t.defaultModel, ko = (t, e) => t.scopes[e];
|
|
1993
1993
|
function Ht(t) {
|
|
@@ -2899,7 +2899,7 @@ function Q(t, e) {
|
|
|
2899
2899
|
}
|
|
2900
2900
|
};
|
|
2901
2901
|
}
|
|
2902
|
-
function
|
|
2902
|
+
function xo(t) {
|
|
2903
2903
|
let e = [], s;
|
|
2904
2904
|
const n = () => {
|
|
2905
2905
|
clearTimeout(s), s = void 0;
|
|
@@ -2911,7 +2911,7 @@ function Oo(t) {
|
|
|
2911
2911
|
ot(i) && (JSON.stringify([...e, i]).length > 2800 && n(), e.push(i), e.length === 8 ? n() : s ??= setTimeout(n, 250));
|
|
2912
2912
|
};
|
|
2913
2913
|
}
|
|
2914
|
-
function
|
|
2914
|
+
function Oo(t) {
|
|
2915
2915
|
let e = Promise.resolve(), s = null, n = null;
|
|
2916
2916
|
const i = () => n ??= t.read().catch((a) => {
|
|
2917
2917
|
throw n = null, a;
|
|
@@ -4417,7 +4417,7 @@ function Et(t, e) {
|
|
|
4417
4417
|
return !0;
|
|
4418
4418
|
return !1;
|
|
4419
4419
|
}
|
|
4420
|
-
function
|
|
4420
|
+
function xa(t) {
|
|
4421
4421
|
const e = [], s = t.data, n = t;
|
|
4422
4422
|
return n.data = Tt(s, e), n.attachments = e.length, { packet: n, buffers: e };
|
|
4423
4423
|
}
|
|
@@ -4442,7 +4442,7 @@ function Tt(t, e, s) {
|
|
|
4442
4442
|
}
|
|
4443
4443
|
return t;
|
|
4444
4444
|
}
|
|
4445
|
-
function
|
|
4445
|
+
function Oa(t, e) {
|
|
4446
4446
|
return t.data = tn(t.data, e), delete t.attachments, t;
|
|
4447
4447
|
}
|
|
4448
4448
|
function tn(t, e) {
|
|
@@ -4474,10 +4474,10 @@ const Pa = [
|
|
|
4474
4474
|
"removeListener"
|
|
4475
4475
|
// used by the Node.js EventEmitter
|
|
4476
4476
|
];
|
|
4477
|
-
var
|
|
4477
|
+
var O;
|
|
4478
4478
|
(function(t) {
|
|
4479
4479
|
t[t.CONNECT = 0] = "CONNECT", t[t.DISCONNECT = 1] = "DISCONNECT", t[t.EVENT = 2] = "EVENT", t[t.ACK = 3] = "ACK", t[t.CONNECT_ERROR = 4] = "CONNECT_ERROR", t[t.BINARY_EVENT = 5] = "BINARY_EVENT", t[t.BINARY_ACK = 6] = "BINARY_ACK";
|
|
4480
|
-
})(
|
|
4480
|
+
})(O || (O = {}));
|
|
4481
4481
|
class Da {
|
|
4482
4482
|
/**
|
|
4483
4483
|
* Encoder constructor
|
|
@@ -4494,8 +4494,8 @@ class Da {
|
|
|
4494
4494
|
* @param {Object} obj - packet object
|
|
4495
4495
|
*/
|
|
4496
4496
|
encode(e) {
|
|
4497
|
-
return (e.type ===
|
|
4498
|
-
type: e.type ===
|
|
4497
|
+
return (e.type === O.EVENT || e.type === O.ACK) && Et(e) ? this.encodeAsBinary({
|
|
4498
|
+
type: e.type === O.EVENT ? O.BINARY_EVENT : O.BINARY_ACK,
|
|
4499
4499
|
nsp: e.nsp,
|
|
4500
4500
|
data: e.data,
|
|
4501
4501
|
id: e.id
|
|
@@ -4506,7 +4506,7 @@ class Da {
|
|
|
4506
4506
|
*/
|
|
4507
4507
|
encodeAsString(e) {
|
|
4508
4508
|
let s = "" + e.type;
|
|
4509
|
-
return (e.type ===
|
|
4509
|
+
return (e.type === O.BINARY_EVENT || e.type === O.BINARY_ACK) && (s += e.attachments + "-"), e.nsp && e.nsp !== "/" && (s += e.nsp + ","), e.id != null && (s += e.id), e.data != null && (s += JSON.stringify(e.data, this.replacer)), s;
|
|
4510
4510
|
}
|
|
4511
4511
|
/**
|
|
4512
4512
|
* Encode packet as 'buffer sequence' by removing blobs, and
|
|
@@ -4514,7 +4514,7 @@ class Da {
|
|
|
4514
4514
|
* a list of buffers.
|
|
4515
4515
|
*/
|
|
4516
4516
|
encodeAsBinary(e) {
|
|
4517
|
-
const s =
|
|
4517
|
+
const s = xa(e), n = this.encodeAsString(s.packet), i = s.buffers;
|
|
4518
4518
|
return i.unshift(n), i;
|
|
4519
4519
|
}
|
|
4520
4520
|
}
|
|
@@ -4539,8 +4539,8 @@ class wn extends F {
|
|
|
4539
4539
|
if (this.reconstructor)
|
|
4540
4540
|
throw new Error("got plaintext data when reconstructing a packet");
|
|
4541
4541
|
s = this.decodeString(e);
|
|
4542
|
-
const n = s.type ===
|
|
4543
|
-
n || s.type ===
|
|
4542
|
+
const n = s.type === O.BINARY_EVENT;
|
|
4543
|
+
n || s.type === O.BINARY_ACK ? (s.type = n ? O.EVENT : O.ACK, this.reconstructor = new Ua(s)) : super.emitReserved("decoded", s);
|
|
4544
4544
|
} else if (In(e) || e.base64)
|
|
4545
4545
|
if (this.reconstructor)
|
|
4546
4546
|
s = this.reconstructor.takeBinaryData(e), s && (this.reconstructor = null, super.emitReserved("decoded", s));
|
|
@@ -4560,9 +4560,9 @@ class wn extends F {
|
|
|
4560
4560
|
const n = {
|
|
4561
4561
|
type: Number(e.charAt(0))
|
|
4562
4562
|
};
|
|
4563
|
-
if (
|
|
4563
|
+
if (O[n.type] === void 0)
|
|
4564
4564
|
throw new Error("unknown packet type " + n.type);
|
|
4565
|
-
if (n.type ===
|
|
4565
|
+
if (n.type === O.BINARY_EVENT || n.type === O.BINARY_ACK) {
|
|
4566
4566
|
const r = s + 1;
|
|
4567
4567
|
for (; e.charAt(++s) !== "-" && s != e.length; )
|
|
4568
4568
|
;
|
|
@@ -4615,17 +4615,17 @@ class wn extends F {
|
|
|
4615
4615
|
}
|
|
4616
4616
|
static isPayloadValid(e, s) {
|
|
4617
4617
|
switch (e) {
|
|
4618
|
-
case
|
|
4618
|
+
case O.CONNECT:
|
|
4619
4619
|
return Yn(s);
|
|
4620
|
-
case
|
|
4620
|
+
case O.DISCONNECT:
|
|
4621
4621
|
return s === void 0;
|
|
4622
|
-
case
|
|
4622
|
+
case O.CONNECT_ERROR:
|
|
4623
4623
|
return typeof s == "string" || Yn(s);
|
|
4624
|
-
case
|
|
4625
|
-
case
|
|
4624
|
+
case O.EVENT:
|
|
4625
|
+
case O.BINARY_EVENT:
|
|
4626
4626
|
return Array.isArray(s) && (typeof s[0] == "number" || typeof s[0] == "string" && Pa.indexOf(s[0]) === -1);
|
|
4627
|
-
case
|
|
4628
|
-
case
|
|
4627
|
+
case O.ACK:
|
|
4628
|
+
case O.BINARY_ACK:
|
|
4629
4629
|
return Array.isArray(s);
|
|
4630
4630
|
}
|
|
4631
4631
|
}
|
|
@@ -4650,7 +4650,7 @@ class Ua {
|
|
|
4650
4650
|
*/
|
|
4651
4651
|
takeBinaryData(e) {
|
|
4652
4652
|
if (this.buffers.push(e), this.buffers.length === this.reconPack.attachments) {
|
|
4653
|
-
const s =
|
|
4653
|
+
const s = Oa(this.reconPack, this.buffers);
|
|
4654
4654
|
return this.finishedReconstruction(), s;
|
|
4655
4655
|
}
|
|
4656
4656
|
return null;
|
|
@@ -4673,7 +4673,7 @@ const ja = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
|
4673
4673
|
Decoder: wn,
|
|
4674
4674
|
Encoder: Da,
|
|
4675
4675
|
get PacketType() {
|
|
4676
|
-
return
|
|
4676
|
+
return O;
|
|
4677
4677
|
}
|
|
4678
4678
|
}, Symbol.toStringTag, { value: "Module" }));
|
|
4679
4679
|
function ce(t, e, s) {
|
|
@@ -4811,7 +4811,7 @@ class ur extends F {
|
|
|
4811
4811
|
if (s.unshift(e), this._opts.retries && !this.flags.fromQueue && !this.flags.volatile)
|
|
4812
4812
|
return this._addToQueue(s), this;
|
|
4813
4813
|
const a = {
|
|
4814
|
-
type:
|
|
4814
|
+
type: O.EVENT,
|
|
4815
4815
|
data: s
|
|
4816
4816
|
};
|
|
4817
4817
|
if (a.options = {}, a.options.compress = this.flags.compress !== !1, typeof s[s.length - 1] == "function") {
|
|
@@ -4919,7 +4919,7 @@ class ur extends F {
|
|
|
4919
4919
|
*/
|
|
4920
4920
|
_sendConnectPacket(e) {
|
|
4921
4921
|
this.packet({
|
|
4922
|
-
type:
|
|
4922
|
+
type: O.CONNECT,
|
|
4923
4923
|
data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, e) : e
|
|
4924
4924
|
});
|
|
4925
4925
|
}
|
|
@@ -4965,21 +4965,21 @@ class ur extends F {
|
|
|
4965
4965
|
onpacket(e) {
|
|
4966
4966
|
if (e.nsp === this.nsp)
|
|
4967
4967
|
switch (e.type) {
|
|
4968
|
-
case
|
|
4968
|
+
case O.CONNECT:
|
|
4969
4969
|
e.data && e.data.sid ? this.onconnect(e.data.sid, e.data.pid) : this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
|
|
4970
4970
|
break;
|
|
4971
|
-
case
|
|
4972
|
-
case
|
|
4971
|
+
case O.EVENT:
|
|
4972
|
+
case O.BINARY_EVENT:
|
|
4973
4973
|
this.onevent(e);
|
|
4974
4974
|
break;
|
|
4975
|
-
case
|
|
4976
|
-
case
|
|
4975
|
+
case O.ACK:
|
|
4976
|
+
case O.BINARY_ACK:
|
|
4977
4977
|
this.onack(e);
|
|
4978
4978
|
break;
|
|
4979
|
-
case
|
|
4979
|
+
case O.DISCONNECT:
|
|
4980
4980
|
this.ondisconnect();
|
|
4981
4981
|
break;
|
|
4982
|
-
case
|
|
4982
|
+
case O.CONNECT_ERROR:
|
|
4983
4983
|
this.destroy();
|
|
4984
4984
|
const n = new Error(e.data.message);
|
|
4985
4985
|
n.data = e.data.data, this.emitReserved("connect_error", n);
|
|
@@ -5014,7 +5014,7 @@ class ur extends F {
|
|
|
5014
5014
|
let n = !1;
|
|
5015
5015
|
return function(...i) {
|
|
5016
5016
|
n || (n = !0, s.packet({
|
|
5017
|
-
type:
|
|
5017
|
+
type: O.ACK,
|
|
5018
5018
|
id: e,
|
|
5019
5019
|
data: i
|
|
5020
5020
|
}));
|
|
@@ -5083,7 +5083,7 @@ class ur extends F {
|
|
|
5083
5083
|
* @return self
|
|
5084
5084
|
*/
|
|
5085
5085
|
disconnect() {
|
|
5086
|
-
return this.connected && this.packet({ type:
|
|
5086
|
+
return this.connected && this.packet({ type: O.DISCONNECT }), this.destroy(), this.connected && this.onclose("io client disconnect"), this;
|
|
5087
5087
|
}
|
|
5088
5088
|
/**
|
|
5089
5089
|
* Alias for {@link disconnect()}.
|
|
@@ -6820,8 +6820,8 @@ class hr {
|
|
|
6820
6820
|
...typeof M.blockedOrigin == "string" ? { blockedOrigin: M.blockedOrigin } : {},
|
|
6821
6821
|
...typeof M.securitySettingsUrl == "string" ? { securitySettingsUrl: M.securitySettingsUrl } : {}
|
|
6822
6822
|
}, r === "conversations" && e === "/commands");
|
|
6823
|
-
const S = M === "Token expired" ? "token_expired" : M === "Invalid token" ? "invalid_token" : M?.reason,
|
|
6824
|
-
throw new T(E.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : E.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${E.status})`, C, !1,
|
|
6823
|
+
const S = M === "Token expired" ? "token_expired" : M === "Invalid token" ? "invalid_token" : M?.reason, x = E.status === 401 && ["missing_token", "token_expired", "invalid_token", "user_not_found"].includes(S) ? { requestId: g, authTransport: "http", authEndpoint: `${r ?? (d ? "embed" : "runtime")}:${["snapshot", "me", "bootstrap", "commands", "activity", "session-history"].includes(e.split("/").pop()) ? e.split("/").pop() : "other"}`, reason: S, retryable: S === "token_expired" && (M === "Token expired" || M.retryable === !0) } : void 0;
|
|
6824
|
+
throw new T(E.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : E.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${E.status})`, C, !1, x);
|
|
6825
6825
|
}
|
|
6826
6826
|
return await E.json();
|
|
6827
6827
|
} catch (E) {
|
|
@@ -6849,10 +6849,10 @@ class hr {
|
|
|
6849
6849
|
});
|
|
6850
6850
|
const S = he(M) ? { httpRequest: M } : void 0;
|
|
6851
6851
|
if (C !== null) {
|
|
6852
|
-
const
|
|
6852
|
+
const x = C !== "deadline" && C !== "unexpected_abort";
|
|
6853
6853
|
throw new T(
|
|
6854
|
-
|
|
6855
|
-
|
|
6854
|
+
x ? "The request was cancelled." : C === "deadline" ? "The request timed out. Please try again." : "The connection was interrupted. Please try again.",
|
|
6855
|
+
x ? "request_cancelled" : C === "deadline" ? "request_timed_out" : "connection_interrupted",
|
|
6856
6856
|
!0,
|
|
6857
6857
|
S
|
|
6858
6858
|
);
|
|
@@ -8621,7 +8621,7 @@ function br(t, e, s) {
|
|
|
8621
8621
|
};
|
|
8622
8622
|
}
|
|
8623
8623
|
const Ir = "suggest_share_on_socials";
|
|
8624
|
-
function
|
|
8624
|
+
function xc(t) {
|
|
8625
8625
|
let e = t;
|
|
8626
8626
|
if (typeof t == "string")
|
|
8627
8627
|
try {
|
|
@@ -8629,10 +8629,10 @@ function Oc(t) {
|
|
|
8629
8629
|
} catch {
|
|
8630
8630
|
return null;
|
|
8631
8631
|
}
|
|
8632
|
-
const s =
|
|
8632
|
+
const s = Oc(e);
|
|
8633
8633
|
return s ? typeof s.showSharePrompt == "boolean" ? s.showSharePrompt : s.ok === !0 && typeof s.message == "string" && s.message.includes("social-sharing prompt") ? !0 : null : null;
|
|
8634
8634
|
}
|
|
8635
|
-
function
|
|
8635
|
+
function Oc(t) {
|
|
8636
8636
|
return t && typeof t == "object" && !Array.isArray(t) ? t : null;
|
|
8637
8637
|
}
|
|
8638
8638
|
const Pc = "save_runtime_captured_skill";
|
|
@@ -8641,7 +8641,7 @@ function Dc(t) {
|
|
|
8641
8641
|
}
|
|
8642
8642
|
const bs = "pluno.productAgent.transportId", Uc = "pluno.productAgent.transportIdentity", Is = "pluno.productAgent.transportIdentity.event", Nc = 50, jc = globalThis.setTimeout.bind(globalThis);
|
|
8643
8643
|
let Qe = null;
|
|
8644
|
-
const
|
|
8644
|
+
const xt = /* @__PURE__ */ new Set(), ws = /* @__PURE__ */ new Map();
|
|
8645
8645
|
async function Bc(t = wr()) {
|
|
8646
8646
|
const e = t.randomUUID(), s = t.storage.getItem(bs);
|
|
8647
8647
|
let n = s ?? t.randomUUID(), i = !1, r = !1;
|
|
@@ -8686,24 +8686,24 @@ async function Lc(t = !1) {
|
|
|
8686
8686
|
skipStoredIdentityCollisionCheck: t
|
|
8687
8687
|
}), Qe.then((i) => {
|
|
8688
8688
|
const r = (a) => {
|
|
8689
|
-
a.persisted || (i.release(), Qe = null,
|
|
8689
|
+
a.persisted || (i.release(), Qe = null, xt.clear(), window.removeEventListener("pagehide", r));
|
|
8690
8690
|
};
|
|
8691
8691
|
window.addEventListener("pagehide", r);
|
|
8692
8692
|
}));
|
|
8693
8693
|
const e = await Qe, s = Fc();
|
|
8694
|
-
|
|
8694
|
+
xt.add(s);
|
|
8695
8695
|
let n = !1;
|
|
8696
8696
|
return {
|
|
8697
8697
|
// A stable per-tab base keeps reload routing intact, while slots isolate multiple live SDK instances in one tab.
|
|
8698
8698
|
transportId: s === 0 ? e.transportId : `${e.transportId}.${s}`,
|
|
8699
8699
|
release: () => {
|
|
8700
|
-
n || (n = !0,
|
|
8700
|
+
n || (n = !0, xt.delete(s));
|
|
8701
8701
|
}
|
|
8702
8702
|
};
|
|
8703
8703
|
}
|
|
8704
8704
|
function Fc() {
|
|
8705
8705
|
let t = 0;
|
|
8706
|
-
for (;
|
|
8706
|
+
for (; xt.has(t); )
|
|
8707
8707
|
t += 1;
|
|
8708
8708
|
return t;
|
|
8709
8709
|
}
|
|
@@ -9920,7 +9920,7 @@ function As(t) {
|
|
|
9920
9920
|
const r = (c) => {
|
|
9921
9921
|
if (!c || typeof c != "object")
|
|
9922
9922
|
return null;
|
|
9923
|
-
const d = c, u = d.data, l = u && typeof u == "object" ? u : {}, h =
|
|
9923
|
+
const d = c, u = d.data, l = u && typeof u == "object" ? u : {}, h = xr(c);
|
|
9924
9924
|
return {
|
|
9925
9925
|
id: typeof d.id == "string" ? d.id : null,
|
|
9926
9926
|
streamId: l.type === "message" && l.role === "assistant" && typeof l.id == "string" ? l.id : null,
|
|
@@ -9981,7 +9981,7 @@ const ud = "https://app.pluno.ai", hd = 2e4, pd = 1e4, fd = 6e4, gd = 6e4, md =
|
|
|
9981
9981
|
".pdf:application/pdf",
|
|
9982
9982
|
".png:image/png",
|
|
9983
9983
|
".webp:image/webp"
|
|
9984
|
-
]), gu = ".pdf,.png,.jpg,.jpeg,.webp", kn = 64e3, qs = 4e3, Rn = 30, Sd = 2e3, kd = 1e3, Ar = "Image is too large for model vision input.", Rd = "pluno.productAgent.state.", ln = "pluno.productAgent.pendingEvents.", Gt = "pluno.productAgent.activeToolCalls.", Ad = 100,
|
|
9984
|
+
]), gu = ".pdf,.png,.jpg,.jpeg,.webp", kn = 64e3, qs = 4e3, Rn = 30, Sd = 2e3, kd = 1e3, Ar = "Image is too large for model vision input.", Rd = "pluno.productAgent.state.", ln = "pluno.productAgent.pendingEvents.", Gt = "pluno.productAgent.activeToolCalls.", Ad = 100, Ot = /* @__PURE__ */ new Set();
|
|
9985
9985
|
let vt = null;
|
|
9986
9986
|
function Ed(t, e = Math.random) {
|
|
9987
9987
|
const s = Math.min(dn, vd * 2 ** t), n = 1 - bi + e() * bi * 2;
|
|
@@ -10058,13 +10058,13 @@ class Jt {
|
|
|
10058
10058
|
now: () => Date.now(),
|
|
10059
10059
|
onError: (i) => this.handleDirectoryTransportError(i),
|
|
10060
10060
|
onPersonalModel: (i) => {
|
|
10061
|
-
const r =
|
|
10061
|
+
const r = Oe(i);
|
|
10062
10062
|
this.options.productVariant !== "personal" || !r || (this.lastPersonalModel = r, this.state.sessionId === null && !this.draftModelExplicit && this.draftModel !== r && (this.draftModel = r, this.emit("state", this.getState())));
|
|
10063
10063
|
}
|
|
10064
10064
|
}), void 0, $o(async () => {
|
|
10065
10065
|
if (!this.token || !this.state.user || this.state.status === "closed") throw new Error("Product Agent is not authenticated");
|
|
10066
10066
|
return this.options.activeUsersLoader ? (await this.options.activeUsersLoader()).count : zo(this.options.backendUrl);
|
|
10067
|
-
})), this.draftModel = (e.productVariant === "personal" ?
|
|
10067
|
+
})), this.draftModel = (e.productVariant === "personal" ? Oe(e.model) : e.model) ?? (e.productVariant === "personal" ? ns[0].value : "gpt-6.1-sol"), this.modelClientScopeId = Gc(e.clientId, () => crypto.randomUUID()), this.directoryConversationScopeId = `conversation:${this.modelClientScopeId}`, this.createDirectoryAdapters(), this.clientRuntime.engine.dispatch({
|
|
10068
10068
|
type: "model.scope_open",
|
|
10069
10069
|
clientScopeId: this.modelClientScopeId,
|
|
10070
10070
|
sessionId: null,
|
|
@@ -10090,6 +10090,7 @@ class Jt {
|
|
|
10090
10090
|
socketAuthTimer = null;
|
|
10091
10091
|
reconnectAttempts = 0;
|
|
10092
10092
|
embeddedRecoveryTimer = null;
|
|
10093
|
+
embeddedRecoveryTokenExpired = !1;
|
|
10093
10094
|
recoveryDiagnosticId = crypto.randomUUID();
|
|
10094
10095
|
rejectedDiagnosticsToken = null;
|
|
10095
10096
|
lastRecoveryStage = "token_provider";
|
|
@@ -10247,12 +10248,12 @@ class Jt {
|
|
|
10247
10248
|
const e = ++this.conversationAdapterGeneration;
|
|
10248
10249
|
this.conversationObservation?.dispose(), this.conversationUnsubscribe?.();
|
|
10249
10250
|
const s = this.directoryAuthority, n = () => e === this.conversationAdapterGeneration;
|
|
10250
|
-
this.operationTimingReporter =
|
|
10251
|
+
this.operationTimingReporter = xo((f) => {
|
|
10251
10252
|
n() && !this.clientRuntime.isDisposed && this.reportHealthSignal("operation_timing", { timings: f.map((y) => ({ ...y, entrySurface: this.options.entrySurface })) });
|
|
10252
10253
|
});
|
|
10253
10254
|
const i = `pa.conversation.delivery:${this.modelClientScopeId}:${s.authorityId}`, r = `${i}:cancellations`;
|
|
10254
10255
|
this.authenticatedUserId && this.options.restorePersistedState === !1 && sessionStorage.removeItem(r);
|
|
10255
|
-
const a = this.authenticatedUserId ? hs(r) : null, o =
|
|
10256
|
+
const a = this.authenticatedUserId ? hs(r) : null, o = Oo({
|
|
10256
10257
|
authorityId: s.authorityId,
|
|
10257
10258
|
isCurrent: n,
|
|
10258
10259
|
read: async () => a ? JSON.parse(a) : null,
|
|
@@ -10896,7 +10897,7 @@ class Jt {
|
|
|
10896
10897
|
return this.draftModel;
|
|
10897
10898
|
}
|
|
10898
10899
|
setModel(e) {
|
|
10899
|
-
const s = this.options.productVariant === "personal" ?
|
|
10900
|
+
const s = this.options.productVariant === "personal" ? Oe(e) ?? e : e;
|
|
10900
10901
|
this.draftModelExplicit = !0, this.draftModel !== s && (this.draftModel = s, this.emit("state", this.getState()));
|
|
10901
10902
|
}
|
|
10902
10903
|
retryLastMessage(e) {
|
|
@@ -11042,7 +11043,7 @@ class Jt {
|
|
|
11042
11043
|
warmupId: this.activeComposerWarmupId,
|
|
11043
11044
|
page: ae()
|
|
11044
11045
|
}
|
|
11045
|
-
} }), this.activeComposerWarmupId = null, this.lastUserMessagePageUrl = null, this.draftModelExplicit = !1, this.draftModel = (this.options.productVariant === "personal" ? this.lastPersonalModel ??
|
|
11046
|
+
} }), this.activeComposerWarmupId = null, this.lastUserMessagePageUrl = null, this.draftModelExplicit = !1, this.draftModel = (this.options.productVariant === "personal" ? this.lastPersonalModel ?? Oe(this.options.model) : this.options.model) ?? (this.options.productVariant === "personal" ? ns[0].value : "gpt-6.1-sol"), this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: null }), this.beginDirectoryProvisional();
|
|
11046
11047
|
}
|
|
11047
11048
|
listSessions(e = {}) {
|
|
11048
11049
|
return this.clientRuntime.route("directory", { core: async () => {
|
|
@@ -11369,7 +11370,7 @@ class Jt {
|
|
|
11369
11370
|
if (Object.values(s.optimisticEntries).some((i) => i.id === e && i.sessionId === null)) return;
|
|
11370
11371
|
!this.options.keepRunsActiveOnSessionNavigation && this.state.sessionId !== e && this.stopConversation("session_switch"), this.retainNavigatedConversation();
|
|
11371
11372
|
const n = "conversation:" + this.modelClientScopeId + ":" + z();
|
|
11372
|
-
this.directoryConversationScopeId = n, this.lastUserMessagePageUrl = null, this.draftModelExplicit = !1, this.draftModel = (this.options.productVariant === "personal" ?
|
|
11373
|
+
this.directoryConversationScopeId = n, this.lastUserMessagePageUrl = null, this.draftModelExplicit = !1, this.draftModel = (this.options.productVariant === "personal" ? Oe(this.options.model) : this.options.model) ?? (this.options.productVariant === "personal" ? ns[0].value : "gpt-6.1-sol"), this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: e }), this.directoryScope.bind(this.modelClientScopeId, this.directoryConversationScopeId, e).then(async () => {
|
|
11373
11374
|
await this.directoryScope.persist(), this.state.sessionId === e && (s.intents[e]?.observe && this.conversationObservation?.refresh(e).catch((i) => this.handleDirectoryTransportError(i)), this.send({ type: "page.upsert", sessionId: e, page: ae(), model: this.getModel() }));
|
|
11374
11375
|
});
|
|
11375
11376
|
}
|
|
@@ -11815,7 +11816,7 @@ class Jt {
|
|
|
11815
11816
|
}
|
|
11816
11817
|
if ((e.code === "unauthorized" || e.code === "401") && e.reason === "token_expired" && e.retryable === !0 && this.options.tokenProvider) {
|
|
11817
11818
|
const s = this.socket;
|
|
11818
|
-
s instanceof L ? this.refreshDefaultTransportCredentials(s) : (this.invalidateProviderToken(), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), s?.close());
|
|
11819
|
+
s instanceof L ? this.refreshDefaultTransportCredentials(s) : (this.invalidateProviderToken(), this.startEmbeddedRecoveryBudget(!0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), s?.close());
|
|
11819
11820
|
return;
|
|
11820
11821
|
}
|
|
11821
11822
|
if (this.options.productVariant === "customer_embedded" && /^4[0-9]{2}$/.test(String(e.code)) && !["401", "408", "425", "429"].includes(String(e.code)) && e.retryable !== !0 && (e.stage === "executor_registration" || e.stage === "socket_admission" || e.stage === "bootstrap")) {
|
|
@@ -11842,7 +11843,7 @@ class Jt {
|
|
|
11842
11843
|
if (!e || typeof e != "object") return;
|
|
11843
11844
|
const s = It(e, "id");
|
|
11844
11845
|
if (!s) return;
|
|
11845
|
-
const n = e.metadata, i = n && typeof n == "object" ? n.model : void 0, r = this.options.productVariant === "personal" ?
|
|
11846
|
+
const n = e.metadata, i = n && typeof n == "object" ? n.model : void 0, r = this.options.productVariant === "personal" ? Oe(typeof i == "string" ? i : void 0) : i;
|
|
11846
11847
|
this.clientRuntime.engine.accept({
|
|
11847
11848
|
type: "model.history_received",
|
|
11848
11849
|
clientScopeId: this.modelClientScopeId,
|
|
@@ -11940,7 +11941,7 @@ class Jt {
|
|
|
11940
11941
|
if (this.pageLifecycleCleanup)
|
|
11941
11942
|
return;
|
|
11942
11943
|
const e = () => {
|
|
11943
|
-
|
|
11944
|
+
Or(this.options.clientId, this.activeBrowserToolCalls.values());
|
|
11944
11945
|
};
|
|
11945
11946
|
window.addEventListener("pagehide", e), window.addEventListener("beforeunload", e), this.pageLifecycleCleanup = () => {
|
|
11946
11947
|
window.removeEventListener("pagehide", e), window.removeEventListener("beforeunload", e);
|
|
@@ -11975,10 +11976,14 @@ class Jt {
|
|
|
11975
11976
|
});
|
|
11976
11977
|
}, bd)));
|
|
11977
11978
|
}
|
|
11978
|
-
startEmbeddedRecoveryBudget() {
|
|
11979
|
-
if (this.options.productVariant !== "customer_embedded" || this.
|
|
11980
|
-
this.
|
|
11981
|
-
|
|
11979
|
+
startEmbeddedRecoveryBudget(e = !1) {
|
|
11980
|
+
if (this.options.productVariant !== "customer_embedded" || this.authenticationFailure) return;
|
|
11981
|
+
if (this.embeddedRecoveryTimer !== null) {
|
|
11982
|
+
if (!e || this.embeddedRecoveryTokenExpired || !this.authenticatedUserId) return;
|
|
11983
|
+
this.clearEmbeddedRecoveryBudget();
|
|
11984
|
+
}
|
|
11985
|
+
this.embeddedRecoveryTokenExpired = e, this.recoveryDiagnosticId = crypto.randomUUID();
|
|
11986
|
+
const s = this.authenticatedUserId ? (e ? 30 : 10) * 6e4 : 12e4;
|
|
11982
11987
|
this.embeddedRecoveryTimer = window.setTimeout(() => {
|
|
11983
11988
|
this.embeddedRecoveryTimer = null, this.connectionAttemptId += 1, this.tokenAbortController?.abort(), this.tokenAbortController = null, this.tokenRequest = null, this.connectionInProgress = !1, this.reportTransportDiagnostic("auth_refresh_failed", {
|
|
11984
11989
|
stage: this.lastRecoveryStage,
|
|
@@ -11989,10 +11994,10 @@ class Jt {
|
|
|
11989
11994
|
"connection_failed",
|
|
11990
11995
|
!1
|
|
11991
11996
|
), !0);
|
|
11992
|
-
},
|
|
11997
|
+
}, s);
|
|
11993
11998
|
}
|
|
11994
11999
|
clearEmbeddedRecoveryBudget() {
|
|
11995
|
-
this.embeddedRecoveryTimer !== null && window.clearTimeout(this.embeddedRecoveryTimer), this.embeddedRecoveryTimer = null;
|
|
12000
|
+
this.embeddedRecoveryTimer !== null && window.clearTimeout(this.embeddedRecoveryTimer), this.embeddedRecoveryTimer = null, this.embeddedRecoveryTokenExpired = !1;
|
|
11996
12001
|
}
|
|
11997
12002
|
connectionFailureDiagnostic(e, s) {
|
|
11998
12003
|
const n = e instanceof ue ? e.status : e instanceof T && e.code === "unauthorized" ? 401 : e instanceof T && /^[45][0-9]{2}$/.test(e.code) ? Number(e.code) : void 0, i = n !== void 0 && Number.isInteger(n) && n >= 400 && n <= 599 ? n : void 0, a = !(e instanceof T && ["unauthorized", "403", "update_required", "executor_replaced"].includes(e.code)) && Cs(e) && i !== 401 && i !== 403;
|
|
@@ -12096,7 +12101,7 @@ class Jt {
|
|
|
12096
12101
|
!1,
|
|
12097
12102
|
{ reason: s ? "invalid_token" : "token_expired" }
|
|
12098
12103
|
));
|
|
12099
|
-
s && (this.invalidCredentialRecoveryAttempted = !0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, this.reportTransportDiagnostic("auth_refresh_started", r), e.pause(), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
|
|
12104
|
+
s && (this.invalidCredentialRecoveryAttempted = !0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, this.reportTransportDiagnostic("auth_refresh_started", r), e.pause(), this.startEmbeddedRecoveryBudget(r.authReason === "token_expired"), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
|
|
12100
12105
|
let a = "token_provider";
|
|
12101
12106
|
this.lastRecoveryStage = a;
|
|
12102
12107
|
const o = (async () => {
|
|
@@ -12166,7 +12171,7 @@ class Jt {
|
|
|
12166
12171
|
this.listeners[e]?.forEach((i) => i(s));
|
|
12167
12172
|
}
|
|
12168
12173
|
}
|
|
12169
|
-
const
|
|
12174
|
+
const xs = /* @__PURE__ */ new WeakMap();
|
|
12170
12175
|
function Er(t) {
|
|
12171
12176
|
const e = window.__plunoProductAgentNetworkCapture ?? qd();
|
|
12172
12177
|
return e.subscribers.add(t), () => {
|
|
@@ -12225,7 +12230,7 @@ function qd() {
|
|
|
12225
12230
|
return y;
|
|
12226
12231
|
}, o = function(p, m, f, y, b) {
|
|
12227
12232
|
const k = n.call(this, p, m, f ?? !0, y ?? void 0, b ?? void 0), R = typeof m == "string" ? m : m.toString();
|
|
12228
|
-
return
|
|
12233
|
+
return xs.set(this, {
|
|
12229
12234
|
requestId: Ps("xhr"),
|
|
12230
12235
|
method: String(p ?? "GET").toUpperCase(),
|
|
12231
12236
|
url: me(R, qs),
|
|
@@ -12235,11 +12240,11 @@ function qd() {
|
|
|
12235
12240
|
excluded: De(R)
|
|
12236
12241
|
}), k;
|
|
12237
12242
|
}, c = function(p, m) {
|
|
12238
|
-
const f = i.call(this, p, m), y =
|
|
12243
|
+
const f = i.call(this, p, m), y = xs.get(this);
|
|
12239
12244
|
return y && Object.keys(y.requestHeaders).length < Rn && (y.requestHeaders[p] = qn(p, m), y.excluded = y.excluded || De(y.url, y.requestHeaders)), f;
|
|
12240
12245
|
}, d = function(p) {
|
|
12241
12246
|
try {
|
|
12242
|
-
const m =
|
|
12247
|
+
const m = xs.get(this);
|
|
12243
12248
|
m && (m.excluded = m.excluded || De(m.url, m.requestHeaders, p), m.requestBody = Ci(p), m.excluded || this.addEventListener(
|
|
12244
12249
|
"loadend",
|
|
12245
12250
|
() => {
|
|
@@ -12354,8 +12359,8 @@ function _i(t) {
|
|
|
12354
12359
|
const Cd = 5e3, Md = 12e4;
|
|
12355
12360
|
function Tr() {
|
|
12356
12361
|
const t = [
|
|
12357
|
-
|
|
12358
|
-
|
|
12362
|
+
Od(),
|
|
12363
|
+
xd()
|
|
12359
12364
|
].filter((e) => typeof e == "function");
|
|
12360
12365
|
return () => {
|
|
12361
12366
|
for (const e of t.reverse())
|
|
@@ -12368,10 +12373,10 @@ function mu(t) {
|
|
|
12368
12373
|
s(), e();
|
|
12369
12374
|
};
|
|
12370
12375
|
}
|
|
12371
|
-
function
|
|
12376
|
+
function xd() {
|
|
12372
12377
|
return br(globalThis, "getPageSnapshot", async () => An());
|
|
12373
12378
|
}
|
|
12374
|
-
function
|
|
12379
|
+
function Od() {
|
|
12375
12380
|
return br(globalThis, "pageImages", {
|
|
12376
12381
|
inspectImage: async (e, s) => await Pd(e, s)
|
|
12377
12382
|
});
|
|
@@ -12586,13 +12591,13 @@ function Kd() {
|
|
|
12586
12591
|
};
|
|
12587
12592
|
}
|
|
12588
12593
|
function Wd(t) {
|
|
12589
|
-
return
|
|
12590
|
-
|
|
12594
|
+
return Ot.add(t), vt || (vt = Gd()), () => {
|
|
12595
|
+
Ot.delete(t), Ot.size === 0 && (vt?.(), vt = null);
|
|
12591
12596
|
};
|
|
12592
12597
|
}
|
|
12593
12598
|
function Gd() {
|
|
12594
12599
|
const t = () => {
|
|
12595
|
-
for (const r of Array.from(
|
|
12600
|
+
for (const r of Array.from(Ot))
|
|
12596
12601
|
r();
|
|
12597
12602
|
}, e = window.history.pushState.bind(window.history), s = window.history.replaceState.bind(window.history), n = ((...r) => {
|
|
12598
12603
|
const a = e(...r);
|
|
@@ -12617,9 +12622,9 @@ function An() {
|
|
|
12617
12622
|
(f) => qr(f) && !f.parentElement?.closest(n)
|
|
12618
12623
|
);
|
|
12619
12624
|
for (const f of i.slice(0, 3))
|
|
12620
|
-
s("Active overlay",
|
|
12621
|
-
const r = Jd(), a = r ?
|
|
12622
|
-
s("Main page content", a), s("Additional visible page text",
|
|
12625
|
+
s("Active overlay", Os(nt(f), e));
|
|
12626
|
+
const r = Jd(), a = r ? Os(nt(r), e) : "";
|
|
12627
|
+
s("Main page content", a), s("Additional visible page text", Os(nt(document.body), e));
|
|
12623
12628
|
const o = t.map(([f, y]) => `${f}:
|
|
12624
12629
|
${y}`).join(`
|
|
12625
12630
|
|
|
@@ -12641,7 +12646,7 @@ function Fe(t) {
|
|
|
12641
12646
|
|
|
12642
12647
|
`).trim();
|
|
12643
12648
|
}
|
|
12644
|
-
function
|
|
12649
|
+
function Os(t, e) {
|
|
12645
12650
|
let s = Fe(t);
|
|
12646
12651
|
for (const n of e)
|
|
12647
12652
|
s = s.replace(n, "");
|
|
@@ -12749,18 +12754,18 @@ function Qd(t, e) {
|
|
|
12749
12754
|
if (p >= 1e3 && !E || v.has(w) || r.has(_) || w.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || q.display === "none" || q.visibility === "hidden")
|
|
12750
12755
|
return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
|
|
12751
12756
|
p += 1;
|
|
12752
|
-
const C = m(w), M = Mr(w), S = o.has(C) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(_) || _ === "a" && w.hasAttribute("href"),
|
|
12753
|
-
for (const D of
|
|
12757
|
+
const C = m(w), M = Mr(w), S = o.has(C) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(_) || _ === "a" && w.hasAttribute("href"), x = Array.from(w.children).filter((D) => D instanceof HTMLElement), U = /* @__PURE__ */ new Map();
|
|
12758
|
+
for (const D of x) {
|
|
12754
12759
|
const $ = f(D);
|
|
12755
12760
|
U.set($, (U.get($) ?? 0) + 1);
|
|
12756
12761
|
}
|
|
12757
12762
|
const H = /* @__PURE__ */ new Map(), ze = /* @__PURE__ */ new Map();
|
|
12758
|
-
for (const D of
|
|
12763
|
+
for (const D of x) {
|
|
12759
12764
|
const $ = f(D), be = ze.get($) ?? 0;
|
|
12760
12765
|
ze.set($, be + 1), (U.get($) ?? 0) > 8 && be >= 6 && !u.has(D) && H.set($, (H.get($) ?? 0) + 1);
|
|
12761
12766
|
}
|
|
12762
12767
|
const ct = /* @__PURE__ */ new Map(), Cn = /* @__PURE__ */ new Set(), Xt = [], Mn = [];
|
|
12763
|
-
for (const D of
|
|
12768
|
+
for (const D of x) {
|
|
12764
12769
|
const $ = f(D), be = U.get($) ?? 0, Pn = ct.get($) ?? 0;
|
|
12765
12770
|
if (ct.set($, Pn + 1), be > 8 && Pn >= 6 && !u.has(D)) {
|
|
12766
12771
|
Cn.has($) || (Xt.push([`… ${H.get($) ?? 0} similar siblings omitted`]), Cn.add($));
|
|
@@ -12773,11 +12778,11 @@ function Qd(t, e) {
|
|
|
12773
12778
|
if (w.shadowRoot)
|
|
12774
12779
|
for (const D of Array.from(w.shadowRoot.children))
|
|
12775
12780
|
D instanceof HTMLElement && Yt.push(I(D, A + 1));
|
|
12776
|
-
const dt = [...Mn, ...Yt], Zt = M.length > 0 || S || dt.some((D) => D.hasUsefulContent),
|
|
12781
|
+
const dt = [...Mn, ...Yt], Zt = M.length > 0 || S || dt.some((D) => D.hasUsefulContent), xn = Fe(
|
|
12777
12782
|
[M, ...dt.map((D) => D.textPreview)].filter(Boolean).join(" ")
|
|
12778
|
-
).slice(0, 180), Wr = w.hasAttribute("contenteditable") && (M.length > 0 || !w.querySelector("[contenteditable]")),
|
|
12783
|
+
).slice(0, 180), Wr = w.hasAttribute("contenteditable") && (M.length > 0 || !w.querySelector("[contenteditable]")), On = d.some((D) => w.hasAttribute(D)) || !!C || Wr, es = (w.getClientRects().length > 0 || q.display === "contents") && (s.has(_) || On || E) && (Zt || E) && (!i.has(_) || Zt || On || E), ts = es ? 1 : 0, He = [];
|
|
12779
12784
|
if (es) {
|
|
12780
|
-
const D = dt.some((be) => be.containsTextElement), $ = n.has(_) && !D ?
|
|
12785
|
+
const D = dt.some((be) => be.containsTextElement), $ = n.has(_) && !D ? xn : M;
|
|
12781
12786
|
He.push(Cr(w, c, a, $.slice(0, 180)));
|
|
12782
12787
|
}
|
|
12783
12788
|
for (const D of Xt)
|
|
@@ -12796,7 +12801,7 @@ function Qd(t, e) {
|
|
|
12796
12801
|
return {
|
|
12797
12802
|
lines: He,
|
|
12798
12803
|
hasUsefulContent: Zt,
|
|
12799
|
-
textPreview:
|
|
12804
|
+
textPreview: xn,
|
|
12800
12805
|
containsTextElement: n.has(_) || dt.some((D) => D.containsTextElement)
|
|
12801
12806
|
};
|
|
12802
12807
|
};
|
|
@@ -13029,10 +13034,10 @@ function Ai(t) {
|
|
|
13029
13034
|
}
|
|
13030
13035
|
function vu(t, e) {
|
|
13031
13036
|
return Array.isArray(t) ? fl(
|
|
13032
|
-
t.map((s) =>
|
|
13037
|
+
t.map((s) => xr(s, e)).filter((s) => s !== null)
|
|
13033
13038
|
) : [];
|
|
13034
13039
|
}
|
|
13035
|
-
function
|
|
13040
|
+
function xr(t, e) {
|
|
13036
13041
|
if (!t || typeof t != "object")
|
|
13037
13042
|
return null;
|
|
13038
13043
|
const s = t, n = s.data;
|
|
@@ -13087,7 +13092,7 @@ function Or(t, e) {
|
|
|
13087
13092
|
}), a;
|
|
13088
13093
|
}
|
|
13089
13094
|
if (i.type === "function_call_output") {
|
|
13090
|
-
const r =
|
|
13095
|
+
const r = xc(i.output);
|
|
13091
13096
|
if (r !== null)
|
|
13092
13097
|
return {
|
|
13093
13098
|
id: String(s.id ?? crypto.randomUUID()),
|
|
@@ -13349,7 +13354,7 @@ function Sl(t, e) {
|
|
|
13349
13354
|
const n = JSON.parse(s), i = typeof n.sessionId == "string" ? n.sessionId : null;
|
|
13350
13355
|
if (e !== void 0 && i !== e)
|
|
13351
13356
|
return null;
|
|
13352
|
-
const r = Array.isArray(n.messages) ? n.messages.map(
|
|
13357
|
+
const r = Array.isArray(n.messages) ? n.messages.map(Ol).filter((a) => !!a) : [];
|
|
13353
13358
|
return {
|
|
13354
13359
|
sessionId: i,
|
|
13355
13360
|
messages: r
|
|
@@ -13384,7 +13389,7 @@ function Re(t, e) {
|
|
|
13384
13389
|
return;
|
|
13385
13390
|
}
|
|
13386
13391
|
}
|
|
13387
|
-
function
|
|
13392
|
+
function Or(t, e) {
|
|
13388
13393
|
try {
|
|
13389
13394
|
const s = `${Gt}${t}`, n = location.href, i = location.origin, r = Array.from(e, (a) => ({
|
|
13390
13395
|
...a,
|
|
@@ -13407,7 +13412,7 @@ function Ti(t, e) {
|
|
|
13407
13412
|
} catch {
|
|
13408
13413
|
return;
|
|
13409
13414
|
}
|
|
13410
|
-
|
|
13415
|
+
Or(t, e);
|
|
13411
13416
|
}
|
|
13412
13417
|
function Rl(t) {
|
|
13413
13418
|
try {
|
|
@@ -13494,7 +13499,7 @@ function Dr(t, e) {
|
|
|
13494
13499
|
} : t;
|
|
13495
13500
|
}
|
|
13496
13501
|
function Ur(t) {
|
|
13497
|
-
return t.type ||
|
|
13502
|
+
return t.type || xl(t.name) || "application/octet-stream";
|
|
13498
13503
|
}
|
|
13499
13504
|
function Cl(t) {
|
|
13500
13505
|
Nr({
|
|
@@ -13514,11 +13519,11 @@ function Ml(t) {
|
|
|
13514
13519
|
const e = t.trim().toLowerCase(), s = e.lastIndexOf(".");
|
|
13515
13520
|
return s >= 0 ? e.slice(s) : "";
|
|
13516
13521
|
}
|
|
13517
|
-
function
|
|
13522
|
+
function xl(t) {
|
|
13518
13523
|
const e = t.toLowerCase();
|
|
13519
13524
|
return e.endsWith(".png") ? "image/png" : e.endsWith(".jpg") || e.endsWith(".jpeg") ? "image/jpeg" : e.endsWith(".webp") ? "image/webp" : e.endsWith(".gif") ? "image/gif" : e.endsWith(".pdf") ? "application/pdf" : null;
|
|
13520
13525
|
}
|
|
13521
|
-
function
|
|
13526
|
+
function Ol(t) {
|
|
13522
13527
|
if (!t || typeof t != "object")
|
|
13523
13528
|
return null;
|
|
13524
13529
|
const e = t;
|
|
@@ -76,7 +76,7 @@ function sh(t, e, n, i) {
|
|
|
76
76
|
function oh(t) {
|
|
77
77
|
return Gr(t) > 0.5 ? [24, 24, 27] : [250, 250, 249];
|
|
78
78
|
}
|
|
79
|
-
const rh = "0.1.
|
|
79
|
+
const rh = "0.1.313", ci = {
|
|
80
80
|
version: rh
|
|
81
81
|
}, fe = (t) => typeof t == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(t) ? t : null;
|
|
82
82
|
function Nd(t) {
|
|
@@ -9490,6 +9490,7 @@ class Qa {
|
|
|
9490
9490
|
socketAuthTimer = null;
|
|
9491
9491
|
reconnectAttempts = 0;
|
|
9492
9492
|
embeddedRecoveryTimer = null;
|
|
9493
|
+
embeddedRecoveryTokenExpired = !1;
|
|
9493
9494
|
recoveryDiagnosticId = crypto.randomUUID();
|
|
9494
9495
|
rejectedDiagnosticsToken = null;
|
|
9495
9496
|
lastRecoveryStage = "token_provider";
|
|
@@ -11215,7 +11216,7 @@ class Qa {
|
|
|
11215
11216
|
}
|
|
11216
11217
|
if ((e.code === "unauthorized" || e.code === "401") && e.reason === "token_expired" && e.retryable === !0 && this.options.tokenProvider) {
|
|
11217
11218
|
const n = this.socket;
|
|
11218
|
-
n instanceof Ee ? this.refreshDefaultTransportCredentials(n) : (this.invalidateProviderToken(), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), n?.close());
|
|
11219
|
+
n instanceof Ee ? this.refreshDefaultTransportCredentials(n) : (this.invalidateProviderToken(), this.startEmbeddedRecoveryBudget(!0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), n?.close());
|
|
11219
11220
|
return;
|
|
11220
11221
|
}
|
|
11221
11222
|
if (this.options.productVariant === "customer_embedded" && /^4[0-9]{2}$/.test(String(e.code)) && !["401", "408", "425", "429"].includes(String(e.code)) && e.retryable !== !0 && (e.stage === "executor_registration" || e.stage === "socket_admission" || e.stage === "bootstrap")) {
|
|
@@ -11375,10 +11376,14 @@ class Qa {
|
|
|
11375
11376
|
});
|
|
11376
11377
|
}, Ym)));
|
|
11377
11378
|
}
|
|
11378
|
-
startEmbeddedRecoveryBudget() {
|
|
11379
|
-
if (this.options.productVariant !== "customer_embedded" || this.
|
|
11380
|
-
this.
|
|
11381
|
-
|
|
11379
|
+
startEmbeddedRecoveryBudget(e = !1) {
|
|
11380
|
+
if (this.options.productVariant !== "customer_embedded" || this.authenticationFailure) return;
|
|
11381
|
+
if (this.embeddedRecoveryTimer !== null) {
|
|
11382
|
+
if (!e || this.embeddedRecoveryTokenExpired || !this.authenticatedUserId) return;
|
|
11383
|
+
this.clearEmbeddedRecoveryBudget();
|
|
11384
|
+
}
|
|
11385
|
+
this.embeddedRecoveryTokenExpired = e, this.recoveryDiagnosticId = crypto.randomUUID();
|
|
11386
|
+
const n = this.authenticatedUserId ? (e ? 30 : 10) * 6e4 : 12e4;
|
|
11382
11387
|
this.embeddedRecoveryTimer = window.setTimeout(() => {
|
|
11383
11388
|
this.embeddedRecoveryTimer = null, this.connectionAttemptId += 1, this.tokenAbortController?.abort(), this.tokenAbortController = null, this.tokenRequest = null, this.connectionInProgress = !1, this.reportTransportDiagnostic("auth_refresh_failed", {
|
|
11384
11389
|
stage: this.lastRecoveryStage,
|
|
@@ -11389,10 +11394,10 @@ class Qa {
|
|
|
11389
11394
|
"connection_failed",
|
|
11390
11395
|
!1
|
|
11391
11396
|
), !0);
|
|
11392
|
-
},
|
|
11397
|
+
}, n);
|
|
11393
11398
|
}
|
|
11394
11399
|
clearEmbeddedRecoveryBudget() {
|
|
11395
|
-
this.embeddedRecoveryTimer !== null && window.clearTimeout(this.embeddedRecoveryTimer), this.embeddedRecoveryTimer = null;
|
|
11400
|
+
this.embeddedRecoveryTimer !== null && window.clearTimeout(this.embeddedRecoveryTimer), this.embeddedRecoveryTimer = null, this.embeddedRecoveryTokenExpired = !1;
|
|
11396
11401
|
}
|
|
11397
11402
|
connectionFailureDiagnostic(e, n) {
|
|
11398
11403
|
const i = e instanceof Ze ? e.status : e instanceof L && e.code === "unauthorized" ? 401 : e instanceof L && /^[45][0-9]{2}$/.test(e.code) ? Number(e.code) : void 0, s = i !== void 0 && Number.isInteger(i) && i >= 400 && i <= 599 ? i : void 0, a = !(e instanceof L && ["unauthorized", "403", "update_required", "executor_replaced"].includes(e.code)) && qr(e) && s !== 401 && s !== 403;
|
|
@@ -11496,7 +11501,7 @@ class Qa {
|
|
|
11496
11501
|
!1,
|
|
11497
11502
|
{ reason: n ? "invalid_token" : "token_expired" }
|
|
11498
11503
|
));
|
|
11499
|
-
n && (this.invalidCredentialRecoveryAttempted = !0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, this.reportTransportDiagnostic("auth_refresh_started", o), e.pause(), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
|
|
11504
|
+
n && (this.invalidCredentialRecoveryAttempted = !0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, this.reportTransportDiagnostic("auth_refresh_started", o), e.pause(), this.startEmbeddedRecoveryBudget(o.authReason === "token_expired"), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
|
|
11500
11505
|
let a = "token_provider";
|
|
11501
11506
|
this.lastRecoveryStage = a;
|
|
11502
11507
|
const r = (async () => {
|
package/package.json
CHANGED