openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
13 lines • 30.5 kB
JavaScript
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as isPromiseLike}from"./promise-like-OKzBwzLG.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{m as scopeLegacySessionKeyToAgent}from"./session-key-BPgKfU2m.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{d as resolveAgentVerboseDefault,r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import{c as measureDiagnosticsTimelineSpanSync,s as measureDiagnosticsTimelineSpan}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{i as sha256StableValue}from"./node-crypto-DPk8agfR.mjs";import{Es as validateChatStartupParams,ys as validateChatHistoryParams}from"./src-BDZMFmKa.mjs";import{n as GATEWAY_CLIENT_IDS}from"./client-info-Dr3-kuD1.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{n as findModelCatalogEntry}from"./model-catalog-lookup-bSGgKRpi.mjs";import{t as activeSessionOperations,vt as getSessionControllerEntryForOperation}from"./session-controller.state-BIDbpLPn.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{m as resolveOperatorRolePolicy}from"./operator-role-policy-g-dxw0h4.mjs";import{O as resolveEffectiveChatHistoryMaxChars}from"./chat-display-projection.canvas-BobptIQs.mjs";import{t as composeTranscriptDisplay}from"./transcript-display-position-Ct20PUM8.mjs";import{D as captureSessionStoreScopeMatcher,E as captureRpcSourceScopeMatcher,T as captureGatewayScopeMatcher}from"./session-controller.lifecycle-M3NLAkoz.mjs";import{a as jsonUtf8BytesOrInfinity}from"./json-utf8-bytes-BzjXgHQ3.mjs";import{l as isOpenClawDeliveryMirrorAssistantMessage}from"./transcript-only-openclaw-assistant-mgMsWI54.mjs";import{Y as readSessionPendingInputReceiptsInWorker}from"./session-accessor-CY8UYP4m.mjs";import{n as projectTranscriptEntryMessage}from"./session-transcript-entry-message-BS7nfUPc.mjs";import{r as resolveRequestedSessionAgentId,s as tryResolveSessionCompatibilityOwnerAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{a as resolveSessionStoreIdentity}from"./session-store-key-DZXBwthg.mjs";import{t as captureSessionActorTranscriptRead}from"./session-actor-transcript-read-CNdxAppm.mjs";import{n as getSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{t as SessionMutationFactsUnavailableError}from"./session-sharing-incognito-PoZmE8H2.mjs";import{b as resolveSessionVisibility,d as isGatewayAdmin,u as hiddenSessionNotFound}from"./session-sharing-policy-CQ0Zqotl.mjs";import{t as prepareSessionMutationFacts}from"./session-sharing-preparation-Bx3oY7gx.mjs";import{a as getRpcSourceIdentity,c as getRpcSourceStartedAt,r as getRpcSourceForGateway,v as listRpcSourceEntries,w as resolveRpcSourceSessionProgressState}from"./session-controller.rpc-sources-IDCkO6sT.mjs";import{n as chatRunBelongsToSelectedAgent}from"./chat-run-owner-7fxQMRQN.mjs";import{c as getSubagentSessionListReadSnapshotIdentity,f as prepareOptionalSubagentSessionListReadCache}from"./subagent-registry-state-6jDCy1Tv.mjs";import{o as prepareProjectedSessionSharing}from"./session-sharing-read-Cm-EAfc6.mjs";import"./session-sharing-BmRcWi9h.mjs";import{n as SerializedJsonArray}from"./serialized-json-DvvcynCi.mjs";import{a as prepareSessionFastModePresentation,i as projectOperatorModelRead}from"./operator-model-presentation-IlcJ6QN7.mjs";import{n as resolveConfiguredThinkingDefaultCore}from"./model-thinking-default-core-BJEqnORl.mjs";import"./model-thinking-default-DP-enq9i.mjs";import{r as resolveSessionModelRef}from"./session-model-ref-B_XpQbtb.mjs";import{i as resolveGatewayModelThinkingProfile,t as getSessionDefaults}from"./session-utils-model-Cp0PM3hO.mjs";import{R as buildGatewaySessionRow,c as withReadySessionRows}from"./session-row-prepared-read-B7-BN1nJ.mjs";import{t as buildGatewaySessionSnapshot}from"./session-event-payload-BnNsf5q3.mjs";import{t as resolveCurrentUserProfileDisplay}from"./current-user-profile-display-DM7faKkD.mjs";import{r as readPreparedGatewayModelMetadata}from"./server-model-catalog-view-CnvXj2ku.mjs";import{t as readAcpSessionMetaForEntries}from"./session-meta-readonly-DaAFldTz.mjs";import{t as prepareProjectedSessionPresentation}from"./session-row-presentation-Cx3z_qAN.mjs";import{i as resolveVisibleActiveSessionRunState}from"./session-active-runs-BW6_s1BH.mjs";import{t as readChatRunProgressEvents}from"./server-chat-progress-snapshot-i6aFQfFo.mjs";import{r as registerDeflatedSegment}from"./ws-compression-DDnYcEuy.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{n as createCurrentUserProfileMessageProjector}from"./chat-display-projection.core-Cc0urtjV.mjs";import{n as projectAgentHistoryActivity}from"./agent-activity-events-B_8ZX8AG.mjs";import{a as isAssistantTtsSupplementMessage}from"./chat-display-projection.history-BLPBlOOA.mjs";import{f as createPreparedSessionHistorySubagentProjection,p as isAppendOnlySessionHistoryDelta,t as createSessionActorTranscriptReader}from"./session-transcript-memory-reader-DHqE4Ev8.mjs";import{g as resolveActiveEmbeddedRunOwnerForOperation}from"./runs-CZphmRD3.mjs";import{t as resolveGatewayModelSelectionPolicy}from"./session-model-selection-policy-CZHAMiO-.mjs";import"./session-utils-Cd7daNqX.mjs";import"./chat-display-projection-CtPpZudi.mjs";import{t as readSessionHistoryPageInWorker}from"./session-history-worker-runtime-BMT2ekk0.mjs";import{i as resolveClaudeCliBindingSessionId}from"./cli-session-history.claude-Bmfw0g4U.mjs";import{a as withChatStartupDiagnostics}from"./chat-server-timing-4lqMRkNU.mjs";import{a as createChatHistoryActivityProjection,c as getMaxChatHistoryMessagesBytes,i as chatHistoryActivityBytes,n as boundInFlightRunSnapshotForChatHistory,s as createChatHistoryDeltaByteCounter,u as reportOmittedChatHistory}from"./chat-history-budget-xZqiK_CO.mjs";import{a as decodeChatHistoryPageCursor,i as prepareChatHistoryResponsePage,n as readChatHistoryPage,o as resolveChatHistorySelectorError}from"./chat-history-pages-BMMeNxIS.mjs";import{t as prepareForwardedMessageCronJobNameResolver}from"./chat-display-projection.cron-Crkajb6k.mjs";import{n as withPreparedSessionResolve}from"./sessions-resolve-rQaWEUQn.mjs";import{r as readChatPendingInputs,t as captureQueuedChatInputRunIds}from"./chat-pending-inputs-BLswMFaP.mjs";import{n as createChannelMentionProjector,t as projectSessionMessagePayload}from"./session-transcript-message-MmK625Lw.mjs";import{t as resolveSessionHistoryUnavailableMessage}from"./session-history-error-BU0H0Ed7.mjs";import{t as handleChatMetadataRequest}from"./chat-metadata-handler-BOB-gvTV.mjs";
//!src/gateway/chat-inflight-snapshot.ts
function projectInFlightRunSnapshot(e){const t=e.chatRunState.runs.get(e.runId);const n=e.chatRunState.resolveBuffer(e.runId);const r=t?.planSnapshot;const i=readChatRunProgressEvents(t?.progressSnapshot);return{runId:e.runId,text:n.suppress?``:n.text,...e.startedAtMs===void 0?{}:{startedAt:e.startedAtMs},...e.sessionAbortable?{sessionAbortable:true}:{},...r?{plan:r}:{},...i?.length?{events:i}:{}}}
//!src/gateway/chat-inflight-snapshot.runtime.ts
function resolveInFlightRunSnapshot(e){const t=captureRpcSourceScopeMatcher(e);const matchesKey=(t,n)=>{const r=getRpcSourceIdentity(t);if(r.sessionKey!==n)return false;if(n!==`global`)return true;const i=normalizeOptionalLowercaseString(e.agentId)??normalizeOptionalLowercaseString(e.defaultAgentId);if(!i)return false;return(normalizeOptionalLowercaseString(r.agentId)??normalizeOptionalLowercaseString(e.defaultAgentId))===i};let n;for(const[r,i]of listRpcSourceEntries()){if(!t(i)||!resolveRpcSourceSessionProgressState(i)||i.adapter.controlUiVisible===false||i.input.abortSignal.aborted||i.adapter.kind===`agent`||!matchesKey(i,e.requestedSessionKey)&&!matchesKey(i,e.canonicalSessionKey))continue;const a=getRpcSourceStartedAt(i);if(n===void 0||(a??0)>(n.startedAtMs??0)||(a??0)===(n.startedAtMs??0)&&r>n.runId)n={runId:r,startedAtMs:a}}if(n===void 0)return;return projectInFlightRunSnapshot({chatRunState:e.chatRunState,runId:n.runId,startedAtMs:n.startedAtMs})}
//!src/gateway/server-methods/chat-history-delta.ts
const CHAT_HISTORY_DELTA_MAX_EVENTS=200;const CHAT_HISTORY_DELTA_MAX_BYTES=1e6;function chatHistoryDeltaLimits(e){return{cursor:e.cursor,maxBytes:Math.min(e.maxBytes??Infinity,CHAT_HISTORY_DELTA_MAX_BYTES),maxEvents:CHAT_HISTORY_DELTA_MAX_EVENTS}}async function readChatHistoryDelta(e,t,n){t?.throwIfAborted();const r=captureSessionActorTranscriptRead(e.scope,t);if(r){if(r.missing)return{kind:`reset`};const i=await r.read(`session.history.delta`,{options:chatHistoryDeltaLimits(e)});const a=createSessionActorTranscriptReader(r);if(i.kind===`page`)await a.prepareVisibility(i.events.flatMap(e=>e.messageSeq===void 0?[]:[projectTranscriptEntryMessage(e.event,e.messageSeq,e.displayPosition)]));const o=await projectChatHistoryDelta(e,i,a.subagentCoordination,n);t?.throwIfAborted();r.assertCurrent();return o}if(e.incognito||isIncognitoSessionKey(e.sessionKey))return{kind:`reset`};const i={...e.scope,sessionEntry:e.scope.sessionEntry?{sessionId:e.scope.sessionEntry.sessionId}:void 0};const{readSessionHistoryPageInWorker:a}=await import(`./session-history-worker-runtime-DwT_7nJS.mjs`);const o=await a({kind:`delta`,params:{target:i,limits:chatHistoryDeltaLimits(e)}},t);return projectChatHistoryDelta(e,o.delta,createPreparedSessionHistorySubagentProjection(o.subagentCoordination,o.assertCurrent),n)}async function projectChatHistoryDelta(e,t,n,r){const i=Math.min(e.maxBytes??Infinity,CHAT_HISTORY_DELTA_MAX_BYTES);n.assertCurrent?.();if(!isAppendOnlySessionHistoryDelta(t))return{kind:`reset`};const a=t.events.map(e=>e.messageSeq===void 0?void 0:projectTranscriptEntryMessage(e.event,e.messageSeq,e.displayPosition));const o=r?await r.project(a):a;n.assertCurrent?.();const s=await prepareForwardedMessageCronJobNameResolver(t.events.flatMap(e=>e.messageSeq===void 0?[]:[projectTranscriptEntryMessage(e.event,e.messageSeq,e.displayPosition)]));n.assertCurrent?.();let c={assistantErrorPending:false,turnBoundaryPending:false};const l=createCurrentUserProfileMessageProjector(resolveCurrentUserProfileDisplay);const u=[];const d=[];let f=2;const p=t.events.length>1?createChatHistoryDeltaByteCounter(e.sessionSnapshot):void 0;for(const[r,a]of t.events.entries()){if(a.messageSeq===void 0)continue;const t=asOptionalRecord(o[r]);if(!t)continue;if(isOpenClawDeliveryMirrorAssistantMessage(t)&&asOptionalRecord(asOptionalRecord(t)?.openclawDeliveryMirror)?.kind===`channel-final`)return{kind:`reset`};if(isAssistantTtsSupplementMessage(t))return{kind:`reset`};const m=asOptionalRecord(a.event)?.id;const h=projectSessionMessagePayload({agentId:e.agentId,historyDelta:true,includePluginSteering:e.includePluginSteering,maxChars:e.maxChars,toolResultMaxChars:e.toolResultMaxChars,message:t,...typeof m===`string`&&m?{messageId:m}:{},messageSeq:a.messageSeq,transcriptPosition:a.displayPosition,projectionState:c,projectCurrentUserProfile:l,subagentCoordination:n,resolveCronJobName:s,sessionKey:e.sessionKey,sessionSnapshot:e.sessionSnapshot});if(h.requiresHistoryReset)return{kind:`reset`};c=h.projectionState;if(c.assistantErrorPending)return{kind:`reset`};if(h.payload){f+=(p?p(h.payload):jsonUtf8BytesOrInfinity(h.payload))+(u.length>0?1:0);if(f>i)return{kind:`reset`};u.push(h.payload);if(typeof m===`string`)d.push({messageId:m,message:t})}}n.assertCurrent?.();const m=[...createChatHistoryActivityProjection(u.map(e=>e.message),projectAgentHistoryActivity(d)).values()];const h=chatHistoryActivityBytes(m);if(f+h>i)return{kind:`reset`};return{activeLeafEntryId:t.activeLeafEntryId,deltaCursor:t.cursor,kind:`delta`,activity:m,messages:composeTranscriptDisplay(u,e=>e.message),messagesBytes:f,activityBytes:h}}
//!src/gateway/server-methods/chat-history-recovery.ts
function resolveEmbeddedAgentRunRecoverySnapshot(e){const t=captureSessionStoreScopeMatcher(e);const n=captureGatewayScopeMatcher(e.resolveGatewayContext);const r=Array.from(activeSessionOperations()).filter(r=>{const i=getSessionControllerEntryForOperation(r);const a=i.target;return a!==void 0&&i.attachment?.projectSessionActive!==false&&t(a.storeScope,r.agentId)&&n(r)&&!r.result&&(e.sessionId===void 0||r.sessionId===e.sessionId)&&(i.aliases.has(e.requestedSessionKey)||i.aliases.has(e.canonicalSessionKey))&&chatRunBelongsToSelectedAgent({agentId:r.agentId,sessionKey:r.key,selectedAgentId:e.agentId??a.agentId??e.defaultAgentId,defaultAgentId:e.defaultAgentId})});const i=r.length===1?r[0]:void 0;const a=i&&getSessionControllerEntryForOperation(i).target;if(!i||!a)return;const o=resolveActiveEmbeddedRunOwnerForOperation(i);if(!o)return;const s=e.chatRunState.registry.peek(o.runId);const c=s&&getRpcSourceForGateway(s.clientRunId,e.resolveGatewayContext,a);const l=s&&c?.input.claim?.operation===i&&(s.sessionKey===e.requestedSessionKey||s.sessionKey===e.canonicalSessionKey)&&chatRunBelongsToSelectedAgent({agentId:s.agentId,sessionKey:s.sessionKey,selectedAgentId:e.agentId,defaultAgentId:e.defaultAgentId})?s.clientRunId:o.runId;return projectInFlightRunSnapshot({chatRunState:e.chatRunState,runId:l,startedAtMs:o.startedAtMs,sessionAbortable:true})}function respondChatHistoryUnavailable(e,t,n){t(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,n,{details:{method:e},retryable:true,retryAfterMs:250}))}function respondChatHistoryReadError(e,t,n){const r=resolveSessionHistoryUnavailableMessage(n);if(r===void 0)throw n;respondChatHistoryUnavailable(e,t,r)}
//!src/gateway/server-methods/chat-history-session-read.ts
async function prepareChatHistorySessionRead({context:e,client:t,respond:n,signal:r,sessionMutationAuthorization:i,method:a,sessionKey:o,agentIdOverride:s,requestedSessionId:c,retainedSessionId:l}){const unavailable=e=>respondChatHistoryUnavailable(a,n,e);const u=getSessionRowProjection(e);if(!u){unavailable(`session rows are initializing; reload the conversation`);return}const queries=e=>{const t=resolveRequestedSessionAgentId(e,o,s,`read`);if(!t.ok)return[];const{canonicalKey:n,agentId:r}=resolveSessionStoreIdentity({cfg:e,sessionKey:o,agentId:t.agentId});return[{key:n,agentId:r}]};const selectSession=e=>{const t=e.state.cfg;const r=resolveRequestedSessionAgentId(t,o,s,`read`);if(!r.ok){n(false,void 0,r.error);return}const i=resolveSessionStoreIdentity({cfg:t,sessionKey:o,agentId:r.agentId});const a=e.describe({key:i.canonicalKey,agentId:i.agentId});const c=a?{agentId:a.agentId,canonicalKey:a.key}:i;const u=a?.storeTarget.storePath??resolveSessionStorePathCore(t.session?.store,{agentId:c.agentId});return{cfg:t,...c,record:a,entry:a?.storedEntry??a?.entry,storePath:u,sourcePath:l&&a&&!isIncognitoSessionKey(a.key)?e.readSource(a)?.path:u,storeKeys:[c.canonicalKey],store:{}}};const authorizeSharingFacts=(e,r)=>{i?.assertCurrent();if(e.entry?!r.canReadTarget({...e,entry:e.entry,storeKey:e.canonicalKey,storeKeys:[e.canonicalKey]}):c&&!l&&!isGatewayAdmin(t)){n(false,void 0,hiddenSessionNotFound(e.canonicalKey));return}return r};const authorizeSharing=(e,n)=>authorizeSharingFacts(e,prepareProjectedSessionPresentation(n,t).sharing);const d=await measureDiagnosticsTimelineSpan(`gateway.${a}.session_entry`,()=>withReadySessionRows(u,queries,e=>{const t=selectSession(e);return t&&authorizeSharing(t,e)?t:void 0}),{config:e.getRuntimeConfig(),phase:a});r?.throwIfAborted();if(!d)return;const{agentId:f,storePath:p,canonicalKey:m,entry:h}=d;const readTranscriptOwner=async()=>{if(!c)return true;const e=await readSessionHistoryPageInWorker({kind:`transcript-binding`,params:{target:{agentId:f,sessionId:c,storePath:p}}},r);if(!e)return false;const t=e.sessionKey;return(t===`global`||t===`unknown`?t:scopeLegacySessionKeyToAgent({sessionKey:t,agentId:f}))===m};if(c&&!await readTranscriptOwner()){if(l)unavailable(`retained chat history is no longer available`);else n(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`sessionId does not belong to sessionKey`));return}let g;try{if(!d.entry&&!isIncognitoSessionKey(o)){g=await prepareSessionMutationFacts({cfg:d.cfg,sessionKey:o,agentId:d.agentId,allowMissing:true});r?.throwIfAborted()}const readCurrentSharing=e=>{const t=selectSession(e);if(!t)return;if(g){let r;try{r=g.readCurrent(e.state.cfg).target?.entry}catch(e){if(!(e instanceof SessionMutationFactsUnavailableError))throw e;unavailable(e.message);return}if(r){if(authorizeSharing({...t,entry:r},e)){if(t.entry)unavailable(`session changed while reading history; reload the conversation`);else n(false,void 0,hiddenSessionNotFound(t.canonicalKey))}return}}const r=t.entry;if(h&&(!r||t.agentId!==f||t.canonicalKey!==m||t.storePath!==p||!l&&(!e.describe({key:m,agentId:f,storePath:p},d.record)||r.sessionId!==h.sessionId||r.lifecycleRevision!==h.lifecycleRevision||h.sessionStartedAt!==void 0&&r.sessionStartedAt!==h.sessionStartedAt))){unavailable(`session changed while reading history; reload the conversation`);return}const i=authorizeSharing(t,e);if(!i)return;return r?{visibility:resolveSessionVisibility(r),sharingRole:i.roleForTarget({...t,entry:r,storeKey:t.canonicalKey})}:{}};if(g&&!await withReadySessionRows(u,queries,readCurrentSharing)){g.release();return}r?.throwIfAborted();return{selectedSession:d,entry:h,queries,readCurrentSharing,readTranscriptOwner,rowProjection:u,async publishRetainedTranscript(n){for(let i=0;i<2;i+=1){let a;try{const i=await prepareSessionMutationFacts({cfg:e.getRuntimeConfig(),sessionKey:m,agentId:f,allowMissing:true});a=i.release;if(!await n.verify()){unavailable(`retained chat history changed while reading`);return}r?.throwIfAborted();const o=e.getRuntimeConfig();const s=i.readCurrent(o);const c=s.target;if(h&&!c||c&&(c.agentId!==f||c.canonicalKey!==m||s.sourcePath!==d.sourcePath)||n.requireCurrentSession&&c?.entry.sessionId!==l){unavailable(`retained session changed while reading history`);return}const g=authorizeSharingFacts({entry:c?.entry,canonicalKey:m,agentId:f,storePath:p},prepareProjectedSessionSharing({cfg:u.getPolicyConfig(),client:t??null,isMember:(e,t)=>Boolean(c&&e.agentId===c.agentId&&e.canonicalKey===c.canonicalKey&&e.storePath===c.storePath&&s.membership.has(t))}));if(!g)return;const _=c?resolveSessionVisibility(c.entry):void 0;const v=c?g.roleForTarget(c):void 0;if(_!==n.sharing.visibility||v!==n.sharing.sharingRole){unavailable(`session access changed while reading history`);return}const y=n.publish();if(isPromiseLike(y)){Promise.resolve(y).catch(()=>{});throw new Error(`Retained history publication must remain synchronous`)}return}catch(e){if(!(e instanceof SessionMutationFactsUnavailableError)||i===1)throw e}finally{a?.()}}},release:()=>g?.release()}}catch(e){g?.release();if(e instanceof SessionMutationFactsUnavailableError){unavailable(e.message);return}throw e}}
//!src/gateway/server-methods/chat-history-handler.ts
async function handleChatHistoryRequest({params:e,respond:t,client:n,context:r,method:i,signal:a,sessionMutationAuthorization:o,retainedTranscript:s,acceptsSerializedJson:c,acceptsDeflatedSegments:l,req:u}){const{sessionKey:d,limit:f,offset:p,cursor:m,knownState:h,messageId:g,sessionId:_,maxChars:v,toolResultMaxChars:y,maxBytes:b,pendingBefore:x,inputRunIds:S}=e;const C=decodeChatHistoryPageCursor(m);const w=n?.connect.client?.id===GATEWAY_CLIENT_IDS.CONTROL_UI;const T=C?.messageId??g;const E=C?void 0:m;const D=s?.sessionId;const O=D??C?.sessionId??_;const k=resolveChatHistorySelectorError(e,C,D);if(k){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,k));return}if(!getSubagentSessionListReadSnapshotIdentity())await prepareOptionalSubagentSessionListReadCache();a?.throwIfAborted();const A=await prepareChatHistorySessionRead({context:r,sessionMutationAuthorization:o,client:n,respond:t,signal:a,method:i,sessionKey:d,agentIdOverride:normalizeOptionalString(e.agentId),requestedSessionId:O,retainedSessionId:D});if(!A)return;try{const{selectedSession:e,entry:o,queries:m,readCurrentSharing:g,readTranscriptOwner:_,rowProjection:D}=A;const{cfg:k,agentId:j,storePath:M,canonicalKey:N}=e;const readStartupProjection=()=>measureDiagnosticsTimelineSpan(`gateway.${i}.startup_projection`,async()=>{try{return await r.readChatStartupProjection?.({agentId:j,sessionKey:N,sessionEntry:o,readPolicy:i===`chat.history`?`ready`:`current`})}catch(e){r.logGateway.debug(`${i} continuing without prepared startup projection: ${formatErrorMessage(e)}`);return}},{config:k,phase:i,attributes:{agentId:j}});const ee=o?.authProfileOverride?.trim()?readStartupProjection():void 0;const P=O??o?.sessionId;const F={storePath:M,physicalPaths:D.physicalPaths,resolveGatewayContext:r.resolveGatewayContext};const I=P?captureQueuedChatInputRunIds({...F,sessionKey:N,sessionId:P,agentId:j}):void 0;const L=O&&O!==o?.sessionId?void 0:o;const te=resolveSessionModelRef(k,o,j,{allowPluginNormalization:false});const R=f??200;const z=Math.min(b??Infinity,getMaxChatHistoryMessagesBytes());const B=Math.min(b??524288,z);const V=resolveEffectiveChatHistoryMaxChars(v);const H=P&&P===o?.sessionId?await measureDiagnosticsTimelineSpan(`gateway.${i}.pending_inputs`,()=>readChatPendingInputs({agentId:j,sessionKey:N,sessionId:P,storePath:M},{before:x,limit:R,maxChars:V,queuedRunIds:I,cronStorePath:r.cronStorePath,resolveGatewayContext:r.resolveGatewayContext,physicalPaths:D.physicalPaths})):{items:[],total:0};const U=S?!T&&P&&P===o?.sessionId?(await readSessionPendingInputReceiptsInWorker({agentId:j,sessionKey:N,sessionId:P,storePath:M},{runIds:S})).map(e=>e.state===`pending`&&!e.cancelled&&I?.has(e.runId)?{runId:e.runId,state:e.state,queued:true}:e):[]:void 0;const W=U?.flatMap(e=>e.state===`consumed`?[{runId:e.runId,consumedByEventId:e.consumedByEventId}]:[]);const G=createChannelMentionProjector(r,n,N);let K;const q=c&&i===u.method;const ne=q&&l&&!resolveOperatorRolePolicy(n,r.getCommittedRuntimeConfig?.()??k)?.modelPolicy;try{K=E!==void 0?{messages:[]}:await measureDiagnosticsTimelineSpan(`gateway.${i}.history_page`,()=>readChatHistoryPage({encodeResponse:q,deflateResponse:ne,includePluginSteering:w,entry:L,provider:te.provider,sessionId:P,storePath:M,sessionAgentId:j,canonicalKey:N,max:R,maxHistoryBytes:z,responseHistoryBytes:B,effectiveMaxChars:V,toolResultMaxChars:y,offset:p,messageId:T,...C?{pageCursor:C}:{}},a,G),{config:k,phase:i,attributes:{limit:R,hasMessageId:Boolean(T),hasOffset:p!==void 0}})}catch(e){respondChatHistoryReadError(i,t,e);return}if(K.encodedResponse&&K.encodedMessagesDeflate)registerDeflatedSegment(K.encodedResponse.messages,K.encodedMessagesDeflate);const{messages:re,messagesBytes:ie,responseHistoryBytes:J,omission:Y,...ae}=K.encodedResponse?{...K.encodedResponse,messages:new SerializedJsonArray(K.encodedResponse.messages),activity:K.encodedResponse.activity?new SerializedJsonArray(K.encodedResponse.activity):void 0}:prepareChatHistoryResponsePage(K,{entry:L,maxHistoryBytes:z,responseHistoryBytes:B,messageId:T});if(Y)reportOmittedChatHistory({...Y,maxHistoryBytes:J,logDebug:e=>r.logGateway.debug(e)});const X=tryResolveSessionCompatibilityOwnerAgentId(k,d);const Z=await(ee??readStartupProjection());const Q=i===`chat.startup`?Z?.metadata:void 0;const{sessionModelCatalog:oe,defaultModelCatalog:$}=Z??{};const se={context:r,client:n,agentId:j,catalog:$};const presentHistory=e=>{const t=projectOperatorModelRead(se,e);if(h===void 0)return t;const n={commands:Q?Z?.commandsRevision:void 0,pendingInputs:sha256StableValue(t.pendingInputs).digest,sessionInfo:t.sessionInfo?sha256StableValue({...t.sessionInfo,snapshotAt:void 0}).digest:void 0};return{...t,stateRevision:n,...n.commands&&h.commands===n.commands?{metadata:{...t.metadata,commands:void 0}}:{},...E!==void 0&&h?.pendingInputs===n.pendingInputs?{pendingInputs:void 0}:{},...E!==void 0&&h?.sessionInfo===n.sessionInfo?{sessionInfo:void 0,sessionInfoSnapshotAt:t.sessionInfo?.snapshotAt}:{}}};const[ce]=o?[]:await readAcpSessionMetaForEntries({cfg:k,entries:[{agentId:j,sessionKey:N,entry:void 0}]});const presentRead=c=>{const l={...F,physicalPaths:c.physicalPaths};const u=g(c);if(!u)return;const f=measureDiagnosticsTimelineSpanSync(`gateway.${i}.session_info`,()=>prepareProjectedSessionPresentation(c,n).snapshot({key:N,agentId:j,storePath:M}).row??(o?void 0:buildGatewaySessionRow({...e,key:N,preparedAcpMeta:ce??null,preparedRuntimeOwnership:null,modelCatalog:oe,rowContext:D.state.rowContext})),{config:k,phase:i});if(!o&&f){const e=prepareSessionFastModePresentation(n);f.fastMode=e(f.fastMode);f.effectiveFastMode=e(f.effectiveFastMode)}if(o&&!f){respondChatHistoryUnavailable(i,t,`session changed while reading history; reload the conversation`);return}const p=resolveVisibleActiveSessionRunState({...l,requestedKey:d,canonicalKey:N,sessionId:P,...j?{agentId:j}:{},defaultAgentId:X,includeTerminalPersistence:true});if(f){Object.assign(f,u);f.hasActiveRun=p.active;if(p.runIds!==void 0)f.activeRunIds=p.runIds;if(p.active)f.status=p.status??`running`}const h=resolveEmbeddedAgentRunRecoverySnapshot({...l,chatRunState:r.chatRunState,requestedSessionKey:d,canonicalSessionKey:N,sessionId:P,agentId:j,defaultAgentId:X});if(f&&Object.hasOwn(K,`activeLeafEntryId`))f.activeLeafEntryId=K.activeLeafEntryId??null;const v=E===void 0?{...getSessionDefaults(k,$,{agentId:j,allowPluginNormalization:false,metadataSnapshot:readPreparedGatewayModelMetadata(k),providerPolicySource:`active`}),modelSelectionTarget:resolveGatewayModelSelectionPolicy({callerScopes:n?.connect?.scopes??[],cfg:k}).target}:void 0;for(const[e,t]of[[f,oe],[v,$]]){if(!e)continue;const{modelProvider:n,model:r}=e;if(typeof(t&&n&&r?findModelCatalogEntry(t,{provider:n,modelId:r}):void 0)?.reasoning===`boolean`&&n&&r){Object.assign(e,resolveGatewayModelThinkingProfile({cfg:k,agentId:j,provider:n,model:r,modelCatalog:t,agentRuntime:e.agentRuntime?.id,sessionKey:e===f?N:void 0,providerPolicySource:`active`}));e.thinkingOptions=e.thinkingLevels?.map(({label:e})=>e);continue}delete e.thinkingLevels;delete e.thinkingOptions;e.thinkingDefault=resolveAgentConfig(k,j)?.thinkingDefault??(n&&r?resolveConfiguredThinkingDefaultCore({cfg:k,provider:n,model:r}):k.agents?.defaults?.thinkingDefault)}const b=f?.thinkingLevel??f?.thinkingDefault??v?.thinkingDefault;const x=o?.verboseLevel??resolveAgentVerboseDefault(k,j);if(f)f.verboseLevel=x;const S=resolveInFlightRunSnapshot({...l,chatRunState:r.chatRunState,requestedSessionKey:d,canonicalSessionKey:N,agentId:j,defaultAgentId:X})??h;if(E!==void 0)return async()=>{if(!f||!P||!M||resolveClaudeCliBindingSessionId(o)){t(true,{kind:`reset`});return}const e=buildGatewaySessionSnapshot({sessionRow:f,agentId:j,activeRunState:p});let n;try{n=await readChatHistoryDelta({maxChars:V,toolResultMaxChars:y,includePluginSteering:w,agentId:j,cursor:E,maxBytes:B,scope:{agentId:j,sessionEntry:o,sessionId:P,sessionKey:N,storePath:M},sessionKey:N,sessionSnapshot:e,incognito:o?.incognito},a,G)}catch(e){respondChatHistoryReadError(i,t,e);return}return withReadySessionRows(D,m,e=>{const r=g(e);if(!r)return;if(r.visibility!==u.visibility||r.sharingRole!==u.sharingRole){respondChatHistoryUnavailable(i,t,`session changed while reading history; reload the conversation`);return}if(n.kind===`reset`){t(true,n);return}f.activeLeafEntryId=n.activeLeafEntryId;const a=boundInFlightRunSnapshotForChatHistory({snapshot:S,messages:n.messages,getMessagesBytes:()=>n.messagesBytes,maxBytes:B-n.activityBytes});const o={kind:`delta`,messages:n.messages,...n.activity.length>0?{activity:n.activity}:{},deltaCursor:n.deltaCursor,pendingInputs:H,...U?{inputReceipts:U,inputConsumptions:W}:{},sessionInfo:f,...a?{inFlightRun:a}:{},...Q?{metadata:Q}:{}};t(true,presentHistory(o))})};const C=boundInFlightRunSnapshotForChatHistory({snapshot:S,messages:[],getMessagesBytes:()=>ie,maxBytes:J});const T={sessionKey:d,sessionId:P,messages:re,...ae,pendingInputs:H,...U?{inputReceipts:U,inputConsumptions:W}:{},...K.deltaCursor?{deltaCursor:K.deltaCursor}:{},...K.windowReset?{windowReset:true}:{},...K.responseOffset!==void 0?{offset:K.responseOffset}:{},defaults:v,sessionInfo:f,thinkingLevel:b,fastMode:prepareSessionFastModePresentation(n)(o?.fastMode),toolOverrides:o?.toolOverrides&&structuredClone(o.toolOverrides),verboseLevel:x,...C?{inFlightRun:C}:{},...Q?{metadata:Q}:{}};if(s)return()=>A.publishRetainedTranscript({verify:async()=>await _()&&(await s.verifyRetainedState?.()??true),requireCurrentSession:s.requireCurrentSession===true,sharing:u,publish:()=>t(true,presentHistory(T))});t(true,presentHistory(T))};await(await measureDiagnosticsTimelineSpan(`gateway.${i}.projection_final`,()=>withReadySessionRows(D,m,presentRead)))?.()}finally{A.release()}}const chatHistoryHandlers={"chat.history":defineValidatedGatewayHandler(`chat.history`,validateChatHistoryParams,e=>handleChatHistoryRequest({...e,method:`chat.history`})),"chat.startup":withChatStartupDiagnostics(async e=>{if(!assertValidParams(e.params,validateChatStartupParams,`chat.startup`,e.respond))return;if(`sessionKey`in e.params){await handleChatHistoryRequest({...e,params:e.params,method:`chat.startup`});return}const t=e.client?.connId?.trim();if(t){e.context.subscribeSessionEvents(t);if(!e.context.getSessionEventSubscriberConnIds().has(t)){e.respond(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`connection closed before chat startup`));return}}const{shortId:n,slugHint:r,agentId:i,limit:a,maxBytes:o,toolResultMaxChars:s}=e.params;const c=getSessionRowProjection(e.context);if(!c){respondChatHistoryUnavailable(`chat.startup`,e.respond,`session rows are initializing; reload the conversation`);return}const l=await withPreparedSessionResolve({projection:c,client:e.client,p:{shortId:n,slugHint:r,agentId:i,allowMissing:true},isCurrent:()=>getSessionRowProjection(e.context)===c},t=>{e.sessionMutationAuthorization?.assertCurrent();if(!t.ok){e.respond(false,void 0,t.error);return}if(`missing`in t||`ambiguous`in t){e.respond(true,{resolution:{ok:false,...`ambiguous`in t?{candidates:t.candidates}:{}}});return}return t});if(!l)return;await handleChatHistoryRequest({...e,params:{sessionKey:l.key,agentId:l.agentId,limit:a,maxBytes:o,toolResultMaxChars:s},method:`chat.startup`,respond:(t,n,r,i)=>e.respond(t,t?{...asOptionalRecord(n),resolution:l}:n,r,i)})}),"chat.metadata":handleChatMetadataRequest};export{handleChatHistoryRequest as n,prepareChatHistorySessionRead as r,chatHistoryHandlers as t};