@pluno/product-agent-web 0.1.220 → 0.1.221
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/README.md +8 -0
- package/dist/activeUsersCounter.d.ts +0 -7
- package/dist/adapters/web/activeUsers.d.ts +4 -0
- package/dist/adapters/web/backendHttp.d.ts +12 -0
- package/dist/adapters/web/backendTransport.d.ts +54 -0
- package/dist/adapters/web/directoryAdapters.d.ts +85 -0
- package/dist/adapters/web/directoryScope.d.ts +42 -0
- package/dist/adapters/web/modelScope.d.ts +3 -0
- package/dist/adapters/web/socketIOTransport.d.ts +72 -0
- package/dist/chatPresentation.d.ts +2 -0
- package/dist/core/active-users/reducer.d.ts +47 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/model-selection/commands.d.ts +22 -0
- package/dist/core/model-selection/contracts.d.ts +3 -1
- package/dist/core/model-selection/events.d.ts +15 -0
- package/dist/core/model-selection/reducer.d.ts +4 -0
- package/dist/core/model-selection/selectors.d.ts +10 -0
- package/dist/core/model-selection/state.d.ts +22 -0
- package/dist/core/protocol/modelRouting.d.ts +2 -0
- package/dist/core/session-directory/contracts.d.ts +202 -0
- package/dist/core/session-directory/membership.d.ts +4 -0
- package/dist/core/session-directory/reducer.d.ts +4 -0
- package/dist/core/session-directory/selectors.d.ts +2 -0
- package/dist/core/session-directory/state.d.ts +6 -0
- package/dist/index.d.ts +28 -16
- package/dist/interruptState.d.ts +2 -0
- package/dist/product-agent-runtime.cjs +1 -1
- package/dist/product-agent-runtime.js +384 -315
- package/dist/product-agent-sdk.js +7611 -3447
- package/dist/product-agent-widget.js +8794 -4769
- package/dist/public/operationRoutes.d.ts +1 -0
- package/dist/runtime/composition.d.ts +27 -7
- package/dist/runtime/modelSelection.d.ts +14 -0
- package/dist/runtimeClient.d.ts +10 -0
- package/dist/sessionRecoveryPolling.d.ts +3 -0
- package/dist/timelineReconciliation.d.ts +1 -0
- package/dist/uiInvariants.d.ts +6 -0
- package/dist/widget.d.ts +1 -0
- package/package.json +4 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { PAClientScopeId, PASessionId } from "../kernel/state";
|
|
2
|
+
import type { PADirectoryCommand, PADirectoryState } from "./contracts";
|
|
3
|
+
export declare function reduceDirectoryMembership(state: PADirectoryState, input: PADirectoryCommand): PADirectoryState;
|
|
4
|
+
export declare function isDirectoryTabEligible(state: PADirectoryState, client: PAClientScopeId, sessionId: PASessionId): boolean;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { PAEffectResultEvent } from "../kernel/effects";
|
|
2
|
+
import type { PAReduction } from "../kernel/reducer";
|
|
3
|
+
import type { PADirectoryCommand, PADirectoryEffects, PADirectoryEvent, PADirectoryState } from "./contracts";
|
|
4
|
+
export declare function reduceDirectory(state: PADirectoryState, input: PADirectoryCommand | PADirectoryEvent | PAEffectResultEvent<PADirectoryEffects>): PAReduction<PADirectoryState, PADirectoryEffects>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { PADirectoryQuery, PADirectoryQueryState, PADirectoryState } from "./contracts";
|
|
2
|
+
export declare function freezeDirectoryValue<T>(value: T): T;
|
|
3
|
+
export declare function createDirectoryState(): PADirectoryState;
|
|
4
|
+
export declare function directoryQueryKey(query: PADirectoryQuery): string;
|
|
5
|
+
export declare function selectDirectoryPagesForOrigin(queries: Readonly<Record<string, PADirectoryQueryState>>, origin: string | null): readonly PADirectoryQueryState[];
|
|
6
|
+
export declare function selectCombinedDirectoryPage(pages: readonly PADirectoryQueryState[]): PADirectoryQueryState | undefined;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ActiveUsersCounterValue } from "./activeUsersCounter";
|
|
1
2
|
import type { ProductAgentTaskStatus } from "./taskPageTitle";
|
|
2
3
|
import type { ProductAgentEntityQueryData, ProductAgentAccountProjection, ProductAgentInteraction, ProductAgentInteractionAction, ProductAgentQueryState } from "./runtimeState";
|
|
3
4
|
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";
|
|
@@ -129,6 +130,7 @@ export type ProductAgentAppearance = {
|
|
|
129
130
|
};
|
|
130
131
|
export type ProductAgentTurnPhase = "sending" | "starting" | "thinking";
|
|
131
132
|
export type ProductAgentState = {
|
|
133
|
+
activeUsersCount?: number | null;
|
|
132
134
|
status: "idle" | "connecting" | "connected" | "reconnecting" | "closed" | "error";
|
|
133
135
|
user: ProductAgentUser | null;
|
|
134
136
|
sessionId: string | null;
|
|
@@ -164,6 +166,7 @@ export declare class ProductAgentTokenProviderError extends Error {
|
|
|
164
166
|
constructor(message: string, retryable: boolean, status?: number | undefined, retryAfterMs?: number | undefined);
|
|
165
167
|
}
|
|
166
168
|
export type ProductAgentInitOptions = {
|
|
169
|
+
activeUsersLoader?: () => Promise<ActiveUsersCounterValue>;
|
|
167
170
|
token?: string;
|
|
168
171
|
tokenProvider?: (context?: ProductAgentTokenProviderContext) => Promise<string>;
|
|
169
172
|
backendUrl?: string;
|
|
@@ -180,6 +183,7 @@ export type ProductAgentInitOptions = {
|
|
|
180
183
|
restorePersistedState?: boolean;
|
|
181
184
|
expectedPersistedSessionId?: string | null;
|
|
182
185
|
runtimeCommunityId?: string;
|
|
186
|
+
localRuntimeClientId?: string | null;
|
|
183
187
|
automationRunId?: string;
|
|
184
188
|
keepRunsActiveOnSessionNavigation?: boolean;
|
|
185
189
|
capturePageContent?: boolean;
|
|
@@ -283,6 +287,8 @@ export declare class ProductAgentSessionEngine {
|
|
|
283
287
|
private connectionAttemptId;
|
|
284
288
|
private connectionInProgress;
|
|
285
289
|
private token;
|
|
290
|
+
private rejectedTransportToken;
|
|
291
|
+
private refreshingDefaultCredentials;
|
|
286
292
|
private tokenExpiresAtMs;
|
|
287
293
|
private tokenRequest;
|
|
288
294
|
private tokenAbortController;
|
|
@@ -298,12 +304,13 @@ export declare class ProductAgentSessionEngine {
|
|
|
298
304
|
private activeComposerWarmupId;
|
|
299
305
|
private activeComposerWarmupScope;
|
|
300
306
|
private pendingWarmupAckTimer;
|
|
301
|
-
private
|
|
302
|
-
private readonly
|
|
303
|
-
private
|
|
304
|
-
private
|
|
305
|
-
private
|
|
306
|
-
private
|
|
307
|
+
private directoryAuthority;
|
|
308
|
+
private readonly directoryHttp;
|
|
309
|
+
private directoryScope;
|
|
310
|
+
private directoryObservation;
|
|
311
|
+
private directoryConversationScopeId;
|
|
312
|
+
private directoryProvisionalId;
|
|
313
|
+
private readonly conversationRecoveries;
|
|
307
314
|
private account;
|
|
308
315
|
private usingPaidCreditFallback;
|
|
309
316
|
private readonly accountListeners;
|
|
@@ -314,8 +321,6 @@ export declare class ProductAgentSessionEngine {
|
|
|
314
321
|
private integrationAuthStatusByRequestId;
|
|
315
322
|
private integrationAuthErrorByRequestId;
|
|
316
323
|
private tabGroupsPermissionNeeded;
|
|
317
|
-
private pendingSessionPinRequests;
|
|
318
|
-
private pendingSessionRenameRequests;
|
|
319
324
|
private sessionLoadRequestId;
|
|
320
325
|
private sessionLoadRequestTimer;
|
|
321
326
|
private pendingSessionSubscription;
|
|
@@ -348,7 +353,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
348
353
|
private pendingClientMessageId;
|
|
349
354
|
private pendingUserMessageEvent;
|
|
350
355
|
private failedUserMessageEvent;
|
|
351
|
-
private
|
|
356
|
+
private readonly modelClientScopeId;
|
|
352
357
|
private activeClientMessageId;
|
|
353
358
|
private activeRunAckObserved;
|
|
354
359
|
private activeResponseUserMessageId;
|
|
@@ -363,6 +368,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
363
368
|
private readonly attachmentFiles;
|
|
364
369
|
private sessionBrowserApisCleanup;
|
|
365
370
|
private readonly activeBrowserToolCalls;
|
|
371
|
+
private readonly cancelledSubmissions;
|
|
366
372
|
private readonly stoppedTurns;
|
|
367
373
|
private readonly pendingToolLoadingByCallId;
|
|
368
374
|
private readonly terminalToolCallIds;
|
|
@@ -376,6 +382,12 @@ export declare class ProductAgentSessionEngine {
|
|
|
376
382
|
private state;
|
|
377
383
|
private constructor();
|
|
378
384
|
static init(options: ProductAgentInitOptions): Promise<ProductAgentSessionEngine>;
|
|
385
|
+
private createConversationRecovery;
|
|
386
|
+
private createDirectoryAdapters;
|
|
387
|
+
private initializeDirectory;
|
|
388
|
+
private handleDirectoryTransportError;
|
|
389
|
+
private beginDirectoryProvisional;
|
|
390
|
+
private selectDirectorySession;
|
|
379
391
|
on<T extends EventName>(eventName: T, listener: Listener<T>): () => void;
|
|
380
392
|
getState(): ProductAgentState;
|
|
381
393
|
stageProactiveSuggestionQuestion(question: string): void;
|
|
@@ -407,6 +419,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
407
419
|
private updateAttachmentInState;
|
|
408
420
|
private prepareEmbedAttachmentUpload;
|
|
409
421
|
private fetchEmbedAttachmentUpload;
|
|
422
|
+
private getStopClientMessageId;
|
|
410
423
|
stop(): void;
|
|
411
424
|
startNewSession(options?: {
|
|
412
425
|
notifyTransport?: boolean;
|
|
@@ -422,6 +435,9 @@ export declare class ProductAgentSessionEngine {
|
|
|
422
435
|
loadMoreSessionHistory(): Promise<void>;
|
|
423
436
|
setSessionPinned(sessionId: string, pinned: boolean): Promise<void>;
|
|
424
437
|
renameSession(sessionId: string, title: string): Promise<void>;
|
|
438
|
+
private getDirectoryQuery;
|
|
439
|
+
private toSessionHistoryEntry;
|
|
440
|
+
private refreshDirectoryQuery;
|
|
425
441
|
getInteractions(): readonly ProductAgentInteraction[];
|
|
426
442
|
subscribeInteractions(listener: (interactions: readonly ProductAgentInteraction[]) => void): () => void;
|
|
427
443
|
actOnInteraction(interactionId: string, action: ProductAgentInteractionAction, expectedRevision: number, input?: {
|
|
@@ -460,6 +476,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
460
476
|
private clearStarterPromptUrlRefreshTimer;
|
|
461
477
|
private flushQueuedClientEvents;
|
|
462
478
|
private resetForAuthenticationScopeChange;
|
|
479
|
+
private applyAuthenticatedDirectoryIdentity;
|
|
463
480
|
private rememberSessionTimeline;
|
|
464
481
|
private getCachedSessionTimeline;
|
|
465
482
|
private flushPendingWidgetLifecycleEvents;
|
|
@@ -484,12 +501,7 @@ export declare class ProductAgentSessionEngine {
|
|
|
484
501
|
private handleRetryableRecoveryError;
|
|
485
502
|
private clearRetryTimers;
|
|
486
503
|
private rememberUserMessageClientMessageIds;
|
|
487
|
-
private rejectPendingSessionHistoryRequests;
|
|
488
504
|
private clearSessionLoadRequest;
|
|
489
|
-
private sendSessionMutation;
|
|
490
|
-
private resolvePendingSessionMutation;
|
|
491
|
-
private rejectPendingSessionMutation;
|
|
492
|
-
private rejectPendingSessionMutationRequests;
|
|
493
505
|
private markThinkingProgress;
|
|
494
506
|
private scheduleThinkingWatchdog;
|
|
495
507
|
private clearThinkingWatchdog;
|
|
@@ -522,6 +534,8 @@ export declare class ProductAgentSessionEngine {
|
|
|
522
534
|
private enableNetworkCapture;
|
|
523
535
|
private enqueueNetworkEvent;
|
|
524
536
|
private scheduleReconnect;
|
|
537
|
+
private replaceDefaultTransportCredentials;
|
|
538
|
+
private refreshDefaultTransportCredentials;
|
|
525
539
|
private startHeartbeat;
|
|
526
540
|
private stopHeartbeat;
|
|
527
541
|
private clearHeartbeatAckTimer;
|
|
@@ -533,8 +547,6 @@ export declare class ProductAgentSessionEngine {
|
|
|
533
547
|
private replaceTimedOutSocket;
|
|
534
548
|
private setState;
|
|
535
549
|
private setReconnectingState;
|
|
536
|
-
private startSessionRecoveryPolling;
|
|
537
|
-
private stopSessionRecoveryPolling;
|
|
538
550
|
private applySessionRecoverySnapshot;
|
|
539
551
|
private emit;
|
|
540
552
|
}
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function g(i){return{key:i,status:"not_requested",data:null,error:null,requestId:0,updatedAt:null}}class I{constructor(e,t,s=(n,o)=>o){this.loader=t,this.merge=s,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,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 m(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 D(i,e,t){if(t==="replace"||i===null)return e;const s={...i.entitiesById,...e.entitiesById},n=[...i.ids];for(const o of e.ids)i.entitiesById[o]||n.push(o);return{entitiesById:s,ids:n,nextCursor:e.nextCursor}}function O(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function x(i){return i.visible?i.minimized?{state:"minimized"}:{state:i.open?"visible_open":"visible_closed"}:{state:"hidden"}}function L(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 q(i){if(!i||typeof i!="object")return!1;const e=i.paidCreditFallbackModel;return typeof e=="string"&&e.length>0}function Q(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 U(i){const e=i.hasDraftMessage||i.hasPreSubmittedAttachment;return i.hasRunningAssistantTurn&&!i.hasDraftMessage?{action:"stop",disabled:!i.canStopRunningTurn}:{action:"send",disabled:!e||!i.canSubmitMessage}}class ${constructor(e,t,s=20){this.loadPage=t,this.limit=s,this.recentQuery=new I(`${e}:recent`,async({cursor:n})=>m(await this.loadPage({cursor:n,limit:this.limit,pinned:!1}).then(o=>({entities:o.sessions,nextCursor:o.nextCursor}))),D),this.pinnedQuery=new I(`${e}:pinned`,async()=>m({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=[...f(t.data),...f(e.data)],n=new Map(s.map(a=>[a.id,a])),o=Array.from(n.values()).map(a=>this.applyOverrides(a,this.completedRefreshSequence)),l=Array.from(this.optimisticEntities.values()).filter(a=>!n.has(a.id)).reverse(),r=e.data||t.data||l.length>0?m({entities:[...l,...o],nextCursor:e.data?.nextCursor??null}):null;return{key:e.key.slice(0,-7),status:B(e,t),data:r,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=[...f(this.pinnedQuery.getState().data),...f(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 o=this.pinnedOverrides.get(e.id);return o&&(t>=o.confirmAfterRefresh&&e.isPinned===!0===o.pinned?this.pinnedOverrides.delete(e.id):s={...s,isPinned:o.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 f(i){return i?i.ids.map(e=>i.entitiesById[e]).filter(e=>!!e):[]}function B(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 K{constructor(e,t=null){this.storage=e,t&&(this.decisions=new Map(t.filter(w).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(w).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(!R(t))throw new Error(`Interaction action ${t} is not a persistence decision.`);const n=s.now??new Date,o={promptKey:e.key,category:e.category,action:t,scope:e.scope,decidedAt:n.toISOString(),nextEligibleAt:this.getNextEligibleAt(e,t,n,s.snoozeUntil)},l=t==="dont_show_again"?this.getCategoryKey(e):this.getExactKey(e),r=new Map(this.decisions);return r.set(l,o),await this.storage.save([...r.values()]),this.decisions=r,o}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=b(e.scope);return e.action==="dont_show_again"?`${t}:category:${e.category}`:`${t}:interaction:${e.promptKey}`}getExactKey(e){return`${b(e.scope)}:interaction:${e.key}`}getCategoryKey(e){return`${b(e.scope)}:category:${e.category}`}}function N(i,e){return{load:async()=>k(i,e),save:async t=>i.setItem(e,JSON.stringify(t))}}function k(i,e){const t=i.getItem(e);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(w):[]}function b(i){return`${i.level}:${i.key}`}function R(i){return i==="dismiss"||i==="later"||i==="snooze"||i==="never"||i==="dont_show_again"}function w(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")&&R(e.action)&&!!(e.scope&&typeof e.scope=="object"&&typeof e.scope.level=="string"&&typeof e.scope.key=="string")}const j={working:"⏳",completed:"✅",failed:"❗",stopped:"⏹️"},F=/^(?:⌛|⏳|✅|❗|⏹️) Pluno(?:: )?/;function C(i,e){if(!e)return y(i);const t=y(i),s=`${j[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=y(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?y(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=C(this.baseTitle,this.status);this.lastAppliedTitle=e,this.titleDocument.getTitle()!==e&&this.titleDocument.setTitle(e)}}function H(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 y(i){return i.replace(F,"")}function P(i,e){const t=new Set([i.assistantDraftRespondsToUserMessageId,i.activeResponseUserMessageId,i.messages.filter(n=>n.role==="user").slice(-1)[0]?.id].filter(n=>!!n)),s=i.messages.filter(n=>!(n.dataType==="run_status"&&n.loading&&t.has(n.respondsToUserMessageId??""))).map(n=>t.has(n.respondsToUserMessageId??"")?{...n,loading:!1}:n);for(const n of t)s.some(o=>o.respondsToUserMessageId===n&&(o.dataType==="run_status"||o.dataType==="run_error"||o.role==="assistant"&&o.phase!=="commentary"))||s.push({id:`local-interrupted:${n}`,role:"system",dataType:"run_status",content:"Run stopped by user.",createdAt:e,respondsToUserMessageId:n});return{...i,messages:s,isThinking:!1,isRetrying:!1,pendingMessageStatus:null,turnPhase:null,taskStatus:"stopped",lastError:null,lastErrorCode:null}}const S=i=>i===null||typeof i=="string"&&/^[a-zA-Z0-9:_-]{1,160}$/.test(i);function G(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))&&S(e.sessionId)&&S(e.responseItemId)&&S(e.respondsToUserMessageId)&&typeof e.panelVisible=="boolean"&&typeof e.documentVisible=="boolean"&&typeof e.loading=="boolean"}const M=500;function V(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>M?`${e.slice(0,M-1)}…`:e}const Z={"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 J(i){return typeof i=="string"&&i.startsWith("ui_invariant:")&&Object.prototype.hasOwnProperty.call(Z,i.slice(13))}function T(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 W(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.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 G(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"||J(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 Y{constructor(e,t,s){this.adapter=t,this.state=A(e),this.model=s}adapter;listeners={};attachmentFiles=new Map;sessionHistoryListeners=new Set;interactionListeners=new Set;accountListeners=new Set;state;sessionHistoryState=g("unavailable");model;interactions=[];account=null;stagedProactiveSuggestionClientMessageId=null;unacknowledgedSubmissions=new Map;submissionGeneration=0;stoppedProjection=null;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 A(this.state)}updateProjection(e,t,s,n,o){if(this.destroyed)return;const l=this.state;if(this.state=A(e),l.user?.id===e.user?.id)for(const r of this.state.messages){if(r.role!=="user"||!r.attachments?.length)continue;const a=r.clientMessageId,d=l.messages.find(u=>u.role==="user"&&(u.id===r.id||a&&u.clientMessageId===a));l.sessionId!==e.sessionId&&!(l.sessionId===null&&a&&d?.clientMessageId===a)||(r.attachments=_(d?.attachments,r.attachments))}if(this.stoppedProjection){const r=this.stoppedProjection,a=new Set(r.messages.filter(c=>c.role==="user").map(c=>c.id)),d=e.sessionId===r.sessionId&&e.user?.id===r.user?.id,u=e.messages.some(c=>c.role==="user"&&!a.has(c.id)&&!r.messages.some(h=>h.clientMessageId&&h.clientMessageId===c.clientMessageId));if(!d||u)this.stoppedProjection=null;else{const c=[r.activeResponseUserMessageId,r.assistantDraftRespondsToUserMessageId,r.messages.filter(v=>v.role==="user").slice(-1)[0]?.id].filter(Boolean),h=c.length>0&&c.every(v=>e.messages.some(p=>p.respondsToUserMessageId===v&&!p.loading&&(p.dataType==="run_status"||p.dataType==="run_error"||p.role==="assistant"&&p.phase!=="commentary")));this.state=P(h?this.state:{...this.state,messages:r.messages,assistantDraft:r.assistantDraft},new Date().toISOString()),this.stoppedProjection=this.getState()}}for(const[r,a]of this.unacknowledgedSubmissions){if(e.user?.id!==a.userId||a.sessionId!==null&&e.sessionId!==a.sessionId){this.unacknowledgedSubmissions.delete(r);continue}const d=this.state.messages.find(u=>u.clientMessageId===r);if(d){d.attachments=_(a.message.attachments,d.attachments),this.unacknowledgedSubmissions.delete(r);continue}a.sessionId??=e.sessionId,this.state.messages.push(a.message),this.state.pendingMessageStatus="sending",this.state.turnPhase??="sending",this.state.taskStatus??="working"}if(t!==void 0&&(this.model=t),s&&JSON.stringify(s)!==JSON.stringify(this.sessionHistoryState)){this.sessionHistoryState=E(s);for(const r of this.sessionHistoryListeners)r(this.getSessionHistoryState())}if(n&&JSON.stringify(n)!==JSON.stringify(this.interactions)){this.interactions=n.map(r=>({...r}));for(const r of this.interactionListeners)r(this.getInteractions())}if(o!==void 0&&JSON.stringify(o)!==JSON.stringify(this.account)){this.account=o?{...o}:null;for(const r of this.accountListeners)r(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:V(s)}:{}}).catch(()=>{})}sendMessage(e,t={}){const s=e.trim(),n=t.attachments??[];if(!s&&n.length===0)return Promise.resolve(null);const o=t.clientMessageId??(t.proactiveSuggestionQuestion&&this.stagedProactiveSuggestionClientMessageId?this.stagedProactiveSuggestionClientMessageId:crypto.randomUUID()),l=t.submittedAt??Date.now(),r=this.state,a=this.submissionGeneration,d={id:`local-${o}`,role:"user",content:s,createdAt:new Date().toISOString(),...n.length>0?{attachments:n}:{},clientMessageId:o};this.unacknowledgedSubmissions.set(o,{message:{...d,attachments:d.attachments?.map(c=>({...c}))},sessionId:r.sessionId,userId:r.user?.id}),this.state={...this.state,messages:[...this.state.messages,d],pendingMessageStatus:"sending",turnPhase:this.state.isThinking?this.state.turnPhase:"sending",taskStatus:"working",isRetrying:!1,lastError:null};const u=this.enqueueOperation(()=>this.sendMessageNow(s,{...t,clientMessageId:o,submittedAt:l},r,a));return this.emit("state",this.getState()),u}async sendMessageNow(e,t,s,n){const o=e,l=t.clientMessageId;let r=t.attachments??[],a=!1;if(n!==this.submissionGeneration)return null;try{if(await this.adapter.dispatch({type:"conversation.stage",content:o,clientMessageId:l,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,attachments:r.length>0?r.map(T):void 0,submittedAt:t.submittedAt}),n!==this.submissionGeneration)return null;if(a=!0,r.length>0){if(!this.adapter.uploadAttachment)throw new Error("The runtime does not support attachments.");const u=[];for(const c of r){if(c.sandboxPath||c.storageKey){u.push(c);continue}const h=c.id?this.attachmentFiles.get(c.id):void 0;if(!h)throw new Error(`Attachment bytes are unavailable for ${c.name}`);if(u.push(await this.adapter.uploadAttachment(h,c,{clientMessageId:l})),n!==this.submissionGeneration)return null}r=u}const d=await this.adapter.dispatch({type:"conversation.send",content:o,clientMessageId:l,initiatedBy:t.initiatedBy,invocation:t.invocation,proactiveSuggestionQuestion:t.proactiveSuggestionQuestion,...t.automationOnboarding?{automationOnboarding:!0}:{},attachments:r.length>0?r.map(T):void 0});if(n!==this.submissionGeneration)return null;for(const u of t.attachments??[])u.id&&this.attachmentFiles.delete(u.id);return l===this.stagedProactiveSuggestionClientMessageId&&(this.stagedProactiveSuggestionClientMessageId=null),d?.clientMessageId??l}catch(d){if(n!==this.submissionGeneration)return null;throw this.unacknowledgedSubmissions.delete(l),this.state={...this.state,messages:this.state.messages.filter(u=>u.id!==`local-${l}`&&u.id!==`optimistic-user-message:${l}`),pendingMessageStatus:s.pendingMessageStatus,turnPhase:s.turnPhase,isThinking:s.isThinking,taskStatus:s.taskStatus},this.emit("state",this.getState()),a&&await this.adapter.dispatch({type:"conversation.fail_staged",clientMessageId:l,message:d instanceof Error?d.message:String(d)}),d}}getModel(){return this.model}setModel(e){return this.dispatch({type:"session.set_model",model:e}).then(()=>{})}retryLastMessage(){return this.stoppedProjection=null,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(){const e=this.cancelPendingSubmissions();this.state=P(this.state,new Date().toISOString()),this.stoppedProjection=this.getState(),this.emit("state",this.getState());const t=this.adapter.dispatch({type:"run.stop",...e.length?{clientMessageIds:e}:{}});return this.operationQueue=t.then(()=>{},()=>{}),t.then(()=>{})}cancelPendingSubmissions(){const e=[...this.unacknowledgedSubmissions.keys()];this.submissionGeneration++;for(const t of this.unacknowledgedSubmissions.values())for(const s of t.message.attachments??[])s.id&&this.attachmentFiles.delete(s.id);return this.unacknowledgedSubmissions.clear(),this.operationQueue=Promise.resolve(),e}startNewSession(e={}){return this.cancelPendingSubmissions(),this.stoppedProjection=null,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 s=this.getSessionHistoryState().data;return{sessions:s?s.ids.map(n=>s.entitiesById[n]):[],nextCursor:s?.nextCursor??null}}if(!t?.sessionHistoryPage)throw new Error("Session list command did not return a page.");return t.sessionHistoryPage}getSessionHistoryState(){return E(this.sessionHistoryState)}subscribeSessionHistory(e){return this.sessionHistoryListeners.add(e),e(this.getSessionHistoryState()),()=>this.sessionHistoryListeners.delete(e)}refreshSessionHistory(){return this.dispatch({type:"session.list",limit:20}).then(()=>{})}loadMoreSessionHistory(){const e=this.sessionHistoryState.data?.nextCursor??null;return e?this.dispatch({type:"session.list",cursor:e}).then(()=>{}):Promise.resolve()}setSessionPinned(e,t){return this.dispatch({type:"session.pin",sessionId:e,pinned:t}).then(()=>{})}renameSession(e,t){return this.dispatch({type:"session.rename",sessionId:e,title:t}).then(()=>{})}getInteractions(){return this.interactions.map(e=>({...e}))}subscribeInteractions(e){return this.interactionListeners.add(e),e(this.getInteractions()),()=>this.interactionListeners.delete(e)}actOnInteraction(e,t,s,n={}){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 _(i,e){if(!e||!i)return e;const t=new Map;for(const s of i){const n=s.previewUrl;s.id&&n&&t.set(s.id,n)}return e.map(s=>{const n=s.id?t.get(s.id):void 0;return n?{...s,previewUrl:n}:s})}function A(i){return{...i,starterPrompts:[...i.starterPrompts],appearance:i.appearance?{...i.appearance}:null,messages:i.messages.map(e=>{const t={...e,attachments:e.attachments?.map(l=>({...l}))},s=e.assistantDraftItemId,n=e.clientMessageId,o=e.proactiveSuggestionClientMessageId;return o&&Object.defineProperty(t,"proactiveSuggestionClientMessageId",{value:o,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 E(i){return{...i,data:i.data?m({entities:O(i.data).map(e=>({...e})),nextCursor:i.data.nextCursor}):null}}exports.ProductAgentInteractionManager=K;exports.ProductAgentQueryController=I;exports.ProductAgentRemoteRuntimeClient=Y;exports.ProductAgentSessionHistoryManager=$;exports.ProductAgentTaskPageTitleController=z;exports.createLocalStorageInteractionDecisionStorage=N;exports.createProductAgentQueryState=g;exports.createProductAgentTaskPageTitleDocument=H;exports.formatProductAgentTaskPageTitle=C;exports.hasProductAgentPaidCreditFallback=q;exports.isProductAgentRuntimeCommand=W;exports.mergeProductAgentEntityPages=D;exports.normalizeProductAgentEntityPage=m;exports.readLocalStorageInteractionDecisions=k;exports.reconcileProductAgentSubmissionGate=L;exports.resolveProductAgentBillingPresentation=Q;exports.resolveProductAgentComposerAction=U;exports.resolveProductAgentWidgetPresentation=x;exports.selectProductAgentQueryEntities=O;
|