@pluno/product-agent-web 0.1.241 → 0.1.244
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/conversation/display.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/operationTiming.d.ts +1 -1
- package/dist/product-agent-runtime.cjs +1 -1
- package/dist/product-agent-runtime.js +1 -1
- package/dist/product-agent-sdk.js +14 -14
- package/dist/product-agent-widget.js +14 -14
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type PAInvocation = "user" | "automation" | "scheduled_continuation" | "private_continuation";
|
|
2
|
-
export type PAEntrySurface = "extension_sidepanel" | "extension_widget" | "main_web_chat" | "whatsapp" | "automation" | "mcp" | "embedded_widget" | "embedded_custom_ui";
|
|
2
|
+
export type PAEntrySurface = "extension_sidepanel" | "extension_widget" | "main_web_chat" | "whatsapp" | "email" | "automation" | "mcp" | "embedded_widget" | "embedded_custom_ui";
|
|
3
3
|
export type PADisplayAttachment = Readonly<{
|
|
4
4
|
id: string | null;
|
|
5
5
|
name: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { type RenderedErrorEvidence, type UiInvariantEvidence } from "./renderDi
|
|
|
5
5
|
import type { ProductAgentTaskStatus } from "./taskPageTitle";
|
|
6
6
|
import type { ProductAgentEntityQueryData, ProductAgentAccountProjection, ProductAgentSubmissionContext, ProductAgentInteraction, ProductAgentInteractionAction, ProductAgentQueryState } from "./runtimeState";
|
|
7
7
|
export type ProductAgentModel = "anthropic/claude-opus-5" | "anthropic/claude-sonnet-5" | "deepseek/deepseek-chat-v3.1" | "deepseek/deepseek-v4-flash" | "gpt-5.4-nano" | "gpt-5.4-mini" | "gpt-5.4" | "gpt-5.6-luna" | "gpt-5.6-terra" | "gpt-5.6-sol";
|
|
8
|
-
export type ProductAgentEntrySurface = "extension_sidepanel" | "extension_widget" | "main_web_chat" | "whatsapp" | "automation" | "mcp" | "embedded_widget" | "embedded_custom_ui";
|
|
8
|
+
export type ProductAgentEntrySurface = "extension_sidepanel" | "extension_widget" | "main_web_chat" | "whatsapp" | "email" | "automation" | "mcp" | "embedded_widget" | "embedded_custom_ui";
|
|
9
9
|
export type ProductAgentProductVariant = "personal" | "customer_embedded";
|
|
10
10
|
export type ProductAgentLegacyEntrySurface = "sidepanel" | "browser_extension_page_ui" | "sdk_preview_widget" | "browser_extension_sdk_preview" | "sdk-preview" | "main_chat" | "automation_run";
|
|
11
11
|
export type ProductAgentInvocation = "user" | "automation" | "scheduled_continuation" | "private_continuation";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export declare const OPERATION_TIMING_STAGES: readonly ["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"];
|
|
2
2
|
export type OperationTimingStage = typeof OPERATION_TIMING_STAGES[number];
|
|
3
3
|
export type OperationTiming = {
|
|
4
|
-
entrySurface?: "extension_sidepanel" | "extension_widget" | "main_web_chat" | "embedded_widget" | "embedded_custom_ui" | "automation" | "mcp" | "whatsapp";
|
|
4
|
+
entrySurface?: "extension_sidepanel" | "extension_widget" | "main_web_chat" | "embedded_widget" | "embedded_custom_ui" | "automation" | "mcp" | "whatsapp" | "email";
|
|
5
5
|
operation: "send" | "stop";
|
|
6
6
|
layer: "renderer" | "sdk" | "extension" | "http";
|
|
7
7
|
stage: OperationTimingStage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function g(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class P{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=g(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=g(e),this.trailingLoad=null,this.publish())}reset(){this.state=g(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,i=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:i},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||i!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||i!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function f(s){const e={},t=[];for(const i of s.entities)e[i.id]||t.push(i.id),e[i.id]=i;return{entitiesById:e,ids:t,nextCursor:s.nextCursor}}function j(s,e,t){if(t==="replace"||s===null)return e;const i={...s.entitiesById,...e.entitiesById},n=[...s.ids];for(const r of e.ids)s.entitiesById[r]||n.push(r);return{entitiesById:i,ids:n,nextCursor:e.nextCursor}}function U(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function V(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function J(s,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:s??{allowed:!0,reason:"allowed",actions:[]}}function W(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function Y(s){return s?s.submissionGate?.allowed===!1?{state:"action_required",reason:s.submissionGate.reason}:s.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:s.creditLimit!==null&&s.creditLimit>0&&s.creditsRemaining!==null&&s.creditsRemaining>0&&s.creditsRemaining/s.creditLimit<=.2?{state:"low_credits"}:s.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function X(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function ee(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const L="Pluno is reconnecting. Try again in a moment.";function $(s){return(s instanceof Error?s.message:s)===L}class te{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new P(`${e}:recent`,async({cursor:n})=>f(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),j),this.pinnedQuery=new P(`${e}:pinned`,async()=>f({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),i=[...m(t.data),...m(e.data)],n=new Map(i.map(d=>[d.id,d])),r=Array.from(n.values()).map(d=>this.applyOverrides(d,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(d=>!n.has(d.id)).reverse(),a=e.data||t.data||o.length>0?f({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:se(e,t),data:a,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,i=>({...i,isActive:t}))}setPinned(e,t){const i={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,i),this.updateEntity(e,n=>({...n,isPinned:t})),i}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,i){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:i})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,i=>({...i,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...m(this.pinnedQuery.getState().data),...m(this.recentQuery.getState().data)],t=new Set(e.map(i=>i.id));for(const i of this.optimisticEntities.keys())t.has(i)&&this.optimisticEntities.delete(i);for(const i of e)this.applyOverrides(i,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const i=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...i.sessions),t=i.nextCursor}while(t);return e}applyOverrides(e,t){let i=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):i={...i,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):i={...i,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(i={...i,customTitle:this.titleOverrides.get(e.id)??null}),i}updateProjection(){this.publish()}updateEntity(e,t){const i=this.optimisticEntities.get(e);i&&this.optimisticEntities.set(e,t(i)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function m(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function se(s,e){return s.status==="error"||e.status==="error"?"error":s.status==="loading"||e.status==="loading"?"loading":s.status==="refreshing"||e.status==="refreshing"?"refreshing":s.status==="loading_more"?"loading_more":s.status==="ready"||e.status==="ready"?"ready":"not_requested"}function R(s){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(s);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function b(s){if(s===null||typeof s=="string"||typeof s=="boolean")return!0;if(typeof s=="number")return Number.isFinite(s);if(Array.isArray(s))return s.every(b);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(b)}function K(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(K),Object.freeze(s)),s}function ie(s){if(!b(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function ne(s,e){if(!e)return!1;const t=s.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const i=Object.values(s.items).sort((r,o)=>R(r.created_at).localeCompare(R(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of i)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&s.streams[r.id]?.state==="finished"&&s.streams[r.id].revision>=r.data.revision))return!0;return!1}class re{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(T).map(i=>[this.getDecisionKey(i),i])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const i=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(i);if(n&&n.version>=t.version)continue;if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");const r=n?.payload.kind==="personal_channel"&&n.lifecycle==="completed"?"completed":t.lifecycle,o=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,K(ie({...t,lifecycle:r,payload:o}))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id)}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={share:null,integrations:[],channel:null},i=e?this.conversationReader(e):null;if(!i)return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,o)=>r.version-o.version||r.id.localeCompare(o.id));for(const r of n){const o=r.payload;if(o.kind==="sharing"){if(t.share=null,!o.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const a=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:o.variant,userPrompt:a?.type==="user_message"?a.data.content:"",assistantAnswer:""},terminal:!o.wait_for_terminal||ne(i,r.user_message_id)}}else o.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:o.request_id,appSlug:o.app_slug,appName:o.app_name,appLogo:o.app_logo??void 0,expiresAt:o.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(o.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:o.request_id,channel:o.channel,managementUrl:o.management_url},lifecycle:r.lifecycle}}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(T).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));return i!==void 0&&i>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));if(i!==void 0&&i>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const i=this.getExactKey(e),n=this.scheduledEligibility.get(i);return n!==void 0?n:(this.scheduledEligibility.set(i,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(i=>i>e),...Array.from(this.decisions.values()).map(i=>i.nextEligibleAt?Date.parse(i.nextEligibleAt):Number.NaN).filter(i=>Number.isFinite(i)&&i>e)];return t.length>0?Math.min(...t):null}act(e,t,i={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,i));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,i){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!F(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=i.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,i.snoozeUntil)},o=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),a=new Map(this.decisions);return a.set(o,r),await this.storage.save([...a.values()]),this.decisions=a,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,i,n){if(t==="later")return new Date(i.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=i.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=_(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${_(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${_(e.scope)}:category:${e.category}`}}function oe(s,e){return{load:async()=>z(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function z(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(T):[]}function _(s){return`${s.level}:${s.key}`}function F(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function T(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&F(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ae={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},de=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function Q(s,e){if(!e)return I(s);const t=I(s),i=`${ae[e]} Pluno`;return t?`${i}: ${t}`:i}class ce{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,i=await e();i===void 0||t!==this.liveStatusVersion||(i?this.applyStatus(i):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=I(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,i=this.lastAppliedTitle===null?I(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):i!==e&&this.titleDocument.setTitle(i)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=Q(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function le(s){return{getTitle:()=>s.title,setTitle:e=>{s.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(s.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function I(s){return s.replace(de,"")}const p=s=>typeof s=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(s)?s:null;function ue(s){if(!s||typeof s!="object")return!1;const e=s,t=n=>Number.isSafeInteger(n)&&n>=0,i=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&p(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||p(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&p(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||i(e.lastIntent))&&(e.lastSelection===null||i(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(i)}function B(s){if(!s||typeof s!="object")return!1;const e=s;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 q=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],E=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),v=s=>s===null||E(s),pe=s=>typeof s=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(s)&&Number.isFinite(Date.parse(s));function G(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&v(e.sessionId)&&E(e.itemId)&&v(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&v(e.runId)&&(e.createdAt===null||pe(e.createdAt))}function he(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner"].includes(i))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(i=>i===null||t(i))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(i=>i===null||p(i)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(i=>typeof i=="boolean")&&["state","account","interactions","local","sidepanel_layout"].includes(e.renderSource)&&(e.owner===void 0||ue(e.owner))}function H(s){if(!s||typeof s!="object"||Object.keys(s).some(i=>i!=="before"&&i!=="current"))return!1;const e=i=>{if(!i||typeof i!="object")return!1;const n=i;return Object.keys(i).every(r=>[...q,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context"].includes(r))&&(n.context===void 0||he(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&v(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&q.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(E))},t=s;return(t.before===null||e(t.before))&&e(t.current)}function ge(s){if(s.details!==void 0&&!b(s.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:s.code,message:s.message,retryable:s.retryable,...s.details===void 0?{}:{details:s.details}}}function S(s,e="runtime_error"){const t=s!==null&&typeof s=="object"?s:null,i=typeof s=="string"?s:t&&"message"in t&&typeof t.message=="string"?t.message:"",n=t&&"code"in t&&typeof t.code=="string"&&t.code.trim()?t.code:e,r=t&&"details"in t?t.details:null,o=r&&typeof r=="object"?r:{},a={...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 ge({code:n,message:i.trim()&&i.trim()!=="[object Object]"?i:"The Product Agent operation failed. Try again.",retryable:!!(t&&"retryable"in t&&t.retryable===!0),...Object.keys(a).length?{details:a}:{}})}function Z(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(i))&&p(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(i=>i==null||t(i))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(i=>i===null||p(i)!==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(i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(i))}const fe=["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"],me=Math.random().toString(36).slice(2);let ye=0;const C=()=>`timing:${me}:${++ye}`,y=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function M(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs"].includes(t))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&fe.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&y(e.spanId)&&y(e.requestId)&&(e.clientMessageId===null||y(e.clientMessageId))&&(e.sessionId===null||y(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function k(s,e){if(!s)return{mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,o,a)=>{const d={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o))};s&&M(d)&&Promise.resolve().then(()=>s(d)).catch(()=>{})};return{mark:n=>i(n,"observed",t,C()),measure(n,r){const o=performance.now(),a=C();return i(n,"started",o,a),r().then(d=>(i(n,"completed",o,a),d),d=>{throw i(n,"failed",o,a),d})}}}const A=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function ve(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&A(e.sessionId)&&A(e.responseItemId)&&A(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}const D=500;function be(s){const e=s.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>D?`${e.slice(0,D-1)}…`:e}function Ie(s,e,t="stopped",i){const n=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(a=>a.role==="user").slice(-1)[0]?.id].filter(a=>!!a)),r=s.messages.filter(a=>!(a.dataType==="run_status"&&a.loading&&n.has(a.respondsToUserMessageId??""))).map(a=>n.has(a.respondsToUserMessageId??"")?{...a,loading:!1}:a);for(const a of n)r.some(d=>d.respondsToUserMessageId===a&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||r.some(d=>d.role==="user"&&d.id===a)&&r.push({id:`local-interrupted:${a}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":"Run stopped by user.",createdAt:e,respondsToUserMessageId:a});const o=s.segments?.map(a=>({...a,outcomeIds:[...a.outcomeIds,...r.filter(d=>d.id===`local-interrupted:${a.userMessageId}`&&!a.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...s,messages:r,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&r.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const _e={"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 Se(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(_e,s.slice(13))}function x(s){return{...s.id===void 0?{}:{id:s.id},name:s.name,mimeType:s.mimeType,sizeBytes:s.sizeBytes,...s.sandboxPath===void 0?{}:{sandboxPath:s.sandboxPath},...s.storageKey===void 0?{}:{storageKey:s.storageKey},...s.fileUrl===void 0?{}:{fileUrl:s.fileUrl}}}function Ae(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;switch(e.type){case"runtime.connect":case"session.new":case"run.retry":return!0;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return ve(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return M(e.timing);case"runtime.report_displayed_error":return(e.httpRequest===void 0||Z(e.httpRequest))&&(e.historyRefreshFailure===void 0||B(e.historyRefreshFailure))&&(e.renderedError===void 0||G(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||H(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Se(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class we{constructor(e,t,i){this.adapter=t,this.state=w(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=g("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Set;operationQueue=Promise.resolve();destroyed=!1;on(e,t){const i=this.listeners[e]??new Set;return i.add(t),this.listeners[e]=i,()=>i.delete(t)}getState(){const e=w(this.state);for(const[n,r]of this.submissionPreviews)e.messages.some(o=>o.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(o=>({...o}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error,e.lastErrorCode="message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews];if(!t.length)return e;const i=Ie(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:i.messages,segments:i.segments}:i}updateProjection(e,t,i,n,r){if(this.destroyed)return;const o=this.getState();(o.user?.id!==e.user?.id||o.selectionKey!==void 0&&o.selectionKey!==e.selectionKey||o.selectionKey===void 0&&o.sessionId!==null&&o.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const a of e.messages)a.role==="user"&&this.submissionPreviews.delete(a.id);this.state=w(e);for(const a of this.stopPreviews)e.messages.some(d=>d.respondsToUserMessageId===a&&!d.provisional&&d.loading!==!0&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"&&(d.streamState===void 0||["finished","stopped","failed"].includes(d.streamState))))&&this.stopPreviews.delete(a);if(o.user?.id===e.user?.id)for(const a of this.state.messages){if(a.role!=="user"||!a.attachments?.length)continue;const d=o.messages.find(c=>c.role==="user"&&c.id===a.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&d)||(a.attachments=Pe(d?.attachments,a.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=N(i);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const a of this.accountListeners)a(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0,this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionPreviews.clear(),this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}warmup(e="panel_open"){return this.adapter.dispatch({type:"runtime.warmup",reason:e}).then(()=>{})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&M(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,i){i!==void 0&&!H(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;n!==void 0&&!G(n)||r!==void 0&&!B(r)||this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...Z(o)?{httpRequest:o}:{},...i?{displayedMessage:be(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim(),n=t.attachments??[];if(!i&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(c=>c.id?[c.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(c=>({...c}))}});const d=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:o},a);return this.emit("state",this.getState()),d.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,o=k(c=>{i===this.submissionGeneration&&this.reportOperationTiming(c)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],d=!1;if(i!==this.submissionGeneration)return null;try{if(!await o.measure("staging_ipc",async()=>{const l=await this.enqueueOperation(async()=>this.destroyed||i!==this.submissionGeneration?null:{result:this.adapter.dispatch({type:"conversation.stage",initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(x):void 0,submittedAt:t.submittedAt})});return l?(await l.result,l):null})||i!==this.submissionGeneration)return null;if(d=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of a){if(u.sandboxPath||u.storageKey){l.push(u);continue}const O=u.id?this.attachmentFiles.get(u.id):void 0;if(!O)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(O,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}a=l}const h=await o.measure("send_ipc",()=>this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,...t.automationOnboarding?{automationOnboarding:!0}:{},attachments:a.length>0?a.map(x):void 0}));if(i!==this.submissionGeneration)return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),h?.clientMessageId??r}catch(c){if(i!==this.submissionGeneration)return null;if($(c))for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=S(c).message,this.emit("state",this.getState())),d&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:S(c).message}),c}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}retryLastMessage(){return this.dispatch({type:"run.retry"}),!0}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=k(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:i[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:i,promise:Promise.resolve()};this.pendingStop=r;for(const d of i)this.stopPreviews.add(d);const o=this.submissionGeneration;r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(o===this.submissionGeneration){for(const c of i)this.stopPreviews.delete(c);this.stopError=S(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState());const a=r.promise;return this.operationQueue=a.then(()=>{},()=>{}),a.then(()=>{})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const i of this.pendingTransfers.values())for(const n of i)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const i of this.submissionPreviews.values())i.pending=!1;return this.operationQueue=Promise.resolve(),t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const i=this.getSessionHistoryState().data;return{sessions:i?i.ids.map(n=>i.entitiesById[n]):[],nextCursor:i?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return N(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,i,n={}){return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),this.dispatch({type:"session.load",sessionId:e}).then(()=>{})}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const i=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=i,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:i}).then(()=>{})}dispatch(e){return e.type==="session.list"?this.adapter.dispatch(e):this.enqueueOperation(()=>this.adapter.dispatch(e))}enqueueOperation(e){const t=this.operationQueue.then(e);return this.operationQueue=t.then(()=>{},()=>{}),t}emit(e,t){const i=this.listeners[e];for(const n of i??[])n(t)}}function Pe(s,e){if(!e||!s)return e;const t=new Map;for(const i of s){const n=i.previewUrl;i.id&&n&&t.set(i.id,n)}return e.map(i=>{const n=i.id?t.get(i.id):void 0;return n?{...i,previewUrl:n}:i})}function w(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},i=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),i&&Object.defineProperty(t,"assistantDraftItemId",{value:i,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:s.activeScheduledFollowUps?.map(e=>({...e}))??null}}function N(s){return{...s,data:s.data?f({entities:U(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=L;exports.ProductAgentInteractionManager=re;exports.ProductAgentQueryController=P;exports.ProductAgentRemoteRuntimeClient=we;exports.ProductAgentSessionHistoryManager=te;exports.ProductAgentTaskPageTitleController=ce;exports.canSubmitPersonalProductAgentMessage=X;exports.createLocalStorageInteractionDecisionStorage=oe;exports.createProductAgentQueryState=g;exports.createProductAgentTaskPageTitleDocument=le;exports.formatProductAgentTaskPageTitle=Q;exports.hasProductAgentPaidCreditFallback=W;exports.isProductAgentAuthReconnectError=$;exports.isProductAgentRuntimeCommand=Ae;exports.mergeProductAgentEntityPages=j;exports.normalizeProductAgentEntityPage=f;exports.readLocalStorageInteractionDecisions=z;exports.reconcileProductAgentSubmissionGate=J;exports.resolveProductAgentBillingPresentation=Y;exports.resolveProductAgentComposerAction=ee;exports.resolveProductAgentWidgetPresentation=V;exports.selectProductAgentQueryEntities=U;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function g(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class P{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=g(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=g(e),this.trailingLoad=null,this.publish())}reset(){this.state=g(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,i=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:i},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||i!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||i!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function f(s){const e={},t=[];for(const i of s.entities)e[i.id]||t.push(i.id),e[i.id]=i;return{entitiesById:e,ids:t,nextCursor:s.nextCursor}}function j(s,e,t){if(t==="replace"||s===null)return e;const i={...s.entitiesById,...e.entitiesById},n=[...s.ids];for(const r of e.ids)s.entitiesById[r]||n.push(r);return{entitiesById:i,ids:n,nextCursor:e.nextCursor}}function U(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function V(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function J(s,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:s??{allowed:!0,reason:"allowed",actions:[]}}function W(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function Y(s){return s?s.submissionGate?.allowed===!1?{state:"action_required",reason:s.submissionGate.reason}:s.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:s.creditLimit!==null&&s.creditLimit>0&&s.creditsRemaining!==null&&s.creditsRemaining>0&&s.creditsRemaining/s.creditLimit<=.2?{state:"low_credits"}:s.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function X(s){return s.submissionAllowed&&s.isAuthenticated&&s.hasWorkspace&&!s.isWebsiteBlocked&&s.isCurrentPageResolved&&!s.isSubmitting&&!s.hasPendingMessage}function ee(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}const L="Pluno is reconnecting. Try again in a moment.";function $(s){return(s instanceof Error?s.message:s)===L}class te{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new P(`${e}:recent`,async({cursor:n})=>f(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),j),this.pinnedQuery=new P(`${e}:pinned`,async()=>f({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),i=[...m(t.data),...m(e.data)],n=new Map(i.map(d=>[d.id,d])),r=Array.from(n.values()).map(d=>this.applyOverrides(d,this.completedRefreshSequence)),o=Array.from(this.optimisticEntities.values()).filter(d=>!n.has(d.id)).reverse(),a=e.data||t.data||o.length>0?f({entities:[...o,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:se(e,t),data:a,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,i=>({...i,isActive:t}))}setPinned(e,t){const i={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,i),this.updateEntity(e,n=>({...n,isPinned:t})),i}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,i){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:i})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,i=>({...i,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...m(this.pinnedQuery.getState().data),...m(this.recentQuery.getState().data)],t=new Set(e.map(i=>i.id));for(const i of this.optimisticEntities.keys())t.has(i)&&this.optimisticEntities.delete(i);for(const i of e)this.applyOverrides(i,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const i=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...i.sessions),t=i.nextCursor}while(t);return e}applyOverrides(e,t){let i=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):i={...i,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):i={...i,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(i={...i,customTitle:this.titleOverrides.get(e.id)??null}),i}updateProjection(){this.publish()}updateEntity(e,t){const i=this.optimisticEntities.get(e);i&&this.optimisticEntities.set(e,t(i)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function m(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function se(s,e){return s.status==="error"||e.status==="error"?"error":s.status==="loading"||e.status==="loading"?"loading":s.status==="refreshing"||e.status==="refreshing"?"refreshing":s.status==="loading_more"?"loading_more":s.status==="ready"||e.status==="ready"?"ready":"not_requested"}function R(s){const e=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(?:Z|\+00:00)$/.exec(s);if(!e)throw new Error("Display timestamps must retain the backend UTC precision.");return`${e[1]}.${(e[2]??"").padEnd(6,"0")}`}function b(s){if(s===null||typeof s=="string"||typeof s=="boolean")return!0;if(typeof s=="number")return Number.isFinite(s);if(Array.isArray(s))return s.every(b);if(typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e!==Object.prototype&&e!==null?!1:Object.values(s).every(b)}function K(s){return s!==null&&typeof s=="object"&&!Object.isFrozen(s)&&(Object.values(s).forEach(K),Object.freeze(s)),s}function ie(s){if(!b(s))throw new Error("Conversation inputs must be JSON-safe values.");return JSON.parse(JSON.stringify(s))}function ne(s,e){if(!e)return!1;const t=s.executionByUserMessage[e];if(t)return["completed","stopped","failed"].includes(t.phase);const i=Object.values(s.items).sort((r,o)=>R(r.created_at).localeCompare(R(o.created_at))||r.id.localeCompare(o.id));let n=!1;for(const r of i)if(r.type==="user_message"&&(n=r.id===e),!!n&&(r.type==="stopped"||r.type==="error"||r.type==="final_response"&&s.streams[r.id]?.state==="finished"&&s.streams[r.id].revision>=r.data.revision))return!0;return!1}class re{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(T).map(i=>[this.getDecisionKey(i),i])),this.initialized=!0)}storage;conversationReader=null;sources=new Map;invalidateAuth=()=>{};installConversationSources(e,t=()=>{}){this.sources.clear(),this.conversationReader=e,this.invalidateAuth=t}receiveConversationSources(e){for(const t of e){if(!Number.isSafeInteger(t.version)||t.version<0)throw new Error("Invalid interaction source version.");const i=JSON.stringify([t.conversation_id,t.id]),n=this.sources.get(i);if(n&&n.version>=t.version)continue;if(n&&n.payload.kind!==t.payload.kind)throw new Error("Interaction kind changed.");const r=n?.payload.kind==="personal_channel"&&n.lifecycle==="completed"?"completed":t.lifecycle,o=n?.payload.kind==="sharing"&&t.payload.kind==="sharing"?{...t.payload,variant:n.payload.variant}:t.payload;this.sources.set(i,K(ie({...t,lifecycle:r,payload:o}))),t.payload.kind==="integration_auth"&&this.invalidateAuth(t.payload.request_id)}}getIntegrationSource(e){return[...this.sources.values()].find(t=>t.payload.kind==="integration_auth"&&t.payload.request_id===e&&this.conversationReader?.(t.conversation_id))??null}getConversationInputs(e){if(!this.conversationReader)return;const t={share:null,integrations:[],channel:null},i=e?this.conversationReader(e):null;if(!i)return t;const n=[...this.sources.values()].filter(r=>r.conversation_id===e).sort((r,o)=>r.version-o.version||r.id.localeCompare(o.id));for(const r of n){const o=r.payload;if(o.kind==="sharing"){if(t.share=null,!o.eligible||r.lifecycle!=="pending"||r.invocation!=="user"||!["main_web_chat","automation","extension_sidepanel","extension_widget"].includes(r.entry_surface??""))continue;const a=r.user_message_id?i.items[r.user_message_id]:null;t.share={revision:r.version,candidate:{id:r.id,variant:o.variant,userPrompt:a?.type==="user_message"?a.data.content:"",assistantAnswer:""},terminal:!o.wait_for_terminal||ne(i,r.user_message_id)}}else o.kind==="integration_auth"?t.integrations.push({revision:r.version,request:{type:"pipedream_auth_required",authRequestId:o.request_id,appSlug:o.app_slug,appName:o.app_name,appLogo:o.app_logo??void 0,expiresAt:o.expires_at},lifecycle:r.lifecycle==="pending"&&Date.parse(o.expires_at)<=Date.now()?"expired":r.lifecycle}):t.channel={revision:r.version,request:{type:"personal_channel_connection_required",requestId:o.request_id,channel:o.channel,managementUrl:o.management_url},lifecycle:r.lifecycle}}return t}decisions=new Map;scheduledEligibility=new Map;initialized=!1;actionQueue=Promise.resolve();async initialize(){if(this.initialized)return;const e=await this.storage.load();this.decisions=new Map(e.filter(T).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));return i!==void 0&&i>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const i=this.scheduledEligibility.get(this.getExactKey(e));if(i!==void 0&&i>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const i=this.getExactKey(e),n=this.scheduledEligibility.get(i);return n!==void 0?n:(this.scheduledEligibility.set(i,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(i=>i>e),...Array.from(this.decisions.values()).map(i=>i.nextEligibleAt?Date.parse(i.nextEligibleAt):Number.NaN).filter(i=>Number.isFinite(i)&&i>e)];return t.length>0?Math.min(...t):null}act(e,t,i={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,i));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,i){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!F(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=i.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,i.snoozeUntil)},o=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),a=new Map(this.decisions);return a.set(o,r),await this.storage.save([...a.values()]),this.decisions=a,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,i,n){if(t==="later")return new Date(i.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=i.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=_(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${_(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${_(e.scope)}:category:${e.category}`}}function oe(s,e){return{load:async()=>z(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function z(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(T):[]}function _(s){return`${s.level}:${s.key}`}function F(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function T(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&F(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const ae={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},de=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function Q(s,e){if(!e)return I(s);const t=I(s),i=`${ae[e]} Pluno`;return t?`${i}: ${t}`:i}class ce{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,i=await e();i===void 0||t!==this.liveStatusVersion||(i?this.applyStatus(i):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=I(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,i=this.lastAppliedTitle===null?I(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):i!==e&&this.titleDocument.setTitle(i)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=Q(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function le(s){return{getTitle:()=>s.title,setTitle:e=>{s.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(s.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function I(s){return s.replace(de,"")}const p=s=>typeof s=="string"&&/^[a-zA-Z0-9:_.-]{1,160}$/.test(s)?s:null;function ue(s){if(!s||typeof s!="object")return!1;const e=s,t=n=>Number.isSafeInteger(n)&&n>=0,i=n=>n&&typeof n=="object"&&Object.keys(n).every(r=>["sequence","at","type","changed","generation","sessionId","scopeId","requestId","effectId","clientScopeId","reason","effectKind","eventType","itemCount","removedCount","projectionReady"].includes(r))&&t(n.sequence)&&t(n.at)&&p(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||p(r)!==null)&&(n.projectionReady===null||typeof n.projectionReady=="boolean");return Object.keys(e).every(n=>["ownerId","revision","dropped","lastIntent","lastSelection","transitions"].includes(n))&&p(e.ownerId)!==null&&t(e.revision)&&t(e.dropped)&&(e.lastIntent==null||i(e.lastIntent))&&(e.lastSelection===null||i(e.lastSelection))&&Array.isArray(e.transitions)&&e.transitions.length<=16&&e.transitions.every(i)}function B(s){if(!s||typeof s!="object")return!1;const e=s;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 q=["messageKeys","canonicalItemKeys","terminalResponseKeys","toolCallKeys","activeResponseKeys"],E=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s),v=s=>s===null||E(s),pe=s=>typeof s=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(s)&&Number.isFinite(Date.parse(s));function G(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(s).every(t=>["sessionId","itemId","userMessageId","createdAt","runId","retryable"].includes(t))&&v(e.sessionId)&&E(e.itemId)&&v(e.userMessageId)&&(e.retryable===void 0||typeof e.retryable=="boolean")&&v(e.runId)&&(e.createdAt===null||pe(e.createdAt))}function he(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["capturedAt","selectionKey","userId","loading","draft","thinking","connected","hasError","phase","queryStatus","queryRequestId","queryUpdatedAt","renderSource","selectionFencePending","guardCreatedAt","owner"].includes(i))&&t(e.capturedAt)&&[e.queryUpdatedAt,e.guardCreatedAt].every(i=>i===null||t(i))&&[e.selectionKey,e.userId,e.phase,e.queryStatus,e.queryRequestId].every(i=>i===null||p(i)!==null)&&[e.loading,e.draft,e.thinking,e.connected,e.hasError,e.selectionFencePending].every(i=>typeof i=="boolean")&&["state","account","interactions","local","sidepanel_layout"].includes(e.renderSource)&&(e.owner===void 0||ue(e.owner))}function H(s){if(!s||typeof s!="object"||Object.keys(s).some(i=>i!=="before"&&i!=="current"))return!1;const e=i=>{if(!i||typeof i!="object")return!1;const n=i;return Object.keys(i).every(r=>[...q,"sessionId","runtimeItemCount","welcome","truncated","thinkingSequence","context"].includes(r))&&(n.context===void 0||he(n.context))&&(n.thinkingSequence===void 0||Array.isArray(n.thinkingSequence)&&n.thinkingSequence.length<=20&&n.thinkingSequence.every(r=>r==="user"||r==="thinking"))&&v(n.sessionId)&&Number.isSafeInteger(n.runtimeItemCount)&&n.runtimeItemCount>=0&&typeof n.welcome=="boolean"&&typeof n.truncated=="boolean"&&q.every(r=>Array.isArray(n[r])&&n[r].length<=20&&n[r].every(E))},t=s;return(t.before===null||e(t.before))&&e(t.current)}function ge(s){if(s.details!==void 0&&!b(s.details))throw new TypeError("Product Agent transported error details must be JSON-safe.");return{code:s.code,message:s.message,retryable:s.retryable,...s.details===void 0?{}:{details:s.details}}}function S(s,e="runtime_error"){const t=s!==null&&typeof s=="object"?s:null,i=typeof s=="string"?s:t&&"message"in t&&typeof t.message=="string"?t.message:"",n=t&&"code"in t&&typeof t.code=="string"&&t.code.trim()?t.code:e,r=t&&"details"in t?t.details:null,o=r&&typeof r=="object"?r:{},a={...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 ge({code:n,message:i.trim()&&i.trim()!=="[object Object]"?i:"The Product Agent operation failed. Try again.",retryable:!!(t&&"retryable"in t&&t.retryable===!0),...Object.keys(a).length?{details:a}:{}})}function Z(s){if(!s||typeof s!="object")return!1;const e=s,t=i=>Number.isSafeInteger(i)&&i>=0;return Object.keys(e).every(i=>["requestId","method","route","status","abortTrigger","owner","elapsedMs","attempt","category","responseHeadersMs","responseBodyMs","queryRequestId","ownerId","authorityGeneration","sessionId","release","upstreamRequestId","upstreamTraceId"].includes(i))&&p(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(i=>i==null||t(i))&&t(e.elapsedMs)&&t(e.attempt)&&e.attempt>=1&&e.attempt<=10&&[e.queryRequestId,e.ownerId,e.sessionId].every(i=>i===null||p(i)!==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(i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9_:;=./-]{1,160}$/.test(i))}const fe=["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"],me=Math.random().toString(36).slice(2);let ye=0;const C=()=>`timing:${me}:${++ye}`,y=s=>typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function M(s){if(!s||typeof s!="object")return!1;const e=s;return Object.keys(e).every(t=>["entrySurface","operation","layer","stage","status","spanId","requestId","clientMessageId","sessionId","occurredAt","durationMs"].includes(t))&&(e.entrySurface===void 0||["extension_sidepanel","extension_widget","main_web_chat","embedded_widget","embedded_custom_ui","automation","mcp","whatsapp","email"].includes(e.entrySurface))&&["send","stop"].includes(e.operation)&&["renderer","sdk","extension","http"].includes(e.layer)&&fe.includes(e.stage)&&["started","completed","failed","observed"].includes(e.status)&&y(e.spanId)&&y(e.requestId)&&(e.clientMessageId===null||y(e.clientMessageId))&&(e.sessionId===null||y(e.sessionId))&&typeof e.occurredAt=="string"&&e.occurredAt.length<=40&&Number.isFinite(Date.parse(e.occurredAt))&&Number.isSafeInteger(e.durationMs)&&e.durationMs>=0}function k(s,e){if(!s)return{mark:n=>{},measure:(n,r)=>r()};const t=performance.now(),i=(n,r,o,a)=>{const d={...e,stage:n,status:r,spanId:a,occurredAt:new Date().toISOString(),durationMs:Math.max(0,Math.round(performance.now()-o))};s&&M(d)&&Promise.resolve().then(()=>s(d)).catch(()=>{})};return{mark:n=>i(n,"observed",t,C()),measure(n,r){const o=performance.now(),a=C();return i(n,"started",o,a),r().then(d=>(i(n,"completed",o,a),d),d=>{throw i(n,"failed",o,a),d})}}}const A=s=>s===null||typeof s=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(s);function ve(s){if(!s||typeof s!="object")return!1;const e=s;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&A(e.sessionId)&&A(e.responseItemId)&&A(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}const D=500;function be(s){const e=s.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>D?`${e.slice(0,D-1)}…`:e}function Ie(s,e,t="stopped",i){const n=new Set(i??[s.assistantDraftRespondsToUserMessageId,s.activeResponseUserMessageId,s.messages.filter(a=>a.role==="user").slice(-1)[0]?.id].filter(a=>!!a)),r=s.messages.filter(a=>!(a.dataType==="run_status"&&a.loading&&n.has(a.respondsToUserMessageId??""))).map(a=>n.has(a.respondsToUserMessageId??"")?{...a,loading:!1}:a);for(const a of n)r.some(d=>d.respondsToUserMessageId===a&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"))||r.some(d=>d.role==="user"&&d.id===a)&&r.push({id:`local-interrupted:${a}`,role:"system",dataType:"run_status",provisional:t==="stopping",content:t==="stopping"?"Stopping…":"Run stopped by user.",createdAt:e,respondsToUserMessageId:a});const o=s.segments?.map(a=>({...a,outcomeIds:[...a.outcomeIds,...r.filter(d=>d.id===`local-interrupted:${a.userMessageId}`&&!a.outcomeIds.includes(d.id)).map(d=>d.id)]}));return{...s,messages:r,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,segments:o,activity:{phase:t,activeItemId:null},isLoadingSession:s.isLoadingSession&&r.length===0,taskStatus:t==="stopped"?"stopped":null,lastError:null,lastErrorCode:null}}const _e={"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 Se(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(_e,s.slice(13))}function x(s){return{...s.id===void 0?{}:{id:s.id},name:s.name,mimeType:s.mimeType,sizeBytes:s.sizeBytes,...s.sandboxPath===void 0?{}:{sandboxPath:s.sandboxPath},...s.storageKey===void 0?{}:{storageKey:s.storageKey},...s.fileUrl===void 0?{}:{fileUrl:s.fileUrl}}}function Ae(s){if(!s||typeof s!="object"||!("type"in s))return!1;const e=s;switch(e.type){case"runtime.connect":case"session.new":case"run.retry":return!0;case"run.stop":return e.clientMessageIds===void 0||Array.isArray(e.clientMessageIds)&&e.clientMessageIds.length<=100&&e.clientMessageIds.every(t=>typeof t=="string"&&t.length>0&&t.length<=160);case"runtime.report_response_visibility":return ve(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_operation_timing":return M(e.timing);case"runtime.report_displayed_error":return(e.httpRequest===void 0||Z(e.httpRequest))&&(e.historyRefreshFailure===void 0||B(e.historyRefreshFailure))&&(e.renderedError===void 0||G(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||H(e.uiInvariant))&&(e.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||Se(e.reason))&&(e.clientMessageId===void 0||typeof e.clientMessageId=="string");case"runtime.widget_lifecycle":return(e.action==="opened"||e.action==="closed"||e.action==="minimized")&&typeof e.trigger=="string";case"session.load":return typeof e.sessionId=="string"&&e.sessionId.length>0;case"session.list":return(e.cursor===void 0||e.cursor===null||typeof e.cursor=="string")&&(e.limit===void 0||typeof e.limit=="number")&&(e.pinned===void 0||typeof e.pinned=="boolean");case"composer.select_model":case"session.set_model":return typeof e.model=="string";case"session.pin":return typeof e.sessionId=="string"&&typeof e.pinned=="boolean";case"session.rename":return typeof e.sessionId=="string"&&typeof e.title=="string";case"interaction.act":return typeof e.interactionId=="string"&&typeof e.action=="string"&&typeof e.expectedRevision=="number";case"conversation.stage_proactive_suggestion":return typeof e.question=="string"&&typeof e.clientMessageId=="string";case"conversation.stage":return typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.submittedAt===void 0||typeof e.submittedAt=="number")&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.attachments===void 0||Array.isArray(e.attachments));case"conversation.fail_staged":return typeof e.clientMessageId=="string"&&typeof e.message=="string";case"conversation.send":return typeof e.content=="string"&&typeof e.clientMessageId=="string"&&(e.requestedModel===void 0||typeof e.requestedModel=="string")&&(e.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class we{constructor(e,t,i){this.adapter=t,this.state=w(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=g("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;pendingTransfers=new Map;submissionPreviews=new Map;submissionGeneration=0;pendingStop=null;stopError=null;stopPreviews=new Set;operationQueue=Promise.resolve();destroyed=!1;on(e,t){const i=this.listeners[e]??new Set;return i.add(t),this.listeners[e]=i,()=>i.delete(t)}getState(){const e=w(this.state);for(const[n,r]of this.submissionPreviews)e.messages.some(o=>o.id===n)||(e.messages.push({...r.message,attachments:r.message.attachments?.map(o=>({...o}))}),e.segments&&(e.segments=[...e.segments,{id:n,userMessageId:n,activityIds:[],outcomeIds:[],collapsed:!1}]),e.isLoadingSession=!1,r.pending&&(e.activeResponseUserMessageId=n,e.pendingMessageStatus="sending",e.turnPhase="sending",e.activity={phase:"submitting",activeItemId:null}),r.error&&(e.lastError=r.error,e.lastErrorCode="message_delivery_failed"));this.stopError&&(e.lastError=this.stopError,e.lastErrorCode="stop_failed");const t=[...this.stopPreviews];if(!t.length)return e;const i=Ie(e,"","stopping",t);return e.activeResponseUserMessageId&&!this.stopPreviews.has(e.activeResponseUserMessageId)?{...e,messages:i.messages,segments:i.segments}:i}updateProjection(e,t,i,n,r){if(this.destroyed)return;const o=this.getState();(o.user?.id!==e.user?.id||o.selectionKey!==void 0&&o.selectionKey!==e.selectionKey||o.selectionKey===void 0&&o.sessionId!==null&&o.sessionId!==e.sessionId)&&(this.cancelPendingSubmissions(),this.submissionPreviews.clear());for(const a of e.messages)a.role==="user"&&this.submissionPreviews.delete(a.id);this.state=w(e);for(const a of this.stopPreviews)e.messages.some(d=>d.respondsToUserMessageId===a&&!d.provisional&&d.loading!==!0&&(d.dataType==="run_status"||d.dataType==="run_error"||d.role==="assistant"&&d.phase!=="commentary"&&(d.streamState===void 0||["finished","stopped","failed"].includes(d.streamState))))&&this.stopPreviews.delete(a);if(o.user?.id===e.user?.id)for(const a of this.state.messages){if(a.role!=="user"||!a.attachments?.length)continue;const d=o.messages.find(c=>c.role==="user"&&c.id===a.id);o.sessionId!==e.sessionId&&!(o.sessionId===null&&d)||(a.attachments=Pe(d?.attachments,a.attachments))}if(t!==void 0&&(this.model=t),i&&JSON.stringify(i)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=N(i);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0&&JSON.stringify(r)!==JSON.stringify(this.account)){this.account=r?{...r}:null;for(const a of this.accountListeners)a(this.getAccount())}this.emit("state",this.getState())}async connect(){await this.dispatch({type:"runtime.connect"})}destroy(){if(!this.destroyed){this.destroyed=!0,this.pendingStop=null,this.stopPreviews.clear(),this.pendingTransfers.clear(),this.submissionPreviews.clear(),this.attachmentFiles.clear(),this.sessionHistoryListeners.clear(),this.interactionListeners.clear(),this.accountListeners.clear();for(const e of Object.values(this.listeners))e?.clear();this.adapter.onDisconnect?.()}}warmup(e="panel_open"){return this.adapter.dispatch({type:"runtime.warmup",reason:e}).then(()=>{})}recordWidgetLifecycle(e,t){this.dispatch({type:"runtime.widget_lifecycle",action:e,trigger:t})}reportOperationTiming(e){!this.destroyed&&M(e)&&this.adapter.dispatch({type:"runtime.report_operation_timing",timing:e}).catch(()=>{})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t,i){i!==void 0&&!H(i)||this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t,...i?{uiInvariant:i}:{}}).catch(()=>{})}reportDisplayedError(e,t,i,n,r){const o=e==="conversation_error"&&!n?this.getState().conversationDiagnostics?.httpRequest:void 0;n!==void 0&&!G(n)||r!==void 0&&!B(r)||this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...n?{renderedError:n}:{},...r?{historyRefreshFailure:r}:{},...Z(o)?{httpRequest:o}:{},...i?{displayedMessage:be(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim(),n=t.attachments??[];if(!i&&n.length===0)return Promise.resolve(null);this.pendingStop=null,this.stopError=null;const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),o=t.submittedAt??Date.now(),a=this.submissionGeneration;this.pendingTransfers.set(r,n.flatMap(c=>c.id?[c.id]:[])),this.submissionPreviews.set(r,{pending:!0,message:{id:r,role:"user",content:i,createdAt:"",attachments:n.map(c=>({...c}))}});const d=this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:o},a);return this.emit("state",this.getState()),d.finally(()=>{this.pendingTransfers.delete(r)})}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId,o=k(c=>{i===this.submissionGeneration&&this.reportOperationTiming(c)},{operation:"send",layer:"renderer",requestId:r,clientMessageId:r,sessionId:this.state.sessionId});o.mark("submit");let a=t.attachments??[],d=!1;if(i!==this.submissionGeneration)return null;try{if(!await o.measure("staging_ipc",async()=>{const l=await this.enqueueOperation(async()=>this.destroyed||i!==this.submissionGeneration?null:{result:this.adapter.dispatch({type:"conversation.stage",initiatedBy:t.initiatedBy,invocation:t.invocation,automationOnboarding:t.automationOnboarding,content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(x):void 0,submittedAt:t.submittedAt})});return l?(await l.result,l):null})||i!==this.submissionGeneration)return null;if(d=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const l=[];for(const u of a){if(u.sandboxPath||u.storageKey){l.push(u);continue}const O=u.id?this.attachmentFiles.get(u.id):void 0;if(!O)throw new Error(`Attachment bytes are unavailable for ${u.name}`);if(l.push(await o.measure("attachment_transfer",()=>this.adapter.uploadAttachment(O,u,{clientMessageId:r}))),i!==this.submissionGeneration)return null}a=l}const h=await o.measure("send_ipc",()=>this.adapter.dispatch({type:"conversation.send",content:n,clientMessageId:r,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,...t.automationOnboarding?{automationOnboarding:!0}:{},attachments:a.length>0?a.map(x):void 0}));if(i!==this.submissionGeneration)return null;for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),h?.clientMessageId??r}catch(c){if(i!==this.submissionGeneration)return null;if($(c))for(const l of t.attachments??[])l.id&&this.attachmentFiles.delete(l.id);const h=this.submissionPreviews.get(r);throw h&&(h.pending=!1,h.error=S(c).message,this.emit("state",this.getState())),d&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:S(c).message}),c}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}retryLastMessage(){return this.dispatch({type:"run.retry"}),!0}createLocalAttachment(e){const t=crypto.randomUUID();return this.attachmentFiles.set(t,e),{id:t,name:e.name||"attachment",mimeType:e.type||"application/octet-stream",sizeBytes:e.size}}stop(){if(this.pendingStop)return this.pendingStop.promise;const e=this.getState(),t=this.cancelPendingSubmissions(!1),i=[...new Set([...t,e.activeResponseUserMessageId,e.messages.filter(d=>d.role==="user").slice(-1)[0]?.id].filter(d=>!!d))],n=k(d=>this.reportOperationTiming(d),{operation:"stop",layer:"renderer",requestId:crypto.randomUUID(),clientMessageId:i[0]??null,sessionId:e.sessionId});n.mark("stop");const r={userMessageIds:i,promise:Promise.resolve()};this.pendingStop=r;for(const d of i)this.stopPreviews.add(d);const o=this.submissionGeneration;r.promise=n.measure("stop_ipc",()=>this.adapter.dispatch({type:"run.stop",...t.length?{clientMessageIds:t}:{}})).then(()=>{},d=>{if(o===this.submissionGeneration){for(const c of i)this.stopPreviews.delete(c);this.stopError=S(d).message}}).finally(()=>{this.destroyed||o!==this.submissionGeneration||(this.pendingStop===r&&(this.pendingStop=null),this.emit("state",this.getState()))}),this.emit("state",this.getState());const a=r.promise;return this.operationQueue=a.then(()=>{},()=>{}),a.then(()=>{})}cancelPendingSubmissions(e=!0){this.pendingStop=null,e&&this.stopPreviews.clear(),this.stopError=null;const t=[...this.pendingTransfers.keys()];this.submissionGeneration++;for(const i of this.pendingTransfers.values())for(const n of i)this.attachmentFiles.delete(n);this.pendingTransfers.clear();for(const i of this.submissionPreviews.values())i.pending=!1;return this.operationQueue=Promise.resolve(),t}startNewSession(e={}){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){const t=await this.dispatch({type:"session.list",...e});if(t===void 0){const i=this.getSessionHistoryState().data;return{sessions:i?i.ids.map(n=>i.entitiesById[n]):[],nextCursor:i?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return N(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,i,n={}){return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:i,...n}).then(()=>{})}getAccount(){return this.account?{...this.account}:null}subscribeAccount(e){return this.accountListeners.add(e),e(this.getAccount()),()=>this.accountListeners.delete(e)}refreshAccount(){return Promise.resolve()}loadSession(e){return this.cancelPendingSubmissions(),this.submissionPreviews.clear(),this.emit("state",this.getState()),this.dispatch({type:"session.load",sessionId:e}).then(()=>{})}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const i=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=i,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:i}).then(()=>{})}dispatch(e){return e.type==="session.list"?this.adapter.dispatch(e):this.enqueueOperation(()=>this.adapter.dispatch(e))}enqueueOperation(e){const t=this.operationQueue.then(e);return this.operationQueue=t.then(()=>{},()=>{}),t}emit(e,t){const i=this.listeners[e];for(const n of i??[])n(t)}}function Pe(s,e){if(!e||!s)return e;const t=new Map;for(const i of s){const n=i.previewUrl;i.id&&n&&t.set(i.id,n)}return e.map(i=>{const n=i.id?t.get(i.id):void 0;return n?{...i,previewUrl:n}:i})}function w(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(o=>({...o}))},i=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),i&&Object.defineProperty(t,"assistantDraftItemId",{value:i,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:s.activeScheduledFollowUps?.map(e=>({...e}))??null}}function N(s){return{...s,data:s.data?f({entities:U(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.PRODUCT_AGENT_AUTH_RECONNECTING_ERROR_MESSAGE=L;exports.ProductAgentInteractionManager=re;exports.ProductAgentQueryController=P;exports.ProductAgentRemoteRuntimeClient=we;exports.ProductAgentSessionHistoryManager=te;exports.ProductAgentTaskPageTitleController=ce;exports.canSubmitPersonalProductAgentMessage=X;exports.createLocalStorageInteractionDecisionStorage=oe;exports.createProductAgentQueryState=g;exports.createProductAgentTaskPageTitleDocument=le;exports.formatProductAgentTaskPageTitle=Q;exports.hasProductAgentPaidCreditFallback=W;exports.isProductAgentAuthReconnectError=$;exports.isProductAgentRuntimeCommand=Ae;exports.mergeProductAgentEntityPages=j;exports.normalizeProductAgentEntityPage=f;exports.readLocalStorageInteractionDecisions=z;exports.reconcileProductAgentSubmissionGate=J;exports.resolveProductAgentBillingPresentation=Y;exports.resolveProductAgentComposerAction=ee;exports.resolveProductAgentWidgetPresentation=V;exports.selectProductAgentQueryEntities=U;
|
|
@@ -686,7 +686,7 @@ const C = () => `timing:${re}:${++oe}`, f = (s) => typeof s == "string" && /^[a-
|
|
|
686
686
|
function E(s) {
|
|
687
687
|
if (!s || typeof s != "object") return !1;
|
|
688
688
|
const e = s;
|
|
689
|
-
return Object.keys(e).every((t) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(t)) && (e.entrySurface === void 0 || ["extension_sidepanel", "extension_widget", "main_web_chat", "embedded_widget", "embedded_custom_ui", "automation", "mcp", "whatsapp"].includes(e.entrySurface)) && ["send", "stop"].includes(e.operation) && ["renderer", "sdk", "extension", "http"].includes(e.layer) && ne.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && f(e.spanId) && f(e.requestId) && (e.clientMessageId === null || f(e.clientMessageId)) && (e.sessionId === null || f(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
689
|
+
return Object.keys(e).every((t) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(t)) && (e.entrySurface === void 0 || ["extension_sidepanel", "extension_widget", "main_web_chat", "embedded_widget", "embedded_custom_ui", "automation", "mcp", "whatsapp", "email"].includes(e.entrySurface)) && ["send", "stop"].includes(e.operation) && ["renderer", "sdk", "extension", "http"].includes(e.layer) && ne.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && f(e.spanId) && f(e.requestId) && (e.clientMessageId === null || f(e.clientMessageId)) && (e.sessionId === null || f(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
690
690
|
}
|
|
691
691
|
function k(s, e) {
|
|
692
692
|
if (!s) return {
|
|
@@ -168,7 +168,7 @@ const Fs = () => `timing:${Bn}:${++Ln}`, He = (s) => typeof s == "string" && /^[
|
|
|
168
168
|
function je(s) {
|
|
169
169
|
if (!s || typeof s != "object") return !1;
|
|
170
170
|
const e = s;
|
|
171
|
-
return Object.keys(e).every((t) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(t)) && (e.entrySurface === void 0 || ["extension_sidepanel", "extension_widget", "main_web_chat", "embedded_widget", "embedded_custom_ui", "automation", "mcp", "whatsapp"].includes(e.entrySurface)) && ["send", "stop"].includes(e.operation) && ["renderer", "sdk", "extension", "http"].includes(e.layer) && Nn.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && He(e.spanId) && He(e.requestId) && (e.clientMessageId === null || He(e.clientMessageId)) && (e.sessionId === null || He(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
171
|
+
return Object.keys(e).every((t) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(t)) && (e.entrySurface === void 0 || ["extension_sidepanel", "extension_widget", "main_web_chat", "embedded_widget", "embedded_custom_ui", "automation", "mcp", "whatsapp", "email"].includes(e.entrySurface)) && ["send", "stop"].includes(e.operation) && ["renderer", "sdk", "extension", "http"].includes(e.layer) && Nn.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && He(e.spanId) && He(e.requestId) && (e.clientMessageId === null || He(e.clientMessageId)) && (e.sessionId === null || He(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
172
172
|
}
|
|
173
173
|
function me(s, e) {
|
|
174
174
|
if (!s) return {
|
|
@@ -1283,9 +1283,9 @@ class er {
|
|
|
1283
1283
|
if (t) for (const [r, o] of Object.entries(i)) {
|
|
1284
1284
|
if (!o.observe || this.observations.has(r)) continue;
|
|
1285
1285
|
const a = new Ze({
|
|
1286
|
-
activeIntervalMs:
|
|
1287
|
-
idleIntervalMs:
|
|
1288
|
-
maxFailureIntervalMs:
|
|
1286
|
+
activeIntervalMs: 6e4,
|
|
1287
|
+
idleIntervalMs: 6e4,
|
|
1288
|
+
maxFailureIntervalMs: 6e4,
|
|
1289
1289
|
isActiveTurn: () => !1,
|
|
1290
1290
|
poll: async () => {
|
|
1291
1291
|
for (; !this.disposed && Q(this.options) && this.observations.get(r)?.history === a; ) {
|
|
@@ -1298,9 +1298,9 @@ class er {
|
|
|
1298
1298
|
}
|
|
1299
1299
|
}
|
|
1300
1300
|
}), c = new Ze({
|
|
1301
|
-
activeIntervalMs:
|
|
1302
|
-
idleIntervalMs:
|
|
1303
|
-
maxFailureIntervalMs:
|
|
1301
|
+
activeIntervalMs: 15e3,
|
|
1302
|
+
idleIntervalMs: 6e4,
|
|
1303
|
+
maxFailureIntervalMs: 6e4,
|
|
1304
1304
|
isActiveTurn: () => {
|
|
1305
1305
|
const u = e.engine.getState().slices.conversation;
|
|
1306
1306
|
return !!u.sessions[r]?.preparation || ["thinking", "steering", "queued", "stopping"].includes(u.sessions[r]?.execution?.phase ?? "idle") || Object.values(u.submissions).some((l) => l.sessionId === r && !l.cancelled && !["accepted", "failed"].includes(l.delivery));
|
|
@@ -1632,7 +1632,7 @@ function ar(s) {
|
|
|
1632
1632
|
return e() && i.directory.memberships[t]?.members.length ? i.conversation.sessions[t] ?? null : null;
|
|
1633
1633
|
}, s.invalidateAuth), async (t) => (!e() || t.authorityId !== s.authority.authorityId || t.generation !== s.authority.generation || !s.runtime().engine.getState().slices.directory.memberships[t.sessionId]?.members.length || (s.manager.receiveConversationSources(t.sources), s.notify()), null);
|
|
1634
1634
|
}
|
|
1635
|
-
const cr = "0.1.
|
|
1635
|
+
const cr = "0.1.244", dr = {
|
|
1636
1636
|
version: cr
|
|
1637
1637
|
};
|
|
1638
1638
|
function et(s) {
|
|
@@ -4455,17 +4455,17 @@ class Xi {
|
|
|
4455
4455
|
h.signal.aborted || (p.trigger = b, h.abort());
|
|
4456
4456
|
}, f = () => m("transport_disposed"), y = () => m(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(o?.reason) ? o.reason : "caller_cancelled");
|
|
4457
4457
|
this.requests.signal.addEventListener("abort", f, { once: !0 }), o?.addEventListener("abort", y, { once: !0 });
|
|
4458
|
-
const v =
|
|
4458
|
+
const v = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && n === "POST", S = setTimeout(() => m("deadline"), v ? 3e4 : 15e3), A = ho(), _ = Date.now();
|
|
4459
4459
|
let I = null, R = null, q = null, V = null;
|
|
4460
4460
|
try {
|
|
4461
4461
|
const b = await Promise.resolve(fetch(l, {
|
|
4462
4462
|
method: n ?? (i === void 0 ? "GET" : "POST"),
|
|
4463
4463
|
cache: "no-store",
|
|
4464
4464
|
signal: h.signal,
|
|
4465
|
-
headers: { "x-product-agent-auth-request-id": A, authorization: u || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...
|
|
4465
|
+
headers: { "x-product-agent-auth-request-id": A, authorization: u || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...v ? { "x-request-id": A } : {} },
|
|
4466
4466
|
...i === void 0 ? {} : { body: JSON.stringify(i) }
|
|
4467
4467
|
})).catch((C) => {
|
|
4468
|
-
throw
|
|
4468
|
+
throw v && C instanceof TypeError ? new w("The connection was interrupted. Please try again.", "connection_interrupted", !0) : C;
|
|
4469
4469
|
});
|
|
4470
4470
|
if (I = Date.now(), R = b.status, q = ei(b.headers.get("x-request-id")), V = ei(b.headers.get("x-cloud-trace-context")), !b.ok) {
|
|
4471
4471
|
const C = b.status === 401 ? "unauthorized" : b.status === 426 ? "update_required" : String(b.status), T = (await b.json().catch(() => null))?.detail;
|
|
@@ -4486,7 +4486,7 @@ class Xi {
|
|
|
4486
4486
|
const C = p.trigger ?? ((b instanceof Error || b instanceof DOMException) && b.name === "AbortError" ? "unexpected_abort" : null), T = {
|
|
4487
4487
|
requestId: A,
|
|
4488
4488
|
method: n ?? (i === void 0 ? "GET" : "POST"),
|
|
4489
|
-
route:
|
|
4489
|
+
route: v ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
|
|
4490
4490
|
status: R,
|
|
4491
4491
|
abortTrigger: C,
|
|
4492
4492
|
category: C === "deadline" ? "request_timed_out" : C === "unexpected_abort" ? "connection_interrupted" : C ? "request_cancelled" : b instanceof w ? b.code : "invalid_response",
|
|
@@ -4515,14 +4515,14 @@ class Xi {
|
|
|
4515
4515
|
z
|
|
4516
4516
|
);
|
|
4517
4517
|
}
|
|
4518
|
-
throw b instanceof w && z ? new w(b.message, b.code, b.outcomeUnknown, { ...b.detail, ...z }, b.backendRefusal) :
|
|
4518
|
+
throw b instanceof w && z ? new w(b.message, b.code, b.outcomeUnknown, { ...b.detail, ...z }, b.backendRefusal) : v && z ? new w(
|
|
4519
4519
|
"The conversation response could not be read. Please try again.",
|
|
4520
4520
|
"connection_interrupted",
|
|
4521
4521
|
!0,
|
|
4522
4522
|
z
|
|
4523
4523
|
) : b;
|
|
4524
4524
|
} finally {
|
|
4525
|
-
clearTimeout(
|
|
4525
|
+
clearTimeout(S), this.requests.signal.removeEventListener("abort", f), o?.removeEventListener("abort", y);
|
|
4526
4526
|
}
|
|
4527
4527
|
}
|
|
4528
4528
|
}
|
|
@@ -291,7 +291,7 @@ const pc = () => `timing:${ap}:${++cp}`, ns = (t) => typeof t == "string" && /^[
|
|
|
291
291
|
function Br(t) {
|
|
292
292
|
if (!t || typeof t != "object") return !1;
|
|
293
293
|
const e = t;
|
|
294
|
-
return Object.keys(e).every((n) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(n)) && (e.entrySurface === void 0 || ["extension_sidepanel", "extension_widget", "main_web_chat", "embedded_widget", "embedded_custom_ui", "automation", "mcp", "whatsapp"].includes(e.entrySurface)) && ["send", "stop"].includes(e.operation) && ["renderer", "sdk", "extension", "http"].includes(e.layer) && rp.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && ns(e.spanId) && ns(e.requestId) && (e.clientMessageId === null || ns(e.clientMessageId)) && (e.sessionId === null || ns(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
294
|
+
return Object.keys(e).every((n) => ["entrySurface", "operation", "layer", "stage", "status", "spanId", "requestId", "clientMessageId", "sessionId", "occurredAt", "durationMs"].includes(n)) && (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) && rp.includes(e.stage) && ["started", "completed", "failed", "observed"].includes(e.status) && ns(e.spanId) && ns(e.requestId) && (e.clientMessageId === null || ns(e.clientMessageId)) && (e.sessionId === null || ns(e.sessionId)) && typeof e.occurredAt == "string" && e.occurredAt.length <= 40 && Number.isFinite(Date.parse(e.occurredAt)) && Number.isSafeInteger(e.durationMs) && e.durationMs >= 0;
|
|
295
295
|
}
|
|
296
296
|
function Fn(t, e) {
|
|
297
297
|
if (!t) return {
|
|
@@ -1406,9 +1406,9 @@ class Sp {
|
|
|
1406
1406
|
if (n) for (const [o, a] of Object.entries(i)) {
|
|
1407
1407
|
if (!a.observe || this.observations.has(o)) continue;
|
|
1408
1408
|
const r = new hs({
|
|
1409
|
-
activeIntervalMs:
|
|
1410
|
-
idleIntervalMs:
|
|
1411
|
-
maxFailureIntervalMs:
|
|
1409
|
+
activeIntervalMs: 6e4,
|
|
1410
|
+
idleIntervalMs: 6e4,
|
|
1411
|
+
maxFailureIntervalMs: 6e4,
|
|
1412
1412
|
isActiveTurn: () => !1,
|
|
1413
1413
|
poll: async () => {
|
|
1414
1414
|
for (; !this.disposed && ot(this.options) && this.observations.get(o)?.history === r; ) {
|
|
@@ -1421,9 +1421,9 @@ class Sp {
|
|
|
1421
1421
|
}
|
|
1422
1422
|
}
|
|
1423
1423
|
}), c = new hs({
|
|
1424
|
-
activeIntervalMs:
|
|
1425
|
-
idleIntervalMs:
|
|
1426
|
-
maxFailureIntervalMs:
|
|
1424
|
+
activeIntervalMs: 15e3,
|
|
1425
|
+
idleIntervalMs: 6e4,
|
|
1426
|
+
maxFailureIntervalMs: 6e4,
|
|
1427
1427
|
isActiveTurn: () => {
|
|
1428
1428
|
const u = e.engine.getState().slices.conversation;
|
|
1429
1429
|
return !!u.sessions[o]?.preparation || ["thinking", "steering", "queued", "stopping"].includes(u.sessions[o]?.execution?.phase ?? "idle") || Object.values(u.submissions).some((p) => p.sessionId === o && !p.cancelled && !["accepted", "failed"].includes(p.delivery));
|
|
@@ -1820,7 +1820,7 @@ function Op(t) {
|
|
|
1820
1820
|
return e() && i.directory.memberships[n]?.members.length ? i.conversation.sessions[n] ?? null : null;
|
|
1821
1821
|
}, t.invalidateAuth), async (n) => (!e() || n.authorityId !== t.authority.authorityId || n.generation !== t.authority.generation || !t.runtime().engine.getState().slices.directory.memberships[n.sessionId]?.members.length || (t.manager.receiveConversationSources(n.sources), t.notify()), null);
|
|
1822
1822
|
}
|
|
1823
|
-
const Ql = "0.1.
|
|
1823
|
+
const Ql = "0.1.244", Np = {
|
|
1824
1824
|
version: Ql
|
|
1825
1825
|
}, Tt = /* @__PURE__ */ Object.create(null);
|
|
1826
1826
|
Tt.open = "0";
|
|
@@ -4509,17 +4509,17 @@ class pd {
|
|
|
4509
4509
|
h.signal.aborted || (g.trigger = C, h.abort());
|
|
4510
4510
|
}, f = () => y("transport_disposed"), w = () => y(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(a?.reason) ? a.reason : "caller_cancelled");
|
|
4511
4511
|
this.requests.signal.addEventListener("abort", f, { once: !0 }), a?.addEventListener("abort", w, { once: !0 });
|
|
4512
|
-
const b =
|
|
4512
|
+
const b = o === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && s === "POST", _ = setTimeout(() => y("deadline"), b ? 3e4 : 15e3), T = Dh(), x = Date.now();
|
|
4513
4513
|
let A = null, q = null, D = null, Q = null;
|
|
4514
4514
|
try {
|
|
4515
4515
|
const C = await Promise.resolve(fetch(p, {
|
|
4516
4516
|
method: s ?? (i === void 0 ? "GET" : "POST"),
|
|
4517
4517
|
cache: "no-store",
|
|
4518
4518
|
signal: h.signal,
|
|
4519
|
-
headers: { "x-product-agent-auth-request-id": T, authorization: u || o === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...
|
|
4519
|
+
headers: { "x-product-agent-auth-request-id": T, authorization: u || o === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...b ? { "x-request-id": T } : {} },
|
|
4520
4520
|
...i === void 0 ? {} : { body: JSON.stringify(i) }
|
|
4521
4521
|
})).catch((B) => {
|
|
4522
|
-
throw
|
|
4522
|
+
throw b && B instanceof TypeError ? new O("The connection was interrupted. Please try again.", "connection_interrupted", !0) : B;
|
|
4523
4523
|
});
|
|
4524
4524
|
if (A = Date.now(), q = C.status, D = Ec(C.headers.get("x-request-id")), Q = Ec(C.headers.get("x-cloud-trace-context")), !C.ok) {
|
|
4525
4525
|
const B = C.status === 401 ? "unauthorized" : C.status === 426 ? "update_required" : String(C.status), z = (await C.json().catch(() => null))?.detail;
|
|
@@ -4540,7 +4540,7 @@ class pd {
|
|
|
4540
4540
|
const B = g.trigger ?? ((C instanceof Error || C instanceof DOMException) && C.name === "AbortError" ? "unexpected_abort" : null), z = {
|
|
4541
4541
|
requestId: T,
|
|
4542
4542
|
method: s ?? (i === void 0 ? "GET" : "POST"),
|
|
4543
|
-
route:
|
|
4543
|
+
route: b ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
|
|
4544
4544
|
status: q,
|
|
4545
4545
|
abortTrigger: B,
|
|
4546
4546
|
category: B === "deadline" ? "request_timed_out" : B === "unexpected_abort" ? "connection_interrupted" : B ? "request_cancelled" : C instanceof O ? C.code : "invalid_response",
|
|
@@ -4569,14 +4569,14 @@ class pd {
|
|
|
4569
4569
|
ee
|
|
4570
4570
|
);
|
|
4571
4571
|
}
|
|
4572
|
-
throw C instanceof O && ee ? new O(C.message, C.code, C.outcomeUnknown, { ...C.detail, ...ee }, C.backendRefusal) :
|
|
4572
|
+
throw C instanceof O && ee ? new O(C.message, C.code, C.outcomeUnknown, { ...C.detail, ...ee }, C.backendRefusal) : b && ee ? new O(
|
|
4573
4573
|
"The conversation response could not be read. Please try again.",
|
|
4574
4574
|
"connection_interrupted",
|
|
4575
4575
|
!0,
|
|
4576
4576
|
ee
|
|
4577
4577
|
) : C;
|
|
4578
4578
|
} finally {
|
|
4579
|
-
clearTimeout(
|
|
4579
|
+
clearTimeout(_), this.requests.signal.removeEventListener("abort", f), a?.removeEventListener("abort", w);
|
|
4580
4580
|
}
|
|
4581
4581
|
}
|
|
4582
4582
|
}
|
package/package.json
CHANGED