@pluno/product-agent-web 0.1.321 → 0.1.322
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function 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 M{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 M(`${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 M(`${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 F(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(F),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,F(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=P(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${P(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${P(e.scope)}:category:${e.category}`}}function de(i,e){return{load:async()=>U(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function U(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function P(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 H(i,e){if(!e)return E(i);const t=E(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=E(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?E(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function 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 E(i){return i.replace(le,"")}const he="0.1.321",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 Q(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 T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Ee(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Pe(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 Te={"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 Me(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Te,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 Ee(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||Q(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"||Me(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!1;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;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=Pe(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&&!Q(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={}){if(t.proactiveSuggestionQuestion!==void 0)return Promise.reject(new Error("Personal Product Agent has retired."));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??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,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){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,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}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){return Promise.resolve()}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=M;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=pe;exports.formatProductAgentTaskPageTitle=H;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=U;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 M{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 M(`${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 M(`${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 F(i){return i!==null&&typeof i=="object"&&!Object.isFrozen(i)&&(Object.values(i).forEach(F),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,F(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=P(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${P(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${P(e.scope)}:category:${e.category}`}}function de(i,e){return{load:async()=>U(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function U(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(k):[]}function P(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 H(i,e){if(!e)return E(i);const t=E(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=E(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?E(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=H(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function 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 E(i){return i.replace(le,"")}const he="0.1.322",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 Q(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 T=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function Ee(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&T(e.sessionId)&&T(e.responseItemId)&&T(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}function Pe(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 Te={"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 Me(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Te,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 Ee(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||Q(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"||Me(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!1;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;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=Pe(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&&!Q(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={}){if(t.proactiveSuggestionQuestion!==void 0)return Promise.reject(new Error("Personal Product Agent has retired."));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??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,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){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,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}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){return Promise.resolve()}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=M;exports.ProductAgentRemoteRuntimeClient=ke;exports.ProductAgentSessionHistoryManager=ne;exports.ProductAgentTaskPageTitleController=ue;exports.createLocalStorageInteractionDecisionStorage=de;exports.createProductAgentQueryState=I;exports.createProductAgentTaskPageTitleDocument=pe;exports.formatProductAgentTaskPageTitle=H;exports.isProductAgentAuthReconnectError=R;exports.isProductAgentRuntimeCommand=Re;exports.mergeProductAgentEntityPages=L;exports.normalizeProductAgentEntityPage=_;exports.readLocalStorageInteractionDecisions=U;exports.reconcileProductAgentSubmissionGate=ee;exports.resolveProductAgentBillingPresentation=se;exports.resolveProductAgentComposerAction=ie;exports.resolveProductAgentWidgetPresentation=te;exports.selectProductAgentQueryEntities=$;
|
|
@@ -522,7 +522,7 @@ function Re(i) {
|
|
|
522
522
|
function E(i) {
|
|
523
523
|
return i.replace(se, "");
|
|
524
524
|
}
|
|
525
|
-
const ne = "0.1.
|
|
525
|
+
const ne = "0.1.322", 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) {
|
|
@@ -846,7 +846,7 @@ function wr(t, e = null) {
|
|
|
846
846
|
} : void 0);
|
|
847
847
|
return { ...i, ...a ? { auth: a } : {}, submissionGate: o };
|
|
848
848
|
}
|
|
849
|
-
const _r = "0.1.
|
|
849
|
+
const _r = "0.1.322", Tt = {
|
|
850
850
|
version: _r
|
|
851
851
|
};
|
|
852
852
|
function We(t) {
|
|
@@ -940,7 +940,7 @@ function vs(t) {
|
|
|
940
940
|
function nn(t) {
|
|
941
941
|
return ["history_load_failed", "request_timed_out", "connection_interrupted", "408", "425", "429"].includes(t) || /^5\d\d$/.test(t);
|
|
942
942
|
}
|
|
943
|
-
const
|
|
943
|
+
const Er = "Message storage has not confirmed this submission. Reconnect to check its status.";
|
|
944
944
|
function qt(t) {
|
|
945
945
|
if (!Number.isSafeInteger(t) || t < 0) throw new Error("Invalid conversation revision.");
|
|
946
946
|
}
|
|
@@ -979,7 +979,7 @@ function Is(t, e) {
|
|
|
979
979
|
};
|
|
980
980
|
return { ...t, execution: e, executionByUserMessage: s };
|
|
981
981
|
}
|
|
982
|
-
function
|
|
982
|
+
function kr(t) {
|
|
983
983
|
const e = /* @__PURE__ */ new Set();
|
|
984
984
|
for (const s of Object.values(t.items)) {
|
|
985
985
|
const i = Rt(s), n = t.streams[s.id];
|
|
@@ -1106,7 +1106,7 @@ function Tr(t, e, s, i) {
|
|
|
1106
1106
|
for (const y of m.removed_items) c = $t(c, y);
|
|
1107
1107
|
for (const y of m.items) c = bs(c, y);
|
|
1108
1108
|
for (const y of m.streams) c = rn(c, y);
|
|
1109
|
-
if (c = Is(c, m.execution), c = $t(c, {
|
|
1109
|
+
if (c = Is(c, m.execution), m.follow_ups_version === 0 && m.follow_ups.length === 0 ? c = { ...c, followUps: [], followUpsVersion: Number.MAX_SAFE_INTEGER } : c = $t(c, {
|
|
1110
1110
|
type: "conversation.follow_ups.updated",
|
|
1111
1111
|
conversation_id: m.conversation_id,
|
|
1112
1112
|
version: m.follow_ups_version,
|
|
@@ -1159,7 +1159,7 @@ function Tr(t, e, s, i) {
|
|
|
1159
1159
|
if (s.clients[e.clientScopeId] !== e.conversationScopeId) throw new Error("Submission selection has changed.");
|
|
1160
1160
|
const { type: a, authorityId: c, generation: d, prepareContext: u, reconcileAcceptance: l, waitForAuthentication: h, ...f } = e, m = t.submissions[e.userMessageId];
|
|
1161
1161
|
if (m) {
|
|
1162
|
-
const { contextPreparation: b, requestedModel: I, sessionId: w, delivery:
|
|
1162
|
+
const { contextPreparation: b, requestedModel: I, sessionId: w, delivery: E, cancelled: k, cancellationReason: D, error: S, executionVersion: q, ...A } = m;
|
|
1163
1163
|
if (Ze(A) !== Ze(f)) throw new Error("User-message identity cannot be reused with different input.");
|
|
1164
1164
|
return { state: t, effects: r };
|
|
1165
1165
|
}
|
|
@@ -1241,7 +1241,7 @@ function Tr(t, e, s, i) {
|
|
|
1241
1241
|
requestId: e.requestId,
|
|
1242
1242
|
lane: e.lane,
|
|
1243
1243
|
before: e.lane === "history" ? c.cursor : null,
|
|
1244
|
-
refreshItemIds:
|
|
1244
|
+
refreshItemIds: kr(a),
|
|
1245
1245
|
retryPreparation: c.error?.code === "history_preparation_failed"
|
|
1246
1246
|
}, u = Object.values(t.submissions).filter((f) => f.sessionId === e.sessionId && f.delivery === "accepted" && f.executionVersion === null).map((f) => f.userMessageId), l = t.requestSequence + 1, h = `conversation:${t.generation}:${l}`;
|
|
1247
1247
|
n = {
|
|
@@ -1340,7 +1340,7 @@ function pi(t, e) {
|
|
|
1340
1340
|
return { sessionId: t.sessionId, clientMessageId: e };
|
|
1341
1341
|
}
|
|
1342
1342
|
const dt = { code: "personal_product_agent_retired", message: "Personal Product Agent has retired.", retryable: !1 };
|
|
1343
|
-
function
|
|
1343
|
+
function Es(t) {
|
|
1344
1344
|
let e = t;
|
|
1345
1345
|
const s = [];
|
|
1346
1346
|
if (!t.effectsEnabled || !t.authorityId) return { state: t, effects: s };
|
|
@@ -1589,20 +1589,20 @@ function Mr(t, e, s, i) {
|
|
|
1589
1589
|
delivery: (w.contextPreparation === null && !m.deliveries[I]?.handoffRecovery || !m.deliveries[I]) && !w.cancelled && w.delivery !== "accepted" ? "failed" : w.delivery === "sending" ? "uncertain" : w.delivery,
|
|
1590
1590
|
error: w.delivery !== "accepted" && F(w, m.deliveries[I]) ? dt : w.contextPreparation === null && !m.deliveries[I]?.handoffRecovery && !w.cancelled && !["unauthorized", "auth_reconnecting"].includes(w.error?.code ?? "") ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : !m.deliveries[I] && w.delivery !== "accepted" && !w.cancelled ? { code: "submission_interrupted", message: "Message preparation was interrupted. Retry this message.", retryable: !0 } : w.error
|
|
1591
1591
|
}])),
|
|
1592
|
-
deliveries: Object.fromEntries(Object.entries(m.submissions).map(([I, w],
|
|
1593
|
-
const
|
|
1592
|
+
deliveries: Object.fromEntries(Object.entries(m.submissions).map(([I, w], E) => {
|
|
1593
|
+
const k = m.deliveries[I], D = w.contextPreparation === null && !k?.handoffRecovery, S = w.delivery === "accepted" ? "accepted" : k?.acceptance ?? (k && (k.step === "send" || k.step === "receipt") ? "uncertain" : "unissued");
|
|
1594
1594
|
return [I, {
|
|
1595
|
-
...hi(w,
|
|
1596
|
-
...
|
|
1595
|
+
...hi(w, E),
|
|
1596
|
+
...k,
|
|
1597
1597
|
acceptance: S,
|
|
1598
|
-
allocation: w.sessionId !== null ? "resolved" :
|
|
1598
|
+
allocation: w.sessionId !== null ? "resolved" : k?.allocation ?? (k?.step === "upload" ? "uncertain" : "unissued"),
|
|
1599
1599
|
effectId: null,
|
|
1600
1600
|
// Readiness is authority-local and must be re-established after restart. Captured input stays immutable.
|
|
1601
|
-
step: S === "uncertain" && (
|
|
1601
|
+
step: S === "uncertain" && (k?.step === "send" || k?.handoffRecovery) && k.phase !== "done" ? "receipt" : k?.step ?? null,
|
|
1602
1602
|
prepared: S === "accepted",
|
|
1603
|
-
queuePosition:
|
|
1603
|
+
queuePosition: k?.queuePosition ?? E,
|
|
1604
1604
|
// Retired inputs can only reconcile their original receipt, including interrupted preparation.
|
|
1605
|
-
phase: S === "accepted" ? "done" : S === "uncertain" && F(w,
|
|
1605
|
+
phase: S === "accepted" ? "done" : S === "uncertain" && F(w, k) ? "uncertain" : D || !k ? "failed" : ["running", "waiting"].includes(k.phase) ? "uncertain" : k.phase
|
|
1606
1606
|
}];
|
|
1607
1607
|
})),
|
|
1608
1608
|
// Retired warmup hints must never replay; other durable commands retain their recovery state.
|
|
@@ -1730,7 +1730,7 @@ function Mr(t, e, s, i) {
|
|
|
1730
1730
|
return h && !h.cancelled && !["accepted", "failed"].includes(h.delivery) && !a.durableSubmissionIds.includes(l);
|
|
1731
1731
|
});
|
|
1732
1732
|
c.length !== a.pendingDurabilityIds.length && (a = { ...a, pendingDurabilityIds: c });
|
|
1733
|
-
const d =
|
|
1733
|
+
const d = Es(a), u = Rs(t, d.state, s, e.type === "conversation.recover" && t.checkpointError !== null);
|
|
1734
1734
|
return { state: u.state, effects: [...u.effects, ...o.effects, ...d.effects], interactionSources: o.interactionSources };
|
|
1735
1735
|
}
|
|
1736
1736
|
const Cr = [
|
|
@@ -2211,7 +2211,7 @@ const lt = /* @__PURE__ */ Object.create(null);
|
|
|
2211
2211
|
Object.keys(ae).forEach((t) => {
|
|
2212
2212
|
lt[ae[t]] = t;
|
|
2213
2213
|
});
|
|
2214
|
-
const
|
|
2214
|
+
const ks = { type: "error", data: "parser error" }, un = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", hn = typeof ArrayBuffer == "function", pn = (t) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(t) : t && t.buffer instanceof ArrayBuffer, Hs = ({ type: t, data: e }, s, i) => un && e instanceof Blob ? s ? i(e) : yi(e, i) : hn && (e instanceof ArrayBuffer || pn(e)) ? s ? i(e) : yi(new Blob([e]), i) : i(ae[t] + (e || "")), yi = (t, e) => {
|
|
2215
2215
|
const s = new FileReader();
|
|
2216
2216
|
return s.onload = function() {
|
|
2217
2217
|
const i = s.result.split(",")[1];
|
|
@@ -2256,7 +2256,7 @@ const Gr = (t) => {
|
|
|
2256
2256
|
data: t.substring(1)
|
|
2257
2257
|
} : {
|
|
2258
2258
|
type: lt[s]
|
|
2259
|
-
} :
|
|
2259
|
+
} : ks;
|
|
2260
2260
|
}, Qr = (t, e) => {
|
|
2261
2261
|
if (Jr) {
|
|
2262
2262
|
const s = Gr(t);
|
|
@@ -2337,7 +2337,7 @@ function eo(t, e) {
|
|
|
2337
2337
|
break;
|
|
2338
2338
|
const c = tt(s, 8), d = new DataView(c.buffer, c.byteOffset, c.length), u = d.getUint32(0);
|
|
2339
2339
|
if (u > Math.pow(2, 21) - 1) {
|
|
2340
|
-
a.enqueue(
|
|
2340
|
+
a.enqueue(ks);
|
|
2341
2341
|
break;
|
|
2342
2342
|
}
|
|
2343
2343
|
n = u * Math.pow(2, 32) + d.getUint32(4), i = 3;
|
|
@@ -2348,7 +2348,7 @@ function eo(t, e) {
|
|
|
2348
2348
|
a.enqueue(Ks(r ? c : Kt.decode(c), e)), i = 0;
|
|
2349
2349
|
}
|
|
2350
2350
|
if (n === 0 || n > t) {
|
|
2351
|
-
a.enqueue(
|
|
2351
|
+
a.enqueue(ks);
|
|
2352
2352
|
break;
|
|
2353
2353
|
}
|
|
2354
2354
|
}
|
|
@@ -3252,7 +3252,7 @@ class me extends j {
|
|
|
3252
3252
|
}
|
|
3253
3253
|
}
|
|
3254
3254
|
me.protocol = gn;
|
|
3255
|
-
class
|
|
3255
|
+
class Eo extends me {
|
|
3256
3256
|
constructor() {
|
|
3257
3257
|
super(...arguments), this._upgrades = [];
|
|
3258
3258
|
}
|
|
@@ -3324,7 +3324,7 @@ class ko extends me {
|
|
|
3324
3324
|
return s;
|
|
3325
3325
|
}
|
|
3326
3326
|
}
|
|
3327
|
-
let
|
|
3327
|
+
let ko = class extends Eo {
|
|
3328
3328
|
constructor(e, s = {}) {
|
|
3329
3329
|
const i = typeof e == "object", n = i ? { ...e } : { ...s };
|
|
3330
3330
|
(!n.transports || n.transports && typeof n.transports[0] == "string") && (n.transports = (n.transports || ["polling", "websocket", "webtransport"]).map((r) => wo[r]).filter((r) => !!r)), super(i ? n : e, n);
|
|
@@ -4297,7 +4297,7 @@ class Cs extends j {
|
|
|
4297
4297
|
open(e) {
|
|
4298
4298
|
if (~this._readyState.indexOf("open"))
|
|
4299
4299
|
return this;
|
|
4300
|
-
this.engine = new
|
|
4300
|
+
this.engine = new ko(this.uri, this.opts);
|
|
4301
4301
|
const s = this.engine, i = this;
|
|
4302
4302
|
this._readyState = "opening", this.skipReconnect = !1;
|
|
4303
4303
|
const n = ie(s, "open", function() {
|
|
@@ -5107,7 +5107,7 @@ function Ho(t) {
|
|
|
5107
5107
|
const f = h[0];
|
|
5108
5108
|
if (o.before !== null && f.next_cursor === o.before)
|
|
5109
5109
|
throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
|
|
5110
|
-
const m = h.reduce((g, y) => y.execution.version > g.version ? y.execution : g, f.execution), p = h.reduce((g, y) => y.follow_ups_version > g.follow_ups_version ? y : g, f);
|
|
5110
|
+
const m = h.reduce((g, y) => y.execution.version > g.version ? y.execution : g, f.execution), p = h.find((g) => g.follow_ups_version === 0 && g.follow_ups.length === 0) ?? h.reduce((g, y) => y.follow_ups_version > g.follow_ups_version ? y : g, f);
|
|
5111
5111
|
return { snapshot: {
|
|
5112
5112
|
...f,
|
|
5113
5113
|
execution: m,
|
|
@@ -5313,7 +5313,7 @@ function pe(t, e, s) {
|
|
|
5313
5313
|
let _ = g ? "submitting" : y ? "awaiting_execution" : l?.phase ?? "idle";
|
|
5314
5314
|
const b = Object.entries(t.stops).filter(([v]) => v === s || n !== null && e.selections[v]?.sessionId === n).map(([, v]) => v).find((v) => (!o.length || v.userMessageIds.includes(o[o.length - 1].userMessageId) || !g && !y && ne(l).some((C) => v.userMessageIds.includes(C))) && (!l || l.version <= v.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(l.phase) || o.some((C) => C.cancelled && C.executionVersion === null && v.userMessageIds.includes(C.userMessageId)))), I = l && ["thinking", "steering", "queued", "stopping"].includes(l.phase) || o.some((v) => v.delivery === "accepted" && v.executionVersion === null && b?.userMessageIds.includes(v.userMessageId));
|
|
5315
5315
|
b && I && !g && (!l || !["thinking", "steering", "queued", "stopping"].includes(l.phase) || ne(l).every((v) => b.userMessageIds.includes(v))) && (_ = "stopping"), b && !I && !g && o.some((v) => v.cancelled && v.executionVersion === null && b.userMessageIds.includes(v.userMessageId)) && (_ = o.some((v) => b.userMessageIds.includes(v.userMessageId) && ["sending", "uncertain"].includes(v.delivery)) ? "stopping" : "stopped");
|
|
5316
|
-
const w = ["thinking", "steering", "queued"].includes(_),
|
|
5316
|
+
const w = ["thinking", "steering", "queued"].includes(_), E = t.stops[s] ?? b, k = E?.userMessageIds.filter((v) => !["completed", "failed"].includes(r?.executionByUserMessage[v]?.phase ?? "")) ?? [], D = k.some((v) => {
|
|
5317
5317
|
const C = o.find(($) => $.userMessageId === v);
|
|
5318
5318
|
return !Object.values(t.operations).some(($) => $.command.type === "run.stop" && $.command.payload.expectedUserMessageId === v && $.phase === "done") && (C?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(C.delivery) || !!(l && ne(l).includes(v) && ["thinking", "steering", "queued", "stopping"].includes(l.phase)));
|
|
5319
5319
|
}), S = l?.user_message_ids ?? [], q = g || y ? p?.userMessageId ?? null : S[S.length - 1] ?? null, A = u.find((v) => v.userMessageId === q), P = w ? [...A?.activityIds ?? []].reverse().find((v) => d[v] === "open") ?? null : null, T = n !== null && !!e.selections[s]?.provisionalId && a.length === 0 && o.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
|
|
@@ -5334,7 +5334,7 @@ function pe(t, e, s) {
|
|
|
5334
5334
|
removedItems: r?.removedItems ?? {},
|
|
5335
5335
|
streamStates: d,
|
|
5336
5336
|
preparation: r?.preparation ?? null,
|
|
5337
|
-
stop:
|
|
5337
|
+
stop: E ? { ...E, userMessageIds: k, pending: D } : null,
|
|
5338
5338
|
segments: u.map((v, C) => ({ ...v, collapsed: w ? v.userMessageId !== q : C < u.length - 1 || v.activityIds.length > 0 })),
|
|
5339
5339
|
activity: { phase: _, activeItemId: P, userMessageId: q, executionKey: JSON.stringify([...ne(l)].sort()) },
|
|
5340
5340
|
// Staging transfers the immutable input to the core. Waiting for backend acceptance leaves
|
|
@@ -5360,7 +5360,7 @@ function Wo(t, e) {
|
|
|
5360
5360
|
return K({ scopes: Object.fromEntries([...new Set(Object.values(e.clients))].map((s) => [s, pe(t, e, s)])) });
|
|
5361
5361
|
}
|
|
5362
5362
|
const Go = /(\]\()(\/api\/product-agent\/attachments\/download\?[^)\s]+)(\))/g;
|
|
5363
|
-
function
|
|
5363
|
+
function ke(t, e) {
|
|
5364
5364
|
return e ? t.replace(
|
|
5365
5365
|
Go,
|
|
5366
5366
|
(s, i, n, r) => `${i}${new URL(n, e).toString()}${r}`
|
|
@@ -5411,21 +5411,21 @@ function Jo(t, e, s, i) {
|
|
|
5411
5411
|
};
|
|
5412
5412
|
switch (t.type) {
|
|
5413
5413
|
case "user_message":
|
|
5414
|
-
return { ...r, role: "user", content:
|
|
5414
|
+
return { ...r, role: "user", content: ke(t.data.content, i), attachments: t.data.attachments.map((o) => Si(o, i)) };
|
|
5415
5415
|
case "final_response":
|
|
5416
5416
|
return {
|
|
5417
5417
|
...r,
|
|
5418
5418
|
role: "assistant",
|
|
5419
5419
|
phase: "final_answer",
|
|
5420
|
-
content:
|
|
5420
|
+
content: ke(t.data.content, i),
|
|
5421
5421
|
attachments: t.data.attachments.map((o) => Si(o, i)),
|
|
5422
5422
|
loading: n,
|
|
5423
5423
|
streamState: s
|
|
5424
5424
|
};
|
|
5425
5425
|
case "commentary":
|
|
5426
|
-
return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content:
|
|
5426
|
+
return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content: ke(t.data.content, i), loading: n };
|
|
5427
5427
|
case "tool_summary":
|
|
5428
|
-
return { ...r, role: "tool", dataType: "tool_summary", content:
|
|
5428
|
+
return { ...r, role: "tool", dataType: "tool_summary", content: ke(t.data.content, i), loading: n };
|
|
5429
5429
|
// The supported public renderer recognizes run_error; a bare error system row is silently omitted.
|
|
5430
5430
|
case "error":
|
|
5431
5431
|
return {
|
|
@@ -5484,10 +5484,10 @@ function Wt(t, e, s, i) {
|
|
|
5484
5484
|
}] : [S];
|
|
5485
5485
|
}), g = e?.error != null && t.historyRefreshFailure != null && t.historyRefreshFailure.consecutiveFailures < 4, y = g ? null : e?.error ?? null, _ = [...t.submissions].reverse().find((S) => t.pendingDurabilityIds?.includes(S.userMessageId)), b = _ ? {
|
|
5486
5486
|
code: "submission_checkpoint_pending",
|
|
5487
|
-
message:
|
|
5487
|
+
message: Er,
|
|
5488
5488
|
details: { requestId: _.requestId }
|
|
5489
5489
|
} : null, I = u?.delivery === "failed" && !u.cancelled && !f ? u.error : y ?? b;
|
|
5490
|
-
let
|
|
5490
|
+
let E = {
|
|
5491
5491
|
isRetrying: t.isRetrying ?? !1,
|
|
5492
5492
|
historyRefreshFailure: I === e?.error ? t.historyRefreshFailure ?? null : null,
|
|
5493
5493
|
conversationDiagnostics: {
|
|
@@ -5530,21 +5530,21 @@ function Wt(t, e, s, i) {
|
|
|
5530
5530
|
lastErrorSecuritySettingsUrl: typeof I?.details?.securitySettingsUrl == "string" ? I.details.securitySettingsUrl : null
|
|
5531
5531
|
};
|
|
5532
5532
|
for (const S of t.optimistic.filter((q) => q.cancelled && !t.stop?.userMessageIds.includes(q.userMessageId))) {
|
|
5533
|
-
const q = Os(
|
|
5534
|
-
|
|
5533
|
+
const q = Os(E, "", "stopped", [S.userMessageId], Ri(S.cancellationReason));
|
|
5534
|
+
E = { ...E, messages: q.messages, segments: q.segments };
|
|
5535
5535
|
}
|
|
5536
5536
|
if (t.stop) {
|
|
5537
5537
|
const S = Os(
|
|
5538
|
-
|
|
5538
|
+
E,
|
|
5539
5539
|
"",
|
|
5540
5540
|
t.stop.pending ? "stopping" : "stopped",
|
|
5541
5541
|
t.stop.userMessageIds,
|
|
5542
5542
|
Ri(t.stop.reason ?? "user_requested")
|
|
5543
5543
|
);
|
|
5544
|
-
|
|
5544
|
+
E = { ...E, messages: S.messages, segments: S.segments };
|
|
5545
5545
|
}
|
|
5546
|
-
const
|
|
5547
|
-
return { ...
|
|
5546
|
+
const k = new Map(E.segments.flatMap((S, q) => [S.userMessageId, ...S.activityIds, ...S.outcomeIds].filter((A) => A !== null).map((A) => [A, q]))), D = (S) => k.get(S.id) ?? k.get(S.respondsToUserMessageId ?? "") ?? 1 / 0;
|
|
5547
|
+
return { ...E, messages: [...E.messages].sort((S, q) => D(S) - D(q)) };
|
|
5548
5548
|
}
|
|
5549
5549
|
function Ri(t) {
|
|
5550
5550
|
switch (t) {
|
|
@@ -5703,7 +5703,7 @@ function il(t) {
|
|
|
5703
5703
|
};
|
|
5704
5704
|
}
|
|
5705
5705
|
const Zo = "Pluno is reconnecting. Try again in a moment.";
|
|
5706
|
-
function
|
|
5706
|
+
function Ei(t) {
|
|
5707
5707
|
return (t instanceof Error ? t.message : t) === Zo;
|
|
5708
5708
|
}
|
|
5709
5709
|
function ea() {
|
|
@@ -5712,7 +5712,7 @@ function ea() {
|
|
|
5712
5712
|
const e = Array.from(t, (s) => s.toString(16).padStart(2, "0")).join("");
|
|
5713
5713
|
return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
|
|
5714
5714
|
}
|
|
5715
|
-
const
|
|
5715
|
+
const ki = (t) => t && /^[a-zA-Z0-9_:;=./-]{1,160}$/.test(t) ? t : null;
|
|
5716
5716
|
class An {
|
|
5717
5717
|
constructor(e) {
|
|
5718
5718
|
this.options = e, this.auth = e.auth;
|
|
@@ -5771,7 +5771,7 @@ class An {
|
|
|
5771
5771
|
}, p = () => m("transport_disposed"), g = () => m(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(o?.reason) ? o.reason : "caller_cancelled");
|
|
5772
5772
|
this.requests.signal.addEventListener("abort", p, { once: !0 }), o?.addEventListener("abort", g, { once: !0 });
|
|
5773
5773
|
const y = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && n === "POST", _ = /^\/conversations(?:\/[^/]+)?$/.test(e) && (n ?? (i === void 0 ? "GET" : "POST")) === "GET", b = setTimeout(() => m("deadline"), _ ? 6e4 : y ? 3e4 : 15e3), I = ea(), w = Date.now();
|
|
5774
|
-
let
|
|
5774
|
+
let E = null, k = !1, D = null, S = null, q = null;
|
|
5775
5775
|
try {
|
|
5776
5776
|
const A = await Promise.resolve(fetch(u, {
|
|
5777
5777
|
method: n ?? (i === void 0 ? "GET" : "POST"),
|
|
@@ -5780,9 +5780,9 @@ class An {
|
|
|
5780
5780
|
headers: { "x-product-agent-auth-request-id": I, authorization: d || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...y ? { "x-request-id": I } : {} },
|
|
5781
5781
|
...i === void 0 ? {} : { body: JSON.stringify(i) }
|
|
5782
5782
|
})).catch((P) => {
|
|
5783
|
-
throw
|
|
5783
|
+
throw k = !0, P;
|
|
5784
5784
|
});
|
|
5785
|
-
if (
|
|
5785
|
+
if (E = Date.now(), D = A.status, S = ki(A.headers.get("x-request-id")), q = ki(A.headers.get("x-cloud-trace-context")), !A.ok) {
|
|
5786
5786
|
const P = A.status === 401 ? "unauthorized" : A.status === 426 ? "update_required" : String(A.status), T = (await A.json().catch(() => null))?.detail;
|
|
5787
5787
|
if (A.status === 410 && T?.code === "personal_product_agent_retired" && typeof T.message == "string")
|
|
5788
5788
|
throw new R(
|
|
@@ -5816,9 +5816,9 @@ class An {
|
|
|
5816
5816
|
route: y ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
|
|
5817
5817
|
status: D,
|
|
5818
5818
|
abortTrigger: P,
|
|
5819
|
-
category: P === "deadline" ? "request_timed_out" : P === "unexpected_abort" ? "connection_interrupted" : P ? "request_cancelled" : A instanceof R ? A.code :
|
|
5820
|
-
responseHeadersMs:
|
|
5821
|
-
responseBodyMs:
|
|
5819
|
+
category: P === "deadline" ? "request_timed_out" : P === "unexpected_abort" ? "connection_interrupted" : P ? "request_cancelled" : A instanceof R ? A.code : k ? "connection_interrupted" : "invalid_response",
|
|
5820
|
+
responseHeadersMs: E === null ? null : Math.max(0, E - w),
|
|
5821
|
+
responseBodyMs: E === null ? null : Math.max(0, Date.now() - E),
|
|
5822
5822
|
owner: P === "deadline" ? "http_deadline" : P === "transport_disposed" ? "http_transport" : P && P !== "unexpected_abort" ? "conversation_query" : D === null ? "browser" : "http_response",
|
|
5823
5823
|
elapsedMs: Math.max(0, Date.now() - w),
|
|
5824
5824
|
attempt: c,
|
|
@@ -5843,7 +5843,7 @@ class An {
|
|
|
5843
5843
|
);
|
|
5844
5844
|
}
|
|
5845
5845
|
throw A instanceof R && v ? new R(A.message, A.code, A.outcomeUnknown, { ...A.detail, ...v }, A.backendRefusal) : v ? new R(
|
|
5846
|
-
|
|
5846
|
+
k ? "The connection was interrupted. Please try again." : y ? "The conversation response could not be read. Please try again." : "The response could not be read. Please try again.",
|
|
5847
5847
|
"connection_interrupted",
|
|
5848
5848
|
!0,
|
|
5849
5849
|
v
|
|
@@ -5860,7 +5860,7 @@ function Ve(t) {
|
|
|
5860
5860
|
}
|
|
5861
5861
|
return t;
|
|
5862
5862
|
}
|
|
5863
|
-
function
|
|
5863
|
+
function En() {
|
|
5864
5864
|
return Ve({
|
|
5865
5865
|
authorityId: null,
|
|
5866
5866
|
generation: 0,
|
|
@@ -5910,7 +5910,7 @@ function ve(t) {
|
|
|
5910
5910
|
const e = t.origin.trim();
|
|
5911
5911
|
return { ...t, origin: e.includes("://") ? new URL(e).origin : e.toLowerCase() };
|
|
5912
5912
|
}
|
|
5913
|
-
function
|
|
5913
|
+
function kn(t, e) {
|
|
5914
5914
|
return t.request(`/conversations/${encodeURIComponent(e)}`, {}, void 0, "GET", t.auth.client_kind === "extension" ? "extension" : void 0);
|
|
5915
5915
|
}
|
|
5916
5916
|
function Ti(t) {
|
|
@@ -5942,7 +5942,7 @@ function ia(t) {
|
|
|
5942
5942
|
if (t.http.auth.client_kind === "embed") {
|
|
5943
5943
|
const a = await t.http.request("/conversations", { ...r, page_url: n.origin ?? t.pageUrl() });
|
|
5944
5944
|
Ue(t, i), o = { entries: await Promise.all(a.sessions.map(async (d) => ({
|
|
5945
|
-
...await
|
|
5945
|
+
...await kn(t.http, d.id),
|
|
5946
5946
|
...typeof d.isActive == "boolean" ? { is_active: d.isActive } : {}
|
|
5947
5947
|
}))), next_cursor: a.nextCursor };
|
|
5948
5948
|
} else
|
|
@@ -5996,7 +5996,7 @@ class na {
|
|
|
5996
5996
|
isActiveTurn: () => this.options.isActiveTurn(n),
|
|
5997
5997
|
poll: async () => {
|
|
5998
5998
|
try {
|
|
5999
|
-
return await
|
|
5999
|
+
return await kn(this.options.http, n);
|
|
6000
6000
|
} catch (c) {
|
|
6001
6001
|
throw this.options.onError(c), c;
|
|
6002
6002
|
}
|
|
@@ -6879,7 +6879,7 @@ function _e(t, e, s) {
|
|
|
6879
6879
|
if (e.expectedGeneration !== t.generation || e.generation <= t.generation) return { state: t, effects: n };
|
|
6880
6880
|
const r = e.adoptLocalSubmissions && !t.authorityId ? Object.fromEntries(Object.entries(t.clients).filter(([, o]) => t.selections[o]?.sessionId === null)) : {};
|
|
6881
6881
|
i = {
|
|
6882
|
-
...
|
|
6882
|
+
...En(),
|
|
6883
6883
|
authorityId: e.authorityId,
|
|
6884
6884
|
generation: e.generation,
|
|
6885
6885
|
clients: r,
|
|
@@ -7321,7 +7321,7 @@ class Ra {
|
|
|
7321
7321
|
features: K(ms()),
|
|
7322
7322
|
interactions: K(fs()),
|
|
7323
7323
|
modelSelection: ha(),
|
|
7324
|
-
directory:
|
|
7324
|
+
directory: En(),
|
|
7325
7325
|
conversation: sn()
|
|
7326
7326
|
}) }),
|
|
7327
7327
|
reducer: (n, r) => {
|
|
@@ -7333,7 +7333,7 @@ class Ra {
|
|
|
7333
7333
|
return { state: Object.freeze({ revision: n.revision + 1, slices: Object.freeze({ ...n.slices, ...d }) }), effects: c.effects };
|
|
7334
7334
|
}
|
|
7335
7335
|
if (Ia(o)) {
|
|
7336
|
-
const c = _e(n.slices.directory, o, n.slices.conversation), d =
|
|
7336
|
+
const c = _e(n.slices.directory, o, n.slices.conversation), d = Es(Ss(n.slices.conversation, c.state, o.type === "directory.authority_replace" && o.adoptLocalSubmissions === !0)), u = Rs(n.slices.conversation, d.state, c.state, c.state.clients !== n.slices.directory.clients), l = u.state, h = Di(n.slices.conversation, l, c.state);
|
|
7337
7337
|
return { state: h === n.slices.directory && l === n.slices.conversation ? n : Object.freeze({
|
|
7338
7338
|
revision: n.revision + 1,
|
|
7339
7339
|
slices: Object.freeze({ ...n.slices, directory: h, conversation: l })
|
|
@@ -7370,7 +7370,7 @@ class Ra {
|
|
|
7370
7370
|
}).state);
|
|
7371
7371
|
}
|
|
7372
7372
|
d = Di(n.slices.conversation, c.state, d);
|
|
7373
|
-
const l =
|
|
7373
|
+
const l = Es(Ss(c.state, d)), h = Rs(c.state, l.state, d);
|
|
7374
7374
|
let f = n.slices;
|
|
7375
7375
|
const m = [], p = c.interactionSources, g = f.account.authority;
|
|
7376
7376
|
if (p && g && g.authorityId === p.authorityId && g.generation === p.generation) {
|
|
@@ -7455,7 +7455,7 @@ class Ra {
|
|
|
7455
7455
|
}
|
|
7456
7456
|
}
|
|
7457
7457
|
}
|
|
7458
|
-
const Aa = "pluno-product-agent-attachments",
|
|
7458
|
+
const Aa = "pluno-product-agent-attachments", Ea = 1, Ds = "files", ka = 1440 * 60 * 1e3;
|
|
7459
7459
|
async function Ta(t) {
|
|
7460
7460
|
const e = await Ot();
|
|
7461
7461
|
await Mn(e, "readwrite", (s) => s.put(t));
|
|
@@ -7483,7 +7483,7 @@ async function qn(t, e) {
|
|
|
7483
7483
|
});
|
|
7484
7484
|
});
|
|
7485
7485
|
}
|
|
7486
|
-
async function qa(t =
|
|
7486
|
+
async function qa(t = ka) {
|
|
7487
7487
|
const e = await Ot(), s = Date.now() - t;
|
|
7488
7488
|
await Js(e, "readwrite", async (i) => {
|
|
7489
7489
|
const n = i.index("lastUsedAt");
|
|
@@ -7492,7 +7492,7 @@ async function qa(t = Ea) {
|
|
|
7492
7492
|
}
|
|
7493
7493
|
function Ot() {
|
|
7494
7494
|
return typeof indexedDB > "u" ? Promise.reject(new Error("Product Agent attachment storage is unavailable")) : new Promise((t, e) => {
|
|
7495
|
-
const s = indexedDB.open(Aa,
|
|
7495
|
+
const s = indexedDB.open(Aa, Ea);
|
|
7496
7496
|
s.onupgradeneeded = () => {
|
|
7497
7497
|
const n = s.result.createObjectStore(Ds, { keyPath: "attachmentId" });
|
|
7498
7498
|
n.createIndex("lastUsedAt", "lastUsedAt", { unique: !1 }), n.createIndex("sessionId", "sessionId", { unique: !1 }), n.createIndex("origin", "origin", { unique: !1 });
|
|
@@ -8484,11 +8484,11 @@ class ll {
|
|
|
8484
8484
|
return r;
|
|
8485
8485
|
} catch (u) {
|
|
8486
8486
|
if (i !== this.submissionGeneration) return null;
|
|
8487
|
-
if (
|
|
8487
|
+
if (Ei(u))
|
|
8488
8488
|
for (const m of s.attachments ?? [])
|
|
8489
8489
|
m.id && this.attachmentFiles.delete(m.id);
|
|
8490
8490
|
const h = Q(u).code === "command_not_received";
|
|
8491
|
-
!c && !
|
|
8491
|
+
!c && !Ei(u) && (d || h || s.selectionKey !== void 0) && this.submissionRetries.set(r, {
|
|
8492
8492
|
retry: async () => (d && await this.connect(), this.sendMessageNow(e, { ...s, reconcileAcceptance: !d && !h }, i)),
|
|
8493
8493
|
attachmentIds: (s.attachments ?? []).flatMap((m) => m.id ? [m.id] : [])
|
|
8494
8494
|
});
|
|
@@ -8865,7 +8865,7 @@ function Ac(t, e = Math.random) {
|
|
|
8865
8865
|
const s = Math.min(Ns, gc * 2 ** t), i = 1 - Li + e() * Li * 2;
|
|
8866
8866
|
return Math.min(Ns, Math.round(s * i));
|
|
8867
8867
|
}
|
|
8868
|
-
function
|
|
8868
|
+
function Ec(t) {
|
|
8869
8869
|
const e = t.split(".")[1];
|
|
8870
8870
|
if (!e)
|
|
8871
8871
|
return null;
|
|
@@ -9141,19 +9141,19 @@ class xt {
|
|
|
9141
9141
|
requestId: p.requestId,
|
|
9142
9142
|
clientMessageId: p.userMessageId,
|
|
9143
9143
|
sessionId: p.sessionId
|
|
9144
|
-
}), b = (w,
|
|
9144
|
+
}), b = (w, E) => _.measure(w, () => at(y, E));
|
|
9145
9145
|
let I = p.contextPreparation ?? { pageContent: "", sessionTabs: [] };
|
|
9146
9146
|
if (p.contextPreparation === null) {
|
|
9147
|
-
await b("first_frame", () => new Promise((
|
|
9147
|
+
await b("first_frame", () => new Promise((E) => {
|
|
9148
9148
|
if (document.visibilityState !== "visible") {
|
|
9149
|
-
setTimeout(
|
|
9149
|
+
setTimeout(E, 0);
|
|
9150
9150
|
return;
|
|
9151
9151
|
}
|
|
9152
|
-
const
|
|
9153
|
-
cancelAnimationFrame(S), document.removeEventListener("visibilitychange", D), setTimeout(
|
|
9152
|
+
const k = () => {
|
|
9153
|
+
cancelAnimationFrame(S), document.removeEventListener("visibilitychange", D), setTimeout(E, 0);
|
|
9154
9154
|
}, D = () => {
|
|
9155
|
-
document.visibilityState !== "visible" &&
|
|
9156
|
-
}, S = requestAnimationFrame(
|
|
9155
|
+
document.visibilityState !== "visible" && k();
|
|
9156
|
+
}, S = requestAnimationFrame(k);
|
|
9157
9157
|
document.addEventListener("visibilitychange", D);
|
|
9158
9158
|
}));
|
|
9159
9159
|
const w = p.context.page;
|
|
@@ -9209,14 +9209,14 @@ class xt {
|
|
|
9209
9209
|
const c = this.clientRuntime.engine.getState().slices.conversation, d = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : zt(n);
|
|
9210
9210
|
if (this.authenticatedUserId && !c.submissionOrder.length && !Object.keys(c.operations).length) {
|
|
9211
9211
|
const p = this.queuedClientEvents.filter((_) => _.type === "chat.user_message"), g = d ? JSON.parse(d) : p.length ? Kr(c, p.map((_) => {
|
|
9212
|
-
const { type: b, ...I } = _, w = this.clientRuntime.engine.getState().slices.directory,
|
|
9212
|
+
const { type: b, ...I } = _, w = this.clientRuntime.engine.getState().slices.directory, E = w.clients[this.modelClientScopeId];
|
|
9213
9213
|
return {
|
|
9214
9214
|
command: { type: b, request_id: _.clientMessageId, payload: JSON.parse(JSON.stringify(I)) },
|
|
9215
9215
|
requestedModel: _.model ?? null,
|
|
9216
9216
|
clientScopeId: this.modelClientScopeId,
|
|
9217
|
-
conversationScopeId:
|
|
9217
|
+
conversationScopeId: E,
|
|
9218
9218
|
viewId: `sdk:${this.modelClientScopeId}`,
|
|
9219
|
-
sessionId: _.sessionId ?? w.selections[
|
|
9219
|
+
sessionId: _.sessionId ?? w.selections[E]?.sessionId ?? null,
|
|
9220
9220
|
entrySurface: this.options.entrySurface,
|
|
9221
9221
|
submittedAt: Date.now()
|
|
9222
9222
|
};
|
|
@@ -9277,21 +9277,21 @@ class xt {
|
|
|
9277
9277
|
const I = this.firstResponseTimersByClientMessageId.get(b.userMessageId);
|
|
9278
9278
|
I && (I.sessionId = b.sessionId), this.emit("ack", { clientMessageId: b.userMessageId, sessionId: b.sessionId });
|
|
9279
9279
|
const w = b.sessionId;
|
|
9280
|
-
w && this.getState().sessionId === w && this.directoryHttp.request(`/sessions/${encodeURIComponent(w)}/history`, { limit: 200 }).then((
|
|
9281
|
-
i() && this.getState().sessionId === w && this.state.status !== "closed" && ts(this.clientRuntime, this.modelClientScopeId, w,
|
|
9282
|
-
}).catch((
|
|
9283
|
-
i() && this.getState().sessionId === w && this.handleDirectoryTransportError(
|
|
9280
|
+
w && this.getState().sessionId === w && this.directoryHttp.request(`/sessions/${encodeURIComponent(w)}/history`, { limit: 200 }).then((E) => {
|
|
9281
|
+
i() && this.getState().sessionId === w && this.state.status !== "closed" && ts(this.clientRuntime, this.modelClientScopeId, w, E.turns);
|
|
9282
|
+
}).catch((E) => {
|
|
9283
|
+
i() && this.getState().sessionId === w && this.handleDirectoryTransportError(E);
|
|
9284
9284
|
});
|
|
9285
9285
|
}
|
|
9286
9286
|
(b.cancelled || b.delivery === "failed") && this.clearFirstResponseTimer(b.userMessageId);
|
|
9287
9287
|
}
|
|
9288
9288
|
for (const [b, I] of Object.entries(p.directory.clients)) {
|
|
9289
9289
|
if (!b.startsWith(`background:${this.modelClientScopeId}:`)) continue;
|
|
9290
|
-
const w = pe(p.conversation, p.directory, I),
|
|
9291
|
-
if (this.firstResponseTimersByClientMessageId.size && (u(Wt(w,
|
|
9292
|
-
for (const D of ne(
|
|
9293
|
-
const
|
|
9294
|
-
(y && w.sessionId === this.getState().sessionId || !
|
|
9290
|
+
const w = pe(p.conversation, p.directory, I), E = w.sessionId ? p.conversation.sessions[w.sessionId] : void 0;
|
|
9291
|
+
if (this.firstResponseTimersByClientMessageId.size && (u(Wt(w, E?.queries.current, this.options.backendUrl).messages, w.sessionId), ["failed", "stopped"].includes(w.activity.phase)))
|
|
9292
|
+
for (const D of ne(E?.execution)) this.clearFirstResponseTimer(D);
|
|
9293
|
+
const k = w.activity.phase === "completed" && ne(E?.execution).some((D) => this.firstResponseTimersByClientMessageId.has(D));
|
|
9294
|
+
(y && w.sessionId === this.getState().sessionId || !k && ["completed", "failed", "stopped"].includes(w.activity.phase)) && this.directoryScope.detach(b);
|
|
9295
9295
|
}
|
|
9296
9296
|
const _ = this.getState();
|
|
9297
9297
|
u(_.messages, _.sessionId);
|
|
@@ -9408,7 +9408,7 @@ class xt {
|
|
|
9408
9408
|
throw new ce("Pluno token request was cancelled", !0);
|
|
9409
9409
|
if (typeof d != "string" || !d.trim())
|
|
9410
9410
|
throw new ce("Chat setup did not return a session. Contact your app administrator, then try again.", !1);
|
|
9411
|
-
return this.token = d, this.tokenExpiresAtMs =
|
|
9411
|
+
return this.token = d, this.tokenExpiresAtMs = Ec(d), d;
|
|
9412
9412
|
} finally {
|
|
9413
9413
|
a !== null && window.clearTimeout(a);
|
|
9414
9414
|
}
|
|
@@ -9570,7 +9570,7 @@ class xt {
|
|
|
9570
9570
|
}
|
|
9571
9571
|
destroy() {
|
|
9572
9572
|
if (!this.clientRuntime.isDisposed) {
|
|
9573
|
-
this.disconnect(), this.clearAllFirstResponseTimers(), this.locationChangeCleanup?.(), this.locationChangeCleanup = null, this.cleanupSessionBrowserApis(), this.pageLifecycleCleanup?.(), this.pageLifecycleCleanup = null, this.activeBrowserToolCalls.clear(),
|
|
9573
|
+
this.disconnect(), this.clearAllFirstResponseTimers(), this.locationChangeCleanup?.(), this.locationChangeCleanup = null, this.cleanupSessionBrowserApis(), this.pageLifecycleCleanup?.(), this.pageLifecycleCleanup = null, this.activeBrowserToolCalls.clear(), Ed(this.options.clientId), this.transportIdentity.release(), this.networkCaptureCleanup?.(), this.networkCaptureCleanup = null, this.networkBatchTimer !== null && (window.clearTimeout(this.networkBatchTimer), this.networkBatchTimer = null), this.queuedNetworkEvents = [];
|
|
9574
9574
|
for (const e of Object.values(this.listeners))
|
|
9575
9575
|
e?.clear();
|
|
9576
9576
|
this.accountListeners.clear(), this.interactionListeners.clear(), this.conversationAdapterGeneration++, this.conversationObservation?.dispose(), this.conversationUnsubscribe?.(), this.directoryObservation.dispose(), this.directoryHttp.dispose(), this.clientRuntime.dispose();
|
|
@@ -9662,8 +9662,8 @@ class xt {
|
|
|
9662
9662
|
if (!(w && !w.cancelled && w.delivery !== "accepted" && w.delivery !== "failed"))
|
|
9663
9663
|
if (_?.(), b?.(), w?.delivery === "failed" && !w.cancelled) y(new Error(w.error?.message ?? "Message delivery failed."));
|
|
9664
9664
|
else {
|
|
9665
|
-
const
|
|
9666
|
-
w?.delivery === "accepted" && !w.cancelled && typeof
|
|
9665
|
+
const E = w?.invocation === "user" && w.contextPreparation?.pageContent ? w.context.page?.url : null;
|
|
9666
|
+
w?.delivery === "accepted" && !w.cancelled && typeof E == "string" && c === this.submissionIntentRevision && p === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = E), g(w?.delivery === "accepted" && !w.cancelled ? r : null);
|
|
9667
9667
|
}
|
|
9668
9668
|
};
|
|
9669
9669
|
_ = this.clientRuntime.engine.subscribe(I), b = this.clientRuntime.onDispose(() => {
|
|
@@ -9722,7 +9722,7 @@ class xt {
|
|
|
9722
9722
|
} }), !0);
|
|
9723
9723
|
}
|
|
9724
9724
|
createLocalAttachment(e) {
|
|
9725
|
-
this.options.productVariant === "customer_embedded" &&
|
|
9725
|
+
this.options.productVariant === "customer_embedded" && kd(e);
|
|
9726
9726
|
const s = W(), i = {
|
|
9727
9727
|
id: s,
|
|
9728
9728
|
name: e.name || "attachment",
|
|
@@ -10793,12 +10793,12 @@ class xt {
|
|
|
10793
10793
|
}
|
|
10794
10794
|
const ds = /* @__PURE__ */ new WeakMap();
|
|
10795
10795
|
function Bn(t) {
|
|
10796
|
-
const e = window.__plunoProductAgentNetworkCapture ??
|
|
10796
|
+
const e = window.__plunoProductAgentNetworkCapture ?? kc();
|
|
10797
10797
|
return e.subscribers.add(t), () => {
|
|
10798
10798
|
e.subscribers.delete(t), !(e.subscribers.size > 0) && (e.destroy(), window.__plunoProductAgentNetworkCapture === e && delete window.__plunoProductAgentNetworkCapture);
|
|
10799
10799
|
};
|
|
10800
10800
|
}
|
|
10801
|
-
function
|
|
10801
|
+
function kc() {
|
|
10802
10802
|
const t = /* @__PURE__ */ new Set(), e = (h) => {
|
|
10803
10803
|
t.forEach((f) => {
|
|
10804
10804
|
try {
|
|
@@ -10816,7 +10816,7 @@ function Ec() {
|
|
|
10816
10816
|
}
|
|
10817
10817
|
try {
|
|
10818
10818
|
const y = f instanceof Request ? f : null, _ = Pd(f, y), b = Qn(m?.headers ?? y?.headers);
|
|
10819
|
-
if (!
|
|
10819
|
+
if (!Ee(_, b, m?.body)) {
|
|
10820
10820
|
const w = {
|
|
10821
10821
|
requestId: hs("fetch"),
|
|
10822
10822
|
url: de(_, os),
|
|
@@ -10827,19 +10827,19 @@ function Ec() {
|
|
|
10827
10827
|
startedAt: new Date(p).toISOString()
|
|
10828
10828
|
};
|
|
10829
10829
|
g.then(
|
|
10830
|
-
(
|
|
10831
|
-
xd(
|
|
10830
|
+
(E) => {
|
|
10831
|
+
xd(E, w, p, e).catch(() => {
|
|
10832
10832
|
e({
|
|
10833
10833
|
...w,
|
|
10834
|
-
responseStatus:
|
|
10834
|
+
responseStatus: E.status,
|
|
10835
10835
|
durationMs: Date.now() - p
|
|
10836
10836
|
});
|
|
10837
10837
|
});
|
|
10838
10838
|
},
|
|
10839
|
-
(
|
|
10839
|
+
(E) => {
|
|
10840
10840
|
e({
|
|
10841
10841
|
...w,
|
|
10842
|
-
errorText: de(
|
|
10842
|
+
errorText: de(E instanceof Error ? E.message : String(E)),
|
|
10843
10843
|
durationMs: Date.now() - p
|
|
10844
10844
|
});
|
|
10845
10845
|
}
|
|
@@ -10857,15 +10857,15 @@ function Ec() {
|
|
|
10857
10857
|
requestHeaders: {},
|
|
10858
10858
|
startedAtMs: Date.now(),
|
|
10859
10859
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
10860
|
-
excluded:
|
|
10860
|
+
excluded: Ee(b)
|
|
10861
10861
|
}), _;
|
|
10862
10862
|
}, c = function(f, m) {
|
|
10863
10863
|
const p = n.call(this, f, m), g = ds.get(this);
|
|
10864
|
-
return g && Object.keys(g.requestHeaders).length < Ys && (g.requestHeaders[f] = si(f, m), g.excluded = g.excluded ||
|
|
10864
|
+
return g && Object.keys(g.requestHeaders).length < Ys && (g.requestHeaders[f] = si(f, m), g.excluded = g.excluded || Ee(g.url, g.requestHeaders)), p;
|
|
10865
10865
|
}, d = function(f) {
|
|
10866
10866
|
try {
|
|
10867
10867
|
const m = ds.get(this);
|
|
10868
|
-
m && (m.excluded = m.excluded ||
|
|
10868
|
+
m && (m.excluded = m.excluded || Ee(m.url, m.requestHeaders, f), m.requestBody = Xi(f), m.excluded || this.addEventListener(
|
|
10869
10869
|
"loadend",
|
|
10870
10870
|
() => {
|
|
10871
10871
|
queueMicrotask(() => {
|
|
@@ -10917,7 +10917,7 @@ function Ec() {
|
|
|
10917
10917
|
u = new PerformanceObserver((h) => {
|
|
10918
10918
|
for (const f of h.getEntries()) {
|
|
10919
10919
|
const m = f;
|
|
10920
|
-
if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" ||
|
|
10920
|
+
if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || Ee(m.name))
|
|
10921
10921
|
continue;
|
|
10922
10922
|
const p = performance.timeOrigin + m.startTime;
|
|
10923
10923
|
e({
|
|
@@ -11325,12 +11325,12 @@ function Wc(t, e) {
|
|
|
11325
11325
|
const I = b.getAttribute("data-testid") || b.getAttribute("data-test") || b.getAttribute("data-qa") || b.getAttribute("data-cy") || "";
|
|
11326
11326
|
return `${b.tagName.toLowerCase()}|${m(b)}|${I}`;
|
|
11327
11327
|
}, g = (b, I, w) => {
|
|
11328
|
-
const
|
|
11329
|
-
const S =
|
|
11330
|
-
if (f >= 1e3 && !A || w.has(
|
|
11328
|
+
const E = (k, D) => {
|
|
11329
|
+
const S = k.tagName.toLowerCase(), q = window.getComputedStyle(k), A = u.has(k);
|
|
11330
|
+
if (f >= 1e3 && !A || w.has(k) || r.has(S) || k.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || q.display === "none" || q.visibility === "hidden")
|
|
11331
11331
|
return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
|
|
11332
11332
|
f += 1;
|
|
11333
|
-
const P = m(
|
|
11333
|
+
const P = m(k), T = zn(k), v = a.has(P) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(S) || S === "a" && k.hasAttribute("href"), C = Array.from(k.children).filter((O) => O instanceof HTMLElement), U = /* @__PURE__ */ new Map();
|
|
11334
11334
|
for (const O of C) {
|
|
11335
11335
|
const B = p(O);
|
|
11336
11336
|
U.set(B, (U.get(B) ?? 0) + 1);
|
|
@@ -11347,19 +11347,19 @@ function Wc(t, e) {
|
|
|
11347
11347
|
ii.has(B) || (Ut.push([`… ${$.get(B) ?? 0} similar siblings omitted`]), ii.add(B));
|
|
11348
11348
|
continue;
|
|
11349
11349
|
}
|
|
11350
|
-
const ci =
|
|
11350
|
+
const ci = E(O, D);
|
|
11351
11351
|
ni.push(ci), Ut.push(ci.lines);
|
|
11352
11352
|
}
|
|
11353
11353
|
const Nt = [];
|
|
11354
|
-
if (
|
|
11355
|
-
for (const O of Array.from(
|
|
11356
|
-
O instanceof HTMLElement && Nt.push(
|
|
11354
|
+
if (k.shadowRoot)
|
|
11355
|
+
for (const O of Array.from(k.shadowRoot.children))
|
|
11356
|
+
O instanceof HTMLElement && Nt.push(E(O, D + 1));
|
|
11357
11357
|
const Xe = [...ni, ...Nt], jt = T.length > 0 || v || Xe.some((O) => O.hasUsefulContent), ri = qe(
|
|
11358
11358
|
[T, ...Xe.map((O) => O.textPreview)].filter(Boolean).join(" ")
|
|
11359
|
-
).slice(0, 180), rr =
|
|
11359
|
+
).slice(0, 180), rr = k.hasAttribute("contenteditable") && (T.length > 0 || !k.querySelector("[contenteditable]")), oi = d.some((O) => k.hasAttribute(O)) || !!P || rr, Bt = (k.getClientRects().length > 0 || q.display === "contents") && (s.has(S) || oi || A) && (jt || A) && (!n.has(S) || jt || oi || A), Lt = Bt ? 1 : 0, Oe = [];
|
|
11360
11360
|
if (Bt) {
|
|
11361
11361
|
const O = Xe.some((ue) => ue.containsTextElement), B = i.has(S) && !O ? ri : T;
|
|
11362
|
-
Oe.push($n(
|
|
11362
|
+
Oe.push($n(k, c, o, B.slice(0, 180)));
|
|
11363
11363
|
}
|
|
11364
11364
|
for (const O of Ut)
|
|
11365
11365
|
Oe.push(...ot(O, Lt));
|
|
@@ -11381,7 +11381,7 @@ function Wc(t, e) {
|
|
|
11381
11381
|
containsTextElement: i.has(S) || Xe.some((O) => O.containsTextElement)
|
|
11382
11382
|
};
|
|
11383
11383
|
};
|
|
11384
|
-
return [`--- ${I} ---`, ...
|
|
11384
|
+
return [`--- ${I} ---`, ...E(b, 0).lines].join(`
|
|
11385
11385
|
`);
|
|
11386
11386
|
}, y = [], _ = qe(window.getSelection()?.toString() ?? "");
|
|
11387
11387
|
_ && y.push(`--- selected text ---
|
|
@@ -11627,7 +11627,7 @@ function Hn(t, e) {
|
|
|
11627
11627
|
id: typeof n.id == "string" ? n.id : String(s.id ?? crypto.randomUUID()),
|
|
11628
11628
|
role: "assistant",
|
|
11629
11629
|
...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
|
|
11630
|
-
content:
|
|
11630
|
+
content: ke(
|
|
11631
11631
|
Gi(n.content),
|
|
11632
11632
|
e
|
|
11633
11633
|
),
|
|
@@ -11644,7 +11644,7 @@ function Hn(t, e) {
|
|
|
11644
11644
|
id: String(s.id ?? crypto.randomUUID()),
|
|
11645
11645
|
role: r,
|
|
11646
11646
|
...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
|
|
11647
|
-
content:
|
|
11647
|
+
content: ke(
|
|
11648
11648
|
Gi(n.content),
|
|
11649
11649
|
e
|
|
11650
11650
|
),
|
|
@@ -12038,7 +12038,7 @@ function Ad(t, e) {
|
|
|
12038
12038
|
...e.filter((i) => !s.has(i.callId))
|
|
12039
12039
|
];
|
|
12040
12040
|
}
|
|
12041
|
-
function
|
|
12041
|
+
function Ed(t) {
|
|
12042
12042
|
try {
|
|
12043
12043
|
window.sessionStorage.removeItem(`${Pt}${t}`);
|
|
12044
12044
|
} catch {
|
|
@@ -12077,7 +12077,7 @@ function Wn(t, e) {
|
|
|
12077
12077
|
function Gn(t) {
|
|
12078
12078
|
return t.type || qd(t.name) || "application/octet-stream";
|
|
12079
12079
|
}
|
|
12080
|
-
function
|
|
12080
|
+
function kd(t) {
|
|
12081
12081
|
Jn({
|
|
12082
12082
|
name: t.name,
|
|
12083
12083
|
mimeType: Gn(t),
|
|
@@ -12155,7 +12155,7 @@ function Qn(t) {
|
|
|
12155
12155
|
return e;
|
|
12156
12156
|
}
|
|
12157
12157
|
function si(t, e) {
|
|
12158
|
-
return ir(t) ? Dt : de(
|
|
12158
|
+
return ir(t) ? Dt : de(kt(e), wc);
|
|
12159
12159
|
}
|
|
12160
12160
|
function Pd(t, e) {
|
|
12161
12161
|
return typeof t == "string" ? t : t instanceof URL ? t.toString() : e?.url ?? "";
|
|
@@ -12226,11 +12226,11 @@ function Yi(t) {
|
|
|
12226
12226
|
return t;
|
|
12227
12227
|
const e = t.trim();
|
|
12228
12228
|
if (!e.startsWith("{") && !e.startsWith("["))
|
|
12229
|
-
return
|
|
12229
|
+
return kt(t);
|
|
12230
12230
|
try {
|
|
12231
12231
|
return JSON.stringify(te(JSON.parse(t)));
|
|
12232
12232
|
} catch {
|
|
12233
|
-
return
|
|
12233
|
+
return kt(t);
|
|
12234
12234
|
}
|
|
12235
12235
|
}
|
|
12236
12236
|
function Xn(t) {
|
|
@@ -12239,7 +12239,7 @@ function Xn(t) {
|
|
|
12239
12239
|
const e = t.get("content-type")?.toLowerCase() ?? "", s = t.get("content-length"), i = Number(s);
|
|
12240
12240
|
return s !== null && Number.isInteger(i) && i >= 0 && i <= Xs && (e.startsWith("text/") || e.includes("json") || e.includes("javascript"));
|
|
12241
12241
|
}
|
|
12242
|
-
function
|
|
12242
|
+
function Ee(t, e = {}, s) {
|
|
12243
12243
|
if (Bd(s))
|
|
12244
12244
|
return !0;
|
|
12245
12245
|
const i = Object.entries(e).find(([n]) => n.toLowerCase() === "content-type")?.[1]?.toLowerCase();
|
|
@@ -12256,7 +12256,7 @@ function ke(t, e = {}, s) {
|
|
|
12256
12256
|
}
|
|
12257
12257
|
}
|
|
12258
12258
|
function jd(t, e) {
|
|
12259
|
-
if (
|
|
12259
|
+
if (Ee(t))
|
|
12260
12260
|
return !0;
|
|
12261
12261
|
try {
|
|
12262
12262
|
const s = new URL(t, location.href), i = new URL(e);
|
|
@@ -12322,11 +12322,11 @@ function Kd(t) {
|
|
|
12322
12322
|
}
|
|
12323
12323
|
const Dt = "[REDACTED_SECRET]", le = "[REDACTED_TOKEN]", Vd = "[REDACTED_SIGNED_URL]", Wd = 20, Gd = /^(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|token|api_key|apiKey|apikey|key|secret|signature|sig|password|passwd|pwd|code|state|session|jwt|csrf|csrfToken|xsrf|xsrfToken)$/i, Zn = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, er = /\bBasic\s+[A-Za-z0-9+/=-]{12,}/gi, tr = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, sr = /\b(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|api_key|apiKey|apikey|client_secret|clientSecret|password|secret|token|jwt|csrf|csrfToken|xsrf|xsrfToken)\b\s*[:=]\s*["']?[^"',&\s}]+/gi, Jd = /\bhttps?:\/\/[^\s"'<>]+(?:X-Amz-Signature|X-Goog-Signature|Signature|sig=)[^\s"'<>]*/gi, Qd = /\bhttps?:\/\/[^\s"'<>]+/gi, Xd = /[),.;\]]+$/;
|
|
12324
12324
|
function te(t) {
|
|
12325
|
-
return
|
|
12325
|
+
return Et(t, 0, /* @__PURE__ */ new WeakSet());
|
|
12326
12326
|
}
|
|
12327
|
-
function
|
|
12327
|
+
function Et(t, e, s) {
|
|
12328
12328
|
if (typeof t == "string")
|
|
12329
|
-
return t.startsWith("data:image/") || t.startsWith("data:application/pdf;") ? t :
|
|
12329
|
+
return t.startsWith("data:image/") || t.startsWith("data:application/pdf;") ? t : kt(t);
|
|
12330
12330
|
if (t === null || typeof t != "object")
|
|
12331
12331
|
return t;
|
|
12332
12332
|
if (e >= Wd)
|
|
@@ -12334,10 +12334,10 @@ function kt(t, e, s) {
|
|
|
12334
12334
|
if (s.has(t))
|
|
12335
12335
|
return "[REDACTED_CIRCULAR]";
|
|
12336
12336
|
if (s.add(t), Array.isArray(t))
|
|
12337
|
-
return t.map((n) =>
|
|
12337
|
+
return t.map((n) => Et(n, e + 1, s));
|
|
12338
12338
|
const i = {};
|
|
12339
12339
|
for (const [n, r] of Object.entries(t))
|
|
12340
|
-
n === "pageContent" ? i[n] = r : ir(n) ? i[n] = Dt : i[n] = n.toLowerCase() === "url" ? Yd(r) :
|
|
12340
|
+
n === "pageContent" ? i[n] = r : ir(n) ? i[n] = Dt : i[n] = n.toLowerCase() === "url" ? Yd(r) : Et(r, e + 1, s);
|
|
12341
12341
|
return i;
|
|
12342
12342
|
}
|
|
12343
12343
|
function ir(t) {
|
|
@@ -12345,7 +12345,7 @@ function ir(t) {
|
|
|
12345
12345
|
return e.includes("authorization") || e.includes("cookie") || e.includes("password") || e.includes("passwd") || e === "pwd" || e.includes("secret") || e === "token" || e.endsWith("token") || e.includes("apikey") || e.includes("csrf") || e.includes("xsrf") || e === "jwt" || e === "session" || e === "signature" || e.includes("privatekey");
|
|
12346
12346
|
}
|
|
12347
12347
|
function Yd(t) {
|
|
12348
|
-
return typeof t == "string" ? nr(t) :
|
|
12348
|
+
return typeof t == "string" ? nr(t) : Et(t, 0, /* @__PURE__ */ new WeakSet());
|
|
12349
12349
|
}
|
|
12350
12350
|
function nr(t) {
|
|
12351
12351
|
try {
|
|
@@ -12357,7 +12357,7 @@ function nr(t) {
|
|
|
12357
12357
|
return Zd(t);
|
|
12358
12358
|
}
|
|
12359
12359
|
}
|
|
12360
|
-
function
|
|
12360
|
+
function kt(t) {
|
|
12361
12361
|
return t.replace(Jd, Vd).replace(Qd, el).replace(Zn, `Bearer ${le}`).replace(er, `Basic ${le}`).replace(tr, le).replace(sr, (e, s) => `${s}: ${Dt}`);
|
|
12362
12362
|
}
|
|
12363
12363
|
function Zd(t) {
|
|
@@ -12397,7 +12397,7 @@ export {
|
|
|
12397
12397
|
ec as formatProductAgentTaskPageTitle,
|
|
12398
12398
|
pl as getProductAgentOriginAccessErrorMessage,
|
|
12399
12399
|
hl as installProductAgentPageEnvironment,
|
|
12400
|
-
|
|
12400
|
+
Ei as isProductAgentAuthReconnectError,
|
|
12401
12401
|
dl as isProductAgentRuntimeCommand,
|
|
12402
12402
|
Xo as mergeProductAgentEntityPages,
|
|
12403
12403
|
yt as normalizeProductAgentEntityPage,
|
|
@@ -12406,5 +12406,5 @@ export {
|
|
|
12406
12406
|
il as resolveProductAgentComposerAction,
|
|
12407
12407
|
sl as resolveProductAgentWidgetPresentation,
|
|
12408
12408
|
Yo as selectProductAgentQueryEntities,
|
|
12409
|
-
|
|
12409
|
+
kd as validateProductAgentProviderInputFile
|
|
12410
12410
|
};
|
|
@@ -846,7 +846,7 @@ function au(t, e = null) {
|
|
|
846
846
|
} : void 0);
|
|
847
847
|
return { ...s, ...a ? { auth: a } : {}, submissionGate: r };
|
|
848
848
|
}
|
|
849
|
-
const cu = "0.1.
|
|
849
|
+
const cu = "0.1.322", Cn = {
|
|
850
850
|
version: cu
|
|
851
851
|
};
|
|
852
852
|
function pi(t) {
|
|
@@ -1106,7 +1106,7 @@ function gu(t, e, n, s) {
|
|
|
1106
1106
|
for (const b of m.removed_items) c = Gi(c, b);
|
|
1107
1107
|
for (const b of m.items) c = No(c, b);
|
|
1108
1108
|
for (const b of m.streams) c = Wc(c, b);
|
|
1109
|
-
if (c = Uo(c, m.execution), c = Gi(c, {
|
|
1109
|
+
if (c = Uo(c, m.execution), m.follow_ups_version === 0 && m.follow_ups.length === 0 ? c = { ...c, followUps: [], followUpsVersion: Number.MAX_SAFE_INTEGER } : c = Gi(c, {
|
|
1110
1110
|
type: "conversation.follow_ups.updated",
|
|
1111
1111
|
conversation_id: m.conversation_id,
|
|
1112
1112
|
version: m.follow_ups_version,
|
|
@@ -5280,7 +5280,7 @@ function Dp(t) {
|
|
|
5280
5280
|
const f = h[0];
|
|
5281
5281
|
if (r.before !== null && f.next_cursor === r.before)
|
|
5282
5282
|
throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
|
|
5283
|
-
const m = h.reduce((y, b) => b.execution.version > y.version ? b.execution : y, f.execution), g = h.reduce((y, b) => b.follow_ups_version > y.follow_ups_version ? b : y, f);
|
|
5283
|
+
const m = h.reduce((y, b) => b.execution.version > y.version ? b.execution : y, f.execution), g = h.find((y) => y.follow_ups_version === 0 && y.follow_ups.length === 0) ?? h.reduce((y, b) => b.follow_ups_version > y.follow_ups_version ? b : y, f);
|
|
5284
5284
|
return { snapshot: {
|
|
5285
5285
|
...f,
|
|
5286
5286
|
execution: m,
|
package/package.json
CHANGED