@pluno/product-agent-web 0.1.217 → 0.1.219

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -217,6 +217,25 @@ export type ProductAgentTraceEvent = {
217
217
  monotonicMs: number;
218
218
  data: Record<string, string | number | boolean | null>;
219
219
  };
220
+ export type ResponseVisibilityObservation = {
221
+ observedAt: string;
222
+ sessionId: string | null;
223
+ responseItemId: string | null;
224
+ respondsToUserMessageId: string | null;
225
+ panelVisible: boolean;
226
+ documentVisible: boolean;
227
+ loading: boolean;
228
+ };
229
+ export type ResponseDiagnostics = {
230
+ capturedAt: string;
231
+ authenticated: boolean;
232
+ activeClientMessageId: string | null;
233
+ pendingClientMessageId: string | null;
234
+ clientUserMessageItemId: string | null;
235
+ clientResponseItemId: string | null;
236
+ clientDraftObserved: boolean;
237
+ renderer: ResponseVisibilityObservation | null;
238
+ };
220
239
  export type ProductAgentEventMap = {
221
240
  state: ProductAgentState;
222
241
  message: ProductAgentMessage;
@@ -376,6 +395,7 @@ export declare class ProductAgentSessionEngine {
376
395
  automationOnboarding?: boolean;
377
396
  submittedAt?: number;
378
397
  }): Promise<string | null>;
398
+ reportResponseVisibility(observation: ResponseVisibilityObservation): void;
379
399
  reportInvalidStateTransition(reason: string, clientMessageId?: string): void;
380
400
  reportDisplayedError(reason: string, errorFingerprint: string, displayedMessage?: string): void;
381
401
  getModel(): ProductAgentModel | undefined;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function u(s){return{key:s,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class y{constructor(e,t,i=(n,r)=>r){this.loader=t,this.merge=i,this.state=u(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=u(e),this.trailingLoad=null,this.publish())}reset(){this.state=u(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 h(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 I(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 b(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function M(s){return s.visible?s.minimized?{state:"minimized"}:{state:s.open?"visible_open":"visible_closed"}:{state:"hidden"}}function D(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 k(s){if(!s||typeof s!="object")return!1;const e=s.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function O(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 R(s){const e=s.hasDraftMessage||s.hasPreSubmittedAttachment;return s.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!s.canStopRunningTurn}:{action:"send",disabled:!e||!s.canSubmitMessage}}class C{constructor(e,t,i=20){this.loadPage=t,this.limit=i,this.recentQuery=new y(`${e}:recent`,async({cursor:n})=>h(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),I),this.pinnedQuery=new y(`${e}:pinned`,async()=>h({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=[...g(t.data),...g(e.data)],n=new Map(i.map(o=>[o.id,o])),r=Array.from(n.values()).map(o=>this.applyOverrides(o,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(o=>!n.has(o.id)).reverse(),l=e.data||t.data||a.length>0?h({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:x(e,t),data:l,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=[...g(this.pinnedQuery.getState().data),...g(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 g(s){return s?s.ids.map(e=>s.entitiesById[e]).filter(e=>!!e):[]}function x(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"}class L{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(v).map(i=>[this.getDecisionKey(i),i])),this.initialized=!0)}storage;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(v).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()){for(const[i,n]of this.scheduledEligibility)n<=e&&this.scheduledEligibility.delete(i);const t=[...this.scheduledEligibility.values(),...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(!_(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)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),l=new Map(this.decisions);return l.set(a,r),await this.storage.save([...l.values()]),this.decisions=l,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=m(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${m(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${m(e.scope)}:category:${e.category}`}}function q(s,e){return{load:async()=>E(s,e),save:async t=>s.setItem(e,JSON.stringify(t))}}function E(s,e){const t=s.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.filter(v):[]}function m(s){return`${s.level}:${s.key}`}function _(s){return s==="dismiss"||s==="later"||s==="snooze"||s==="never"||s==="dont_show_again"}function v(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")&&_(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const Q={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},$=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function T(s,e){if(!e)return p(s);const t=p(s),i=`${Q[e]} Pluno`;return t?`${i}: ${t}`:i}class K{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=p(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,i=this.lastAppliedTitle===null?p(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=T(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function B(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 p(s){return s.replace($,"")}const S=500;function z(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>S?`${e.slice(0,S-1)}…`:e}const F={"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 U(s){return typeof s=="string"&&s.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(F,s.slice(13))}function w(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 N(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.stop":case"run.retry":return!0;case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_displayed_error":return(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.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||U(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"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.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.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class H{constructor(e,t,i){this.adapter=t,this.state=f(e),this.model=i}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=u("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;unacknowledgedSubmissions=new Map;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(){return f(this.state)}updateProjection(e,t,i,n,r){if(!this.destroyed){this.state=f(e);for(const[a,l]of this.unacknowledgedSubmissions){if(e.user?.id!==l.userId||l.sessionId!==null&&e.sessionId!==l.sessionId){this.unacknowledgedSubmissions.delete(a);continue}const o=this.state.messages.find(c=>c.clientMessageId===a);if(o){o.attachments=j(l.message.attachments,o.attachments),this.unacknowledgedSubmissions.delete(a);continue}l.sessionId??=e.sessionId,this.state.messages.push(l.message),this.state.pendingMessageStatus="sending",this.state.turnPhase??="sending",this.state.taskStatus??="working"}if(t!==void 0&&(this.model=t),i){this.sessionHistoryState=P(i);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0){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.unacknowledgedSubmissions.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})}reportInvalidStateTransition(e,t){this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t}).catch(()=>{})}reportDisplayedError(e,t,i){this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...i?{displayedMessage:z(i)}:{}}).catch(()=>{})}sendMessage(e,t={}){const i=e.trim(),n=t.attachments??[];if(!i&&n.length===0)return Promise.resolve(null);const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),a=t.submittedAt??Date.now(),l=this.state,o={id:`local-${r}`,role:"user",content:i,createdAt:new Date().toISOString(),...n.length>0?{attachments:n}:{},clientMessageId:r};return this.unacknowledgedSubmissions.set(r,{message:{...o,attachments:o.attachments?.map(c=>({...c}))},sessionId:l.sessionId,userId:l.user?.id}),this.state={...this.state,messages:[...this.state.messages,o],pendingMessageStatus:"sending",turnPhase:this.state.isThinking?this.state.turnPhase:"sending",taskStatus:"working",isRetrying:!1,lastError:null},this.emit("state",this.getState()),this.enqueueOperation(()=>this.sendMessageNow(i,{...t,clientMessageId:r,submittedAt:a},l))}async sendMessageNow(e,t,i){const n=e,r=t.clientMessageId;let a=t.attachments??[],l=!1;try{if(await this.adapter.dispatch({type:"conversation.stage",content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(w):void 0,submittedAt:t.submittedAt}),l=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const c=[];for(const d of a){if(d.sandboxPath||d.storageKey){c.push(d);continue}const A=d.id?this.attachmentFiles.get(d.id):void 0;if(!A)throw new Error(`Attachment bytes are unavailable for ${d.name}`);c.push(await this.adapter.uploadAttachment(A,d,{clientMessageId:r}))}a=c}const o=await 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(w):void 0});for(const c of t.attachments??[])c.id&&this.attachmentFiles.delete(c.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),o?.clientMessageId??r}catch(o){throw this.unacknowledgedSubmissions.delete(r),this.state={...this.state,messages:this.state.messages.filter(c=>c.id!==`local-${r}`&&c.id!==`optimistic-user-message:${r}`),pendingMessageStatus:i.pendingMessageStatus,turnPhase:i.turnPhase,isThinking:i.isThinking,taskStatus:i.taskStatus},this.emit("state",this.getState()),l&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:o instanceof Error?o.message:String(o)}),o}}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(){return this.unacknowledgedSubmissions.clear(),this.dispatch({type:"run.stop"}).then(()=>{})}startNewSession(e={}){return this.unacknowledgedSubmissions.clear(),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){await this.dispatch({type:"session.list",...e});const t=this.sessionHistoryState.data;return{sessions:b(t),nextCursor:t?.nextCursor??null}}getSessionHistoryState(){return P(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,limit:20}).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.unacknowledgedSubmissions.clear(),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 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 j(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 f(s){return{...s,starterPrompts:[...s.starterPrompts],appearance:s.appearance?{...s.appearance}:null,messages:s.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},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 P(s){return{...s,data:s.data?h({entities:b(s.data).map(e=>({...e})),nextCursor:s.data.nextCursor}):null}}exports.ProductAgentInteractionManager=L;exports.ProductAgentQueryController=y;exports.ProductAgentRemoteRuntimeClient=H;exports.ProductAgentSessionHistoryManager=C;exports.ProductAgentTaskPageTitleController=K;exports.createLocalStorageInteractionDecisionStorage=q;exports.createProductAgentQueryState=u;exports.createProductAgentTaskPageTitleDocument=B;exports.formatProductAgentTaskPageTitle=T;exports.hasProductAgentPaidCreditFallback=k;exports.isProductAgentRuntimeCommand=N;exports.mergeProductAgentEntityPages=I;exports.normalizeProductAgentEntityPage=h;exports.readLocalStorageInteractionDecisions=E;exports.reconcileProductAgentSubmissionGate=D;exports.resolveProductAgentBillingPresentation=O;exports.resolveProductAgentComposerAction=R;exports.resolveProductAgentWidgetPresentation=M;exports.selectProductAgentQueryEntities=b;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function u(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class v{constructor(e,t,s=(n,r)=>r){this.loader=t,this.merge=s,this.state=u(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=u(e),this.trailingLoad=null,this.publish())}reset(){this.state=u(this.state.key),this.trailingLoad=null,this.publish()}invalidate(){this.state={...this.state,status:this.state.data===null?"not_requested":"ready",updatedAt:null},this.publish()}load(e="replace",t=null){return this.trailingLoad={mode:e,cursor:t},this.inFlight?this.inFlight:(this.inFlight=this.runLoads().finally(()=>{this.inFlight=null}),this.inFlight)}update(e){this.state={...this.state,data:e(this.state.data)},this.publish()}async runLoads(){for(;this.trailingLoad;){const e=this.trailingLoad;this.trailingLoad=null;const t=this.state.key,s=this.state.requestId+1;this.state={...this.state,status:e.mode==="append"?"loading_more":this.state.data===null?"loading":"refreshing",error:null,requestId:s},this.publish();try{const n=await this.loader({key:t,cursor:e.cursor});if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"ready",data:this.merge(this.state.data,n,e.mode),error:null,updatedAt:Date.now()},this.publish()}catch(n){if(t!==this.state.key||s!==this.state.requestId)continue;this.state={...this.state,status:"error",error:n instanceof Error?n.message:"The query failed."},this.publish()}}}publish(){for(const e of this.listeners)e(this.state)}}function h(i){const e={},t=[];for(const s of i.entities)e[s.id]||t.push(s.id),e[s.id]=s;return{entitiesById:e,ids:t,nextCursor:i.nextCursor}}function E(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const r of e.ids)i.entitiesById[r]||n.push(r);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function A(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function D(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function O(i,e){return e==="limit_exceeded"?{allowed:!1,reason:"credits_exhausted",actions:["upgrade","earn_credits"]}:e==="subscription_required"||e==="subscription_inactive"||e==="payment_issue"||e==="subscription_invalid"||e==="payment_required"?{allowed:!1,reason:"payment_issue",actions:["upgrade"]}:i??{allowed:!0,reason:"allowed",actions:[]}}function k(i){if(!i||typeof i!="object")return!1;const e=i.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function R(i){return i?i.submissionGate?.allowed===!1?{state:"action_required",reason:i.submissionGate.reason}:i.usingPaidCreditFallback===!0?{state:"paid_credit_fallback"}:i.creditLimit!==null&&i.creditLimit>0&&i.creditsRemaining!==null&&i.creditsRemaining>0&&i.creditsRemaining/i.creditLimit<=.2?{state:"low_credits"}:i.creditsUsed!==null?{state:"usage"}:{state:"hidden"}:{state:"hidden"}}function C(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!e?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}class x{constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new v(`${e}:recent`,async({cursor:n})=>h(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(r=>({entities:r.sessions,nextCursor:r.nextCursor}))),E),this.pinnedQuery=new v(`${e}:pinned`,async()=>h({entities:await this.loadAllPinned(),nextCursor:null})),this.recentQuery.subscribe(()=>this.publish()),this.pinnedQuery.subscribe(()=>this.publish())}loadPage;limit;recentQuery;pinnedQuery;listeners=new Set;optimisticEntities=new Map;activityOverrides=new Map;pinnedOverrides=new Map;titleOverrides=new Map;refreshSequence=0;completedRefreshSequence=0;activityReconciliationScheduled=!1;getState(){const e=this.recentQuery.getState(),t=this.pinnedQuery.getState(),s=[...p(t.data),...p(e.data)],n=new Map(s.map(o=>[o.id,o])),r=Array.from(n.values()).map(o=>this.applyOverrides(o,this.completedRefreshSequence)),a=Array.from(this.optimisticEntities.values()).filter(o=>!n.has(o.id)).reverse(),l=e.data||t.data||a.length>0?h({entities:[...a,...r],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:L(e,t),data:l,error:e.error??t.error,requestId:Math.max(e.requestId,t.requestId),updatedAt:Math.max(e.updatedAt??0,t.updatedAt??0)||null}}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}getEntity(e){return this.getState().data?.entitiesById[e]??null}setKey(e){this.optimisticEntities.clear(),this.activityOverrides.clear(),this.pinnedOverrides.clear(),this.titleOverrides.clear(),this.refreshSequence=0,this.completedRefreshSequence=0,this.activityReconciliationScheduled=!1,this.recentQuery.setKey(`${e}:recent`),this.pinnedQuery.setKey(`${e}:pinned`)}refresh(){const e=++this.refreshSequence,t=Promise.all([this.recentQuery.load("replace"),this.pinnedQuery.load("replace")]).then(()=>{this.completedRefreshSequence=Math.max(this.completedRefreshSequence,e),this.reconcileDurableEntities()});return t.then(()=>{!this.hasUnconfirmedActivityOverride()||this.activityReconciliationScheduled||(this.activityReconciliationScheduled=!0,this.refresh().finally(()=>{this.activityReconciliationScheduled=!1}))}),t}loadMore(e){return this.recentQuery.load("append",e)}addOptimistic(e){this.optimisticEntities.set(e.id,e),this.updateProjection()}removeOptimistic(e){this.optimisticEntities.delete(e)&&this.updateProjection()}acknowledgeOptimistic(e,t){this.optimisticEntities.delete(e),this.optimisticEntities.set(t.id,t),this.updateProjection()}setActivity(e,t){this.activityOverrides.set(e,{isActive:t,confirmAfterRefresh:this.completedRefreshSequence+1,releaseAfterRefresh:this.completedRefreshSequence+2}),this.updateEntity(e,s=>({...s,isActive:t}))}setPinned(e,t){const s={pinned:t,confirmAfterRefresh:Number.POSITIVE_INFINITY};return this.pinnedOverrides.set(e,s),this.updateEntity(e,n=>({...n,isPinned:t})),s}confirmPinned(e,t){this.pinnedOverrides.get(e)===t&&(t.confirmAfterRefresh=this.completedRefreshSequence+1)}rollbackPinned(e,t,s){this.pinnedOverrides.get(e)===t&&(this.pinnedOverrides.delete(e),this.updateEntity(e,n=>({...n,isPinned:s})))}setTitle(e,t){this.titleOverrides.set(e,t),this.updateEntity(e,s=>({...s,customTitle:t}))}confirmTitle(e){this.titleOverrides.delete(e)}reconcileDurableEntities(){const e=[...p(this.pinnedQuery.getState().data),...p(this.recentQuery.getState().data)],t=new Set(e.map(s=>s.id));for(const s of this.optimisticEntities.keys())t.has(s)&&this.optimisticEntities.delete(s);for(const s of e)this.applyOverrides(s,this.completedRefreshSequence);this.publish()}async loadAllPinned(){const e=[];let t=null;do{const s=await this.loadPage({cursor:t,limit:this.limit,pinned:!0});e.push(...s.sessions),t=s.nextCursor}while(t);return e}applyOverrides(e,t){let s=e;const n=this.activityOverrides.get(e.id);n&&(t>=n.confirmAfterRefresh&&e.isActive===n.isActive?this.activityOverrides.delete(e.id):t>=n.releaseAfterRefresh?this.activityOverrides.delete(e.id):s={...s,isActive:n.isActive});const r=this.pinnedOverrides.get(e.id);return r&&(t>=r.confirmAfterRefresh&&e.isPinned===!0===r.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:r.pinned}),this.titleOverrides.has(e.id)&&(s={...s,customTitle:this.titleOverrides.get(e.id)??null}),s}updateProjection(){this.publish()}updateEntity(e,t){const s=this.optimisticEntities.get(e);s&&this.optimisticEntities.set(e,t(s)),this.publish()}hasUnconfirmedActivityOverride(){return Array.from(this.activityOverrides.values()).some(e=>this.completedRefreshSequence<e.releaseAfterRefresh)}publish(){for(const e of this.listeners)e(this.getState())}}function p(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function L(i,e){return i.status==="error"||e.status==="error"?"error":i.status==="loading"||e.status==="loading"?"loading":i.status==="refreshing"||e.status==="refreshing"?"refreshing":i.status==="loading_more"?"loading_more":i.status==="ready"||e.status==="ready"?"ready":"not_requested"}class q{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(b).map(s=>[this.getDecisionKey(s),s])),this.initialized=!0)}storage;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(b).map(t=>[this.getDecisionKey(t),t])),this.initialized=!0}isEligible(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));return s!==void 0&&s>t?!1:this.isDecisionEligible(this.decisions.get(this.getExactKey(e)),t)&&this.isDecisionEligible(this.decisions.get(this.getCategoryKey(e)),t)}getDecision(e){return this.decisions.get(this.getExactKey(e))??this.decisions.get(this.getCategoryKey(e))??null}getStatus(e,t=Date.now()){const s=this.scheduledEligibility.get(this.getExactKey(e));if(s!==void 0&&s>t)return"scheduled";const n=this.getDecision(e);return n?n.action==="never"||n.action==="dont_show_again"?"suppressed":n.action==="dismiss"?"resolved":n.nextEligibleAt&&Date.parse(n.nextEligibleAt)>t?"snoozed":"presentable":"presentable"}scheduleEligibility(e,t){const s=this.getExactKey(e),n=this.scheduledEligibility.get(s);return n!==void 0?n:(this.scheduledEligibility.set(s,t),t)}getNextEligibilityAt(e=Date.now()){const t=[...Array.from(this.scheduledEligibility.values()).filter(s=>s>e),...Array.from(this.decisions.values()).map(s=>s.nextEligibleAt?Date.parse(s.nextEligibleAt):Number.NaN).filter(s=>Number.isFinite(s)&&s>e)];return t.length>0?Math.min(...t):null}act(e,t,s={}){const n=this.actionQueue.then(()=>this.applyAction(e,t,s));return this.actionQueue=n.then(()=>{},()=>{}),n}async applyAction(e,t,s){if(!e.allowedActions.includes(t))throw new Error(`Interaction ${e.key} does not allow ${t}.`);if(!T(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,r={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},a=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),l=new Map(this.decisions);return l.set(a,r),await this.storage.save([...l.values()]),this.decisions=l,r}isDecisionEligible(e,t){return e?e.action==="dismiss"||e.action==="never"||e.action==="dont_show_again"?!1:!e.nextEligibleAt||Date.parse(e.nextEligibleAt)<=t:!0}getNextEligibleAt(e,t,s,n){if(t==="later")return new Date(s.getTime()+(e.laterDelayMs??3600*1e3)).toISOString();if(t==="snooze"){if(!n||n.getTime()<=s.getTime())throw new Error("Snooze requires a future next-eligible time.");return n.toISOString()}return null}getDecisionKey(e){const t=m(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${m(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${m(e.scope)}:category:${e.category}`}}function Q(i,e){return{load:async()=>_(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function _(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(b):[]}function m(i){return`${i.level}:${i.key}`}function T(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function b(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.promptKey=="string"&&typeof e.category=="string"&&typeof e.decidedAt=="string"&&(e.nextEligibleAt===null||typeof e.nextEligibleAt=="string")&&T(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const $={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},K=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function M(i,e){if(!e)return g(i);const t=g(i),s=`${$[e]} Pluno`;return t?`${s}: ${t}`:s}class z{constructor(e){this.titleDocument=e}titleDocument;status=null;baseTitle="";lastAppliedTitle=null;stopObserving=null;liveStatusVersion=0;setStatus(e){this.liveStatusVersion+=1,this.applyStatus(e)}clear(){this.liveStatusVersion+=1,this.applyClear()}async syncStatus(e){const t=this.liveStatusVersion,s=await e();s===void 0||t!==this.liveStatusVersion||(s?this.applyStatus(s):this.applyClear())}applyStatus(e){const t=this.titleDocument.getTitle();t!==this.lastAppliedTitle&&(this.baseTitle=g(t)),this.status=e,this.stopObserving||(this.stopObserving=this.titleDocument.observeTitle(()=>this.handleTitleChanged())),this.applyTitle()}applyClear(){const e=this.titleDocument.getTitle(),t=this.lastAppliedTitle!==null&&e===this.lastAppliedTitle,s=this.lastAppliedTitle===null?g(e):e;this.status=null,this.lastAppliedTitle=null,this.stopObserving?.(),this.stopObserving=null,t?this.titleDocument.setTitle(this.baseTitle):s!==e&&this.titleDocument.setTitle(s)}handleTitleChanged(){!this.status||this.titleDocument.getTitle()===this.lastAppliedTitle||this.applyTitle()}applyTitle(){if(!this.status)return;const e=M(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function B(i){return{getTitle:()=>i.title,setTitle:e=>{i.title=e},observeTitle:e=>{const t=new MutationObserver(e);return t.observe(i.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()}}}function g(i){return i.replace(K,"")}const f=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function F(i){if(!i||typeof i!="object")return!1;const e=i;return typeof e.observedAt=="string"&&e.observedAt.length<=40&&Number.isFinite(Date.parse(e.observedAt))&&f(e.sessionId)&&f(e.responseItemId)&&f(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}const w=500;function U(i){const e=i.replace(/\n\s*at\s[\s\S]*$/,"").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,"[REDACTED]").replace(/\b(?:set-cookie|cookie)\s*[:=]\s*[^\n]+/gi,"cookie=[REDACTED]").replace(/\bdata:[^\s<>"']+/gi,"[DATA]").replace(/\b(?:https?:\/\/|www\.)[^\s<>"']+/gi,"[URL]").replace(/\b(?:Bearer|Basic)\s+[^\s,;"']+/gi,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?/g,"[REDACTED]").replace(/\b(?:sk|pk|ghp|gho|github_pat|xoxb|xoxp)[-_][A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/\b((?:access|refresh|id|auth)[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|pwd|secret|token|jwt|authorization|cookie|set-cookie)\b["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}&]+)/gi,"$1=[REDACTED]").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[EMAIL]").replace(/(?:[A-Z]:[\\/]|\\\\|(?:~|\.\.?)?\/|[\w.-]+[\\/])[^\s<>"']+/gi,"[FILE]").replace(new RegExp("(?<![\\w.])(?:[\\w.-]+\\.[A-Z][A-Z0-9]{0,15}|\\.[A-Z][\\w.-]*)\\b","gi"),"[FILE]").replace(/\s+/g," ").trim();return e.length>w?`${e.slice(0,w-1)}…`:e}const N={"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 H(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(N,i.slice(13))}function P(i){return{...i.id===void 0?{}:{id:i.id},name:i.name,mimeType:i.mimeType,sizeBytes:i.sizeBytes,...i.sandboxPath===void 0?{}:{sandboxPath:i.sandboxPath},...i.storageKey===void 0?{}:{storageKey:i.storageKey},...i.fileUrl===void 0?{}:{fileUrl:i.fileUrl}}}function j(i){if(!i||typeof i!="object"||!("type"in i))return!1;const e=i;switch(e.type){case"runtime.connect":case"session.new":case"run.stop":case"run.retry":return!0;case"runtime.report_response_visibility":return F(e.observation);case"runtime.warmup":return e.reason==="panel_open"||e.reason==="extension_install"||e.reason==="composer_input";case"runtime.report_displayed_error":return(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.reason==="submitted_turn_returned_to_welcome_without_new_chat"||e.reason==="new_messages_button_without_user_scroll"||H(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"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.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.automationOnboarding===void 0||typeof e.automationOnboarding=="boolean")&&(e.attachments===void 0||Array.isArray(e.attachments));default:return!1}}class V{constructor(e,t,s){this.adapter=t,this.state=y(e),this.model=s}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=u("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;unacknowledgedSubmissions=new Map;operationQueue=Promise.resolve();destroyed=!1;on(e,t){const s=this.listeners[e]??new Set;return s.add(t),this.listeners[e]=s,()=>s.delete(t)}getState(){return y(this.state)}updateProjection(e,t,s,n,r){if(!this.destroyed){this.state=y(e);for(const[a,l]of this.unacknowledgedSubmissions){if(e.user?.id!==l.userId||l.sessionId!==null&&e.sessionId!==l.sessionId){this.unacknowledgedSubmissions.delete(a);continue}const o=this.state.messages.find(c=>c.clientMessageId===a);if(o){o.attachments=Z(l.message.attachments,o.attachments),this.unacknowledgedSubmissions.delete(a);continue}l.sessionId??=e.sessionId,this.state.messages.push(l.message),this.state.pendingMessageStatus="sending",this.state.turnPhase??="sending",this.state.taskStatus??="working"}if(t!==void 0&&(this.model=t),s){this.sessionHistoryState=I(s);for(const a of this.sessionHistoryListeners)a(this.getSessionHistoryState())}if(n){this.interactions=n.map(a=>({...a}));for(const a of this.interactionListeners)a(this.getInteractions())}if(r!==void 0){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.unacknowledgedSubmissions.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})}reportResponseVisibility(e){this.adapter.dispatch({type:"runtime.report_response_visibility",observation:e}).catch(()=>{})}reportInvalidStateTransition(e,t){this.adapter.dispatch({type:"runtime.report_invalid_state_transition",reason:e,clientMessageId:t}).catch(()=>{})}reportDisplayedError(e,t,s){this.adapter.dispatch({type:"runtime.report_displayed_error",reason:e,errorFingerprint:t,...s?{displayedMessage:U(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){const s=e.trim(),n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);const r=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),a=t.submittedAt??Date.now(),l=this.state,o={id:`local-${r}`,role:"user",content:s,createdAt:new Date().toISOString(),...n.length>0?{attachments:n}:{},clientMessageId:r};return this.unacknowledgedSubmissions.set(r,{message:{...o,attachments:o.attachments?.map(c=>({...c}))},sessionId:l.sessionId,userId:l.user?.id}),this.state={...this.state,messages:[...this.state.messages,o],pendingMessageStatus:"sending",turnPhase:this.state.isThinking?this.state.turnPhase:"sending",taskStatus:"working",isRetrying:!1,lastError:null},this.emit("state",this.getState()),this.enqueueOperation(()=>this.sendMessageNow(s,{...t,clientMessageId:r,submittedAt:a},l))}async sendMessageNow(e,t,s){const n=e,r=t.clientMessageId;let a=t.attachments??[],l=!1;try{if(await this.adapter.dispatch({type:"conversation.stage",content:n,clientMessageId:r,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:a.length>0?a.map(P):void 0,submittedAt:t.submittedAt}),l=!0,a.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const c=[];for(const d of a){if(d.sandboxPath||d.storageKey){c.push(d);continue}const S=d.id?this.attachmentFiles.get(d.id):void 0;if(!S)throw new Error(`Attachment bytes are unavailable for ${d.name}`);c.push(await this.adapter.uploadAttachment(S,d,{clientMessageId:r}))}a=c}const o=await 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(P):void 0});for(const c of t.attachments??[])c.id&&this.attachmentFiles.delete(c.id);return r===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),o?.clientMessageId??r}catch(o){throw this.unacknowledgedSubmissions.delete(r),this.state={...this.state,messages:this.state.messages.filter(c=>c.id!==`local-${r}`&&c.id!==`optimistic-user-message:${r}`),pendingMessageStatus:s.pendingMessageStatus,turnPhase:s.turnPhase,isThinking:s.isThinking,taskStatus:s.taskStatus},this.emit("state",this.getState()),l&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:r,message:o instanceof Error?o.message:String(o)}),o}}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(){return this.unacknowledgedSubmissions.clear(),this.dispatch({type:"run.stop"}).then(()=>{})}startNewSession(e={}){return this.unacknowledgedSubmissions.clear(),e.notifyTransport===!1?Promise.resolve():this.dispatch({type:"session.new"}).then(()=>{})}async listSessions(e={}){await this.dispatch({type:"session.list",...e});const t=this.sessionHistoryState.data;return{sessions:A(t),nextCursor:t?.nextCursor??null}}getSessionHistoryState(){return I(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,limit:20}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){return this.dispatch({type:"interaction.act",interactionId:e,action:t,expectedRevision:s,...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.unacknowledgedSubmissions.clear(),this.dispatch({type:"session.load",sessionId:e}).then(()=>{})}stageProactiveSuggestionQuestion(e){const t=e.trim();if(!t)return Promise.resolve();const s=this.stagedProactiveSuggestionClientMessageId??crypto.randomUUID();return this.stagedProactiveSuggestionClientMessageId=s,this.dispatch({type:"conversation.stage_proactive_suggestion",question:t,clientMessageId:s}).then(()=>{})}dispatch(e){return this.enqueueOperation(()=>this.adapter.dispatch(e))}enqueueOperation(e){const t=this.operationQueue.then(e);return this.operationQueue=t.then(()=>{},()=>{}),t}emit(e,t){const s=this.listeners[e];for(const n of s??[])n(t)}}function Z(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function y(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(a=>({...a}))},s=e.assistantDraftItemId,n=e.clientMessageId,r=e.proactiveSuggestionClientMessageId;return r&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:r,enumerable:!1}),s&&Object.defineProperty(t,"assistantDraftItemId",{value:s,enumerable:!1}),n&&Object.defineProperty(t,"clientMessageId",{value:n,enumerable:!1}),t}),activeScheduledFollowUps:i.activeScheduledFollowUps?.map(e=>({...e}))??null}}function I(i){return{...i,data:i.data?h({entities:A(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.ProductAgentInteractionManager=q;exports.ProductAgentQueryController=v;exports.ProductAgentRemoteRuntimeClient=V;exports.ProductAgentSessionHistoryManager=x;exports.ProductAgentTaskPageTitleController=z;exports.createLocalStorageInteractionDecisionStorage=Q;exports.createProductAgentQueryState=u;exports.createProductAgentTaskPageTitleDocument=B;exports.formatProductAgentTaskPageTitle=M;exports.hasProductAgentPaidCreditFallback=k;exports.isProductAgentRuntimeCommand=j;exports.mergeProductAgentEntityPages=E;exports.normalizeProductAgentEntityPage=h;exports.readLocalStorageInteractionDecisions=_;exports.reconcileProductAgentSubmissionGate=O;exports.resolveProductAgentBillingPresentation=R;exports.resolveProductAgentComposerAction=C;exports.resolveProductAgentWidgetPresentation=D;exports.selectProductAgentQueryEntities=A;
@@ -8,7 +8,7 @@ function h(s) {
8
8
  updatedAt: null
9
9
  };
10
10
  }
11
- class b {
11
+ class A {
12
12
  constructor(e, t, i = (n, r) => r) {
13
13
  this.loader = t, this.merge = i, this.state = h(e);
14
14
  }
@@ -93,31 +93,31 @@ function p(s) {
93
93
  nextCursor: s.nextCursor
94
94
  };
95
95
  }
96
- function _(s, e, t) {
96
+ function P(s, e, t) {
97
97
  if (t === "replace" || s === null) return e;
98
98
  const i = { ...s.entitiesById, ...e.entitiesById }, n = [...s.ids];
99
99
  for (const r of e.ids)
100
100
  s.entitiesById[r] || n.push(r);
101
101
  return { entitiesById: i, ids: n, nextCursor: e.nextCursor };
102
102
  }
103
- function I(s) {
103
+ function _(s) {
104
104
  return s ? s.ids.map((e) => s.entitiesById[e]).filter((e) => !!e) : [];
105
105
  }
106
- function L(s) {
106
+ function Q(s) {
107
107
  return s.visible ? s.minimized ? { state: "minimized" } : { state: s.open ? "visible_open" : "visible_closed" } : { state: "hidden" };
108
108
  }
109
- function q(s, e) {
109
+ function $(s, e) {
110
110
  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: [] };
111
111
  }
112
- function Q(s) {
112
+ function K(s) {
113
113
  if (!s || typeof s != "object") return !1;
114
114
  const e = s.paidCreditFallbackModel;
115
115
  return typeof e == "string" && e.length > 0;
116
116
  }
117
- function $(s) {
117
+ function z(s) {
118
118
  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 <= 0.2 ? { state: "low_credits" } : s.creditsUsed !== null ? { state: "usage" } : { state: "hidden" } : { state: "hidden" };
119
119
  }
120
- function K(s) {
120
+ function B(s) {
121
121
  const e = s.hasDraftMessage || s.hasPreSubmittedAttachment;
122
122
  return s.hasRunningAssistantTurn && !e ? {
123
123
  action: "stop",
@@ -127,9 +127,9 @@ function K(s) {
127
127
  disabled: !e || !s.canSubmitMessage
128
128
  };
129
129
  }
130
- class B {
130
+ class F {
131
131
  constructor(e, t, i = 20) {
132
- this.loadPage = t, this.limit = i, this.recentQuery = new b(
132
+ this.loadPage = t, this.limit = i, this.recentQuery = new A(
133
133
  `${e}:recent`,
134
134
  async ({ cursor: n }) => p(
135
135
  await this.loadPage({ cursor: n, limit: this.limit, pinned: !1 }).then((r) => ({
@@ -137,8 +137,8 @@ class B {
137
137
  nextCursor: r.nextCursor
138
138
  }))
139
139
  ),
140
- _
141
- ), this.pinnedQuery = new b(
140
+ P
141
+ ), this.pinnedQuery = new A(
142
142
  `${e}:pinned`,
143
143
  async () => p({
144
144
  entities: await this.loadAllPinned(),
@@ -170,7 +170,7 @@ class B {
170
170
  }) : null;
171
171
  return {
172
172
  key: e.key.slice(0, -7),
173
- status: P(e, t),
173
+ status: T(e, t),
174
174
  data: l,
175
175
  error: e.error ?? t.error,
176
176
  requestId: Math.max(e.requestId, t.requestId),
@@ -279,13 +279,13 @@ class B {
279
279
  function u(s) {
280
280
  return s ? s.ids.map((e) => s.entitiesById[e]).filter((e) => !!e) : [];
281
281
  }
282
- function P(s, e) {
282
+ function T(s, e) {
283
283
  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";
284
284
  }
285
- class z {
285
+ class U {
286
286
  constructor(e, t = null) {
287
287
  this.storage = e, t && (this.decisions = new Map(
288
- t.filter(y).map((i) => [this.getDecisionKey(i), i])
288
+ t.filter(v).map((i) => [this.getDecisionKey(i), i])
289
289
  ), this.initialized = !0);
290
290
  }
291
291
  storage;
@@ -297,7 +297,7 @@ class z {
297
297
  if (this.initialized) return;
298
298
  const e = await this.storage.load();
299
299
  this.decisions = new Map(
300
- e.filter(y).map((t) => [this.getDecisionKey(t), t])
300
+ e.filter(v).map((t) => [this.getDecisionKey(t), t])
301
301
  ), this.initialized = !0;
302
302
  }
303
303
  isEligible(e, t = Date.now()) {
@@ -318,10 +318,8 @@ class z {
318
318
  return n !== void 0 ? n : (this.scheduledEligibility.set(i, t), t);
319
319
  }
320
320
  getNextEligibilityAt(e = Date.now()) {
321
- for (const [i, n] of this.scheduledEligibility)
322
- n <= e && this.scheduledEligibility.delete(i);
323
321
  const t = [
324
- ...this.scheduledEligibility.values(),
322
+ ...Array.from(this.scheduledEligibility.values()).filter((i) => i > e),
325
323
  ...Array.from(this.decisions.values()).map((i) => i.nextEligibleAt ? Date.parse(i.nextEligibleAt) : Number.NaN).filter((i) => Number.isFinite(i) && i > e)
326
324
  ];
327
325
  return t.length > 0 ? Math.min(...t) : null;
@@ -371,17 +369,17 @@ class z {
371
369
  return `${m(e.scope)}:category:${e.category}`;
372
370
  }
373
371
  }
374
- function F(s, e) {
372
+ function N(s, e) {
375
373
  return {
376
- load: async () => T(s, e),
374
+ load: async () => M(s, e),
377
375
  save: async (t) => s.setItem(e, JSON.stringify(t))
378
376
  };
379
377
  }
380
- function T(s, e) {
378
+ function M(s, e) {
381
379
  const t = s.getItem(e);
382
380
  if (!t) return [];
383
381
  const i = JSON.parse(t);
384
- return Array.isArray(i) ? i.filter(y) : [];
382
+ return Array.isArray(i) ? i.filter(v) : [];
385
383
  }
386
384
  function m(s) {
387
385
  return `${s.level}:${s.key}`;
@@ -389,23 +387,23 @@ function m(s) {
389
387
  function E(s) {
390
388
  return s === "dismiss" || s === "later" || s === "snooze" || s === "never" || s === "dont_show_again";
391
389
  }
392
- function y(s) {
390
+ function v(s) {
393
391
  if (!s || typeof s != "object") return !1;
394
392
  const e = s;
395
393
  return typeof e.promptKey == "string" && typeof e.category == "string" && typeof e.decidedAt == "string" && (e.nextEligibleAt === null || typeof e.nextEligibleAt == "string") && E(e.action) && !!(e.scope && typeof e.scope == "object" && typeof e.scope.level == "string" && typeof e.scope.key == "string");
396
394
  }
397
- const M = {
395
+ const D = {
398
396
  working: "⏳",
399
397
  completed: "✅",
400
398
  failed: "❗",
401
399
  stopped: "⏹️"
402
- }, D = /^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;
403
- function O(s, e) {
400
+ }, O = /^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;
401
+ function k(s, e) {
404
402
  if (!e) return g(s);
405
- const t = g(s), i = `${M[e]} Pluno`;
403
+ const t = g(s), i = `${D[e]} Pluno`;
406
404
  return t ? `${i}: ${t}` : i;
407
405
  }
408
- class U {
406
+ class H {
409
407
  constructor(e) {
410
408
  this.titleDocument = e;
411
409
  }
@@ -439,11 +437,11 @@ class U {
439
437
  applyTitle() {
440
438
  if (!this.status)
441
439
  return;
442
- const e = O(this.baseTitle, this.status);
440
+ const e = k(this.baseTitle, this.status);
443
441
  this.lastAppliedTitle = e, this.titleDocument.getTitle() !== e && this.titleDocument.setTitle(e);
444
442
  }
445
443
  }
446
- function N(s) {
444
+ function j(s) {
447
445
  return {
448
446
  getTitle: () => s.title,
449
447
  setTitle: (e) => {
@@ -460,14 +458,20 @@ function N(s) {
460
458
  };
461
459
  }
462
460
  function g(s) {
463
- return s.replace(D, "");
461
+ return s.replace(O, "");
462
+ }
463
+ const f = (s) => s === null || typeof s == "string" && /^[a-zA-Z0-9:_-]{1,160}$/.test(s);
464
+ function R(s) {
465
+ if (!s || typeof s != "object") return !1;
466
+ const e = s;
467
+ return typeof e.observedAt == "string" && e.observedAt.length <= 40 && Number.isFinite(Date.parse(e.observedAt)) && f(e.sessionId) && f(e.responseItemId) && f(e.respondsToUserMessageId) && typeof e.panelVisible == "boolean" && typeof e.documentVisible == "boolean" && typeof e.loading == "boolean";
464
468
  }
465
469
  const S = 500;
466
- function k(s) {
470
+ function x(s) {
467
471
  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();
468
472
  return e.length > S ? `${e.slice(0, S - 1)}…` : e;
469
473
  }
470
- const x = {
474
+ const C = {
471
475
  "duplicate-message-item": "A canonical message rendered more than once.",
472
476
  "duplicate-canonical-item": "A canonical session item rendered more than once.",
473
477
  "duplicate-tool-call": "A tool call rendered more than once.",
@@ -480,10 +484,10 @@ const x = {
480
484
  "thinking-groups-without-user-message": "Multiple thinking groups appeared without a user message between them.",
481
485
  "thinking-without-progress": "Thinking remained visible without progress for five minutes."
482
486
  };
483
- function R(s) {
484
- return typeof s == "string" && s.startsWith("ui_invariant:") && Object.prototype.hasOwnProperty.call(x, s.slice(13));
487
+ function L(s) {
488
+ return typeof s == "string" && s.startsWith("ui_invariant:") && Object.prototype.hasOwnProperty.call(C, s.slice(13));
485
489
  }
486
- function A(s) {
490
+ function w(s) {
487
491
  return {
488
492
  ...s.id === void 0 ? {} : { id: s.id },
489
493
  name: s.name,
@@ -494,7 +498,7 @@ function A(s) {
494
498
  ...s.fileUrl === void 0 ? {} : { fileUrl: s.fileUrl }
495
499
  };
496
500
  }
497
- function H(s) {
501
+ function V(s) {
498
502
  if (!s || typeof s != "object" || !("type" in s)) return !1;
499
503
  const e = s;
500
504
  switch (e.type) {
@@ -503,12 +507,14 @@ function H(s) {
503
507
  case "run.stop":
504
508
  case "run.retry":
505
509
  return !0;
510
+ case "runtime.report_response_visibility":
511
+ return R(e.observation);
506
512
  case "runtime.warmup":
507
513
  return e.reason === "panel_open" || e.reason === "extension_install" || e.reason === "composer_input";
508
514
  case "runtime.report_displayed_error":
509
515
  return (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);
510
516
  case "runtime.report_invalid_state_transition":
511
- return (e.reason === "submitted_turn_returned_to_welcome_without_new_chat" || e.reason === "new_messages_button_without_user_scroll" || R(e.reason)) && (e.clientMessageId === void 0 || typeof e.clientMessageId == "string");
517
+ return (e.reason === "submitted_turn_returned_to_welcome_without_new_chat" || e.reason === "new_messages_button_without_user_scroll" || L(e.reason)) && (e.clientMessageId === void 0 || typeof e.clientMessageId == "string");
512
518
  case "runtime.widget_lifecycle":
513
519
  return (e.action === "opened" || e.action === "closed" || e.action === "minimized") && typeof e.trigger == "string";
514
520
  case "session.load":
@@ -535,9 +541,9 @@ function H(s) {
535
541
  return !1;
536
542
  }
537
543
  }
538
- class j {
544
+ class Z {
539
545
  constructor(e, t, i) {
540
- this.adapter = t, this.state = f(e), this.model = i;
546
+ this.adapter = t, this.state = y(e), this.model = i;
541
547
  }
542
548
  adapter;
543
549
  listeners = {};
@@ -559,11 +565,11 @@ class j {
559
565
  return i.add(t), this.listeners[e] = i, () => i.delete(t);
560
566
  }
561
567
  getState() {
562
- return f(this.state);
568
+ return y(this.state);
563
569
  }
564
570
  updateProjection(e, t, i, n, r) {
565
571
  if (!this.destroyed) {
566
- this.state = f(e);
572
+ this.state = y(e);
567
573
  for (const [a, l] of this.unacknowledgedSubmissions) {
568
574
  if (e.user?.id !== l.userId || l.sessionId !== null && e.sessionId !== l.sessionId) {
569
575
  this.unacknowledgedSubmissions.delete(a);
@@ -573,7 +579,7 @@ class j {
573
579
  (c) => c.clientMessageId === a
574
580
  );
575
581
  if (o) {
576
- o.attachments = C(
582
+ o.attachments = q(
577
583
  l.message.attachments,
578
584
  o.attachments
579
585
  ), this.unacknowledgedSubmissions.delete(a);
@@ -582,7 +588,7 @@ class j {
582
588
  l.sessionId ??= e.sessionId, this.state.messages.push(l.message), this.state.pendingMessageStatus = "sending", this.state.turnPhase ??= "sending", this.state.taskStatus ??= "working";
583
589
  }
584
590
  if (t !== void 0 && (this.model = t), i) {
585
- this.sessionHistoryState = w(i);
591
+ this.sessionHistoryState = I(i);
586
592
  for (const a of this.sessionHistoryListeners)
587
593
  a(this.getSessionHistoryState());
588
594
  }
@@ -614,6 +620,10 @@ class j {
614
620
  recordWidgetLifecycle(e, t) {
615
621
  this.dispatch({ type: "runtime.widget_lifecycle", action: e, trigger: t });
616
622
  }
623
+ reportResponseVisibility(e) {
624
+ this.adapter.dispatch({ type: "runtime.report_response_visibility", observation: e }).catch(() => {
625
+ });
626
+ }
617
627
  reportInvalidStateTransition(e, t) {
618
628
  this.adapter.dispatch({
619
629
  type: "runtime.report_invalid_state_transition",
@@ -627,7 +637,7 @@ class j {
627
637
  type: "runtime.report_displayed_error",
628
638
  reason: e,
629
639
  errorFingerprint: t,
630
- ...i ? { displayedMessage: k(i) } : {}
640
+ ...i ? { displayedMessage: x(i) } : {}
631
641
  }).catch(() => {
632
642
  });
633
643
  }
@@ -670,7 +680,7 @@ class j {
670
680
  clientMessageId: r,
671
681
  proactiveSuggestionQuestion: t.proactiveSuggestionQuestion,
672
682
  // Preview URLs belong to the renderer's optimistic snapshot and are not valid runtime-command metadata.
673
- attachments: a.length > 0 ? a.map(A) : void 0,
683
+ attachments: a.length > 0 ? a.map(w) : void 0,
674
684
  submittedAt: t.submittedAt
675
685
  }), l = !0, a.length > 0) {
676
686
  if (!this.adapter.uploadAttachment)
@@ -681,9 +691,9 @@ class j {
681
691
  c.push(d);
682
692
  continue;
683
693
  }
684
- const v = d.id ? this.attachmentFiles.get(d.id) : void 0;
685
- if (!v) throw new Error(`Attachment bytes are unavailable for ${d.name}`);
686
- c.push(await this.adapter.uploadAttachment(v, d, { clientMessageId: r }));
694
+ const b = d.id ? this.attachmentFiles.get(d.id) : void 0;
695
+ if (!b) throw new Error(`Attachment bytes are unavailable for ${d.name}`);
696
+ c.push(await this.adapter.uploadAttachment(b, d, { clientMessageId: r }));
687
697
  }
688
698
  a = c;
689
699
  }
@@ -695,7 +705,7 @@ class j {
695
705
  invocation: t.invocation,
696
706
  proactiveSuggestionQuestion: t.proactiveSuggestionQuestion,
697
707
  ...t.automationOnboarding ? { automationOnboarding: !0 } : {},
698
- attachments: a.length > 0 ? a.map(A) : void 0
708
+ attachments: a.length > 0 ? a.map(w) : void 0
699
709
  });
700
710
  for (const c of t.attachments ?? [])
701
711
  c.id && this.attachmentFiles.delete(c.id);
@@ -748,12 +758,12 @@ class j {
748
758
  await this.dispatch({ type: "session.list", ...e });
749
759
  const t = this.sessionHistoryState.data;
750
760
  return {
751
- sessions: I(t),
761
+ sessions: _(t),
752
762
  nextCursor: t?.nextCursor ?? null
753
763
  };
754
764
  }
755
765
  getSessionHistoryState() {
756
- return w(this.sessionHistoryState);
766
+ return I(this.sessionHistoryState);
757
767
  }
758
768
  subscribeSessionHistory(e) {
759
769
  return this.sessionHistoryListeners.add(e), e(this.getSessionHistoryState()), () => this.sessionHistoryListeners.delete(e);
@@ -832,7 +842,7 @@ class j {
832
842
  for (const n of i ?? []) n(t);
833
843
  }
834
844
  }
835
- function C(s, e) {
845
+ function q(s, e) {
836
846
  if (!e || !s) return e;
837
847
  const t = /* @__PURE__ */ new Map();
838
848
  for (const i of s) {
@@ -844,7 +854,7 @@ function C(s, e) {
844
854
  return n ? { ...i, previewUrl: n } : i;
845
855
  });
846
856
  }
847
- function f(s) {
857
+ function y(s) {
848
858
  return {
849
859
  ...s,
850
860
  starterPrompts: [...s.starterPrompts],
@@ -868,33 +878,33 @@ function f(s) {
868
878
  activeScheduledFollowUps: s.activeScheduledFollowUps?.map((e) => ({ ...e })) ?? null
869
879
  };
870
880
  }
871
- function w(s) {
881
+ function I(s) {
872
882
  return {
873
883
  ...s,
874
884
  data: s.data ? p({
875
- entities: I(s.data).map((e) => ({ ...e })),
885
+ entities: _(s.data).map((e) => ({ ...e })),
876
886
  nextCursor: s.data.nextCursor
877
887
  }) : null
878
888
  };
879
889
  }
880
890
  export {
881
- z as ProductAgentInteractionManager,
882
- b as ProductAgentQueryController,
883
- j as ProductAgentRemoteRuntimeClient,
884
- B as ProductAgentSessionHistoryManager,
885
- U as ProductAgentTaskPageTitleController,
886
- F as createLocalStorageInteractionDecisionStorage,
891
+ U as ProductAgentInteractionManager,
892
+ A as ProductAgentQueryController,
893
+ Z as ProductAgentRemoteRuntimeClient,
894
+ F as ProductAgentSessionHistoryManager,
895
+ H as ProductAgentTaskPageTitleController,
896
+ N as createLocalStorageInteractionDecisionStorage,
887
897
  h as createProductAgentQueryState,
888
- N as createProductAgentTaskPageTitleDocument,
889
- O as formatProductAgentTaskPageTitle,
890
- Q as hasProductAgentPaidCreditFallback,
891
- H as isProductAgentRuntimeCommand,
892
- _ as mergeProductAgentEntityPages,
898
+ j as createProductAgentTaskPageTitleDocument,
899
+ k as formatProductAgentTaskPageTitle,
900
+ K as hasProductAgentPaidCreditFallback,
901
+ V as isProductAgentRuntimeCommand,
902
+ P as mergeProductAgentEntityPages,
893
903
  p as normalizeProductAgentEntityPage,
894
- T as readLocalStorageInteractionDecisions,
895
- q as reconcileProductAgentSubmissionGate,
896
- $ as resolveProductAgentBillingPresentation,
897
- K as resolveProductAgentComposerAction,
898
- L as resolveProductAgentWidgetPresentation,
899
- I as selectProductAgentQueryEntities
904
+ M as readLocalStorageInteractionDecisions,
905
+ $ as reconcileProductAgentSubmissionGate,
906
+ z as resolveProductAgentBillingPresentation,
907
+ B as resolveProductAgentComposerAction,
908
+ Q as resolveProductAgentWidgetPresentation,
909
+ _ as selectProductAgentQueryEntities
900
910
  };