@pluno/product-agent-web 0.1.318 → 0.1.319
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/product-agent-runtime.cjs +1 -1
- package/dist/product-agent-runtime.js +31 -33
- package/dist/product-agent-sdk.js +2 -4
- package/dist/product-agent-widget.js +2784 -3414
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function ee(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function I(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class T{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=I(e)}loader;merge;state;listeners=new Set;inFlight=null;trailingLoad=null;getState(){return this.state}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}setKey(e){e!==this.state.key&&(this.state=I(e),this.trailingLoad=null,this.publish())}reset(){this.state=I(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function _(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function L(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function $(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function te(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function se(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function ie(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const G="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===G}class ne{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new T(`${e}:recent`,async({cursor:n})=>_(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),L),this.pinnedQuery=new T(`${e}:pinned`,async()=>_({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?_({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function re(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function U(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(U),Object.freeze(i)),i}function oe(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}class ae{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(!(n&&n.version>=t.version)){if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");t.payload.kind==="integration_auth"&&(this.sources.set(s,U(oe(t))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id))}}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={integrations:[]};if(!(e?this.conversationReader(e):null))return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;a.kind==="integration_auth"&&t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle})}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!B(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=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 de(i,e){return{load:async()=>F(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function F(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 B(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&B(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ce={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},le=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function Q(i,e){if(!e)return P(i);const t=P(i),s=`${ce[e]} Pluno`;return t?`${s}: ${t}`:s}class ue{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=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=Q(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function he(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(le,"")}const pe="0.1.318",ge={version:pe},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function fe(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function H(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),me=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||me(e.createdAt))}function ye(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||fe(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function Z(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(a=>["key","count","rows","truncated"].includes(a))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(a=>a&&Object.keys(a).every(o=>["itemId","groupId"].includes(o))&&y(a.itemId)&&y(a.groupId))))&&(n.context===void 0||ye(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const x=500;function J(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>x?`${e.slice(0,x-1)}…`:e}function be(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function ve(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function Ie(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===be(J(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:ge.version,...n}}}function _e(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,a=s&&"details"in s?s.details:null,o=a&&typeof a=="object"?a:{},c={...typeof o.httpStatus=="number"&&Number.isInteger(o.httpStatus)&&o.httpStatus>=100&&o.httpStatus<=599?{httpStatus:o.httpStatus}:{},errorNormalization:O(o.errorNormalization)?o.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...o.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(o.acceptance))?{acceptance:String(o.acceptance)}:{},...typeof o.securitySettingsUrl=="string"?{securitySettingsUrl:o.securitySettingsUrl}:{},...typeof o.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(o.transportCode)?{transportCode:o.transportCode}:{},...typeof o.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(o.requestId)?{requestId:o.requestId}:{},...typeof o.durationMs=="number"&&Number.isFinite(o.durationMs)&&o.durationMs>=0?{durationMs:o.durationMs}:{},...typeof o.successfulRequests=="number"&&Number.isSafeInteger(o.successfulRequests)&&o.successfulRequests>=0?{successfulRequests:o.successfulRequests}:{}};return _e({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function W(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Se=["submit","stop","staging_ipc","send_ipc","stop_ipc","attachment_transfer","tab_lookup","tab_recovery","session_recovery","conversation_scope","local_stage","view_publication","page_access","authentication","community","preferences","page_capture","session_tabs","context_ready","first_frame","checkpoint","command_http","http_authentication","http_request","receipt_http","attachment_upload","runtime_reading","runtime_stopping","runtime_progress","runtime_stopped","message_painted","reading_painted","stopping_painted","progress_painted","stopped_painted","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],Y=["request_timed_out","delivery_unknown","invalid_ack","acceptance_identity_mismatch","disconnected","executor_not_ready","unauthorized","connection_failed","invalid_response","network_error","type_error","aborted","backend_refusal","unknown"];function Ae(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&Y.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const X=Math.random().toString(36).slice(2);let we=0;const N=()=>`timing:${X}:${++we}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&Y.includes(e.failureCategory))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp","email"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&Se.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function j(i,e){if(e={workerId:X,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,a,o,c)=>{const d={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a)),...r==="failed"?{failureCategory:Ae(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,N()),measure(n,r){const a=performance.now(),o=N();return s(n,"started",a,o),r().then(c=>(s(n,"completed",a,o),c),c=>{throw s(n,"failed",a,o,c),c})}}}const E=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Pe(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))&&E(e.sessionId)&&E(e.responseItemId)&&E(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Me(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),a=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)a.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||a.some(d=>d.role==="user"&&d.id===c)&&a.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const o=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...a.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:a,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&a.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Ee={"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 Te(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Ee,i.slice(13))}function K(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Re(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Pe(e.observation);case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||ve(e.errorDiagnostic))&&(e.httpRequest===void 0||W(e.httpRequest))&&(e.historyRefreshFailure===void 0||H(e.historyRefreshFailure))&&(e.renderedError===void 0||V(e.renderedError))&&(e.reason==="conversation_error"||e.reason==="attachment_error"||e.reason==="history_error"||e.reason==="action_error")&&typeof e.errorFingerprint=="string"&&/^fnv1a-[0-9a-f]{8}$/.test(e.errorFingerprint)&&(e.displayedMessage===void 0||typeof e.displayedMessage=="string"&&e.displayedMessage.length<=500);case"runtime.report_invalid_state_transition":return(e.uiInvariant===void 0||Z(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Te(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 ke{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-6.1-sol",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=I("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;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(o=>o.id)),a=new Set(n.segments?.map(o=>o.id));e.messages=[...n.messages,...e.messages.filter(o=>!r.has(o.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(o=>({...o})),...(e.segments??[]).filter(o=>!a.has(o.id))]),e.removedItems={...n.removedItems,...e.removedItems}}for(const[n,r]of this.submissionPreviews)e.messages.some(a=>a.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(a=>({...a}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error.message,e.lastErrorCode=["unauthorized","401","auth_reconnecting","submission_not_available","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=Me(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const a=this.getState(),o=!this.hasBeenReady&&(!a.user||a.user.id===e.user?.id),c=a.stableSelectionKey!==void 0&&a.stableSelectionKey===e.stableSelectionKey&&a.user?.id===e.user?.id&&a.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!o&&!d&&(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const h=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=h?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 p=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&p!==void 0&&p!=="[]"&&(p!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),a.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=a.messages.find(p=>p.role==="user"&&p.id===l.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&u)||(l.attachments=qe(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=z(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}recordPromptPresented(e,t){this.dispatch({type:"runtime.prompt_presented",feature:e,openingGeneration:t})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!Z(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const a=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!V(n)||r!==void 0&&!H(r))return;const o=Ie(this.getState(),e,s,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:o,...o.clientMessageId?{clientMessageId:o.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...W(a)?{httpRequest:a}:{},...s?{displayedMessage:J(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){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()),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:a,selectionKey:this.state.selectionKey},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,a=j(h=>{s===this.submissionGeneration&&this.reportOperationTiming(h)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const h=await a.measure("staging_ipc",async()=>{if(d){if(!await a.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:o.length>0?o.map(K):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const p=b(u);if(p.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=p),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!h||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),h.result?.submissionAccepted){r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null);for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of o){if(u.sandboxPath||u.storageKey){l.push(u);continue}const p=u.id?this.attachmentFiles.get(u.id):void 0;if(!p)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(p,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}o=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:o.length>0?o.map(K):void 0}),s!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),r}catch(h){if(s!==this.submissionGeneration)return null;if(R(h))for(const f of t.attachments??[])f.id&&this.attachmentFiles.delete(f.id);const u=b(h).code==="command_not_received";!c&&!R(h)&&(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 p=this.submissionPreviews.get(r);throw p&&(p.pending=!1,p.error=b(h),this.emit("state",this.getState())),c&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:b(h).message}),h}finally{this.readinessPendingSubmissions.delete(r)}}getModel(){return this.model}setModel(e){return this.modelExplicit=!0,this.model===e||(this.model=e,this.emit("state",this.getState())),Promise.resolve()}async retryLastMessage(e){const t=e??[...this.submissionPreviews].reverse().find(([,o])=>o.error)?.[0]??this.state.messages.filter(o=>o.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,a=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!s&&!r)throw o;return s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(o),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=j(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const a=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:a);const o=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(o!==this.submissionGeneration||s.every(h=>!this.stopPreviews.has(h)))){for(const h of s)this.stopPreviews.delete(h);this.stopError=b(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,a)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const o=this.state;if(o.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(o.conversationDiagnostics?.failedClientMessageId===e&&o.lastError&&o.lastErrorCode!=="submission_checkpoint_pending"){a(Object.assign(new Error(o.lastError),{code:o.lastErrorCode}));return}const c=o.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){a(new Error(c.content));return}o.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return z(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(a=>a.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){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 qe(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function z(i){return{...i,data:i.data?_({entities:$(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=G;exports.ProductAgentInteractionManager=ae;exports.ProductAgentQueryController=T;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=he;exports.formatProductAgentTaskPageTitle=Q;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=F;exports.reconcileProductAgentSubmissionGate=ee;exports.resolveProductAgentBillingPresentation=se;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=te;exports.selectProductAgentQueryEntities=$;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function ee(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function I(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class T{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=I(e)}loader;merge;state;listeners=new Set;inFlight=null;trailingLoad=null;getState(){return this.state}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}setKey(e){e!==this.state.key&&(this.state=I(e),this.trailingLoad=null,this.publish())}reset(){this.state=I(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function _(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function L(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function $(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function te(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function se(i){return i?i.submissionGate?.allowed===!1?["credits_exhausted","payment_issue","onboarding_required"].includes(i.submissionGate.reason)?{state:"action_required",reason:i.submissionGate.reason}:{state:"hidden"}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function ie(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}const G="Pluno is reconnecting. Try again in a moment.";function R(i){return(i instanceof Error?i.message:i)===G}class ne{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new T(`${e}:recent`,async({cursor:n})=>_(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),L),this.pinnedQuery=new T(`${e}:pinned`,async()=>_({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...S(t.data),...S(e.data)],n=new Map(s.map(c=>[c.id,c])),r=Array.from(n.values()).map(c=>this.applyOverrides(c,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(c=>!n.has(c.id)).reverse(),o=e.data||t.data||a.length>0?_({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:re(e,t),data:o,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...S(this.pinnedQuery.getState().data),...S(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function S(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function re(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}function w(i){if(i===null||typeof i=="string"||typeof i=="boolean")return!0;if(typeof i=="number")return Number.isFinite(i);if(Array.isArray(i))return i.every(w);if(typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e!==Object.prototype&&e!==null?!1:Object.values(i).every(w)}function U(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(U),Object.freeze(i)),i}function oe(i){if(!w(i))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(i))}class ae{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(k).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const s=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(s);if(!(n&&n.version>=t.version)){if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");t.payload.kind==="integration_auth"&&(this.sources.set(s,U(oe(t))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id))}}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={integrations:[]};if(!(e?this.conversationReader(e):null))return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,a)=>r.version-a.version||r.id.localeCompare(a.id));for(const r of n){const a=r.payload;a.kind==="integration_auth"&&t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:a.request_id,appSlug:a.app_slug,appName:a.app_name,appLogo:a.app_logo??void 0,expiresAt:a.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(a.expires_at)<=Date.now()?"expired":r.lifecycle})}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(k).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!B(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),o=new Map(this.decisions);return o.set(a,r),await this.storage.save([...o.values()]),this.decisions=o,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=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 de(i,e){return{load:async()=>F(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function F(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 B(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function k(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&B(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ce={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},le=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function Q(i,e){if(!e)return P(i);const t=P(i),s=`${ce[e]} Pluno`;return t?`${s}: ${t}`:s}class ue{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=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=Q(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function pe(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function P(i){return i.replace(le,"")}const he="0.1.319",ge={version:he},g=i=>typeof i=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(i)?i:null;function fe(i){if(!i||typeof i!="object")return!1;const e=i,t=n=>Number.isSafeInteger(n)&&n>=0,s=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&g(n.type)!==null&&typeof n.changed=="boolean"&&[n.generation,n.itemCount,n.removedCount].every(r=>r===null||t(r))&&[n.sessionId,n.scopeId,n.requestId,n.effectId,n.clientScopeId,n.reason,n.effectKind,n.eventType].every(r=>r===null||g(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&g(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||s(e.lastIntent))&&(e.lastSelection===null||s(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(s)}function H(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","episodeId","consecutiveFailures","transportCode","requestId","durationMs"].includes(t))&&typeof e.sessionId=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(e.sessionId)&&typeof e.episodeId=="string"&&/^[a-zA-Z0-9:_-]{1,500}$/.test(e.episodeId)&&(e.transportCode===void 0||typeof e.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(e.transportCode))&&(e.requestId===void 0||typeof e.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e.requestId))&&(e.durationMs===void 0||typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0)&&Number.isSafeInteger(e.consecutiveFailures)&&e.consecutiveFailures>=1}const D=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],q=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i),y=i=>i===null||q(i),me=i=>typeof i=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(i)&&Number.isFinite(Date.parse(i));function V(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&y(e.sessionId)&&q(e.itemId)&&y(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&y(e.runId)&&(e.createdAt===null||me(e.createdAt))}function ye(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner","sdkVersion","presentationGate","firstObservedAt","confirmationMs"].includes(s))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(s=>s===null||t(s))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(s=>s===null||g(s)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(s=>typeof s=="boolean")&&["state","account","interactions","local","sidepanel_layout","observer"].includes(e.renderSource)&&(e.owner===void 0||fe(e.owner))&&(e.sdkVersion===void 0||typeof e.sdkVersion=="string"&&e.sdkVersion.length<=32&&/^\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]+)?$/.test(e.sdkVersion))&&(e.presentationGate===void 0||["none","authentication","signup"].includes(e.presentationGate))&&[e.firstObservedAt,e.confirmationMs].every(s=>s===void 0||t(s))}function Z(i){if(!i||typeof i!="object"||Object.keys(i).some(s=>s!=="before"&&s!=="current"))return!1;const e=s=>{if(!s||typeof s!="object")return!1;const n=s;return Object.keys(s).every(r=>[...D,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context","duplicateToolCalls"].includes(r))&&(n.duplicateToolCalls===void 0||Array.isArray(n.duplicateToolCalls)&&n.duplicateToolCalls.length<=5&&n.duplicateToolCalls.every(r=>r&&Object.keys(r).every(a=>["key","count","rows","truncated"].includes(a))&&y(r.key)&&Number.isSafeInteger(r.count)&&r.count>=2&&typeof r.truncated=="boolean"&&Array.isArray(r.rows)&&r.rows.length>=1&&r.rows.length<=5&&r.rows.length<=r.count&&r.rows.every(a=>a&&Object.keys(a).every(o=>["itemId","groupId"].includes(o))&&y(a.itemId)&&y(a.groupId))))&&(n.context===void 0||ye(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&y(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&D.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(q))},t=i;return(t.before===null||e(t.before))&&e(t.current)}const x=500;function J(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>x?`${e.slice(0,x-1)}…`:e}function be(i){let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return`fnv1a-${(e>>>0).toString(16).padStart(8,"0")}`}function O(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(i).every(t=>["boundary","category","messageKind"].includes(t))&&["runtime","web_transport","extension_ipc"].includes(e.boundary)&&["error","object","null","array","string","undefined","number","boolean","bigint","symbol","function"].includes(e.category)&&["object_coercion","text","blank","non_text"].includes(e.messageKind)}function ve(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["sessionId","requestId","code","normalization","builds","clientMessageId"].includes(t))&&(e.clientMessageId===void 0||g(e.clientMessageId)!==null)&&[e.sessionId,e.requestId,e.code].every(t=>t===null||g(t)!==null)&&(e.normalization===void 0||O(e.normalization))&&!!e.builds&&typeof e.builds=="object"&&typeof e.builds.sdk=="string"&&Object.entries(e.builds).every(([t,s])=>["sdk","rendererExtension","contentExtension","backgroundExtension"].includes(t)&&typeof s=="string"&&/^\d{1,5}\.\d{1,5}\.\d{1,5}$/.test(s))}function Ie(i,e,t,s,n={}){const r=!s&&e==="conversation_error"&&t!==void 0&&i.conversationDiagnostics?.errorMessageFingerprint===be(J(t))?i.conversationDiagnostics:void 0;return{sessionId:g(i.sessionId),requestId:g(r?.httpRequest?.requestId??r?.errorRequestId??r?.queryRequestId),...g(r?.failedClientMessageId)?{clientMessageId:r.failedClientMessageId}:{},code:r?g(i.lastErrorCode):null,...O(r?.errorNormalization)?{normalization:r.errorNormalization}:{},builds:{sdk:ge.version,...n}}}function _e(i){if(i.details!==void 0&&!w(i.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:i.code,message:i.message,retryable:i.retryable,...i.details===void 0?{}:{details:i.details}}}function b(i,e="runtime_error",t="runtime"){const s=i!==null&&typeof i=="object"?i:null,n=typeof i=="string"?i:s&&"message"in s&&typeof s.message=="string"?s.message:"",r=s&&"code"in s&&typeof s.code=="string"&&s.code.trim()?s.code:e,a=s&&"details"in s?s.details:null,o=a&&typeof a=="object"?a:{},c={...typeof o.httpStatus=="number"&&Number.isInteger(o.httpStatus)&&o.httpStatus>=100&&o.httpStatus<=599?{httpStatus:o.httpStatus}:{},errorNormalization:O(o.errorNormalization)?o.errorNormalization:{boundary:t,category:i instanceof Error?"error":i===null?"null":Array.isArray(i)?"array":typeof i,messageKind:n.trim()==="[object Object]"?"object_coercion":n.trim()?"text":typeof i=="string"||s&&"message"in s&&typeof s.message=="string"?"blank":"non_text"},...o.allocation==="unissued"?{allocation:"unissued"}:{},...["unissued","rejected"].includes(String(o.acceptance))?{acceptance:String(o.acceptance)}:{},...typeof o.securitySettingsUrl=="string"?{securitySettingsUrl:o.securitySettingsUrl}:{},...typeof o.transportCode=="string"&&/^[a-z0-9_]{1,80}$/.test(o.transportCode)?{transportCode:o.transportCode}:{},...typeof o.requestId=="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(o.requestId)?{requestId:o.requestId}:{},...typeof o.durationMs=="number"&&Number.isFinite(o.durationMs)&&o.durationMs>=0?{durationMs:o.durationMs}:{},...typeof o.successfulRequests=="number"&&Number.isSafeInteger(o.successfulRequests)&&o.successfulRequests>=0?{successfulRequests:o.successfulRequests}:{}};return _e({code:r,message:n.trim()&&n.trim()!=="[object Object]"?n:"The Product Agent operation failed. Try again.",retryable:!!(s&&"retryable"in s&&s.retryable===!0),...Object.keys(c).length?{details:c}:{}})}function W(i){if(!i||typeof i!="object")return!1;const e=i,t=s=>Number.isSafeInteger(s)&&s>=0;return Object.keys(e).every(s=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(s))&&g(e.requestId)!==null&&["GET","POST","PUT","PATCH","DELETE"].includes(e.method)&&["/api/product-agent/conversations/:sessionId/snapshot","/api/product-agent/:namespace/commands","/api/product-agent/:namespace/:operation"].includes(e.route)&&(e.status===null||t(e.status)&&e.status>=100&&e.status<=599)&&(e.abortTrigger===null||["deadline","transport_disposed","owner_disposed","authority_retired","observation_released","request_replaced","caller_cancelled","unexpected_abort"].includes(e.abortTrigger))&&["http_deadline","http_transport","conversation_query","browser","http_response"].includes(e.owner)&&(e.category===void 0||/^[a-z0-9_]{1,80}$/.test(e.category))&&[e.responseHeadersMs,e.responseBodyMs].every(s=>s==null||t(s))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(s=>s===null||g(s)!==null)&&(e.authorityGeneration===null||t(e.authorityGeneration))&&typeof e.release=="string"&&/^[a-zA-Z0-9._-]{1,80}$/.test(e.release)&&[e.upstreamRequestId,e.upstreamTraceId].every(s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(s))}const Se=["submit","stop","staging_ipc","send_ipc","stop_ipc","attachment_transfer","tab_lookup","tab_recovery","session_recovery","conversation_scope","local_stage","view_publication","page_access","authentication","community","preferences","page_capture","session_tabs","context_ready","first_frame","checkpoint","command_http","http_authentication","http_request","receipt_http","attachment_upload","runtime_reading","runtime_stopping","runtime_progress","runtime_stopped","message_painted","reading_painted","stopping_painted","progress_painted","stopped_painted","session_tabs_snapshot","tab_window","tab_summary","preparation_deadline","preparation_retired","context_discarded","checkpoint_queue","checkpoint_prepared","checkpoint_restore","checkpoint_prerequisite","checkpoint_bindings","checkpoint_write","checkpoint_cleanup","reload_checkpoint","reload_checkpoint_queue","reload_directory_write","reload_directory_read","reload_storage_read","reload_documents","reload_storage_write","acceptance_received","acceptance_applied","cancellation_queue","cancellation_write"],Y=["request_timed_out","delivery_unknown","invalid_ack","acceptance_identity_mismatch","disconnected","executor_not_ready","unauthorized","connection_failed","invalid_response","network_error","type_error","aborted","backend_refusal","unknown"];function Ae(i){const e=i,t=e?.code;return e?.backendRefusal===!0?"backend_refusal":typeof t=="string"&&t!=="backend_refusal"&&Y.includes(t)?t:e?.name==="AbortError"?"aborted":e?.name==="TypeError"?"type_error":"unknown"}const X=Math.random().toString(36).slice(2);let we=0;const N=()=>`timing:${X}:${++we}`,v=i=>typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function C(i){if(!i||typeof i!="object")return!1;const e=i;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs","failureCategory","tabId","queueDepth","workerId"].includes(t))&&(e.tabId===void 0||Number.isSafeInteger(e.tabId)&&e.tabId>=0)&&(e.queueDepth===void 0||Number.isSafeInteger(e.queueDepth)&&e.queueDepth>=0)&&(e.workerId===void 0||v(e.workerId))&&(e.failureCategory===void 0||e.status==="failed"&&Y.includes(e.failureCategory))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp","email"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&Se.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&v(e.spanId)&&v(e.requestId)&&(e.clientMessageId===null||v(e.clientMessageId))&&(e.sessionId===null||v(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function j(i,e){if(e={workerId:X,...e},!i)return{identity:e,mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),s=(n,r,a,o,c)=>{const d={...e,stage:n,status:r,spanId:o,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-a)),...r==="failed"?{failureCategory:Ae(c)}:{}};i&&C(d)&&Promise.resolve().then(()=>i(d)).catch(()=>{})};return{identity:e,mark:n=>s(n,"observed",t,N()),measure(n,r){const a=performance.now(),o=N();return s(n,"started",a,o),r().then(c=>(s(n,"completed",a,o),c),c=>{throw s(n,"failed",a,o,c),c})}}}const E=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Pe(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))&&E(e.sessionId)&&E(e.responseItemId)&&E(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Me(i,e,t="stopped",s,n="Run stopped by user."){const r=new Set(s??[i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(c=>c.role==="user").slice(-1)[0]?.id].filter(c=>!!c)),a=i.messages.filter(c=>!(c.dataType==="run_status"&&c.loading&&r.has(c.respondsToUserMessageId??""))).map(c=>r.has(c.respondsToUserMessageId??"")?{...c,loading:!1}:c);for(const c of r)a.some(d=>d.respondsToUserMessageId===c&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||a.some(d=>d.role==="user"&&d.id===c)&&a.push({id:`local-interrupted:${c}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":n,createdAt:e,respondsToUserMessageId:c});const o=i.segments?.map(c=>({...c,outcomeIds:[...c.outcomeIds,...a.filter(d=>d.id===`local-interrupted:${c.userMessageId}`&&!c.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...i,messages:a,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:i.isLoadingSession&&a.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const Ee={"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 Te(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Ee,i.slice(13))}function K(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function Re(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":return!0;case"run.retry":return e.clientMessageId===void 0||typeof e.clientMessageId=="string"&&e.clientMessageId.length>0&&e.clientMessageId.length<=160;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return Pe(e.observation);case"runtime.report_operation_timing":return C(e.timing);case"runtime.report_displayed_error":return(e.errorDiagnostic===void 0||ve(e.errorDiagnostic))&&(e.httpRequest===void 0||W(e.httpRequest))&&(e.historyRefreshFailure===void 0||H(e.historyRefreshFailure))&&(e.renderedError===void 0||V(e.renderedError))&&(e.reason==="conversation_error"||e.reason==="attachment_error"||e.reason==="history_error"||e.reason==="action_error")&&typeof e.errorFingerprint=="string"&&/^fnv1a-[0-9a-f]{8}$/.test(e.errorFingerprint)&&(e.displayedMessage===void 0||typeof e.displayedMessage=="string"&&e.displayedMessage.length<=500);case"runtime.report_invalid_state_transition":return(e.uiInvariant===void 0||Z(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Te(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 ke{constructor(e,t,s){this.adapter=t,this.state=A(e),this.hasBeenReady=e.status==="connected"&&e.submissionReady!==!1,this.initialModel=s??"gpt-6.1-sol",this.model=this.initialModel}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=I("unavailable");model;modelExplicit=!1;initialModel;interactions=[];account=null;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(o=>o.id)),a=new Set(n.segments?.map(o=>o.id));e.messages=[...n.messages,...e.messages.filter(o=>!r.has(o.id))],(n.segments||e.segments)&&(e.segments=[...(n.segments??[]).map(o=>({...o})),...(e.segments??[]).filter(o=>!a.has(o.id))]),e.removedItems={...n.removedItems,...e.removedItems}}for(const[n,r]of this.submissionPreviews)e.messages.some(a=>a.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(a=>({...a}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error.message,e.lastErrorCode=["unauthorized","401","auth_reconnecting","submission_not_available","submission_checkpoint_pending"].includes(r.error.code)?r.error.code:"message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews.keys()];if(!t.length)return e;const s=Me(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:s.messages,segments:s.segments}:s}updateProjection(e,t,s,n,r){if(this.destroyed)return;const a=this.getState(),o=!this.hasBeenReady&&(!a.user||a.user.id===e.user?.id),c=a.stableSelectionKey!==void 0&&a.stableSelectionKey===e.stableSelectionKey&&a.user?.id===e.user?.id&&a.sessionId===e.sessionId,d=c&&this.pendingTransfers.size>0&&this.submissionRetries.size===0&&[...this.pendingTransfers.keys()].every(l=>this.readinessPendingSubmissions.has(l));!o&&!d&&(a.user?.id!==e.user?.id||a.selectionKey!==void 0&&a.selectionKey!==e.selectionKey||a.selectionKey===void 0&&a.sessionId!==null&&a.sessionId!==e.sessionId)&&(c||(this.model=t??this.initialModel,this.modelExplicit=!1),this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const l of e.messages)l.role==="user"&&e.receipts?.find(u=>u.userMessageId===l.id)?.durable!==!1&&this.submissionPreviews.delete(l.id);const p=c&&e.sessionId!==null&&e.isLoadingSession&&!e.isDraftSession;this.retainedTranscript=p?this.retainedTranscript??(this.state.isLoadingSession||this.state.messages.length===0?null:{messages:this.state.messages,segments:this.state.segments,removedItems:this.state.removedItems}):null,this.state=A(e),t!==void 0&&!this.modelExplicit&&(this.model=t),e.status==="connected"&&e.submissionReady!==!1&&(this.hasBeenReady=!0);for(const[l,u]of this.stopPreviews){const h=e.activity?.executionKey;(u!==void 0&&u!=="[]"&&h!==void 0&&h!=="[]"&&(h!==u||["completed","failed","stopped"].includes(e.activity.phase))||(u===void 0||u==="[]")&&e.messages.some(m=>m.respondsToUserMessageId===l&&!m.provisional&&m.loading!==!0&&(m.dataType==="run_status"||m.dataType==="run_error"||m.role==="assistant"&&m.phase!=="commentary"&&(m.streamState===void 0||["finished","stopped","failed"].includes(m.streamState)))))&&this.stopPreviews.delete(l)}if(this.pendingStop?.userMessageIds.every(l=>!this.stopPreviews.has(l))&&(this.pendingStop=null),a.user?.id===e.user?.id)for(const l of this.state.messages){if(l.role!=="user"||!l.attachments?.length)continue;const u=a.messages.find(h=>h.role==="user"&&h.id===l.id);a.sessionId!==e.sessionId&&!(a.sessionId===null&&u)||(l.attachments=qe(u?.attachments,l.attachments))}if(s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=z(s);for(const l of this.sessionHistoryListeners)l(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(l=>({...l}));for(const l of this.interactionListeners)l(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const l of this.accountListeners)l(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.durabilityWaiters)e();this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionRetries.clear(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}recordPromptPresented(e,t){this.dispatch({type:"runtime.prompt_presented",feature:e,openingGeneration:t})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&C(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,s){s!==void 0&&!Z(s)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...s?{uiInvariant:s}:{}}).catch(()=>{})}reportDisplayedError(e,t,s,n,r){const a=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;if(n!==void 0&&!V(n)||r!==void 0&&!H(r))return;const o=Ie(this.getState(),e,s,!!n,this.adapter.diagnosticBuilds);this.adapter.dispatch({type:"runtime.report_displayed_error",errorDiagnostic:o,...o.clientMessageId?{clientMessageId:o.clientMessageId}:{},reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...W(a)?{httpRequest:a}:{},...s?{displayedMessage:J(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){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()),a=t.submittedAt??Date.now(),o=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(d=>d.id?[d.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:s,createdAt:"",attachments:n.map(d=>({...d}))}});const c=this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:a,selectionKey:this.state.selectionKey},o);return this.emit("state",this.getState()),c.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId,a=j(p=>{s===this.submissionGeneration&&this.reportOperationTiming(p)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});a.mark("submit");let o=t.attachments??[],c=!1,d=!this.hasBeenReady||this.state.submissionReady===!1;if(s!==this.submissionGeneration)return null;d&&this.readinessPendingSubmissions.add(r);try{const p=await a.measure("staging_ipc",async()=>{if(d){if(!await a.measure("authentication",()=>this.waitForSubmissionReadiness(s)))return null;this.readinessPendingSubmissions.delete(r),d=!1,t={...t,selectionKey:this.state.selectionKey}}return this.destroyed||s!==this.submissionGeneration?null:this.adapter.dispatch({type:"conversation.stage",...t.reconcileAcceptance?{reconcileAcceptance:!0}:{},selectionKey:t.selectionKey,requestedModel:t.requestedModel,initiatedBy:t.initiatedBy,invocation:t.invocation,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:o.length>0?o.map(K):void 0,submittedAt:t.submittedAt}).then(u=>({result:u}),async u=>{const h=b(u);if(h.code!=="submission_checkpoint_pending")throw u;const f=this.submissionPreviews.get(r);return f&&(f.error=h),this.emit("state",this.getState()),await this.waitForSubmissionDurability(r,s)?{result:void 0}:null})});if(!p||s!==this.submissionGeneration)return null;if(c=!0,this.submissionRetries.delete(r),p.result?.submissionAccepted){r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null);for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r}if(o.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of o){if(u.sandboxPath||u.storageKey){l.push(u);continue}const h=u.id?this.attachmentFiles.get(u.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await a.measure("attachment_transfer",()=>this.adapter.uploadAttachment(h,u,{clientMessageId:r}))),s!==this.submissionGeneration)return null}o=l}if(s!==this.submissionGeneration||(await this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,requestedModel:t.requestedModel,selectionKey:t.selectionKey,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:o.length>0?o.map(K):void 0}),s!==this.submissionGeneration))return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===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(([,o])=>o.error)?.[0]??this.state.messages.filter(o=>o.role==="user").slice(-1)[0]?.id;if(!t||this.destroyed)return!1;const s=this.submissionPreviews.get(t);if(s?.pending||this.pendingTransfers.has(t))return!1;const n=this.submissionRetries.get(t),r=n?.retry,a=this.submissionGeneration;try{return n&&r?(s&&(s.pending=!0,s.error=void 0),this.submissionRetries.delete(t),this.pendingTransfers.set(t,n.attachmentIds),this.emit("state",this.getState()),await r()):await this.dispatch({type:"run.retry",clientMessageId:t}),!0}catch(o){if(!s&&!r)throw o;return s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.error=b(o),this.emit("state",this.getState())),!1}finally{r&&this.pendingTransfers.delete(t),s&&a===this.submissionGeneration&&this.submissionPreviews.get(t)===s&&(s.pending=!1,this.emit("state",this.getState()))}}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1);if(!this.hasBeenReady&&t.length>0&&!this.state.isThinking&&this.state.turnPhase===null&&this.state.pendingMessageStatus===null)return this.emit("state",this.getState()),Promise.resolve();const s=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=j(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:s[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:s,promise:Promise.resolve()};this.pendingStop=r;const a=!e.pendingMessageStatus&&["thinking","steering","queued","stopping"].includes(this.state.activity?.phase??"")?this.state.activity?.executionKey:void 0;for(const d of s)this.stopPreviews.set(d,t.includes(d)?void 0:a);const o=this.submissionGeneration;return r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(!(o!==this.submissionGeneration||s.every(p=>!this.stopPreviews.has(p)))){for(const p of s)this.stopPreviews.delete(p);this.stopError=b(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState()),r.promise.then(()=>{})}async waitForSubmissionReadiness(e){let t=()=>{},s=()=>{};return new Promise((n,r)=>{s=()=>{if(this.destroyed||e!==this.submissionGeneration){n(!1);return}if(this.state.lastError&&["connection_failed","unauthorized","update_required"].includes(this.state.lastErrorCode??"")){r(Object.assign(new Error(this.state.lastError),{code:this.state.lastErrorCode}));return}this.hasBeenReady&&this.state.submissionReady!==!1&&n(!0)},this.durabilityWaiters.add(s),t=this.on("state",s),s()}).finally(()=>{t(),this.durabilityWaiters.delete(s)})}async waitForSubmissionDurability(e,t){let s=()=>{},n=()=>{};return new Promise((r,a)=>{n=()=>{if(this.destroyed||t!==this.submissionGeneration){r(!1);return}const o=this.state;if(o.messages.some(d=>d.respondsToUserMessageId===e&&d.dataType==="run_status"&&!d.provisional)){r(!1);return}if(o.conversationDiagnostics?.failedClientMessageId===e&&o.lastError&&o.lastErrorCode!=="submission_checkpoint_pending"){a(Object.assign(new Error(o.lastError),{code:o.lastErrorCode}));return}const c=o.messages.find(d=>d.id===`submission-error:${e}`&&d.dataType==="run_error");if(c){a(new Error(c.content));return}o.receipts?.some(d=>d.userMessageId===e&&d.durable)&&r(!0)},this.durabilityWaiters.add(n),s=this.on("state",n),n()}).finally(()=>{s(),this.durabilityWaiters.delete(n)})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...new Set([...this.pendingTransfers.keys(),...this.submissionRetries.keys()])];this.submissionGeneration++;for(const s of this.durabilityWaiters)s();for(const s of this.pendingTransfers.values())for(const n of s)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const s of this.submissionRetries.values())for(const n of s.attachmentIds)this.attachmentFiles.delete(n);this.submissionRetries.clear();for(const s of this.submissionPreviews.values()){s.pending=!1,s.error?.code==="submission_checkpoint_pending"&&(s.error=void 0);for(const n of s.message.attachments??[])n.id&&this.attachmentFiles.delete(n.id)}return t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.model=this.initialModel,this.modelExplicit=!1,this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.navigate({type:"session.new"})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return z(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){const r=n.expectedSourceVersion===void 0?this.getInteractions().find(a=>a.id===e)?.sourceVersion??null:n.expectedSourceVersion;return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...n,expectedSourceVersion:r,...t==="run"?{requestedModel:n.requestedModel??this.getModel()}:{}}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return e===this.getState().sessionId?this.adapter.dispatch({type:"session.load",sessionId:e}).then(()=>{}):(this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.retainedTranscript=null,this.emit("state",this.getState()),this.navigate({type:"session.load",sessionId:e}))}stageProactiveSuggestionQuestion(e){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 qe(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function z(i){return{...i,data:i.data?_({entities:$(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=G;exports.ProductAgentInteractionManager=ae;exports.ProductAgentQueryController=T;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=pe;exports.formatProductAgentTaskPageTitle=Q;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=F;exports.reconcileProductAgentSubmissionGate=ee;exports.resolveProductAgentBillingPresentation=se;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=te;exports.selectProductAgentQueryEntities=$;
|
|
@@ -522,7 +522,7 @@ function Re(i) {
|
|
|
522
522
|
function M(i) {
|
|
523
523
|
return i.replace(se, "");
|
|
524
524
|
}
|
|
525
|
-
const ne = "0.1.
|
|
525
|
+
const ne = "0.1.319", re = {
|
|
526
526
|
version: ne
|
|
527
527
|
}, g = (i) => typeof i == "string" && /^[a-zA-Z0-9:_.-]{1,160}$/.test(i) ? i : null;
|
|
528
528
|
function oe(i) {
|
|
@@ -587,7 +587,7 @@ function ue(i, e, t, s, n = {}) {
|
|
|
587
587
|
builds: { sdk: re.version, ...n }
|
|
588
588
|
};
|
|
589
589
|
}
|
|
590
|
-
function
|
|
590
|
+
function pe(i) {
|
|
591
591
|
if (i.details !== void 0 && !A(i.details))
|
|
592
592
|
throw new TypeError("Product Agent transported error details must be JSON-safe.");
|
|
593
593
|
return {
|
|
@@ -614,7 +614,7 @@ function b(i, e = "runtime_error", t = "runtime") {
|
|
|
614
614
|
...typeof o.durationMs == "number" && Number.isFinite(o.durationMs) && o.durationMs >= 0 ? { durationMs: o.durationMs } : {},
|
|
615
615
|
...typeof o.successfulRequests == "number" && Number.isSafeInteger(o.successfulRequests) && o.successfulRequests >= 0 ? { successfulRequests: o.successfulRequests } : {}
|
|
616
616
|
};
|
|
617
|
-
return
|
|
617
|
+
return pe({
|
|
618
618
|
code: r,
|
|
619
619
|
message: n.trim() && n.trim() !== "[object Object]" ? n : "The Product Agent operation failed. Try again.",
|
|
620
620
|
retryable: !!(s && "retryable" in s && s.retryable === !0),
|
|
@@ -645,7 +645,7 @@ function H(i) {
|
|
|
645
645
|
"upstreamTraceId"
|
|
646
646
|
].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));
|
|
647
647
|
}
|
|
648
|
-
const
|
|
648
|
+
const he = [
|
|
649
649
|
"submit",
|
|
650
650
|
"stop",
|
|
651
651
|
"staging_ipc",
|
|
@@ -731,7 +731,7 @@ const N = () => `timing:${V}:${++fe}`, v = (i) => typeof i == "string" && /^[a-z
|
|
|
731
731
|
function q(i) {
|
|
732
732
|
if (!i || typeof i != "object") return !1;
|
|
733
733
|
const e = i;
|
|
734
|
-
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" && Q.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) &&
|
|
734
|
+
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" && Q.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) && he.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;
|
|
735
735
|
}
|
|
736
736
|
function j(i, e) {
|
|
737
737
|
if (e = { workerId: V, ...e }, !i) return {
|
|
@@ -940,16 +940,16 @@ class qe {
|
|
|
940
940
|
!o && !d && (a.user?.id !== e.user?.id || a.selectionKey !== void 0 && a.selectionKey !== e.selectionKey || a.selectionKey === void 0 && a.sessionId !== null && a.sessionId !== e.sessionId) && (c || (this.model = t ?? this.initialModel, this.modelExplicit = !1), this.cancelPendingSubmissions(), this.submissionPreviews.clear());
|
|
941
941
|
for (const l of e.messages)
|
|
942
942
|
l.role === "user" && e.receipts?.find((u) => u.userMessageId === l.id)?.durable !== !1 && this.submissionPreviews.delete(l.id);
|
|
943
|
-
const
|
|
944
|
-
this.retainedTranscript =
|
|
943
|
+
const p = c && e.sessionId !== null && e.isLoadingSession && !e.isDraftSession;
|
|
944
|
+
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 = _(e), t !== void 0 && !this.modelExplicit && (this.model = t), e.status === "connected" && e.submissionReady !== !1 && (this.hasBeenReady = !0);
|
|
945
945
|
for (const [l, u] of this.stopPreviews) {
|
|
946
|
-
const
|
|
947
|
-
(u !== void 0 && u !== "[]" &&
|
|
946
|
+
const h = e.activity?.executionKey;
|
|
947
|
+
(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);
|
|
948
948
|
}
|
|
949
949
|
if (this.pendingStop?.userMessageIds.every((l) => !this.stopPreviews.has(l)) && (this.pendingStop = null), a.user?.id === e.user?.id)
|
|
950
950
|
for (const l of this.state.messages) {
|
|
951
951
|
if (l.role !== "user" || !l.attachments?.length) continue;
|
|
952
|
-
const u = a.messages.find((
|
|
952
|
+
const u = a.messages.find((h) => h.role === "user" && h.id === l.id);
|
|
953
953
|
a.sessionId !== e.sessionId && !(a.sessionId === null && u) || (l.attachments = Ie(u?.attachments, l.attachments));
|
|
954
954
|
}
|
|
955
955
|
if (s && JSON.stringify(s) !== JSON.stringify(this.sessionHistoryState)) {
|
|
@@ -1044,8 +1044,8 @@ class qe {
|
|
|
1044
1044
|
});
|
|
1045
1045
|
}
|
|
1046
1046
|
async sendMessageNow(e, t, s) {
|
|
1047
|
-
const n = e, r = t.clientMessageId, a = j((
|
|
1048
|
-
s === this.submissionGeneration && this.reportOperationTiming(
|
|
1047
|
+
const n = e, r = t.clientMessageId, a = j((p) => {
|
|
1048
|
+
s === this.submissionGeneration && this.reportOperationTiming(p);
|
|
1049
1049
|
}, {
|
|
1050
1050
|
operation: "send",
|
|
1051
1051
|
layer: "renderer",
|
|
@@ -1058,7 +1058,7 @@ class qe {
|
|
|
1058
1058
|
if (s !== this.submissionGeneration) return null;
|
|
1059
1059
|
d && this.readinessPendingSubmissions.add(r);
|
|
1060
1060
|
try {
|
|
1061
|
-
const
|
|
1061
|
+
const p = await a.measure("staging_ipc", async () => {
|
|
1062
1062
|
if (d) {
|
|
1063
1063
|
if (!await a.measure("authentication", () => this.waitForSubmissionReadiness(s))) return null;
|
|
1064
1064
|
this.readinessPendingSubmissions.delete(r), d = !1, t = { ...t, selectionKey: this.state.selectionKey };
|
|
@@ -1070,7 +1070,6 @@ class qe {
|
|
|
1070
1070
|
requestedModel: t.requestedModel,
|
|
1071
1071
|
initiatedBy: t.initiatedBy,
|
|
1072
1072
|
invocation: t.invocation,
|
|
1073
|
-
automationOnboarding: t.automationOnboarding,
|
|
1074
1073
|
content: n,
|
|
1075
1074
|
clientMessageId: r,
|
|
1076
1075
|
proactiveSuggestionQuestion: t.proactiveSuggestionQuestion,
|
|
@@ -1078,14 +1077,14 @@ class qe {
|
|
|
1078
1077
|
attachments: o.length > 0 ? o.map(K) : void 0,
|
|
1079
1078
|
submittedAt: t.submittedAt
|
|
1080
1079
|
}).then((u) => ({ result: u }), async (u) => {
|
|
1081
|
-
const
|
|
1082
|
-
if (
|
|
1080
|
+
const h = b(u);
|
|
1081
|
+
if (h.code !== "submission_checkpoint_pending") throw u;
|
|
1083
1082
|
const f = this.submissionPreviews.get(r);
|
|
1084
|
-
return f && (f.error =
|
|
1083
|
+
return f && (f.error = h), this.emit("state", this.getState()), await this.waitForSubmissionDurability(r, s) ? { result: void 0 } : null;
|
|
1085
1084
|
});
|
|
1086
1085
|
});
|
|
1087
|
-
if (!
|
|
1088
|
-
if (c = !0, this.submissionRetries.delete(r),
|
|
1086
|
+
if (!p || s !== this.submissionGeneration) return null;
|
|
1087
|
+
if (c = !0, this.submissionRetries.delete(r), p.result?.submissionAccepted) {
|
|
1089
1088
|
r === this.stagedProactiveSuggestionClientMessageId && (this.stagedProactiveSuggestionClientMessageId = null);
|
|
1090
1089
|
for (const l of t.attachments ?? [])
|
|
1091
1090
|
l.id && this.attachmentFiles.delete(l.id);
|
|
@@ -1100,9 +1099,9 @@ class qe {
|
|
|
1100
1099
|
l.push(u);
|
|
1101
1100
|
continue;
|
|
1102
1101
|
}
|
|
1103
|
-
const
|
|
1104
|
-
if (!
|
|
1105
|
-
if (l.push(await a.measure("attachment_transfer", () => this.adapter.uploadAttachment(
|
|
1102
|
+
const h = u.id ? this.attachmentFiles.get(u.id) : void 0;
|
|
1103
|
+
if (!h) throw new Error(`Attachment bytes are unavailable for ${u.name}`);
|
|
1104
|
+
if (l.push(await a.measure("attachment_transfer", () => this.adapter.uploadAttachment(h, u, { clientMessageId: r }))), s !== this.submissionGeneration) return null;
|
|
1106
1105
|
}
|
|
1107
1106
|
o = l;
|
|
1108
1107
|
}
|
|
@@ -1114,29 +1113,28 @@ class qe {
|
|
|
1114
1113
|
selectionKey: t.selectionKey,
|
|
1115
1114
|
initiatedBy: t.initiatedBy,
|
|
1116
1115
|
invocation: t.invocation,
|
|
1117
|
-
automationOnboarding: t.automationOnboarding,
|
|
1118
1116
|
proactiveSuggestionQuestion: t.proactiveSuggestionQuestion,
|
|
1119
1117
|
attachments: o.length > 0 ? o.map(K) : void 0
|
|
1120
1118
|
}), s !== this.submissionGeneration)) return null;
|
|
1121
1119
|
for (const l of t.attachments ?? [])
|
|
1122
1120
|
l.id && this.attachmentFiles.delete(l.id);
|
|
1123
1121
|
return r === this.stagedProactiveSuggestionClientMessageId && (this.stagedProactiveSuggestionClientMessageId = null), r;
|
|
1124
|
-
} catch (
|
|
1122
|
+
} catch (p) {
|
|
1125
1123
|
if (s !== this.submissionGeneration) return null;
|
|
1126
|
-
if (C(
|
|
1124
|
+
if (C(p))
|
|
1127
1125
|
for (const f of t.attachments ?? [])
|
|
1128
1126
|
f.id && this.attachmentFiles.delete(f.id);
|
|
1129
|
-
const u = b(
|
|
1130
|
-
!c && !C(
|
|
1127
|
+
const u = b(p).code === "command_not_received";
|
|
1128
|
+
!c && !C(p) && (d || u || t.selectionKey !== void 0) && this.submissionRetries.set(r, {
|
|
1131
1129
|
retry: async () => (d && await this.connect(), this.sendMessageNow(e, { ...t, reconcileAcceptance: !d && !u }, s)),
|
|
1132
1130
|
attachmentIds: (t.attachments ?? []).flatMap((f) => f.id ? [f.id] : [])
|
|
1133
1131
|
});
|
|
1134
|
-
const
|
|
1135
|
-
throw
|
|
1132
|
+
const h = this.submissionPreviews.get(r);
|
|
1133
|
+
throw h && (h.pending = !1, h.error = b(p), this.emit("state", this.getState())), c && await this.adapter.dispatch({
|
|
1136
1134
|
type: "conversation.fail_staged",
|
|
1137
1135
|
clientMessageId: r,
|
|
1138
|
-
message: b(
|
|
1139
|
-
}),
|
|
1136
|
+
message: b(p).message
|
|
1137
|
+
}), p;
|
|
1140
1138
|
} finally {
|
|
1141
1139
|
this.readinessPendingSubmissions.delete(r);
|
|
1142
1140
|
}
|
|
@@ -1196,8 +1194,8 @@ class qe {
|
|
|
1196
1194
|
const o = this.submissionGeneration;
|
|
1197
1195
|
return r.promise = n.measure("stop_ipc", () => this.adapter.dispatch({ type: "run.stop", ...t.length ? { clientMessageIds: t } : {} })).then(() => {
|
|
1198
1196
|
}, (d) => {
|
|
1199
|
-
if (!(o !== this.submissionGeneration || s.every((
|
|
1200
|
-
for (const
|
|
1197
|
+
if (!(o !== this.submissionGeneration || s.every((p) => !this.stopPreviews.has(p)))) {
|
|
1198
|
+
for (const p of s) this.stopPreviews.delete(p);
|
|
1201
1199
|
this.stopError = b(d).message;
|
|
1202
1200
|
}
|
|
1203
1201
|
}).finally(() => {
|
|
@@ -846,7 +846,7 @@ function br(t, e = null) {
|
|
|
846
846
|
} : void 0);
|
|
847
847
|
return { ...i, ...a ? { auth: a } : {}, submissionGate: o };
|
|
848
848
|
}
|
|
849
|
-
const Ir = "0.1.
|
|
849
|
+
const Ir = "0.1.319", kt = {
|
|
850
850
|
version: Ir
|
|
851
851
|
};
|
|
852
852
|
function Ke(t) {
|
|
@@ -8424,7 +8424,6 @@ class al {
|
|
|
8424
8424
|
requestedModel: s.requestedModel,
|
|
8425
8425
|
initiatedBy: s.initiatedBy,
|
|
8426
8426
|
invocation: s.invocation,
|
|
8427
|
-
automationOnboarding: s.automationOnboarding,
|
|
8428
8427
|
content: n,
|
|
8429
8428
|
clientMessageId: r,
|
|
8430
8429
|
proactiveSuggestionQuestion: s.proactiveSuggestionQuestion,
|
|
@@ -8468,7 +8467,6 @@ class al {
|
|
|
8468
8467
|
selectionKey: s.selectionKey,
|
|
8469
8468
|
initiatedBy: s.initiatedBy,
|
|
8470
8469
|
invocation: s.invocation,
|
|
8471
|
-
automationOnboarding: s.automationOnboarding,
|
|
8472
8470
|
proactiveSuggestionQuestion: s.proactiveSuggestionQuestion,
|
|
8473
8471
|
attachments: a.length > 0 ? a.map(Di) : void 0
|
|
8474
8472
|
}), i !== this.submissionGeneration)) return null;
|
|
@@ -9655,7 +9653,7 @@ class Ct {
|
|
|
9655
9653
|
context: JSON.parse(JSON.stringify({
|
|
9656
9654
|
page: l,
|
|
9657
9655
|
...s.proactiveSuggestionQuestion ? { proactiveSuggestionQuestion: s.proactiveSuggestionQuestion } : {},
|
|
9658
|
-
metadata:
|
|
9656
|
+
metadata: Fi(this.options.metadata)
|
|
9659
9657
|
})),
|
|
9660
9658
|
invocation: Bc(s.invocation ?? s.initiatedBy),
|
|
9661
9659
|
entrySurface: this.options.entrySurface,
|