openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
103 lines • 201 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{y as isFutureDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import"./src-0ci69Prg.mjs";import{a as extractErrorCode,i as collectNestedErrorCandidates}from"./error-coercion-DlKnt6w-.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as stableStringify}from"./stable-stringify-Cy0VZ0ci.mjs";import{b as uniqueStrings}from"./string-normalization-D_oBUpO3.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{i as createAbortError}from"./src-De06gkOi.mjs";import{l as trackAsyncWork}from"./async-work-scope-DBcxYU4O.mjs";import"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createLazyImportLoader}from"./lazy-promise-CismJCQR.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,w as isSubagentSessionKey,x as isCronSessionKey,y as isAcpSessionKey}from"./session-key-BPgKfU2m.mjs";import{i as waitForAgentInputAdmission}from"./agent-database-preparation-context-CPut921o.mjs";import{o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{a as resolveAgentDir,f as resolveAgentWorkspaceDir,o as resolveAgentEntry}from"./agent-scope-config-CG9CFpGX.mjs";import{r as hasSqliteWorkerOutcomeUnknown}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{t as classifyGatewayStorageFailure}from"./sqlite-error-diagnostics-ASl1MXPN.mjs";import{p as isDiagnosticsEnabled}from"./diagnostic-events-BYBrlAdF.mjs";import{h as withDiagnosticsTimelineObserver,n as emitDiagnosticsTimelineEvent,s as measureDiagnosticsTimelineSpan,u as observeDiagnosticsTimelinePhases}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{h as SessionGoalOperationError}from"./openclaw-state-worker-error-Ca5E4dEV.mjs";import"./sqlite-worker-contract-CcRGAuae.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{K_ as readAgentRuntimeRestrictionErrorDetails}from"./src-BDZMFmKa.mjs";import{n as GATEWAY_CLIENT_IDS,o as isNativeAppUiClient}from"./client-info-Dr3-kuD1.mjs";import{i as resolveProviderIdForAuth}from"./provider-auth-aliases-BRA1A5Vm.mjs";import{n as hasSessionAutoModelFallbackProvenance,t as hasSessionActiveAutoModelFallback}from"./model-override-provenance-Ci-AwHUA.mjs";import{r as hasLegacyAutoFallbackWithoutOrigin}from"./agent-scope-Dw5XRSEh.mjs";import{i as classifyAgentRunTerminalOutcome}from"./agent-run-terminal-outcome-DAG2egzw.mjs";import{d as getAgentEventLifecycleGeneration}from"./agent-events-Dz03BVGI.mjs";import{c as createDynamicSessionSourceAssertion,l as prepareSessionSourceAuthority,s as composeSessionSourceAssertion}from"./session-source-authority-Cun3s-rH.mjs";import{i as claimAgentRunContext,l as getAgentRunContext,o as clearAgentRunContext,w as resolveProjectedAgentRunProgressState}from"./agent-run-registry-ONwZSqWq.mjs";import{f as hasGatewayAdminScope}from"./operator-scopes-bEvB7E5X.mjs";import{n as OPENCLAW_AGENT_RUNTIME_ID}from"./agent-runtime-id-dWmvEQWJ.mjs";import{m as resolveConfiguredModelPolicyAllow}from"./model-selection-shared-CIOFxJ36.mjs";import{n as parseModelRef,t as findNormalizedProviderValue}from"./model-selection-normalize-DU37Sfvg.mjs";import{i as resolveModelFallbackAvailability,t as modelFallbackOverrideFromAvailability}from"./model-selection-config-CnvHkHXn.mjs";import{t as INTERNAL_MESSAGE_CHANNEL}from"./message-channel-constants-BbP_hczw.mjs";import{_ as retainGatewayRootWorkAdmissionContinuation,u as isGatewayRestartDrainError}from"./gateway-work-admission-CnMW3_qr.mjs";import{c as createAgentDatabaseAdmissionErrorShape,t as AgentDatabaseAdmissionError}from"./agent-database-admission-DiJx9iIl.mjs";import{s as readSessionTranscriptRunId}from"./transcript-events-DDI7aMLK.mjs";import{O as createMessageInjectionAuthority,c as bindUserTurnPromptReactionSource,l as getUserTurnTranscriptAdmissionOwner,w as MessageInjectionTargetUnavailableError}from"./session-transcript-read-fence-DE07xwTs.mjs";import{n as extractTextFromChatContent}from"./chat-content-DJBA36Fz.mjs";import{t as captureRequesterOrigin}from"./requester-origin-C_JipMKu.mjs";import{a as sameSessionTranscriptStorePath,t as captureSessionTranscriptStorageEnvironment}from"./transcript-target-binding-CvS-QwUa.mjs";import{n as extractAssistantTextForPhase,t as extractAssistantPhaseText}from"./chat-message-content-BwODI7B3.mjs";import{r as readAssistantDisplayContent}from"./assistant-display-content-DZzkofMk.mjs";import{a as isInternalMessageChannel,l as isWebchatClient,n as isBrowserOperatorUiClient,s as isOperatorUiClient}from"./message-channel-514k57tV.mjs";import"./agent-run-terminal-outcome-WJ5SKlfk.mjs";import{h as resolveAgentRunErrorLifecycleFields,l as isAgentRunDirectAbortReason,m as resolveAgentRunAbortLifecycleFields,o as createAgentRunRestartAbortError,u as isAgentRunRestartAbortReason}from"./run-termination-vr_m9wT0.mjs";import{i as resolveSessionWorkStartError,p as retireProviderReviewAcknowledgment}from"./session-work-start-BNx7xs8p.mjs";import{f as withExecRequestTurn,n as adoptExecRequestSession}from"./exec-request-context-BB4c5QQi.mjs";import{H as bindSessionEffectTransition,Z as captureSessionTarget,r as bindSessionControllerEntryTarget}from"./session-controller.state-BIDbpLPn.mjs";import{M as stripReplyMediaFailureFallback,_ as isReplyPayloadStatusNotice,a as buildTtsSupplementMediaPayload,b as isReplyPayloadTtsSupplement,c as getReplyPayloadMetadata,g as isReplyPayloadSessionWriterDeliveryAuthorized,l as getReplyPayloadTtsSupplement,o as copyReplyPayloadMetadata,p as isHostNoticePayload}from"./reply-payload-C7eQHHoS.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{d as resolveCreatorSandbox,r as authorizeGatewaySessionCreation}from"./operator-role-policy-g-dxw0h4.mjs";import{i as buildSessionCreationStamp}from"./session-entry-provenance-DZd--atF.mjs";import{n as SessionMutationAuthorizationChangedError}from"./session-mutation-authorization-error-D4Cgq_Qr.mjs";import{g as isProgressCardRefreshInputProvenance,y as progressCardRefreshRunProjection}from"./input-provenance-TIcSrNt5.mjs";import{a as resolveCommandAuthorizationAsync}from"./command-auth-CCzMsjar.mjs";import{i as sessionToolOverridesEqual,r as normalizeSessionToolOverrides}from"./session-tool-overrides-B6f4t2kE.mjs";import{o as resolveSessionRoutingContract,t as SESSION_ROUTING_CHANGED_ERROR_REASON}from"./main-session-C6FGqx0x.mjs";import{n as sessionDeliveryChannel}from"./delivery-context.read-DWpauVKG.mjs";import{i as toDatabaseOptions}from"./session-accessor.sqlite-scope-helpers-_Zyjm1vW.mjs";import{n as getSessionActorStorageBinding,o as runWithSessionActorStorage,t as captureSessionActorStorageOwner}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import{t as prepareSqliteScope}from"./session-accessor.sqlite-read-scope-CSiIGQT-.mjs";import"./session-accessor.sqlite-scope-BHH23mIq.mjs";import{v as retainPreparedSessionEntryPredicate}from"./session-accessor.sqlite-entry-cache-publication-state-D1mC85IV.mjs";import{n as appendChatCanvasBlocksToMessage,o as isToolHistoryBlockType}from"./chat-display-projection.canvas-BobptIQs.mjs";import{s as resolveStateContentionPresentation}from"./chat-display-projection.sanitize-DPZ4F1ws.mjs";import{o as hasStagedMediaFacts,p as readPersistedMediaFacts}from"./media-facts-03ZYaqC1.mjs";import{t as combineNonStreamingReplyParts}from"./trim-code-text-BBQxx9yh.mjs";import{r as isSessionTranscriptProjectionUnavailableError,t as SessionTranscriptProjectionUnavailableError}from"./session-transcript-projection-error-Dl5r5Bis.mjs";import{a as withSessionHistoryWorkerDatabase,n as retainSessionHistoryWorkerDatabase}from"./session-transcript-worker-runtime-Cx43k2lO.mjs";import{C as trackSessionControllerSourceWork,E as captureRpcSourceScopeMatcher,V as isCompetingSessionControllerWorkActive,r as readSessionControllerAdmissionError,t as beginSessionEffect,x as retireSessionControllerSourceCancellation}from"./session-controller.lifecycle-M3NLAkoz.mjs";import{m as withoutGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{u as sanitizeAssistantVisibleTextWithProfile}from"./assistant-visible-text-CrogYVOU.mjs";import{t as renderAgentHarnessPreflightUserMessage}from"./user-facing-text-ZTl9Tw-Y.mjs";import{v as renderFailoverCodeUserCopy}from"./user-copy-B1CccoqG.mjs";import{d as renderStorageFailureSummary}from"./assistant-request-failure-copy-JfPT4_J9.mjs";import{F as readSessionSubmittedInput,K as normalizeMessageClientSources,u as rewritePreparedTranscriptMessageAtAnchor}from"./session-accessor-CY8UYP4m.mjs";import{i as assertSessionGoalOperationTime}from"./goals-operation-policy-Dqo_4G9A.mjs";import{i as buildRunUserTurnIdempotencyKey}from"./user-turn-transcript.metadata-BLFL_nrT.mjs";import{n as withSessionActorStorage,t as acquireSessionActorStorage}from"./session-actor-storage-acquisition-B3-E4SDM.mjs";import{a as startSessionTranscriptIndexReconcile,l as waitForSessionTranscriptProjection}from"./session-transcript-reconcile-BewE5zNm.mjs";import{a as prepareSessionCapabilityRead,s as withPreparedSessionCapabilityRead}from"./subagent-session-store-ClkR5Yv6.mjs";import{t as readSessionTranscriptWatermark}from"./session-accessor.sqlite-transcript-watermark-Bw5CuqoL.mjs";import{i as bindUserTurnInputActor,r as acquireSessionInputActor}from"./session-accessor.sqlite-transcript-turn-D-PORSlA.mjs";import{n as withSessionPendingInputAuthorityGuard}from"./session-pending-input-authority-BdRs3JvD.mjs";import{g as withOwnedSessionTranscriptWrites,l as getOwnedSessionTranscriptReader,v as withSessionTranscriptSourcePublication}from"./transcript-write-context-Z5Jo6xkS.mjs";import{r as resolveRequestedSessionAgentId,s as tryResolveSessionCompatibilityOwnerAgentId,t as resolveChatSendSessionKey}from"./session-request-agent-DmeXmT1P.mjs";import{r as prepareQualifiedSessionEntryTarget}from"./session-accessor.entry-B1qUJ4E1.mjs";import{a as isAgentHarnessSessionKey,m as resolveMissingAgentHarnessSessionError}from"./agent-harness-session-key-B6S2Sx8z.mjs";import{c as updateSessionEntry}from"./session-accessor.entry-mutation-CQIwywNM.mjs";import{n as readSessionTranscriptAnchorsAsync,t as readActiveTranscriptEntryAnchorAsync}from"./session-transcript-anchor-read-CKyqDTFK.mjs";import{t as applyAssistantDeliveryDirectives}from"./transcript-assistant-delivery-D7YdegBt.mjs";import"./sessions-DQD7zQ95.mjs";import{n as resolveSessionResetType,t as resolveChannelResetConfig}from"./reset-Cqx9zpZ-.mjs";import{r as logVerbose}from"./globals-l9I53ZKA.mjs";import{t as isReactionEmoji}from"./reaction-emoji-sAzkV_bo.mjs";import{t as GATEWAY_RESTART_UNAVAILABLE_REASON}from"./restart-unavailable-BX-3Xstf.mjs";import{i as isSyntheticGatewayCaller}from"./gateway-personal-caller-BTiNMUbk.mjs";import{i as gatewayClientSessionCreator,o as resolveChatSendCallerContext,r as gatewayClientSenderFields}from"./gateway-client-identity-H5JO7081.mjs";import{s as withQualifiedGatewaySessionStoreTarget}from"./session-utils-store-lookup-CF8NM_6B.mjs";import{n as omitInternalSessionEffectsEntries,t as findCanonicalStoreMatch}from"./session-utils-store-selection-DiiUIML7.mjs";import{n as captureSessionMutationRouting}from"./session-sharing-preparation-Bx3oY7gx.mjs";import{D as updateRpcSourceSessionId,a as getRpcSourceIdentity,c as getRpcSourceStartedAt,g as isRpcSourceRegistered,k as resolveChatRunExpiresAtMs,o as getRpcSourceLifecycleGeneration,p as isRpcSourceActive,r as getRpcSourceForGateway,u as hasRpcSourceForController,v as listRpcSourceEntries}from"./session-controller.rpc-sources-IDCkO6sT.mjs";import{n as chatRunBelongsToSelectedAgent}from"./chat-run-owner-7fxQMRQN.mjs";import{s as transferGatewayLocalUserIngress}from"./local-user-ingress-DFjUgRft.mjs";import{n as isVisibleSpawnedSession}from"./subagent-capabilities-Cq_ZFJj-.mjs";import{n as runOutsideOperatorToolGatewayAuthority}from"./operator-tool-gateway-authority-CWZSjJXg.mjs";import{o as bindWorkerToolPreparation}from"./host-private-capabilities-B_SEzbNU.mjs";import{n as resolveAgentTimeoutMs}from"./timeout-B3hylhqM.mjs";import{t as loadGatewaySessionEntryReadOnlyInWorker}from"./session-utils-store-worker-43BDHG7V.mjs";import{J as captureReplySessionExecutionSelection}from"./session-controller.mailbox-9GxioY-x.mjs";import{c as bindRequesterProfile,r as prepareSessionParticipantInput}from"./session-participant-input-CYW8g9PN.mjs";import{o as resolveInboundReplyToolAuthorityOverlay}from"./reply-tool-authority-inbound-ArHo7f-k.mjs";import{r as runOutsidePreparedModelRuntimePluginGenerationScope}from"./prepared-model-runtime-generation-scope-Cf2EOaL7.mjs";import{n as runWithAgentWorkspaceReadiness}from"./workspace-readiness-NfUrYLg7.mjs";import{i as hasGlobalHooks,n as getGlobalHookRunner}from"./hook-runner-global-DNCi6wD6.mjs";import{n as runAgentHarnessBeforeMessageWriteHook}from"./hook-helpers-Dmbt-AJr.mjs";import{r as retainsUserTurnTranscriptMedia,t as createUserTurnTranscriptRecorder}from"./user-turn-transcript-Bd2SwvOb.mjs";import{r as stopSession}from"./session-controller.stop-DE-wTVTx.mjs";import{l as ExpectedProfileMismatchError}from"./session-sharing-read-Cm-EAfc6.mjs";import"./session-sharing-BmRcWi9h.mjs";import{t as acceptGatewayDeviceSourceAuthority}from"./device-revocation-CZLiYG03.mjs";import{n as getRegisteredAgentHarness}from"./registry-BzjsVuM_.mjs";import"./channel-outbound-BZrgY7lw.mjs";import{a as captureQueuedOperatorRecoverySource}from"./operator-run-authority-DIEMEkD5.mjs";import{i as resolveSessionSubmittedModelRef,r as resolveSessionModelRef}from"./session-model-ref-B_XpQbtb.mjs";import{o as resolveEffectiveAgentRuntime}from"./thinking-runtime-V6V09nGt.mjs";import{c as resolveSessionChildController}from"./session-utils-core-DZPF_XHj.mjs";import{r as resolveGatewayModelSupportsImages}from"./session-utils-model-Cp0PM3hO.mjs";import{s as WORKSPACE_RESULT_LIMIT_ERROR_CODE}from"./workspace-inventory-limits-BmPI7yuU.mjs";import{n as deriveGatewaySessionLifecycleSnapshot}from"./session-lifecycle-projection-DjgAtymz.mjs";import{i as refuseCollaborativeSteering}from"./lifecycle-9W2sZTIl.mjs";import{s as hasPendingFollowupQueueWork}from"./state-t6zhY2pl.mjs";import{n as resolveAgentIdentity}from"./identity-C2YDObs7.mjs";import{t as readAcpSessionMetaForEntries}from"./session-meta-readonly-DaAFldTz.mjs";import{l as resolveAssistantIdentityName}from"./assistant-avatar-DRKaA0CT.mjs";import{d as withQualifiedGatewaySessionEntry,o as prepareDeletedAgentSessionCheck,u as withGatewaySessionEntry}from"./session-utils-store-CbjJRFJe.mjs";import{n as resolveSendPolicy}from"./send-policy-CpTHkwGP.mjs";import{r as emitSessionsChanged}from"./session-change-event-M_-ScXDH.mjs";import{n as resolvePreparedSessionEntryResetFreshness,r as resolveSessionEntryResetFreshness}from"./entry-freshness-C-b3yBDL.mjs";import{i as describeFailoverError}from"./failover-error-DWH-eolC.mjs";import{a as logMessageReceived,r as logMessageProcessed}from"./diagnostic-B89xdArk.mjs";import{r as resolveOperatorSessionCreation}from"./session-creation-provenance-DQXj4E5E.mjs";import"./reply-payload-C6sYX5Rf.mjs";import{t as formatForLog}from"./ws-log-DRCSDKLv.mjs";import{n as chatAbortPendingInputEndCause,t as chatAbortMarkerTimestampMs}from"./server-chat-state-CvHqVUAH.mjs";import{t as errorShapeFromError}from"./error-shape-YjtloQ5m.mjs";import{t as respondError}from"./response-BYbuAh7a.mjs";import{d as createCronCreatorAuthorityCapability,p as runWithCronCreatorAuthorityCapability}from"./cron-creator-authority-context-C9CHxQOU.mjs";import{a as readGatewayRequestMutationAuthority}from"./session-mutation-guards-Bqnc5JYL.mjs";import{n as captureAcpSessionEntryBinding}from"./session-meta-entry.kernel-COvgCRwP.mjs";import{a as resolveActiveReplyRunOwnerForSignal}from"./session-controller.barriers-Dc-Qsape.mjs";import{t as finalizeInboundContext}from"./inbound-context-DhAQpGu-.mjs";import{r as warnLegacyAgentRunStart}from"./agent-run-start-yFzndQ4_.mjs";import{r as resolveTextCommand}from"./commands-registry-normalize-yxTxMnHJ.mjs";import"./commands-registry-Dh5K81S2.mjs";import{n as readAgentRunTerminalOutcome}from"./agent-run-terminal-outcome-BEd4_P7Y.mjs";import{i as dispatchInboundMessageWithProjectedDispatcher}from"./dispatch-OJrrdqsb.mjs";import{a as emitInboundMessageAuditTerminal,r as emitMessageReceivedHooks,s as DispatchSessionRefreshRequiredError}from"./dispatch-from-config-B32cSLwf.mjs";import{t as REPLY_OPERATION_RUN_STATE}from"./reply-operation-run-state-Bhaxv-H2.mjs";import{n as bindReplySourcePreparationRetry,t as bindReplySourceInput}from"./reply-source-binding-CVUlWPnZ.mjs";import{t as COLLABORATIVE_STEERING_DISABLED_TEXT}from"./dispatch-from-config.payloads-DCtvNvw9.mjs";import{i as prepareSessionWriterDeliveryAuthority}from"./session-writer-delivery-authority-B84mAU6U.mjs";import{r as bindPreparedToolAuthority}from"./tool-authority-preparation-Dgurlhwb.mjs";import{t as hasInboundAudio}from"./inbound-media-o_s2S0bh.mjs";import{l as finalizeReplyMessageInjectionAttempt,s as captureCurrentReplyMessageInjectionTarget,t as beginSessionControllerSteer}from"./session-controller.steer-BUP3NUvG.mjs";import{i as captureSessionControllerInterruptBefore}from"./session-controller-CrWZc5Fi.mjs";import{t as isInternalSourceReplyChannel}from"./source-reply-delivery-mode-CAZfEUYS.mjs";import{o as projectChatDisplayMessage}from"./chat-display-projection.core-Cc0urtjV.mjs";import{o as readSessionMessageByIdAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{n as formatAudioTranscriptForAgent,t as DEFAULT_ECHO_TRANSCRIPT_FORMAT}from"./echo-transcript-CpHXF0KN.mjs";import{a as resolveEnvelopeFormatOptions}from"./envelope-B7t5cF__.mjs";import{s as withCurrentUserTurnInput}from"./user-turn-transcript-runtime-context-BjcGASZh.mjs";import{t as assertPreparedSkillLibrarySelection}from"./selection-Bv2Q3fBh.mjs";import{t as DEVICE_FOLDER_ATTACHMENTS_UNSUPPORTED}from"./node-workspace-protocol-B16XmC4W.mjs";import{t as recordSessionCreated}from"./session-created-CttkwWUi.mjs";import{t as resolveQueueSettings}from"./settings-runtime-Bivxfrgr.mjs";import{t as buildInboundMediaNoteProjection}from"./media-note-QK9TKdCK.mjs";import{n as buildInboundUserContextPrefix}from"./inbound-meta-CtkLLC3G.mjs";import{t as recordGatewaySessionRunFailure}from"./session-run-error-C_uXpyWh.mjs";import{t as persistGatewaySessionLifecycleEvent}from"./session-lifecycle-state-gnm2nBgu.mjs";import{t as recordAcceptedSessionParticipantInput}from"./session-participant-input-recording-DJuacI_T.mjs";import{n as resolveChatAttachmentMaxBytes}from"./chat-attachment-policy-Dy6xYpfv.mjs";import{n as attachManagedOutgoingMediaToMessage}from"./managed-image-attachments-CDCJnrtW.mjs";import{a as hasManagedOutgoingAssistantContent,c as prepareAssistantDisplayText,i as hasAssistantDisplayMediaContent,l as sanitizeAssistantDisplayText,o as hasVisibleAssistantFinalMessage,r as extractAssistantDisplayText,s as isMediaBearingPayload,u as stripManagedOutgoingAssistantContentBlocks}from"./chat-assistant-content-eWLWi920.mjs";import"./session-utils-Cd7daNqX.mjs";import{a as prepareWebchatReplyMediaForDisplay,c as readChatSendReplyPayload,l as replaceChatSendReplyPayload,n as captureWebchatReplyMediaScope,o as withPreparedWebchatReplyMedia,s as buildTranscriptReplyTextFromInputs,u as selectChatSendFinalReplyInputs}from"./chat-reply-media-CrSZ3EKC.mjs";import{t as createChannelReplyPipeline}from"./reply-pipeline-BCqCQ6iZ.mjs";import{t as isHumanAddressedChatMessage}from"./chat-human-mentions-CO6cIHJY.mjs";import"./chat-display-projection-CtPpZudi.mjs";import{i as markChatAbortTerminalOutcome,l as waitForChatAbortTerminalPersistence,n as captureChatAbortRegistrationGuard}from"./chat-abort-lifecycle-internal-zVsPSOIf.mjs";import{a as broadcastChatTerminal,c as isSourceReplyTranscriptMirrorPayload,i as broadcastChatQueueNotice,n as broadcastChatError,o as broadcastSideResult,r as broadcastChatFinal,s as isBtwReplyPayload,t as broadcastChatDelta}from"./chat-broadcast-B3al3md-.mjs";import{t as appendInjectedAssistantMessageToTranscript}from"./chat-transcript-inject-HHNNtf8K.mjs";import{n as pendingChatSendDedupeKey}from"./server-shared-2QOCd5Md.mjs";import{i as setGatewayDedupeEntry,t as captureAgentJobSession}from"./agent-job-CPPVvzdb.mjs";import{n as readQueuedChatInputAdmission}from"./queued-chat-input-admission-Co4eVAeD.mjs";import{_ as resolveExplicitOriginBindingTargets,g as resolveChatSendOriginatingRoute,h as isAcpBridgeClient,m as normalizeChatSendRequest}from"./session-create-root-BHh3u8t8.mjs";import{i as roundedChatSendTimingMs,n as prepareChatSendAckTiming,t as createOperatorChatSendServerTiming}from"./chat-server-timing-4lqMRkNU.mjs";import{r as prepareReplyMessageContinuation,t as prepareSteeringDelivery}from"./steering-delivery-preparation-DhpjZ9qL.mjs";import{n as resolveSessionMutationAuthorizationAsync,s as recordSessionOperatorSource}from"./session-sharing-authorization-async-715H6uOk.mjs";import{t as captureWorkerTurnInputSource}from"./worker-turn-transcript-target-Cr2y4w8G.mjs";import{o as resolveSessionNativeRuntimeRestriction}from"./sessions-patch-model-selection-DFalh24s.mjs";import{i as registerChatAbortController,o as updateChatRunProvider,s as resolveChatAbortDiagnosticReason}from"./chat-abort-DTWUmwzL.mjs";import{c as invalidateSkillAuthoringForOtherRequester,i as isDirectGatewayUserClient,n as resolveGatewayInputParticipant,s as resolveGatewayTemplateSetupCronAuthorityAdmission,t as retainGatewayOperatorRun,u as prepareGatewaySkillLibraryTurn}from"./operator-run-cancellation-DxgHskDg.mjs";import{a as captureGatewayClientUploadCommitGuard}from"./upload-policy-QDNTqb_K.mjs";import{a as parseMessageWithAttachments,i as logAttachmentFailure,n as MediaOffloadError,o as persistInboundImagesForTranscript,r as discardPreparedInboundMedia,s as stripImageMediaMarkers,t as INLINE_IMAGE_DURABLE_OMISSION_MARKER}from"./chat-attachments-CZUQzQ-8.mjs";import{i as buildAbortedChatSendPayload,l as readPreRegisteredRun,p as writePreRegisteredChatAbort,t as abortChatRunsForSessionKeyWithPartials,u as resolveChatAbortRequester}from"./chat-abort-runtime-BiN_zmEs.mjs";import{t as scheduleChatDashboardSessionTitle}from"./chat-send-background-XfQeVP38.mjs";import{t as publishCommittedSessionGoalChange}from"./session-goal-change-WaBj1jvr.mjs";import{i as withRepositoryChatDispatch}from"./repository-dispatch-lIwbsIVK.mjs";import{c as rewriteAssistantTranscriptMessageByTurnIndexAndMedia,l as rewriteSourceReplyTranscriptMirrors,n as buildAssistantDisplayRewrite,o as publishAssistantTranscriptRewrite,s as rewriteAssistantTranscriptMessageByIdempotencyKey,t as assistantTranscriptScope}from"./chat-transcript-persistence-Dkuuyx0-.mjs";import{c as withAbortedPartialPersistenceWarning,n as abortedPartialPersistenceError}from"./chat-aborted-partial-DRzVH5wh.mjs";import{t as createAssistantCommentaryMediaCustody}from"./chat-send-commentary-media-COl0qz4o.mjs";import{t as readCommittedSourceReplyContent}from"./chat-transcript-source-reply-owner-jauoqbm1.mjs";import{n as resolveAgentTurnRunObserver}from"./principal-BY316XJl.mjs";import{t as prepareSkillLibrarySessionCreation}from"./skill-library-session-37cdhob-.mjs";import{t as captureGatewayUiCommandTarget}from"./ui-command-target-D3Ntva5O.mjs";import{n as prepareSessionWorkspace}from"./session-create-project-BaBKxuPa.mjs";import{n as readChatSendDiagnostics,r as startChatSendDiagnostics}from"./chat-send-diagnostics-CytHKwsX.mjs";import{n as createChatAbortOps}from"./chat-abort-ops-BUCPKCsd.mjs";import{n as descendantAbortError}from"./chat-abort-descendants-CfGWZ0QV.mjs";import{r as resolveGatewaySessionTurnModelRef}from"./session-utils-store-lineage-DhIn-w5V.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import{performance}from"node:perf_hooks";import{isDeepStrictEqual}from"node:util";
//!src/config/sessions/goals-operations-read.ts
async function lookupSessionGoalOperation(e){assertSessionGoalOperationTime(e.operation,Date.now());const t=captureSessionActorStorageOwner(e,{assertCurrent(){},authorize(){}});if(t)return withSessionActorStorage(e,{lifetime:{assertCurrent(){},assertReadable(){}},authority:t.authority},t=>t.actor.storage.read({type:`session.goal.receipt`,input:{sessionKey:t.actor.target.sessionKey,expectedSessionId:e.expectedSessionId,operation:e.operation}},t.authority));const n={...e,...e.storePath?{storePath:path.resolve(e.storePath)}:{},operation:{...e.operation},env:captureSessionTranscriptStorageEnvironment(e.env??process.env)};const r=captureOpenClawStateWorkerContext({env:n.env});const assertCurrent=()=>{r.maintenanceScope?.assertAdmission();r.admission.assertCurrent()};const i=await prepareSqliteScope(n);assertCurrent();return withSessionHistoryWorkerDatabase(toDatabaseOptions(i),async e=>{const t=await e.readGoalOperationReceipt({sessionKey:i.sessionKey,expectedSessionId:n.expectedSessionId,operation:n.operation,env:n.env});assertCurrent();e.assertCurrent();if(`error`in t)throw new SessionGoalOperationError(t.error.code,t.error.message);return t.receipt})}
//!src/gateway/current-prompt-reaction.ts
function createCurrentPromptReaction(e){return async t=>{t.assertCurrent();const n=getUserTurnTranscriptAdmissionOwner(e.recorder);const r=n?.receipt();if(!n||e.recorder.isBlocked()||!r||r.agentId!==e.agentId||r.sessionKey!==e.sessionKey)throw new Error(`Current WebChat prompt has not been committed.`);const assertCurrent=()=>{t.assertCurrent();if(e.recorder.isBlocked()||n.receipt()!==r)throw new Error(`Current WebChat prompt admission changed.`)};if(!isReactionEmoji(t.emoji))throw new Error(`one emoji grapheme is required`);if(t.dryRun)return{messageId:r.entryId,changed:false,reactions:[]};const{commitSessionReaction:i}=await import(`./session-reaction-mutation-Ov9KJH5S.mjs`);assertCurrent();const a=await i({scope:{agentId:r.agentId,sessionKey:r.sessionKey,storePath:r.storePath},sessionKey:e.sessionKey,sessionId:r.sessionId,agentId:e.agentId,messageId:r.entryId,emoji:t.emoji,remove:t.remove,actor:{type:`agent`,id:e.agentId,label:resolveAgentIdentity(e.context.getRuntimeConfig(),e.agentId)?.name??e.agentId},identityId:`agent:`+e.agentId,context:e.context,assertCurrent});return{messageId:r.entryId,changed:a.changed,reactions:a.reactions}}}
//!src/gateway/server-methods/chat-send-dashboard-authority.ts
function createChatSendDashboardReadAdmission(e){const{admission:t,session:n,assertDashboardReadCurrent:r}=e;if(!r)return;return{agentId:n.agentId,runId:n.clientRunId,sessionKey:n.sessionKey,get sessionId(){return getRpcSourceIdentity(t.sourceRef).sessionId},assertCurrent:r}}async function createChatSendDashboardAuthority(e){const{admission:t,session:n,client:r,context:i,externalAuthorityAdmission:a,externalAdmissionParams:o}=e;const{sessionKey:s}=o;const c=a?.allowsDashboardReads(o);const l=c&&!e.sessionMutationAuthorization?await resolveSessionMutationAuthorizationAsync({client:r,context:i,method:`chat.send`,requestParams:{agentId:n.agentId,sessionKey:s},expectedTarget:{agentId:n.agentId,sessionKey:s,storePath:n.storePath,sessionId:getRpcSourceIdentity(t.sourceRef).sessionId}}):void 0;if(l?.error)throw new SessionMutationAuthorizationChangedError(l.error);const u=e.sessionMutationAuthorization??l?.authorization;if(c&&!u)throw new Error(`Dashboard session authorization is unavailable.`);const d=c&&a?()=>{e.sessionMutationCommitGuard?.();if(t.lifecycleGeneration!==getAgentEventLifecycleGeneration())throw new Error(`Dashboard prompt source lifecycle is no longer active.`);if(t.activeRunAbort.controller.signal.aborted&&!(isRpcSourceRegistered(t.sourceRef)&&t.sourceRef.input.custody.cancellationRetired))t.activeRunAbort.controller.signal.throwIfAborted();if(r?.invalidated||e.hasCurrentClientAuthority?.()===false||!a.allowsDashboardReads(o))throw new Error(`Dashboard message read admission is no longer active.`);(u?.assertAdmittedInputCurrent??u?.assertCurrent)?.()}:void 0;return{release:()=>l?.authorization?.release?.(),assertReadCurrent:d?()=>{t.assertWorkAdmissionCurrent();d()}:void 0,bindPromptRecorder(e){if(!d)return;bindUserTurnPromptReactionSource(e,{agentId:n.agentId,sessionKey:s,assertCurrent:d,createReaction:e=>createCurrentPromptReaction({agentId:n.agentId,sessionKey:s,recorder:e,context:i})})}}}
//!src/gateway/server-methods/chat-send-active-leaf.ts
const ACTIVE_LEAF_CHANGED_ERROR_REASON=`active-leaf-changed`;function assertExpectedLeafActive(e,t){const n=t===null||(e.entry?.sessionId?e.transcript?.onActivePath:t===null);if(n===void 0)throw new Error(`Chat admission omitted its worker-prepared active path`);if(!n)throw new Error(ACTIVE_LEAF_CHANGED_ERROR_REASON)}async function readIncognitoActivePath(e,t,n){const r=e.entry?.sessionId;if(!r)return;return readSessionTranscriptAnchorsAsync({agentId:t,sessionId:r,sessionKey:e.canonicalKey,storePath:e.storePath},{entryIds:[],activePathEntryId:n})}
//!src/gateway/server-methods/chat-send-session-settings.ts
const SESSION_SETTINGS_CHANGED_ERROR_REASON=`session-settings-changed`;function captureAdmittedChatSendSessionSettings(e){const{entry:t,expectedPermissionMode:n,expectedToolOverrides:r}=e;if(n!==void 0&&(t?.permissionMode??null)!==n||r!==void 0&&!sessionToolOverridesEqual(t?.toolOverrides,r))throw new Error(SESSION_SETTINGS_CHANGED_ERROR_REASON);if(!e.commit)return;return Object.freeze({permissionMode:t?.permissionMode,toolOverrides:normalizeSessionToolOverrides(t?.toolOverrides)})}
//!src/gateway/server-methods/chat-send-admission-errors.ts
function resolveChatSendStorageErrorMessage(e){return renderStorageFailureSummary(classifyGatewayStorageFailure(e))}function respondChatSessionRoutingChanged(e){respondError(e,ErrorCodes.INVALID_REQUEST,`session routing changed; review and retry`,{details:{reason:SESSION_ROUTING_CHANGED_ERROR_REASON}})}function respondChatSendAdmissionError(e,t,n){if(isAgentRunRestartAbortReason(e)||isGatewayRestartDrainError(e))return respondError(t,ErrorCodes.UNAVAILABLE,`Gateway is restarting; retry after reconnecting`,{retryable:true,details:{reason:GATEWAY_RESTART_UNAVAILABLE_REASON}});if(e instanceof SessionGoalOperationError)return respondError(t,ErrorCodes.INVALID_REQUEST,e.message,{details:{reason:`goal-${e.code}`}});const r=e instanceof Error?e.message:void 0;if(r===`goal-session-busy`)return respondError(t,ErrorCodes.UNAVAILABLE,`This session still has active or queued work. Wait for it to finish, then retry the Goal.`,{retryable:true,details:{reason:`goal-session-busy`}});if(r===`session-routing-changed`)return respondChatSessionRoutingChanged(t);if(r===`active-leaf-changed`||r===`session-settings-changed`)return respondError(t,ErrorCodes.INVALID_REQUEST,r===`active-leaf-changed`?`active branch changed; review and retry`:`Session settings changed before send. Retry.`,{details:{reason:r}});if(isSessionTranscriptProjectionUnavailableError(e))return respondError(t,ErrorCodes.UNAVAILABLE,`Chat history is rebuilding. Try again shortly.`,{details:{method:`chat.send`},retryable:true,retryAfterMs:250});const i=resolveChatSendStorageErrorMessage(e);const a=errorShapeFromError(i?ErrorCodes.UNAVAILABLE:ErrorCodes.INVALID_REQUEST,e,{message:i??formatForLog(e)});t(false,void 0,a);if(i!==void 0||hasSqliteWorkerOutcomeUnknown(e))n?.(a.message)}
//!src/gateway/server-methods/chat-send-retry.ts
function classifyAcceptedChatSendFailure(e){if(e.executionStarted||e.sideEffectsObserved)return`reconcile`;if(e.phase===`pre-ack`&&e.error instanceof AgentDatabaseAdmissionError&&createAgentDatabaseAdmissionErrorShape(e.error.refusal).retryable)return`client-retry`;if(!isSessionTranscriptProjectionUnavailableError(e.error))return`terminal`;return e.phase===`post-ack`?`retry`:`client-retry`}async function waitForAcceptedChatSendRetry(e,t,n){if(!isSessionTranscriptProjectionUnavailableError(t))throw t;await waitForSessionTranscriptProjection({...e,sessionId:t.sessionId},n)}function createAcceptedChatSendRetry(e){let t=2;return async n=>{while(true)try{return await n()}catch(n){if(t===0||e.classify(n)!==`retry`)throw n;t-=1;await e.waitForRetry(n)}}}
//!src/gateway/server-methods/chat-send-dispatch-errors.ts
function formatReturnedAgentErrors(e){if(e.collaborativeSteeringRefused)return COLLABORATIVE_STEERING_DISABLED_TEXT;if(e.runtimeError!==void 0)return e.runtimeError;const t=e.payloads.map(e=>e.text?.trim()).filter(e=>Boolean(e));const[n,...r]=[...new Set(t)];if(!n||r.length===0)return n||(e.runtimeFailed?`agent run failed`:void 0);if(r.length===1)return`${n}\n\nAdditional error: ${r[0]}`;return`${n}\n\nAdditional errors:\n${r.map(e=>`- ${e}`).join(`
`)}`}function resolveChatSendReturnedOutcome(e){const{runtimeOutcome:t,deliveredReplies:n,agentRunStarted:r,isInternalTextSlashCommandTurn:i}=e;const a=readAgentRunTerminalOutcome(e.dispatchResult);const o=t?classifyAgentRunTerminalOutcome(t):a&&(a===`failed`?`failure`:`success`);const s=o===`cancellation`;const c=o===`failure`||o===`timeout`;const l=n.map(e=>readChatSendReplyPayload(e.input)).filter(e=>e.isError);return{runtimeClassification:o,runtimeCancelled:s,runtimeFailed:c,returnedAgentErrorPayloads:l,hasOnlyFinalWarnings:l.length>0&&n.every(({kind:e,input:t})=>{const n=readChatSendReplyPayload(t);return e===`final`&&n.isError===true||isReplyPayloadStatusNotice(n)}),hasReturnedAgentError:o?c:l.length>0&&(r||!i),returnedAgentErrorMessage:formatReturnedAgentErrors({payloads:l,runtimeError:t?.error,runtimeFailed:c,collaborativeSteeringRefused:e.collaborativeSteeringRefused})}}function resolveDesktopChatSendErrorNotice(e){if(collectNestedErrorCandidates(e).some(e=>extractErrorCode(e)===`WORKSPACE_RESULT_LIMIT`))return`This workspace exceeds OpenClaw's file or size limits.`;const t=classifyGatewayStorageFailure(e);return(t===`SQLITE_BUSY`||t===`SQLITE_LOCKED`?`The request was interrupted because OpenClaw storage is busy.`:resolveChatSendStorageErrorMessage(e)??renderAgentHarnessPreflightUserMessage(e,{audience:`desktop`})??renderFailoverCodeUserCopy(describeFailoverError(e).code))?.split(/(?<=[.!?])\s+|\r?\n/u,1)[0]}function formatChatSendError(e){if(e instanceof DispatchSessionRefreshRequiredError)return`Your message didn't run because the conversation changed. Refresh the conversation, then send it again.\n\n${String(e)}`;return resolveStateContentionPresentation(e)?.errorMessage??resolveChatSendStorageErrorMessage(e)??renderAgentHarnessPreflightUserMessage(e)??renderFailoverCodeUserCopy(describeFailoverError(e).code)??String(e)}async function handleChatSendSetupError(e){const{cleanupAdmittedRun:t,lifecycleGeneration:n}=e.admission;const{agentId:r,clientRunId:i,sessionKey:a}=e.session;const o=getAgentRunContext(i)?.projectSessionMessages===false;if(e.error instanceof ExpectedProfileMismatchError){t();clearAgentRunContext(i,n);e.context.removeChatRun(i,i,a);e.respond(false,void 0,e.error.error);return}const s=formatChatSendError(e.error);const c=resolveStateContentionPresentation(e.error)?.errorKind;const l=resolveAgentRunErrorLifecycleFields(e.error,void 0).stopReason===`restart`?`client-retry`:classifyAcceptedChatSendFailure({error:e.error,phase:`pre-ack`});if(e.committedInput&&l!==`client-retry`&&getAgentRunContext(i)?.projectSessionLifecycle!==false){const t=Date.now();try{await persistGatewaySessionLifecycleEvent({sessionKey:a,agentId:r,expectedWriter:{runId:i,...e.committedInput},event:{runId:i,sessionId:e.committedInput.sessionId,lifecycleGeneration:n,ts:t,data:{phase:`error`,startedAt:getRpcSourceStartedAt(e.admission.activeRunAbort.entry),endedAt:t,error:s,errorKind:c}}});emitSessionsChanged(e.context,{sessionKey:a,agentId:r,reason:`chat.setup-error`})}catch(t){e.context.logGateway.warn(`webchat session lifecycle persist failed after setup error: ${formatForLog(t)}`)}}t();clearAgentRunContext(i,n);e.context.removeChatRun(i,i,a);const u=e.error instanceof SessionMutationAuthorizationChangedError?e.error.error:e.error instanceof SessionGoalOperationError?errorShape(ErrorCodes.INVALID_REQUEST,e.error.message,{details:{code:`GOAL_OPERATION_REJECTED`,reason:e.error.code}}):errorShapeFromError(ErrorCodes.UNAVAILABLE,e.error,{message:s,...l===`client-retry`?{retryable:true,retryAfterMs:250}:{}});const d={runId:i,status:`error`,summary:s};if(e.cacheResult!==false&&l!==`client-retry`)setGatewayDedupeEntry({dedupe:e.context.dedupe,key:`chat:${i}`,session:captureAgentJobSession({...getRpcSourceIdentity(e.admission.activeRunAbort.entry),lifecycleGeneration:getRpcSourceLifecycleGeneration(e.admission.activeRunAbort.entry)}),entry:{ts:Date.now(),ok:false,payload:d,error:u}});e.respond(false,d,u,{runId:i,error:formatForLog(e.error)});if(!o&&l!==`client-retry`)broadcastChatError({terminalEntry:e.admission.activeRunAbort.entry,context:e.context,runId:i,sessionKey:a,agentId:r,errorMessage:s,errorKind:c})}function createChatSendDispatchErrorLifecycle(e){const{admission:t,context:n,isQueuedFollowupEnqueued:r,persistUserTurnTranscript:i,session:a,userTurnRecorder:o}=e;const{activeRunAbort:s,cleanupAdmittedRun:c,lifecycleGeneration:l}=t;const{agentId:u,clientRunId:d,now:f,sessionKey:p}=a;const m=captureChatAbortRegistrationGuard([{runId:d,entry:s.entry}]);const captureJobSession=()=>captureAgentJobSession({...getRpcSourceIdentity(s.entry),lifecycleGeneration:getRpcSourceLifecycleGeneration(s.entry)});const h=getAgentRunContext(d);const g=h?.projectSessionMessages===false;const _=h?.projectSessionLifecycle===false;let v;let y;let b;let x;const classifyFailure=t=>e.injectionDisposition?.isRefused()?`reconcile`:classifyAcceptedChatSendFailure({error:t,phase:`post-ack`,executionStarted:e.isAgentRunStarted(),sideEffectsObserved:e.hasObservedSideEffects?.()});const broadcastError=t=>{if(!g&&(e.isReplyDispatchRun?.()||s.entry.adapter.chatErrorDispatchOwned===true||s.entry.adapter.terminalOutcomeObserved!==true)){if(t.stopReason===`restart`)broadcastChatTerminal({terminalEntry:s.entry,context:n,runId:d,sessionKey:p,agentId:u,state:`aborted`,stopReason:`restart`});else broadcastChatError({terminalEntry:s.entry,context:n,runId:d,sessionKey:p,agentId:u,...t})}};const handleError=async c=>{let l=c;try{await e.injectionDisposition?.settleRefusal()}catch(e){l=new AggregateError([l,e],`Refused input custody could not settle`)}const u=formatChatSendError(l);const p=resolveStateContentionPresentation(l)?.errorKind;const h=resolveDesktopChatSendErrorNotice(l);if(r()){n.logGateway.warn(`webchat dispatch failed after followup queue admission: ${formatForLog(l)}`);return}if(s.entry.adapter.terminalOutcomeObserved===true)await waitForChatAbortTerminalPersistence(s.entry).catch(e=>{n.logGateway.warn(`webchat terminal lifecycle settlement failed: ${formatForLog(e)}`)});const g=resolveAgentRunErrorLifecycleFields(s.controller.signal.reason,void 0);const S=g.stopReason?g:resolveAgentRunErrorLifecycleFields(l,void 0);const C=s.controller.signal.aborted;const w=n.chatRunState.runs.get(d)?.abortMarker;const T=s.entry.adapter.terminalOutcomeObserved===true;if(C&&w!==void 0){v=w;n.logGateway.warn(`chat.send post-dispatch threw after abort for runId=${d}: ${formatForLog(l)}`);if(!o.hasPersisted()&&!o.isBlocked())try{await i()}catch(e){n.logGateway.warn(`webchat user transcript update failed after abort: ${formatForLog(e)}`)}return}n.chatRunState.deleteAbortMarker(d);s.cleanup();b=o.hasPersisted()||o.isBlocked()?void 0:async()=>{await i()};if(!_&&w===void 0&&!T)y={allowUnstartedFailure:!e.isAgentRunStarted()?true:void 0,terminationFields:S,endedAt:Date.now(),error:u,errorKind:p,desktopNotice:h,sessionId:getRpcSourceIdentity(s.entry).sessionId,lifecycleRevision:a.entry?.lifecycleRevision??t.initialSessionEntry?.lifecycleRevision,startedAt:getRpcSourceStartedAt(s.entry)??f};if(!T||e.isReplyDispatchRun?.()||s.entry.adapter.chatErrorDispatchOwned===true){const publish=()=>{if(!m())return;const e=S.stopReason===`restart`;const t=errorShapeFromError(ErrorCodes.UNAVAILABLE,l,{message:u});setGatewayDedupeEntry({dedupe:n.dedupe,key:`chat:${d}`,session:captureJobSession(),entry:{ts:Date.now(),ok:e,payload:e?buildAbortedChatSendPayload({runId:d,stopReason:`restart`,endedAt:y?.endedAt??Date.now()}):{runId:d,status:`error`,summary:u,...S},...e?{}:{error:t}}});broadcastError({errorMessage:u,errorKind:p,stopReason:S.stopReason})};if(y||e.isReplyDispatchRun?.())x=publish;else publish()}};const persistLifecycleError=async e=>{try{await persistGatewaySessionLifecycleEvent({sessionKey:p,...u?{agentId:u}:{},expectedWriter:{...e.allowUnstartedFailure?{allowUnstartedFailure:true}:{},runId:d,sessionId:e.sessionId,lifecycleRevision:e.lifecycleRevision},assertCommitAllowed:()=>{if(!m())throw new Error(`Chat input was replaced before its failure could be persisted`)},event:{runId:d,sessionId:e.sessionId,lifecycleGeneration:l,ts:e.endedAt,data:{phase:`error`,startedAt:e.startedAt,endedAt:e.endedAt,error:e.error,errorKind:e.errorKind,...e.notice?{errorNotice:e.notice}:{},...e.desktopNotice?{desktopErrorNotice:e.desktopNotice}:{},...e.terminationFields}}});if(!g&&!e.terminationFields.aborted)await t.recordFailureNotice?.({runId:d,error:e.error,errorKind:e.errorKind,notice:e.notice});emitSessionsChanged(n,{sessionKey:p,...u?{agentId:u}:{},reason:`chat.dispatch-error`})}catch(e){n.logGateway.warn(`webchat session lifecycle persist failed after error: ${formatForLog(e)}`)}};let S;const captureUnstartedFailure=e=>{S=resolveDesktopChatSendErrorNotice(e);throw e};const recordUnstartedFailure=async n=>{if(_||e.isAgentRunStarted())return;await persistLifecycleError({allowUnstartedFailure:true,terminationFields:{},endedAt:Date.now(),...n,errorKind:resolveStateContentionPresentation(n.error)?.errorKind,notice:n.notice,desktopNotice:S,sessionId:getRpcSourceIdentity(s.entry).sessionId,lifecycleRevision:a.entry?.lifecycleRevision??t.initialSessionEntry?.lifecycleRevision,startedAt:getRpcSourceStartedAt(s.entry)??f})};const settleTerminalPersistence=async()=>{if(e.isReplyDispatchRun?.()&&s.entry)await waitForChatAbortTerminalPersistence(s.entry).catch(e=>{n.logGateway.warn(`webchat terminal lifecycle settlement failed: ${formatForLog(e)}`)})};const finalize=async()=>{await settleTerminalPersistence();const t=y;const clearRun=()=>{if(!r()&&(!e.isAgentRunStarted()||e.isReplyDispatchRun?.())){n.chatRunState.clearRun(d);n.agentRunSeq.delete(d)}};try{if(!t){const e=v??(s.controller.signal.aborted?n.chatRunState.runs.get(d)?.abortMarker:void 0);if(e){const t=chatAbortMarkerTimestampMs(e);setGatewayDedupeEntry({dedupe:n.dedupe,key:`chat:${d}`,session:captureJobSession(),entry:{ts:t,ok:true,payload:buildAbortedChatSendPayload({runId:d,stopReason:s.entry.adapter.abortStopReason??`rpc`,endedAt:t})}})}clearAgentRunContext(d,l);n.removeChatRun(d,d,p);return}await b?.().catch(e=>{n.logGateway.warn(`webchat user transcript update failed after error: ${formatForLog(e)}`)});clearAgentRunContext(d,l);n.removeChatRun(d,d,p);await persistLifecycleError(t)}finally{try{x?.()}finally{clearRun();c()}}};return{broadcastError,captureUnstartedFailure,classifyFailure,finalize,handleError,recordUnstartedFailure,settleTerminalPersistence}}
//!src/gateway/server-methods/chat-send-external-dispatch.ts
function runChatSendExternalDispatch(e,t){const{externalAuthorityAdmission:n,cronCreatorAuthority:r,assertDashboardReadCurrent:i}=e;const run=()=>r&&n?n.run(r,t,e.admission.activeRunAbort.controller.signal):t();const a=e.admission.codexGoalAdmission&&isDirectGatewayUserClient(e.client)&&e.request.goalOperation?e.admission.operatorAuthority?.assertCurrent:n&&i;return a?withRepositoryChatDispatch({client:e.client,agentId:e.session.agentId,sessionKey:e.session.sessionKey,getSessionId:()=>getRpcSourceIdentity(e.admission.sourceRef).sessionId,runId:e.session.clientRunId,assertCurrent:a},run):run()}
//!src/gateway/server-methods/chat-send-reply-context.ts
const REPLY_CONTEXT_BODY_MAX_CHARS=2e3;function buildChatSendReplyInjectionText(e){const t=buildInboundUserContextPrefix(e.ctx,resolveEnvelopeFormatOptions(e.cfg),e.sessionEntry);return t?`${t}\n\n${e.body}`:e.body}function extractReplyTargetText(e){if(typeof e.text===`string`&&e.text.trim())return e.text;if(typeof e.content===`string`&&e.content.trim())return e.content;if(!Array.isArray(e.content))return;const t=e.content.map(e=>{const t=asOptionalRecord(e);return t&&typeof t.text===`string`?t.text:``}).filter(e=>e.trim());return t.length>0?t.join(`
`):void 0}function applyChatSendReplyContextFields(e,t){for(const n of[`ReplyToId`,`ReplyToBody`,`ReplyToSender`])if(t[n]!==void 0)e[n]=t[n]}async function resolveChatSendReplyContext(e){const t=e.replyToId?.trim();if(!t)return{};const n={ReplyToId:t};const r=e.sessionEntry?.sessionId;if(!r)return n;try{const i=await readSessionMessageByIdAsync({agentId:e.agentId,sessionEntry:e.sessionEntry,sessionId:r,sessionKey:e.sessionKey,storePath:e.storePath},t,{allowResetArchiveFallback:true});if(!i.found)return n;const a=projectChatDisplayMessage(i.message,{resolveCronJobName:()=>void 0});if(!a)return n;const o=extractReplyTargetText(a)?.trim();const s=o&&a.role===`assistant`?sanitizeAssistantVisibleTextWithProfile(o,`history`).trim():o;if(!s)return n;n.ReplyToBody=truncateUtf16Safe(s,REPLY_CONTEXT_BODY_MAX_CHARS);n.ReplyToSender=a.role===`assistant`?(await resolveAssistantIdentityName({cfg:e.cfg,agentId:e.agentId})).name:e.userSenderLabel?.trim()||`User`;return n}catch(r){e.warn?.(`chat.send reply context hydration failed for ${t}: ${String(r)}`);return n}}
//!src/gateway/server-methods/chat-send-message-injection.ts
function createChatSendMessageInjectionStarter(e){const{p:t,rawMessage:n,supportsTaskSuggestions:r}=e.request;const{agentId:i,cfg:a,entry:o,sessionKey:s,storePath:c,clientRunId:l,resolvedSessionModel:u}=e.session;const{ctx:d,isInternalTextSlashCommandTurn:f,replyOptionImages:p,replyOptionMedia:m}=e.turn;return async function start(h){try{var g=_usingCtx();const assertCurrent=()=>{e.abortSignal.throwIfAborted();e.assertCurrent?.();e.operatorAuthority?.assertCurrent();h?.()};const _=e.target;if(!_||f)return;const v=g.u(e.diagnostics?.scope(`detail.run_admission.steer_authority`));assertCurrent();const y=prepareSteeringDelivery({agentId:i,sessionKey:s,storePath:c,entry:o,assertCurrent});let b=false;let x;const release=()=>{if(x?.kind===`prepared`)x.release();y.release()};try{const canAdmit=()=>{try{y.assertCurrent();return true}catch(t){if(!(t instanceof MessageInjectionTargetUnavailableError))throw t;e.logGateway.warn(`chat steering rejected; falling back to follow-up dispatch`,{reason:`terminal-delivery-unavailable`,runId:l,activeRunId:_.runId,sessionKey:s,error:t.message});return false}};const{debounceMs:c}=resolveQueueSettings({cfg:a,channel:d.Provider,sessionEntry:o,inlineMode:t.queueMode});const f=e.documentContext?.status===`rendered`?e.documentContext:void 0;const g=f?.images??[];const S=g.length>0?[...p??[],...g.map(e=>({type:`image`,data:e.data,mimeType:e.mimeType}))]:p;const C=await resolveCommandAuthorizationAsync({ctx:d,cfg:a,commandAuthorized:d.CommandAuthorized===true});const w=resolveInboundReplyToolAuthorityOverlay({ctx:d,sessionEntry:{spawnedBy:o?.spawnedBy,permissionMode:e.admittedSessionSettings?.permissionMode,toolOverrides:e.admittedSessionSettings?.toolOverrides},senderIsOwner:C.senderIsOwner,operatorAuthority:e.operatorAuthority,disableTools:false});const{traceAuthorized:T,allowCollaborativeSteering:E,...D}=w;v?.mark(`detail.run_admission.steer_continuation`);x=await prepareReplyMessageContinuation({target:_,assertCurrent,delivery:y,input:{kind:`continuation`,caller:D,config:a,executionSelection:captureReplySessionExecutionSelection({config:a,agentId:i,sessionEntry:o}),selectedRoute:u,fallbackAvailability:resolveModelFallbackAvailability({cfg:a,agentId:i,sessionKey:s,selectedModel:u,hasSessionModelOverride:o?.modelOverrideSource!=="default"&&Boolean(o?.modelOverride||o?.providerOverride)&&!hasLegacyAutoFallbackWithoutOrigin(o),modelOverrideSource:o?.modelOverrideSource==="default"?void 0:o?.modelOverrideSource,hasAutoFallbackProvenance:hasSessionAutoModelFallbackProvenance(o),modelSelectionLocked:o?.modelSelectionLocked})}});if(x.kind===`deferred`){e.logGateway.warn(`chat steering rejected; falling back to follow-up dispatch`,{reason:x.reason,error:x.errorMessage,runId:l,activeRunId:_.runId,sessionKey:s});return}const O=x.kind===`prepared`?x:void 0;v?.mark(`detail.run_admission.steer_delivery`);try{await y.prepareCurrent()}catch(t){assertCurrent();e.logGateway.warn(`chat steering rejected; falling back to follow-up dispatch`,{reason:`terminal-delivery-unavailable`,runId:l,activeRunId:_.runId,sessionKey:s,error:String(t)});return}if(d.media?.some(e=>e.path)&&!hasStagedMediaFacts(d.media)){v?.mark(`detail.run_admission.steer_attachments`);const{stageReplyMedia:t}=await import(`./stage-reply-media-CnM8u0Ix.mjs`);await t({ctx:d,sessionCtx:d,cfg:a,agentId:i,sessionKey:s,workspaceDir:resolveAgentWorkspaceDir(a,i),sessionEntry:o,skillOverrides:e.admittedSessionSettings?.toolOverrides?.skills,abortSignal:e.abortSignal,assertCurrent:()=>{assertCurrent();y.assertCurrent()}})}const k=d.BodyForAgent??d.Body??n;const A=f?.text.trim();const j=d.media?.length||A||e.documentContext?.status===`failed`?[buildInboundMediaNoteProjection(d).text,k.trim(),A].filter(Boolean).join(`
`):k;let M=false;v?.mark(`detail.run_admission.steer_admit`);const N=await beginSessionControllerSteer({input:e.sourceRef.input,retry:start,retryWithdrawnSteer:h!==void 0,target:_,text:t.replyToId?buildChatSendReplyInjectionText({body:j,cfg:a,ctx:d,sessionEntry:o}):j,options:{currentInboundContext:t.replyToId?void 0:{text:buildInboundUserContextPrefix(d,resolveEnvelopeFormatOptions(a),o)},canAdmit:()=>{M=!canAdmit();return!M},assertCurrent:e.assertCurrent||e.operatorAuthority?assertCurrent:void 0,toolAuthorityPreparation:bindPreparedToolAuthority(bindWorkerToolPreparation({authorityKind:e.assertCurrent||e.operatorAuthority?`source-bound`:`run`,assertCurrent,compatAssertCurrent:()=>{assertCurrent();O?.read()},prepareCurrent:async()=>{await O?.prepareCurrent();await y.prepareCurrent()}})),inboundAudio:hasInboundAudio(d),steeringMode:`all`,isInboundUserMessage:true,allowPendingUserInputAnswer:O?.allowPendingUserInputAnswer,allowCollaborativeSteering:a.messages?.queue?.allowCollaborativeSteering===true&&(!d.InputProvenance||d.InputProvenance.kind===`external_user`),...isProgressCardRefreshInputProvenance(d.InputProvenance)?{allowPendingUserInputAnswer:false,debounceMs:0}:{},...O?{toolAuthorityFingerprint:O.fingerprint}:{toolAuthorityOverlay:w},...S?.length?{images:S}:{},...e.imageOrder?.length?{imageOrder:e.imageOrder}:{},...m?.length?{media:m}:{},waitForTranscriptCommit:true,abortSignal:e.abortSignal,...!isProgressCardRefreshInputProvenance(d.InputProvenance)&&c!==void 0?{debounceMs:c}:{},...O?{}:{taskSuggestionDeliveryMode:r?`gateway`:void 0},userTurnTranscriptRecorder:e.userTurnTranscriptRecorder}});if(!N)return;N.outcome.then(release,release);b=true;return M?void 0:N}finally{if(!b)release()}}catch(e){g.e=e}finally{g.d()}}}function createChatSendInjectionDisposition(e,t){let n=false;let r;const i={};const isRefused=()=>n&&t?.collaborativeSteeringFallback===`reject`||i.admission?.status===`skipped`&&i.admission.reason===`collaborative-steering-disabled`;return{runState:i,isRefused,replyOptions:e=>n?{messageInjectionDisposition:`collaborative-steering-disabled`}:e?{messageInjectionDisposition:`rejected`,messageInjectionRejection:r}:{},async observe(e){const a=await e?.outcome;r=a?.status===`rejected`?a:void 0;if(a?.status===`rejected`&&a.reason===`collaborative_steering_disabled`){n=true;if(t?.collaborativeSteeringFallback===`reject`)i.admission={status:`skipped`,reason:`collaborative-steering-disabled`};return}return e},async settleRefusal(){if(isRefused())await refuseCollaborativeSteering(e,i)}}}async function settleChatSendMessageInjection(e){if(!e)return false;const t=await e.outcome;if(t.status===`failed`)throw t.error;return t.status!==`rejected`}async function finalizeAcceptedChatSendMessageInjection(e){const{context:t,ctx:n,session:r}=e;const{agentId:i,cfg:a,clientRunId:o,entry:s,sessionKey:c,storePath:l}=r;const u=finalizeInboundContext(n);const d=isProgressCardRefreshInputProvenance(n.InputProvenance);const f=await finalizeReplyMessageInjectionAttempt({attempt:e.attempt,target:e.target,inboundAudio:hasInboundAudio(u)});if(f.status===`rejected`)return false;recordAcceptedSessionParticipantInput(n,{agentId:i,sessionKey:c,storePath:l});const p=normalizeLowercaseStringOrEmpty(u.Surface??u.Provider??`unknown`);const m=u.To??u.From;const h=u.MessageSidFull??u.MessageSid??u.MessageSidFirst??u.MessageSidLast;const g=f.status===`indeterminate`?f.outcome.errorMessage:void 0;const _=g?d?`progress_refresh_receipt_unconfirmed`:`question_response_indeterminate`:`active_run_injected`;await e.persistUserTurnTranscriptBestEffort();if(isDiagnosticsEnabled(a)){logMessageReceived({sessionKey:c,channel:p,chatId:m,messageId:h,source:`dispatchInboundMessage`});logMessageProcessed({channel:p,chatId:m,messageId:h,sessionKey:c,durationMs:Math.max(0,Date.now()-e.startedAt),outcome:g?`error`:`completed`,reason:_})}emitMessageReceivedHooks({ctx:u,hookRunner:getGlobalHookRunner(),sessionKey:c,timestamp:typeof u.Timestamp===`number`&&Number.isFinite(u.Timestamp)?u.Timestamp:void 0});emitInboundMessageAuditTerminal({cfg:a,counts:{tool:0,block:0,final:0},ctx:u,observedRunId:o,startedAt:e.startedAt,terminal:g?{outcome:`error`,options:{reason:_,error:g}}:{outcome:`completed`,options:{reason:_}}});const v=Date.now();if(s)r.entry={...s,updatedAt:v};await updateSessionEntry({storePath:l,sessionKey:c},()=>({updatedAt:v}),{skipMaintenance:true,takeCacheOwnership:true}).catch(e=>{t.logGateway.warn(`failed to touch session after accepted steering: ${String(e)}`)});if(!t.chatRunState.hasAbortMarker(o)){setGatewayDedupeEntry({dedupe:t.dedupe,key:`chat:${o}`,session:captureAgentJobSession(e.sourceRef?{...getRpcSourceIdentity(e.sourceRef),lifecycleGeneration:getRpcSourceLifecycleGeneration(e.sourceRef)}:void 0),entry:{ts:Date.now(),ok:d||!g,payload:{runId:o,status:d?`accepted`:g?`error`:`ok`,...g?{summary:g}:{}},...!d&&g?{error:errorShape(ErrorCodes.UNAVAILABLE,g)}:{}}});if(g)broadcastChatError({terminalEntry:e.sourceRef,context:t,runId:o,sessionKey:c,agentId:i,errorMessage:g});else broadcastChatFinal({context:t,runId:o,sessionKey:c,agentId:i,terminalEntry:e.sourceRef})}return true}
//!src/gateway/server-methods/chat-send-reply-delivery.ts
function resolveChatReplyTranscriptStart(e,t,n){const r={agentId:e.agentId,sessionKey:e.sessionKey,sessionId:t.entry?.sessionId??e.backingSessionId,storePath:t.storePath};if(n&&(n.agentId!==r.agentId||n.sessionId!==r.sessionId||n.sessionKey!==r.sessionKey||n.storePath!==r.storePath&&!isSameOpenClawAgentDatabasePath(n.storePath,r.storePath)))return;const i=n??{generation:null,maxSeq:null};return{sessionId:r.sessionId,generation:i.generation,afterSeq:i.maxSeq??0}}function resolveLegacyChatReplyTranscriptStart(e,t){warnLegacyAgentRunStart();const n=t.entry?.sessionId??e.backingSessionId;return resolveChatReplyTranscriptStart(e,t,n?{agentId:e.agentId,sessionId:n,sessionKey:e.sessionKey,storePath:t.storePath,...readSessionTranscriptWatermark({agentId:e.agentId,sessionId:n,sessionKey:e.sessionKey,storePath:t.storePath})}:null)}function resolveChatReplyDeliveryFromAnchors(e){const{facts:t,afterSeq:n,watermark:r,currentWatermark:i}=e;const a=t.anchors.find(t=>t.entryId===e.admissionId);const o=t.anchors.find(t=>t.entryId===e.inputId);const s=t.anchors.find(t=>t.entryId===e.messageId);if(!a||!o)return`missing`;if(!s||s.rawSeq<=n||s.activeMessagePosition<=o.activeMessagePosition)return;if(t.tail?.entries.some(e=>e.role===`user`&&e.anchor&&e.anchor.activeMessagePosition>s.activeMessagePosition))return`missing`;if(i.generation!==r.generation||i.maxSeq!==r.maxSeq||s.generation!==i.generation||t.tail?.lastSeq!==i.maxSeq)return`pending`;return`delivered`}
//!src/gateway/server-methods/chat-send-delivery-authority.ts
async function createChatSendReplyFinalizationAuthority(e,t,n){const{cfg:r,sessionKey:i,agentId:a,sessionLoadOptions:o}=e.session;const s=e.terminalEntry?captureChatAbortRegistrationGuard([{runId:e.session.clientRunId,entry:e.terminalEntry}]):()=>true;const c=/* @__PURE__ */ new Map;try{for(const n of t){const t=getReplyPayloadMetadata(n)?.sessionWriterDeliveryAuthority;if(t&&!c.has(t)){const n=t.agentId??a;c.set(t,await prepareSessionWriterDeliveryAuthority({...t,agentId:n},n===a?e.session.storePath:void 0))}}}catch(e){for(const e of c.values())e.release();throw e}const l=[];const deliveryAuthorized=()=>s()&&(!e.isCurrent||e.isCurrent())&&t.every(e=>{const t=getReplyPayloadMetadata(e)?.sessionWriterDeliveryAuthority;return isReplyPayloadSessionWriterDeliveryAuthorized(e,t?c.get(t)?.authority?.readCurrentSession?.():void 0)});const authorizeDelivery=t=>{if(deliveryAuthorized())return true;e.context.logGateway.warn(`webchat settled final reply skipped: session writer changed before ${t}`);n?.();return false};return{deliveryAuthorized,authorizeDelivery,release:()=>{for(const e of l)e.release();for(const e of c.values())e.release()},captureMediaScope:async()=>{try{const t=await captureWebchatReplyMediaScope({cfg:r,sessionKey:i,agentId:a,sessionLoadOptions:o,requesterContext:e.requesterContext,accountId:e.accountId,assertCurrent:()=>{if(!deliveryAuthorized())throw new Error(`Chat media delivery is no longer authorized.`)}});l.push(t);return t}catch(e){if(!authorizeDelivery(`media preparation`))return;throw e}}}}
//!src/gateway/server-methods/chat-tts-markers.ts
function stripVisibleTextFromTtsSupplement(e){return isReplyPayloadTtsSupplement(e)?buildTtsSupplementMediaPayload(e):e}function resolveTtsSupplementMarkerText(e){const t=e.trim();const n=projectChatDisplayMessage({role:`assistant`,content:[{type:`text`,text:t}]},{maxChars:Number.MAX_SAFE_INTEGER});const r=Array.isArray(n?.content)?n.content:void 0;return extractAssistantDisplayText(r)??(typeof n?.text===`string`?n.text.trim():void 0)??t}function buildTtsSupplementTranscriptMarker(e){const t=getReplyPayloadTtsSupplement(e);if(!t)return;const n=resolveTtsSupplementMarkerText(e.text?.trim()||t.spokenText.trim());return{textSha256:sha256Hex(n)}}function buildMediaOnlyTtsSupplementTranscriptMarker(e){if(e.text?.trim())return;return buildTtsSupplementTranscriptMarker(e)}
//!src/gateway/server-methods/chat-send-reply-finalization.ts
const retainCommittedChatReplyMedia=(e,t)=>{const n=readAssistantDisplayContent(e.message);if(hasManagedOutgoingAssistantContent(n))t(async()=>{await attachManagedOutgoingMediaToMessage({messageId:e.messageId,blocks:n})})};function resolveTranscriptMirrorOwner(e){const t=e.map(e=>getReplyPayloadMetadata(e)?.sourceReplyTranscriptMirror);if(t.every(e=>e?.expectedSessionId===void 0&&!e?.transcriptWriteBlocked))return{kind:`none`};const n=t[0];if(!n)return{kind:`invalid`};const r=n.sessionKey.trim();const i=n.expectedSessionId?.trim();if(!r||!n.transcriptWriteBlocked&&!i||t.some(e=>n.transcriptWriteBlocked&&!e?.transcriptWriteBlocked||e?.sessionKey.trim()!==r||e.expectedSessionId?.trim()!==i||e.agentId!==n.agentId||!n.transcriptWriteBlocked&&e.transcriptWriteBlocked===true))return{kind:`invalid`};return{kind:n.transcriptWriteBlocked?`blocked`:`owner`,owner:{sessionKey:r,...i?{expectedSessionId:i}:{},...n.agentId?{agentId:n.agentId}:{}}}}function buildChatSendBtwSideResult(e){const t=e.map(e=>readChatSendReplyPayload(e.input)).filter(isBtwReplyPayload);const n=combineNonStreamingReplyParts(t.map(e=>e.text));if(t.length===0||!n)return;return{question:expectDefined(t[0],`btw replies entry at 0`).btw.question.trim(),text:n,isError:t.some(e=>e.isError)}}async function finalizeChatSendDispatchedReplies(e){const{context:t,deliveredReplies:n,emitFirstAssistantServerTiming:r,foldCommandBlocks:i,persistUserTurnTranscript:a,session:o,suppressReplies:s}=e;const{agentId:c,backingSessionId:l,cfg:u,clientRunId:d,sessionKey:f,sessionLoadOptions:p}=o;const m=e.state===`aborted`?`aborted`:`stop`;const h=buildChatSendBtwSideResult(n);if(h){broadcastSideResult({context:t,payload:{kind:`btw`,runId:d,sessionKey:f,...c?{agentId:c}:{},...h,ts:Date.now()}});broadcastChatFinal({terminalEntry:e.terminalEntry,context:t,runId:d,sessionKey:f,agentId:c});return}const g=!e.runtimeOwnsTranscript&&n.length>0&&n.every(({input:e})=>{const t=readChatSendReplyPayload(e);const n=getReplyPayloadMetadata(t);return n?.commandReply===true&&n.contextFreeCommand===true&&n.assistantTranscriptOwned!==true});const _=selectChatSendFinalReplyInputs({deliveredReplies:n,foldCommandBlocks:i,suppressReplies:s});const v=_.map(readChatSendReplyPayload);const{authorizeDelivery:y,captureMediaScope:b,release:x}=await createChatSendReplyFinalizationAuthority(e,v,()=>broadcastChatFinal({context:t,runId:d,sessionKey:f,agentId:c,terminalEntry:e.terminalEntry}));try{const n=resolveTranscriptMirrorOwner(v);const i=n.kind===`owner`||n.kind===`blocked`?n.owner:void 0;const o=await b();if(!o)return;const h=await loadGatewaySessionEntryReadOnlyInWorker({cfg:t.getRuntimeConfig(),key:f,...p,projection:[]});const x=i?await loadGatewaySessionEntryReadOnlyInWorker({cfg:t.getRuntimeConfig(),key:i.sessionKey,...p,...i.agentId?{agentId:i.agentId}:{},projection:[]}):void 0;const S=Boolean(n.kind===`owner`&&i&&x?.entry?.sessionId===i.expectedSessionId);if(n.kind===`owner`&&!S)t.logGateway.warn(`webchat transcript append skipped: binding-owned session changed before finalization`);if(n.kind===`invalid`)t.logGateway.warn(`webchat transcript append skipped: inconsistent binding-owned transcript metadata`);if(n.kind===`blocked`)t.logGateway.warn(`webchat transcript append skipped: binding-owned user turn was not persisted`);const C=n.kind===`none`||S;const w=S&&i?i.sessionKey:f;const T=S&&i?i.agentId??c:c;const{storePath:E,entry:D}=S&&x?x:h;const O=D?.sessionId??l??d;const{payloads:k,inputs:A,mediaMessage:j,assistantContent:M,persistedAssistantContent:N,broadcastContent:P,managedMediaPrepareFailed:F}=await prepareWebchatReplyMediaForDisplay({scope:o,storePath:h.storePath,transcriptTarget:{sessionKey:w,agentId:T},inputs:_,abortSignal:e.abortSignal,includeSensitiveMedia:false,includeSensitiveDisplay:true,logGateway:t.logGateway});const I=k.map(e=>buildMediaOnlyTtsSupplementTranscriptMarker(e)).find(e=>Boolean(e));const L=hasAssistantDisplayMediaContent(N)?N:void 0;const R=extractAssistantDisplayText(M)??buildTranscriptReplyTextFromInputs(A);const z=R?.trim()??``;const ee=j?.transcriptText||(F?z:buildTranscriptReplyTextFromInputs(A))||z;let B;const V=v.some(e=>getReplyPayloadMetadata(e)?.assistantTranscriptOwned===true);const te=Boolean((!e.runtimeOwnsTranscript&&!V||S)&&C&&(ee||L?.length));if(g)await a({contextFreeCommand:true});else await a();if(!y(`transcript append`))return;if(te){const e=await appendInjectedAssistantMessageToTranscript({sessionKey:w,message:ee,...L?.length?{content:L}:{},sessionId:O,storePath:E,agentId:T,idempotencyKey:d,stopReason:m,ttsSupplement:I,...g?{contextFreeCommand:true}:{},config:u,onMessageCommitted:retainCommittedChatReplyMedia});if(e.ok)B=P?.length?applyAssistantDeliveryDirectives({...e.message,content:P.map(e=>({...e}))}):e.message;else{t.logGateway.warn(`webchat transcript append failed: ${e.error??`unknown error`}`);const n=stripManagedOutgoingAssistantContentBlocks(N)??stripManagedOutgoingAssistantContentBlocks(M);const r=extractAssistantDisplayText(n)??R;B={role:`assistant`,...n?.length?{content:n}:r?{content:[{type:`text`,text:r}]}:{},...r?{text:r}:{},timestamp:Date.now(),...I?{openclawTtsSupplement:I}:{},stopReason:m,usage:{input:0,output:0,totalTokens:0}}}}else if(P?.length)B={role:`assistant`,content:P,text:extractAssistantDisplayText(P)??``,timestamp:Date.now(),stopReason:m,usage:{input:0,output:0,totalTokens:0}};if(!y(`broadcast`))return;const ne=t.chatRunState.runs.get(d);if(!s&&ne?.bufferIsCurrent?.()!==false)B=appendChatCanvasBlocksToMessage(B,ne?.canvasBlocks??[]);if(hasVisibleAssistantFinalMessage(B)){r();t.chatRunState.flushPendingText(d)}broadcastChatTerminal({terminalEntry:e.terminalEntry,context:t,runId:d,sessionKey:f,agentId:c,message:B,state:e.state,stopReason:e.stopReason})}finally{x()}}
//!src/gateway/server-methods/chat-send-reply-session.ts
function createChatReplySessionReader(e,t,n){const r=e.storePath??resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId});let i={sessionKey:e.sessionKey,sessionId:e.entry?.sessionId??e.backingSessionId,lifecycleRevision:e.entry?.lifecycleRevision,storePath:r};const a=e.sessionTarget;const o=a?.readSource;const s=a&&o&&typeof o.databaseIdentity===`string`&&n&&a.storeKeys.length===1&&a.storeKeys[0]===a.storeKey&&e.capturedReadSources?.length===1&&isDeepStrictEqual(e.capturedReadSources[0],o)?{target:a,source:{...o,databaseIdentity:o.databaseIdentity},assertWorkCurrent:n}:void 0;const c=captureSessionMutationRouting(e.cfg,void 0,[e]);const l=s?()=>{s.assertWorkCurrent();c(t())}:void 0;return{assertRetainedSourceCurrent:l,notePreparedSession(t){if(t.sessionKey===e.sessionKey)i={...t}},captureTranscriptStart(t){const n={entry:i,storePath:i.storePath??r};const a=t===void 0?resolveLegacyChatReplyTranscriptStart(e,n):resolveChatReplyTranscriptStart(e,n,t);return a?{...a,lifecycleRevision:i.lifecycleRevision}:void 0},async readCurrentSession(n=e.sessionKey,i=e.agentId){const a=t();if(s&&l&&n===e.sessionKey&&i===e.agentId){const e=l;e();return withQualifiedGatewaySessionStoreTarget({target:s.target,logicalStorePath:r,preparedSource:{...s.source,assertCurrent:e},includeMembership:false,readOptions:{projection:`exact`},consume:(t,n,r)=>{r();e();omitInternalSessionEffectsEntries(t.store,t.storeKeys);const i=findCanonicalStoreMatch(t.store,t.storeKeys);return{...t,cfg:a,entry:i?.entry,legacyKey:i?.key!==t.canonicalKey?i?.key:void 0}}})}const o=captureSessionMutationRouting(a,void 0,[{sessionKey:n,agentId:i}]);return await loadGatewaySessionEntryReadOnlyInWorker({...e.sessionLoadOptions,cfg:a,key:n,excludeInternalEffects:true,agentId:i,assertActive:()=>o(t())})}}}
//!src/gateway/server-methods/chat-transcript-media-enrichment.ts
async function rewriteAssistantTranscriptMessageById(e){await waitForSessionTranscriptProjection(e.scope,e.abortSignal);e.assertCurrent();const t=await readActiveTranscriptEntryAnchorAsync({...e.scope,entryId:e.messageId});e.assertCurrent();if(!t)return null;const n=await rewritePreparedTranscriptMessageAtAnchor(t,t=>{const n=asOptionalRecord(t);if(n?.role!==`assistant`||readSessionTranscriptRunId(n)!==e.runId)return;return buildAssistantDisplayRewrite({message:n,displayContent:e.content,mediaBySource:e.mediaBySource,responseUsageLine:e.responseUsageLine,managedMediaUrls:e.mediaUrls,retainOriginalText:true})},{active:`sequence`,expectedEntry:{lifecycleRevision:e.expectedLifecycleRevision},assertCurrent:e.assertCurrent,assertNativeCurrent:e.assertCurrent});return n?{generation:n.generation,messageId:e.messageId}:null}
//!src/gateway/server-methods/chat-send-reply-dispatch.ts
function createChatSendReplyDispatch(e){const{accountId:t,getRuntimeConfig:n,isAgentRunStarted:r,logGateway:i,session:a,userTurnRecorder:o}=e;const{backingSessionId:s,cfg:c,clientRunId:l}=a;const u={...a.sessionLoadOptions,clone:false};const{notePreparedSession:d,readCurrentSession:f,captureTranscriptStart:p,assertRetainedSourceCurrent:m}=createChatReplySessionReader(a,n,e.assertWorkCurrent);let h;let g=l;const captureAgentTranscriptStart=(e=l,t)=>{g=e;const n=p(t);h=n;return n!==void 0};const{onModelSelected:_,...v}=createChannelReplyPipeline({cfg:c,agentId:a.agentId,channel:INTERNAL_MESSAGE_CHANNEL});const y=[];const b=/* @__PURE__ */ new Set;const x=createAssistantCommentaryMediaCustody({requesterContext:e.requesterContext,session:{...a,storePath:a.storePath??resolveSessionStorePathCore(c.session?.store,{agentId:a.agentId})},accountId:t,getRunId:()=>g,isCurrent:()=>r()&&e.isRunCurrent?.()===true,abortSignal:e.abortSignal,logGateway:i,prepareAssistantTranscriptMessage:e.prepareAssistantTranscriptMessage});const resolveReplyDeliveryFacts=async(t=0)=>{const i=a.sessionTarget?.readSource;const s=m&&i?retainSessionHistoryWorkerDatabase({agentId:i.agentId,path:i.path}):void 0;try{const i=o.getAdmissionReceipt();const c=h;const l=g;const u=c?.lifecycleRevision;const d=i&&getOwnedSessionTranscriptReader(i);const isRunCurrent=()=>{const t=o.getAdmissionReceipt();return Boolean(i&&i.agentId===a.agentId&&i.sessionKey===a.sessionKey&&r()&&e.isRunCurrent?.()===true&&!e.abortSignal?.aborted&&g===l&&h===c&&t?.logicalTurnId===i.logicalTurnId&&t?.entryId===i.entryId)};const isInspectionCurrent=()=>{if(!isRunCurrent())return false;m?.();s?.owner.assertCurrent();d?.assertCurrent();return true};const isCurrent=async()=>{if(!i||!isRunCurrent())return false;const e=await f();return isRunCurrent()&&e.entry?.sessionId===i.sessionId&&e.entry.lifecycleRevision===u&&e.readSource?.path===i.storePath};if(!i||!c||c.sessionId!==i.sessionId||!(d?isInspectionCurrent():await isCurrent()))return{source:`missing`,terminal:`missing`};const p=i;await waitForSessionTranscriptProjection(p,e.abortSignal);if(!(d||m?isInspectionCurrent():await isCurrent()))return{source:`missing`,terminal:`missing`};const _=captureSessionMutationRouting(n(),void 0,[p]);let v=`pending`;let y=`missing`;await readSessionTranscriptAnchorsAsync(p,{entryIds:[i.entryId],afterSeq:c.afterSeq,includeSession:true,includeWatermark:true,includeMessagesForRunId:l},e.abortSignal,e=>{_(n());if(!isInspectionCurrent()||e.session?.sessionId!==i.sessionId||e.session.lifecycleRevision!==u||!e.watermark){v=`missing`;return}const r=e.anchors.find(e=>e.entryId===i.entryId);if(!r||r.rawSeq!==i.rawSeq){v=`missing`;return}let a=r;for(const t of e.tail?.entries??[])if(t.role===`user`&&t.anchor&&t.anchor.activeMessagePosition>a.activeMessagePosition)a=t.anchor;if(t>0&&a.entryId===r.entryId){v=`missing`;return}v=`missing`;for(const t of e.tail?.entries??[]){const n=asOptionalRecord(t.message);if(n?.role!==`assistant`||readSessionTranscriptRunId(n)!==l)continue;if(!(n.stopReason===`toolUse`||Array.isArray(n.content)&&n.content.some(e=>isToolHistoryBlockType(asOptionalRecord(e)?.type))?extractAssistantTextForPhase(n,{phase:`final_answer`}):extractAssistantPhaseText(n))||!extractAssistantPhaseText(projectChatDisplayMessage(n)))continue;const r=resolveChatReplyDeliveryFromAnchors({facts:e,admissionId:i.entryId,inputId:a.entryId,messageId:t.entryId,afterSeq:c.afterSeq,watermark:e.watermark,currentWatermark:e.watermark});if(r!==void 0){v=r;const e=asOptionalRecord(n.openclawDeliveryMirror);if(e?.kind===`message-tool-source-reply`&&e.final===true){y=r;return}}}});_(n());return isInspectionCurrent()?{source:y,terminal:v}:{source:`missing`,terminal:`missing`}}finally{s?.release()}};const needsAgentMediaTranscriptFinalization=e=>isMediaBearingPayload(e)||Boolean(getReplyPayloadMetadata(e)?.assistantMediaFailures?.length);const agentMediaTranscriptKey=e=>{const t=getReplyPayloadMetadata(e);const n=t?.assistantTranscriptOwned===true?t.assistantTranscriptIdempotencyKey?.trim():void 0;if(n)return`owned:${n}`;if(t?.assistantMessageIndex!==void 0)return`index:${t.assistantMessageIndex}`;const r=t?.assistantTranscriptSource?.committedMessageId;if(r)return`message:${r}`;return`unkeyed`};const appendWebchatAgentMediaTranscriptIfNeeded=async n=>{const o=readChatSendReplyPayload(n);if(!r()||!needsAgentMediaTranscriptFinalization(o))return;const d=agentMediaTranscriptKey(o);if(b.has(d))return;if(isSourceReplyTranscriptMirrorPayload(o))return;const p=e.getReplyDispatchRun?.();const m=p?.getResult().assistantTranscript;if(p&&!m){i.warn(`webchat runtime-owned media skipped: assistant transcript was not persisted`);return}const _=m?.sessionKey??a.sessionKey;const v=m?.agentId??a.agentId;const y=buildTtsSupplementTranscriptMarker(o);const x=await captureWebchatReplyMediaScope({requesterContext:e.requesterContext,cfg:c,sessionKey:_,agentId:v,sessionLoadOptions:{...u,agentId:v},accountId:t,assertCurrent:()=>{e.abortSignal?.throwIfAborted();if(e.isRunCurrent&&!e.isRunCurrent())throw new Error(`Chat media run is no longer current.`)}});try{const{storePath:t,entry:r}=await f(_,v);const a=r?.sessionId??s??l;const{payloads:[u],inputs:p,mediaMessage:S,assistantContent:C,persistedAssistantContent:w,mediaBySource:T}=await prepareWebchatReplyMediaForDisplay({scope:x,storePath:t,inputs:replaceChatSendReplyPayload(n,stripVisibleTextFromTtsSupplement(o)),abortSignal:e.abortSignal,includeSensitiveMedia:o.sensitiveMedia!==true,logGateway:i});if(!u)return;const E=getReplyPayloadMetadata(u)?.assistantMediaFailures??[];const D=E.length>0;const O=hasAssistantDisplayMediaContent(w)||D?w:void 0;if(!O?.length)return;const k=S?.transcriptText??extractAssistantDisplayText(C)??buildTranscriptReplyTextFromInputs(p);const A=getReplyPayloadMetadata(o);const j=uniqueStrings(A?.assistantTranscriptMediaUrls?.length?A.assistantTranscriptMediaUrls:[...Array.isArray(o.mediaUrls)?o.mediaUrls:[],...typeof o.mediaUrl===`string`?[o.mediaUrl]:[]]);const M=m?.idempotencyKey??(A?.assistantTranscriptOwned===true?A.assistantTranscriptIdempotencyKey?.trim():void 0);const N=assistantTranscriptScope({sessionKey:_,sessionId:a,storePath:t,agentId:v});const P=A?.assistantMessageIndex;const F=A?.assistantTranscriptSource?.committedMessageId;let I=null;if(M&&N){if(m&&(await f(_,v)).entry?.sessionId!==m.sessionId){i.warn(`webchat runtime-owned media skipped: transcript session changed`);return}I=await rewriteAssistantTranscriptMessageByIdempotencyKey({content:O,responseUsageLine:A?.responseUsageLine,mediaBySource:T,idempotencyKey:M,managedMediaUrls:j,scope:N});if(!I){i.warn(`webchat runtime-owned assistant media rewrite skipped: transcript identity not found`);return}}else if(F&&N&&!y){const t=await rewriteAssistantTranscriptMessageById({messageId:F,runId:g,content:O,responseUsageLine:A?.responseUsageLine,mediaBySource:T,mediaUrls:j,expectedLifecycleRevision:h?.lifecycleRevision??null,scope:N,assertCurrent:x.assertCurrent,abortSignal:e.abortSignal});if(!t){i.warn(`webchat assistant media rewrite skipped: committed occurrence unavailable`);return}if(h)h.generation=t.generation;I=t}else if(P!==void 0&&N){if(h?.sessionId!==a)return;const e=await rewriteAssistantTranscriptMessageByTurnIndexAndMedia({afterSeq:h.afterSeq,assistantMessageIndex:P,content:O,responseUsageLine:A?.responseUsageLine,mediaBySource:T,expectedGeneration:h.generation,mediaUrls:j,rejectedMediaCount:E.filter(e=>e.code===`invalid-reference`).length,scope:N});if(e){h.generation=e.generation;I=e}}if(I&&N){b.add(d);if(C?.length)await attachManagedOutgoingMediaToMessage({messageId:I.messageId,blocks:C});await publishAssistantTranscriptRewrite({scope:N,rewritten:[I]});return}const L=O.some(e=>e.type===`attachment_error`)&&O.every(e=>e.type===`text`||e.type===`attachment_error`);const R=stripReplyMediaFailureFallback(u.text,E)?.trim();if(P===void 0&&D&&L&&R)return;const z=P!==void 0&&P>=1&&!D&&!y&&!o.isError&&!isReplyPayloadStatusNotice(o)&&!A?.toolErrorWarning&&!A?.nonTerminalToolErrorWarning&&!A?.terminalProviderError;const ee=z?O.filter(e=>e.type!==`text`):O;const B=await appendInjectedAssistantMessageToTranscript({sessionKey:_,message:z?``:k,content:ee,sessionId:a,storePath:t,agentId:v,idempotencyKey:P!==void 0&&P>=1?`${l}:assistant-media:${P}`:`${l}:assistant-media`,ttsSupplement:y,config:c,onMessageCommitted:retainCommittedChatReplyMedia});if(B.ok){b.add(d);return}i.warn(`webchat transcript append failed for media reply: ${B.error??`unknown error`}`)}finally{x.release()}};const deliverInput=async(t,n)=>{const i=readChatSendReplyPayload(t);const a=getReplyPayloadMetadata(i);if(a?.beforeAgentRunBlocked===true||a?.sourceReplyTranscriptMirror?.transcriptWriteBlocked===true)o.markBlocked();switch(n.kind){case`block`:case`final`:y.push({input:t,kind:n.kind});if(n.kind===`block`&&e.onCommandBlock&&!r()&&e.isRunCurrent?.()){const t=y.map(({input:e,kind:t})=>{const n=readChatSendReplyPayload(e);if(t!==`block`||n.isReasoning===true||isBtwReplyPayload(n))return``;return(e.kind===`prepared`?prepareAssistantDisplayText:sanitizeAssistantDisplayText)(n.text,{preserveBoundaries:true})??``});if(t.at(-1))e.onCommandBlock(combineNonStreamingReplyParts(t))}break;case`tool`:if(isMediaBearingPayload(i)){const e=copyReplyPayloadMetadata(i,{...i,text:void 0});y.push(...replaceChatSendReplyPayload(t,e).map(e=>({input:e,kind:`final`})))}}};const S={...v,onError:e=>{i.warn(`webchat dispatch failed: ${formatForLog(e)}`)},deliver:(e,t)=>deliverInput({kind:`raw`,payload:e},t),deliverPrepared:(e,t)=>deliverInput({kind:`prepared`,plan:e},t)};const finalizeAgentMediaTranscript=async()=>{const e=/* @__PURE__ */ new Map;for(const{input:t}of y){const n=readChatSendReplyPayload(t);if(!needsAgentMediaTranscriptFinalization(n))continue;e.set(agentMediaTranscriptKey(n),t)}for(const t of e.values())try{await appendWebchatAgentMediaTranscriptIfNeeded(t)}catch(e){i.warn(`webchat media finalization failed: ${formatForLog(e)}`)}};const runAgentMediaTranscript=async(e,t)=>{return await e.run(async()=>{try{return await x.run(t)}finally{const e=x.lastRewrite;if(e&&h&&e.sessionId===h.sessionId)h.generation=e.generation;await finalizeAgentMediaTranscript()}})};return{captureAgentTranscriptStart,notePreparedSession:d,deliveredReplies:y,dispatcherOptions:S,hasAppendedWebchatAgentMedia:()=>b.size>0,onModelSelected:_,prepareAssistantTranscriptMessage:x.prepareAssistantTranscriptMessage,resolveReplyDelivery:async e=>(await resolveReplyDeliveryFacts(e)).terminal,resolveReplyDeliveryFacts,runAgentMediaTranscript}}
//!src/gateway/server-methods/chat-send-source-finalization.ts
function selectChatSendAgentReplyInputs(e){return e.deliveredReplies.filter(t=>{const n=readChatSendReplyPayload(t.input);return getReplyPayloadMetadata(n)?.sessionWriterDeliveryAuthority||isSourceReplyTranscriptMirrorPayload(n)?t.kind===`final`&&n.isError!==true:!e.hasReturnedAgentErrorPayloads&&isReplyPayloadStatusNotice(n)}).map(e=>e.input)}function createChatSendLateReplyFinalizer(e){const t=e.terminalEntry?captureChatAbortRegistrationGuard([{runId:e.session.clientRunId,entry:e.terminalEntry}]):()=>true;return async({runId:n,clientRunId:r,payloads:i,completion:a,isCurrent:o})=>{let s=i;const{context:c,session:l}=e;const isCurrent=()=>o()&&(r!==l.clientRunId||t());const u={terminalEntry:r===l.clientRunId?e.terminalEntry:void 0,context:c,runId:r,sessionKey:l.sessionKey,agentId:l.agentId};const d=a.kind!==`progress`;let f=false;try{if(!d){const t=s.filter(e=>getReplyPayloadMetadata(e)?.queueAdmissionNotice===`queued`);if(t.length>0){const n=await finalizeChatSendAgentReplyPayloads({...e,terminalEntry:u.terminalEntry,emitFirstAssistantServerTiming:()=>{},inputs:t.map(e=>({kind:`raw`,payload:e})),isCurrent,session:{...l,clientRunId:r},publishMessage:e=>{f=true;const t=typeof e?.text===`string`?e.text:void 0;if(t)broadcastChatQueueNotice({...u,text:t});return false}});s=s.filter(e=>getReplyPayloadMetadata(e)?.queueAdmissionNotice!==`queued`);if(s.length===0)return n}}const t=await finalizeChatSendAgentReplyPayloads({...e,terminalEntry:u.terminalEntry,emitFirstAssistantServerTiming:()=>{},inputs:s.map(e=>({kind:`raw`,payload:e})),isCurrent,session:{...l,clientRunId:r},suppressFinal:a.kind===`failed`||a.kind===`aborted`,publishMessage:(e,t,n)=>{f=true;if(a.kind===`progress`){const i=typeof e?.text===`string`?e.text:void 0;if(i){const e=c.chatRunState.getOrCreate(r);e.releaseBufferAuthority?.();e.releaseBufferAuthority=n;broadcastChatDelta({...u,text:i,isCurrent:()=>c.chatRunState.runs.get(r)===e&&t()});return true}}else{const t=c.chatRunState.runs.get(r);const n=t?.bufferIsCurrent?.()===false?[]:t?.canvasBlocks??[];broadcastChatTerminal({...u,state:`final`,message:appendChatCanvasBlocksToMessage(e??(n.length?{role:`assistant`,content:[],timestamp:Date.now()}:void 0),n),stopReason:a.stopReason})}return false}});if(!isCurrent())return{kind:`dropped`,reason:`no-visible-content`};if(a.kind===`failed`||a.kind===`aborted`||d&&t.kind===`dropped`){const e=c.chatRunState.resolveBuffer(r,{final:true});const t=c.chatRunState.runs.get(r);const n=t?.bufferIsCurrent?.()===false?[]:t?.canvasBlocks??[];const i=a.kind===`completed`&&a.allowCanvasOnly===true&&s.length===0&&n.length>0&&!(t?.rawBuffer??t?.buffer??``).trim();if(a.kind===`failed`||a.kind===`aborted`)c.chatRunState.flushPendingText(r);f=true;broadcastChatTerminal({...u,stopReason:a.stopReason,...a.kind===`failed`?{state:`error`,errorMessage:a.error,errorKind:a.errorKind}:{state:a.kind===`aborted`?`aborted`:`final`,...a.kind===`aborted`&&e.text&&!e.suppress||i?{message:appendChatCanvasBlocksToMessage({role:`assistant`,content:i?[]:[{type:`text`,text:e.text}],timestamp:Date.now()},n)}:{}}})}return d?{kind:`delivered`,hasSourceReplyTranscriptMirror:t.kind===`delivered`&&t.hasSourceReplyTranscriptMirror}:t}catch(e){if(d&&!f&&isCurrent()){c.chatRunState.flushPendingText(r);broadcastChatTerminal({...u,state:`error`,errorMessage:formatErrorMessage(e)})}throw e}finally{if(d){c.removeChatRun(n,r,l.sessionKey);if(isCurrent()){c.chatRunState.clearRun(r);c.agentRunSeq.delete(r)}c.agentRunSeq.delete(n)}}}}async function finalizeChatSendAgentReplyPayloads(e){const{context:t,emitFirstAssistantServerTiming:n,session:r}=e;const{agentId:i,backingSessionId:a,clientRunId:o,sessionKey:s,sessionLoadOptions:c}=r;let l=false;const u=e.inputs.flatMap(e=>{const t=readChatSendReplyPayload(e);const n=getReplyPayloadMetadata(t);if(n?.assistantMessageIndex===void 0&&!n?.assistantTranscriptOwned||n?.sessionWriterDeliveryAuthority||isSourceReplyTranscriptMirrorPayload(t)||isHostNoticePayload(t))return[e];l=true;return replaceChatSendReplyPayload(e,copyReplyPayloadMetadata(t,{...t,text:n?.responseUsageLine}))});const d=u.map(readChatSendReplyPayload);if(d.length===0)return{kind:`dropped`,reason:`no-visible-content`};const{deliveryAuthorized:f,authorizeDelivery:p,captureMediaScope:m,release:h}=await createChatSendReplyFinalizationAuthority(e,d);let g=false;try{const r=d.some(isSourceReplyTranscriptMirrorPayload);const _=await m();if(!_)return{kind:`dropped`,reason:`no-visible-content`};const{storePath:v,entry:y}=await loadGatewaySessionEntryReadOnlyInWorker({cfg:t.getRuntimeConfig(),key:s,...c,projection:[]});const b=y?.sessionId??a??o;const x=assistantTranscriptScope({sessionId:b,sessionKey:s,storePath:v,agentId:i});const S=await Promise.all(d.map(async t=>x?readCommittedSourceReplyContent({scope:x,payload:t,abortSignal:e.abortSignal,assertCurrent:_.assertCurrent}):void 0));_.assertCurrent();const C=S.some(Boolean);const{finalInputsByIndex:w,sourceReplyContentStates:T,sourceReplyBroadcastContent:E}=await withPreparedWebchatReplyMedia({scope:_,storePath:v,inputs:u.filter((e,t)=>!S[t]),abortSignal:e.abortSignal,includeSensitiveMedia:false,logGateway:t.logGateway},async({payloads:e,inputsByIndex:t,buildContent:n})=>{const r=[];const i=[];let a=0;for(const[o]of d.entries()){const s=S[o];if(s){r[o]={broadcastContent:[],persistedContent:s,hasManagedOutgoingContent:hasManagedOutgoingAssistantContent(s),backedManagedOutgoingContent:true};continue}const c=a++;if(!e[c])continue;const{persistedAssistantContent:l,broadcastContent:u}=await n(t[c]??[]);const d={broadcastContent:u??[],persistedContent:l??[],hasManagedOutgoingContent:hasManagedOutgoingAssistantContent(l),backedManagedOutgoingContent:false};r[o]=d;i.push(...d.broadcastContent)}return{finalInputsByIndex:t,sourceReplyContentStates:r,sourceReplyBroadcastContent:i}});const D=extractAssistantDisplayText(E)??buildTranscriptReplyTextFromInputs(w.flat());if(!E.length&&!D&&!C&&!l)return{kind:`dropped`,reason:`no-visible-content`};const O=[];const k=[];for(const[e,t]of d.entries()){const n=T[e];if(!n)continue;const r=getReplyPayloadMetadata(t)?.sourceReplyTranscriptMirror;const i=r?.idempotencyKey;if(typeof i!==`string`||i.trim().length===0||!r)continue;const a={idempotencyKey:i,metadata:r};k.push(a);if(!n.backedManagedOutgoingContent&&hasAssistantDisplayMediaContent(n.persistedContent)){if(!n.hasManagedOutgoingContent)n.backedManagedOutgoingContent=true;O.push({...a,state:n})}}if(!p(`transcript finalization`))return{kind:`dropped`,reason:`no-visible-content`};if(x&&O.length>0){const e=await rewriteSourceReplyTranscriptMirrors({candidates:k,requests:O,scope:x});if(e.length>0){for(const t of e){const e=t.request.state;if(e.hasManagedOutgoingContent)await attachManagedOutgoingMediaToMessage({messageId:t.messageId,blocks:e.persistedContent});e.backedManagedOutgoingContent=true}await publishAssistantTranscriptRewrite({scope:x,rewritten:e})}}const A=T.flatMap(e=>{if(e.hasManagedOutgoingContent&&!e.backedManagedOutgoingContent)return stripManagedOutgoingAssistantContentBlocks(e.broadcastContent)??[{type:`text`,text:`Media reply could not be displayed.`}];return e.broadcastContent});const j=extractAssistantDisplayText(A)??(A.length===0?D:void 0);const M=A.length||j?{role:`assistant`,content:A.length?A:[{type:`text`,text:j}],...j?{text:j}:{},timestamp:Date.now(),stopReason:`stop`,usage:{input:0,output:0,totalTokens:0}}:void 0;if(!e.suppressFinal){if(!p(`broadcast`))return{kind:`dropped`,reason:`no-visible-content`};if(hasVisibleAssistantFinalMessage(M))n();if(e.publishMessage)g=e.publishMessage(M,f,h);else if(M)broadcastChatFinal({terminalEntry:e.terminalEntry,context:t,runId:o,sessionKey:s,agentId:i,message:M})}return{kind:`delivered`,hasSourceReplyTranscriptMirror:r}}catch(e){if(!p(`reply finalization`))return{kind:`dropped`,reason:`no-visible-content`};throw e}finally{if(!g)h()}}async function finalizeChatSendSourceReplies(e){const t=await finalizeChatSendAgentReplyPayloads({...e,inputs:selectChatSendAgentReplyInputs(e)});return t.kind===`delivered`&&t.hasSourceReplyTranscriptMirror}
//!src/gateway/server-methods/chat-send-tool-event-recipients.ts
function registerChatSendToolEventRecipients(e,t){const{client:n,context:r,cfg:i,sessionKey:a,selectedAgent:o,storePath:s}=e;const c=resolveAgentTurnRunObserver({principal:n,registerToolEventRecipient:r.registerToolEventRecipient});if(c){c(t);const e=tryResolveSessionCompatibilityOwnerAgentId(i,a);const n=captureRpcSourceScopeMatcher({storePath:s,resolveGatewayContext:r.resolveGatewayContext});for(const[r,i]of listRpcSourceEntries()){const s=getRpcSourceIdentity(i);const l=o.agentId!==void 0&&chatRunBelongsToSelectedAgent({agentId:s.agentId,sessionKey:s.sessionKey,defaultAgentId:e,selectedAgentId:o.agentId});const u=s.sessionKey===a&&l;if(r!==t&&u&&n(i)&&isRpcSourceActive(i))c(r)}}}
//!src/gateway/server-methods/chat-send-late-followup.ts
function createChatSendLateFollowupDisposition(e){let t=`pending`;const n=[];const recordDrop=(n,r,i=true)=>{if(i&&n.completion.kind!==`progress`){t=`settled`;if(r===`non-webchat-origin`||r===`origin-mismatch`)e.onTerminalDrop?.(n.completion)}e.logGateway.info(`webchat late reply disposition`,{runId:e.runId,followupRunId:n.runId,outcome:`late-and-dropped`,reason:r})};return{recordQueued:()=>{if(t===`pending`)t=isInternalMessageChannel(e.originatingChannel)?`deliver`:`drop`},deliver:Object.assign(async r=>{if(t===`delivering`)return recordDrop(r,`delivery-in-flight`,false);if(t!==`deliver`)return recordDrop(r,t===`pending`?`terminal-not-recorded`:t===`drop`?`non-webchat-origin`:`already-settled`);if(!isInternalMessageChannel(r.originatingChannel))return recordDrop(r,`origin-mismatch`);if(r.completion.kind===`progress`){n.push(...r.payloads.filter(e=>getReplyPayloadMetadata(e)?.queueAdmissionNotice!==`queued`));await e.deliver({...r,clientRunId:e.retainSourceIdentity===false?r.runId:e.runId,isCurrent:()=>t===`deliver`});return}t=`delivering`;try{const i=await e.deliver({...r,clientRunId:e.retainSourceIdentity===false?r.runId:e.runId,payloads:[...n,...r.payloads],isCurrent:()=>t===`delivering`});if(i.kind===`dropped`)return recordDrop(r,i.reason);t=`settled`}catch(e){recordDrop(r,`delivery-failed`);throw e}finally{n.length=0}},{ownsCompletion:e=>t===`deliver`&&isInternalMessageChannel(e),createSourceRetry:()=>{if(t===`delivering`||t===`settled`)throw new Error(`Queued source reply no longer owns recovery delivery`);if(t===`pending`)t=`settled`;const n=createChatSendLateFollowupDisposition({...e,retainSourceIdentity:false,onTerminalDrop:void 0});n.recordQueued();return n.deliver}})}}
//!src/gateway/server-methods/chat-send-turn-adoption.ts
function createChatSendTurnAdoptionLifecycle(e){let t=false;let n=false;const r=captureChatAbortRegistrationGuard([{runId:e.runId,entry:e.sourceRef}]);let i=false;let a;const recordQueuedTerminal=(n,i=false)=>{if(t||!r())return;const a=e.context.chatRunState.runs.get(e.runId);t=true;markChatAbortTerminalOutcome(e.sourceRef);const o=Date.now();const s=n.kind===`failed`;try{setGatewayDedupeEntry({dedupe:e.context.dedupe,key:`chat:${e.runId}`,session:captureAgentJobSession({...getRpcSourceIdentity(e.sourceRef),lifecycleGeneration:getRpcSourceLifecycleGeneration(e.sourceRef)}),entry:{ts:o,ok:!s,payload:n.kind===`aborted`?buildAbortedChatSendPayload({runId:e.runId,endedAt:o,stopReason:n.stopReason}):{runId:e.runId,status:s?n.errorKind??`error`:`completed`,endedAt:o,stopReason:n.stopReason,...s?{summary:n.error}:{}}}});if(i&&!e.suppressReplies)broadcastChatTerminal({terminalEntry:e.sourceRef,context:e.context,runId:e.runId,sessionKey:e.sessionKey,agentId:e.agentId,stopReason:n.stopReason,...s?{state:`error`,errorMessage:n.error,errorKind:n.errorKind}:{state:n.kind===`aborted`?`aborted`:`final`}})}finally{if(r()&&e.context.chatRunState.runs.get(e.runId)===a)e.context.chatRunState.clearRun(e.runId)}};const recordQueuedAbort=t=>recordQueuedTerminal({kind:`aborted`,stopReason:e.sourceRef.adapter.abortStopReason??resolveAgentRunAbortLifecycleFields(e.controller.signal).stopReason},t);const o=e.suppressReplies?void 0:createChatSendLateReplyFinalizer({terminalEntry:e.sourceRef,requesterContext:e.requesterContext,abortSignal:e.controller.signal,accountId:e.accountId,context:e.context,session:e.session});const s=createChatSendLateFollowupDisposition({runId:e.runId,originatingChannel:e.originatingChannel,logGateway:e.context.logGateway,onTerminalDrop:e=>recordQueuedTerminal(e,true),deliver:async n=>{if(n.clientRunId===e.runId&&n.completion.kind!==`progress`&&n.isCurrent()&&r())markChatAbortTerminalOutcome(e.sourceRef);try{const i=o?await o({...n,isCurrent:()=>n.isCurrent()&&r()&&(n.clientRunId!==e.runId||!t)}):{kind:`dropped`,reason:`no-visible-content`};if(n.clientRunId===e.runId&&n.completion.kind!==`progress`){if(n.completion.kind===`failed`&&n.completion.notice)await e.recordUnstartedFailure?.({error:n.completion.error,notice:n.completion.notice});recordQueuedTerminal(n.completion)}return i}catch(t){if(n.clientRunId===e.runId&&n.completion.kind!==`progress`)recordQueuedTerminal({kind:`failed`,error:String(t)});throw t}}});const c=e.sourceRef.adapter.cancel?.bind(e.sourceRef.adapter);e.sourceRef.adapter.cancel=t=>{c?.(t);if(e.sourceRef.input.custody.enqueued&&!e.sourceRef.input.custody.adopted)recordQueuedAbort(e.sourceRef.adapter.projectSessionTerminalPending!==true)};const l={admission:`cancel-only`,abortSignal:e.sourceRef.input.abortSignal,...e.originatingLeafEntryId!==void 0?{originatingLeafEntryId:e.originatingLeafEntryId}:{},ownerKey:e.ownerKey,onAdopted:()=>{e.sourceRef.input.abortSignal.throwIfAborted()},onDeferred:()=>{if(e.hasCronCreatorAuthority)l.cronCreatorAuthorityUnavailable=`queued-local-operator`;const t=e.sourceRef.input;if(!isRpcSourceRegistered(e.sourceRef)||t.abortSignal.aborted||t.phase===`consumed`)return false;a??=e.retainWorkAdmission();setGatewayDedupeEntry({dedupe:e.context.dedupe,key:`chat:${e.runId}`,session:captureAgentJobSession({...getRpcSourceIdentity(e.sourceRef),lifecycleGeneration:getRpcSourceLifecycleGeneration(e.sourceRef)}),entry:{ts:Date.now(),ok:true,payload:{runId:e.runId,status:`accepted`}}});s.recordQueued();e.armOperatorRunCancellation?.();return true},onCancellationRetired:()=>{retireSessionControllerSourceCancellation(e.sourceRef.input);e.retireOperatorRunCancellation?.()},onAbandoned:()=>{if(!e.sourceRef.input.custody.enqueued)return;recordQueuedTerminal({kind:`aborted`,stopReason:`aborted`},e.sourceRef.adapter.projectSessionTerminalPending!==true)},onSettled:()=>{if(i)return;i=true;try{if(!e.sourceRef.input.custody.enqueued||!r())return;e.retireOperatorRunCancellation?.();if(!t&&e.controller.signal.aborted)recordQueuedAbort(e.sourceRef.adapter.projectSessionTerminalPending!==true);if(!t)n=true}finally{a?.();a=void 0}}};bindReplySourceInput(l,e.sourceRef.input);const u=e.sourceRef.adapter.onSettled?.bind(e.sourceRef.adapter);e.sourceRef.adapter.onSettled=async()=>{try{await l.onSettled?.()}finally{await u?.()}};return{lifecycle:l,isEnqueued:()=>!n&&e.sourceRef.input.custody.enqueued===true,isTerminal:()=>t,isSteered:()=>n,onRunStarted:n=>{if(e.sourceRef.input.custody.enqueued&&!t&&r()&&s.deliver.ownsCompletion(e.originatingChannel))e.context.addChatRun(n,{sessionKey:e.sessionKey,agentId:e.agentId,clientRunId:e.runId})},onQueueDisposition:t=>{recordQueuedTerminal({kind:`failed`,error:t===`queue-cap-old`?`Your queued message was dropped because the session queue is full.`:`This message was not queued because the session queue is full.`},true);e.context.logGateway.info(`chat queue turn intentionally skipped`,{runId:e.runId,sessionKey:e.sessionKey,outcome:`skipped`,reason:t})},onQueuedFollowupReplyBatch:Object.assign(async e=>{if(!t&&r())await s.deliver(e)},s.deliver)}}
//!src/gateway/server-methods/chat-send-user-turn.ts
const audioPreflightLoader=createLazyImportLoader(()=>import(`./audio-preflight-DAptvm0f.mjs`));async function resolveChatUiTranscriptEcho(e){const t=e.cfg?.tools?.media?.audio;const n=isWebchatClient(e.clientInfo)||isOperatorUiClient(e.clientInfo)||e.clientInfo?.id===GATEWAY_CLIENT_IDS.MACOS_APP||e.clientInfo?.id===GATEWAY_CLIENT_IDS.IOS_APP||e.clientInfo?.id===GATEWAY_CLIENT_IDS.ANDROID_APP;const r=t?.echoFormat??`📝 "{transcript}"`;if(!n||!t?.echoTranscript||!r.includes(`{transcript}`)||!e.ctx.media?.length)return;e.assertCurrent();const i=await audioPreflightLoader.load().then(({transcribeAudioAttachments:n})=>n({ctx:e.ctx,...e.cfg?{agentDir:resolveAgentDir(e.cfg,e.agentId),workspaceDir:resolveAgentWorkspaceDir(e.cfg,e.agentId)}:{},cfg:{...e.cfg,tools:{...e.cfg?.tools,media:{...e.cfg?.tools?.media,audio:{...t,echoTranscript:false}}}},assertCurrent:e.assertCurrent})).catch(()=>void 0);e.assertCurrent();if(!i)return;e.ctx.Transcript=i;return r.replace(`{transcript}`,()=>i)}function applyChatSendManagedMedia(e,t,n=`replace-empty`){if(t.length===0)return;if(n===`replace-empty`){if(!e.media||e.media.length===0)e.media=t;return}const r=e.media??[];const i=new Set(r.flatMap(e=>e.path?[e.path]:[]));const a=t.filter(e=>!e.path||!i.has(e.path));if(a.length>0)e.media=[...r,...a]}function buildChatSendPromptMedia(e){if(!e.imageOrder.includes(`offloaded`))return;const t=e.offloadedRefs.filter(e=>e.mimeType.startsWith(`image/`)).map(e=>({path:e.path,url:e.mediaRef,contentType:e.mimeType}));return t.length>0?t:void 0}function prepareChatSendUserTurn(e){const{request:t,session:n,admission:r,attachments:i,client:a,logGateway:o,userTurn:s}=e;const c=(async()=>{if(i.parsedImages.length===0&&i.offloadedRefs.length===0)return{entries:[],omission:`none`};return await persistInboundImagesForTranscript({images:i.parsedImages,offloadedRefs:i.offloadedRefs,log:o,logContext:`chat.send`,assertCurrent:()=>{r.assertWorkAdmissionCurrent?.();r.assertClientUploadAllowed?.()}})})();const l=c.then(e=>{const t=e.entries.filter(e=>i.explicitOriginTargetsPlugin||e.imageKind===`inline`||e.imageKind===`offloaded`&&!i.mediaPathOffloads.some(e=>e.contentType?.startsWith(`image/`)));const n=!i.explicitOriginTargetsPlugin;return t.map(e=>Object.assign({path:e.path,contentType:e.fact.contentType??`application/octet-stream`},e.fact.fileName?{fileName:e.fact.fileName}:{},n&&(e.imageKind===`inline`||e.imageKind===`offloaded`)?{hydrationSuppressed:true}:{}))});l.catch(()=>void 0);const u=t.inboundMessage;const d=!t.suppressCommandInterpretation&&u.trim().startsWith(`/`)?`text`:void 0;const buildTextContext=e=>{const n=e===t.inboundMessage?i.parsedMessage:`${e}${i.parsedMessage.slice(t.inboundMessage.length)}`;const r=t.systemProvenanceReceipt?[t.systemProvenanceReceipt,n].filter(Boolean).join(`
`):n;return{Body:r,BodyForAgent:r,BodyForCommands:e,RawBody:n,CommandBody:e}};const f=normalizeOptionalString(a?.connect?.device?.id);const p=normalizeOptionalString(a?.connId);const m=captureGatewayUiCommandTarget(a);const h=f?`device:${f}`:p?`connection:${p}`:void 0;const{originatingChannel:g,originatingTo:_,accountId:v,messageThreadId:y,explicitDeliverRoute:b}=r.originatingRoute;const x=resolveOperatorSessionCreation(a);r.assertWorkAdmissionCurrent?.();const S=n.cfg?resolveCreatorSandbox(n.cfg,x):void 0;const C={...buildTextContext(u),InputProvenance:t.systemInputProvenance,...isProgressCardRefreshInputProvenance(t.systemInputProvenance)?{InternalTurnSource:`progress-card-refresh`}:{},SessionKey:n.sessionKey,AgentId:n.agentId,OriginatingTo:_,ExplicitDeliverRoute:b,AccountId:v,MessageThreadId:y,...d?{CommandSource:d}:{},CommandAuthorized:!t.suppressCommandInterpretation,CommandTurn:d?{kind:`text-slash`,source:d,authorized:true,body:u}:{kind:`normal`,source:`message`,authorized:false,body:u},...t.suppressCommandInterpretation?{CommandInterpretationSuppressed:true}:{},MessageSid:n.clientRunId,SessionCreation:{...x,...S?{sandbox:S}:{}},...resolveChatSendCallerContext(a,t.clientInfo,g),GatewayRunToolBindings:t.toolBindings,GatewayUiCommandTarget:m};const w=readQueuedChatInputAdmission(n.clientRunId)?.requesterProfile;const T=a?.authenticatedUserProfile;const E=!t.systemInputProvenance||t.systemInputProvenance.kind===`external_user`;if(w&&E)bindRequesterProfile(C,{...w,isCurrent:()=>{try{r.assertWorkAdmissionCurrent?.();return w.isCurrent()}catch{return false}}});else if(a&&T&&(a.authenticatedUserId||a.internal?.authenticatedOperator)&&(isBrowserOperatorUiClient(t.clientInfo)||isNativeAppUiClient(t.clientInfo))&&!isSyntheticGatewayCaller(a)&&E){const e=a.authenticatedUserId;const{profileId:t,displayName:n}=T;bindRequesterProfile(C,{id:t,displayName:n,isCurrent:()=>{try{r.assertWorkAdmissionCurrent?.()}catch{return false}return!a.invalidated&&!a.connectionSignal?.aborted&&!isSyntheticGatewayCaller(a)&&Boolean(a.authenticatedUserId||a.internal?.authenticatedOperator)&&a.authenticatedUserId===e&&a.authenticatedUserProfile?.profileId===t}})}if(a)transferGatewayLocalUserIngress(a,C);if(i.mediaPathOffloads.length>0)C.media=i.mediaPathOffloads;const D=i.mediaPathOffloads.some(e=>e.contentType?.startsWith(`image/`));let O;let k;let A=false;s.setInputPromise(c.then(async i=>{A=i.omission===`inline-image-save-failed`;const a=i.entries.map(e=>e.fact);const o=i.entries.flatMap((e,t)=>e.imageKind?[{kind:e.imageKind,factIndex:t}]:[]);const c=e.assertInputCurrent??(()=>{r.assertWorkAdmissionCurrent?.();r.assertClientUploadAllowed?.()});const l=await resolveChatUiTranscriptEcho({clientInfo:t.clientInfo,agentId:n.agentId,cfg:n.cfg,ctx:C,assertCurrent:c});if(l!==void 0&&C.Transcript){O=l;k=formatAudioTranscriptForAgent(C.Transcript)}return{...s.baseInput,...l?{text:[s.baseInput.text,l].filter(Boolean).join(`
`)}:{},...i.omission===`inline-image-save-failed`?{text:[s.baseInput.text,l,INLINE_IMAGE_DURABLE_OMISSION_MARKER].filter(Boolean).join(`
`)}:{},...a.length>0?{media:a}:{},...o.length>0?{mediaImageLayout:{slots:o}}:{}}}));const j=w&&E&&w.isCurrent()?{type:`profile`,id:w.id}:resolveGatewayInputParticipant(a,t.systemInputProvenance);if(j)prepareSessionParticipantInput(C,j,s.baseInput.timestamp);return{prepareSessionCreation:async i=>{if(!t.systemInputProvenance){const t=await prepareSkillLibrarySessionCreation(a,e.getConfig??n.cfg??{},x,i);r.assertWorkAdmissionCurrent?.();C.SessionCreation={...t,...S?{sandbox:S}:{}}}},applyApprovedText:e=>{if(e===t.inboundMessage.trim()&&!k)return;Object.assign(C,buildTextContext(e));let n=e;if(k){const t=A&&e.endsWith(`
`+`[image attachment omitted: durable managed media claim unavailable]`)?INLINE_IMAGE_DURABLE_OMISSION_MARKER:void 0;const r=t?e.slice(0,-(t.length+1)):e;const i=O!==void 0&&(r===O||r.endsWith(`
`+O));n=i&&O!==void 0?r===O?``:r.slice(0,-(O.length+1)):r;const a=buildTextContext(n);C.agentText=[a.BodyForAgent,i?k:void 0,t].filter(Boolean).join(`
`);C.BodyForAgent=C.agentText;if(!i)C.Transcript=void 0;C.BodyForCommands=a.BodyForCommands;C.CommandBody=a.CommandBody;C.RawBody=a.RawBody}if(C.CommandTurn)C.CommandTurn={...C.CommandTurn,body:n}},discardUnreferencedMedia:async e=>{if(!e)return;const t=new Set((readPersistedMediaFacts(e)??[]).flatMap(e=>[e.url,e.path]));const n=await c;await discardPreparedInboundMedia(n.entries.filter(e=>!t.has(e.fact.url)&&!t.has(e.path)),o)},accountId:v,ctx:C,isInternalTextSlashCommandTurn:d===`text`,queuedFollowupOwnerKey:h,pluginBoundMediaPromise:l,managedMediaApplyMode:i.explicitOriginTargetsPlugin?`replace-empty`:`append-missing`,replyOptionImages:D?void 0:i.parsedImages.length>0?i.parsedImages:void 0,replyOptionMedia:buildChatSendPromptMedia(i)}}
//!src/gateway/server-methods/chat-send-agent-dispatch.ts
function startChatDispatch(e){const{diagnostics:t,admissionStartedAt:n,admission:r,attachments:i,client:a,context:o,toolsAllow:s,deferWorkspaceBootstrap:c,skillLibrary:l,cronCreatorAuthority:u,assertDashboardReadCurrent:d,injection:f,request:p,session:m,turn:h,userTurn:g}=e;const{imageOrder:_}=i;const v=isProgressCardRefreshInputProvenance(p.systemInputProvenance);const{activeRunAbort:y,admittedSessionId:b,chatSendTraceAttributes:x,gatewayWorkAdmission:S,messageInjectionTarget:C,retainGatewayWorkAdmission:w}=r;const{agentId:T,cfg:E,clientRunId:D,expectedLeafEntryId:O,storePath:k,selectedAgent:A,sessionKey:j}=m;let{entry:M}=m;const{p:N,supportsTaskSuggestions:P}=p;const{accountId:F,ctx:I,isInternalTextSlashCommandTurn:L,managedMediaApplyMode:R,pluginBoundMediaPromise:z,queuedFollowupOwnerKey:ee,replyOptionImages:B,replyOptionMedia:V}=h;const{persist:te,persistBestEffort:ne,recorder:H}=g;const{beginCapturedMessageInjection:re,replyContextFieldsPromise:U}=f;let W;const ie=createDeferredCore();let G=false;let K;const isRunCurrent=()=>!y.controller.signal.aborted&&isRpcSourceRegistered(y.entry);const q=createChatSendReplyDispatch({getRuntimeConfig:o.getRuntimeConfig,assertWorkCurrent:r.assertWorkAdmissionCurrent,requesterContext:I,accountId:F,prepareAssistantTranscriptMessage:e.prepareAssistantTranscriptMessage,isAgentRunStarted:()=>G,isRunCurrent,abortSignal:y.controller.signal,onCommandBlock:L?e=>broadcastChatDelta({context:o,runId:D,sessionKey:j,agentId:T,text:e,isCurrent:isRunCurrent}):void 0,getReplyDispatchRun:()=>K,logGateway:o.logGateway,session:m,userTurnRecorder:H});const J=createChatSendTurnAdoptionLifecycle({requesterContext:I,accountId:F,sourceRef:r.sourceRef,context:o,runId:D,controller:y.controller,sessionKey:j,agentId:A.agentId,ownerKey:ee,...O!==void 0?{originatingLeafEntryId:O}:{},originatingChannel:r.originatingRoute.originatingChannel,session:m,hasCronCreatorAuthority:u!==void 0,suppressReplies:v,releaseSourceWorkAdmission:r.releaseSourceWorkAdmission,retainWorkAdmission:w,armOperatorRunCancellation:r.armOperatorRunCancellation,retireOperatorRunCancellation:r.retireOperatorRunCancellation,recordUnstartedFailure:e=>X.recordUnstartedFailure(e)});const ae=createChatSendInjectionDisposition({controllerInput:r.sourceRef.input,operatorAuthority:r.operatorAuthority,turnAdoptionLifecycle:J.lifecycle,userTurnTranscriptRecorder:H},E.messages?.queue);let Y=false;const oe={isSteered:()=>Y||J.isSteered(),isEnqueued:J.isEnqueued,isTerminal:J.isTerminal};const X=createChatSendDispatchErrorLifecycle({admission:r,hasObservedSideEffects:()=>Y||W!==void 0||q.deliveredReplies.length>0,injectionDisposition:ae,context:o,isAgentRunStarted:()=>G,isQueuedFollowupEnqueued:()=>J.isEnqueued()||J.isTerminal(),persistUserTurnTranscript:te,session:m,userTurnRecorder:H,isReplyDispatchRun:()=>K!==void 0});const Z=createAcceptedChatSendRetry({classify:X.classifyFailure,waitForRetry:e=>waitForAcceptedChatSendRetry({agentId:T,sessionKey:j,storePath:k},e,y.controller.signal)});bindReplySourcePreparationRetry(r.sourceRef.input,Z);const{emit:se,emitFirstAssistant:ce,dispatchStartedAtMs:le}=createOperatorChatSendServerTiming(e);se(`dispatch-started`);const ue={run:async e=>{try{var n=_usingCtx();const r=n.u(t.scope(`detail.dispatch.admission_wait`));return await S.run(async()=>{try{var n=_usingCtx();r?.finish();Q?.mark(`replyContext`);if(U)applyChatSendReplyContextFields(I,await U);Q?.mark(`runAdmission`);const i=n.u(t.scope(`detail.run_admission.steer_prepare`));W=await withCurrentUserTurnInput(H,re);W?.acceptance.then(e=>{if(e)emitSessionsChanged(o,{sessionKey:j,agentId:T,reason:`agent.input.steering`},{accessChanged:false})},()=>void 0);i?.mark(`detail.run_admission.steer_settlement`);Y=await settleChatSendMessageInjection(W);W=await ae.observe(W);i?.finish();return await(Y?e():withCurrentUserTurnInput(H,e))}catch(e){n.e=e}finally{n.d()}})}catch(e){n.e=e}finally{n.d()}}};const de=createChatSendDashboardReadAdmission({admission:r,session:m,assertDashboardReadCurrent:d});const Q=t.scope(`dispatch`);scheduleChatDashboardSessionTitle({admittedSessionId:b,agentId:T,cfg:E,context:o,request:p,sessionKey:j,storePath:k},ie.promise);const fe=q.runAgentMediaTranscript(ue,()=>measureDiagnosticsTimelineSpan(`gateway.chat_send.dispatch_inbound`,async()=>{if(!Y)r.assertWorkAdmissionCurrent();if(p.humanAddressed)return{queuedFinal:false,counts:{tool:0,block:0,final:0}};let i;if(!Y&&M&&(Object.hasOwn(M,`pendingProjectGitUrl`)||M.pendingWorktree))try{var d=_usingCtx();Q?.mark(`worktree`);m.entry=M={...M};i=prepareSessionWorkspace({admission:r,client:a,context:o,session:m});const e=d.u(t.scope(`detail.dispatch.workspace_prompt_ready`));await i.promptReady;e?.finish();i.assertCurrent()}catch(e){d.e=e}finally{d.d()}const f=i?.assertCurrent;if(W)try{var g=_usingCtx();g.u(t.scope(`detail.run_admission.steer_finalize`));const e=await finalizeAcceptedChatSendMessageInjection({attempt:W,sourceRef:r.sourceRef,context:o,ctx:I,persistUserTurnTranscriptBestEffort:ne,session:m,startedAt:n,target:C});f?.();if(e){Y=true;return{queuedFinal:false,counts:{tool:0,block:0,final:0}}}}catch(e){g.e=e}finally{g.d()}Q?.mark(`preparation`);const v=await prepareGatewaySkillLibraryTurn(l,h.prepareSessionCreation,()=>Q?.mark(`authoring`));r.assertWorkAdmissionCurrent();Q?.mark(`preparation`);const b=await z;f?.();applyChatSendManagedMedia(I,b,R);Q?.mark(`replyInitialization`);const onAgentRunStart=(e,n,i,s)=>{J.onRunStarted(e);t.finish();K=i;if(y.markExecutionStarted())r.armOperatorRunCancellation();G=true;q.captureAgentTranscriptStart(e,s);se(`agent-run-started`,e!==D?{agentRunId:e}:void 0,le);registerChatSendToolEventRecipients({client:a,context:o,cfg:E,sessionKey:j,selectedAgent:A,storePath:k},e);return i?.completionSource};const dispatchInbound=()=>{f?.();return dispatchInboundMessageWithProjectedDispatcher({ctx:I,cfg:E,toolsAllow:s,dispatcherOptions:q.dispatcherOptions,onSessionMetadataChanges:e=>e.forEach(e=>emitSessionsChanged(o,e)),replyOptions:bindReplySourceInput({[REPLY_OPERATION_RUN_STATE]:ae.runState,prepareAssistantTranscriptMessage:q.prepareAssistantTranscriptMessage,...isInternalSourceReplyChannel(I)?{resolveReplyDelivery:q.resolveReplyDelivery,resolveReplyDeliveryFacts:q.resolveReplyDeliveryFacts}:{},...r.admittedSessionSettings?{admittedSessionSettings:r.admittedSessionSettings}:{},runId:D,operatorAuthority:r.operatorAuthority,deferWorkspaceBootstrap:c,providerReviewAcknowledgment:p.providerReviewAcknowledgment,dashboardReadAdmission:de,skillLibraryAuthoring:v,...u?{cronCreatorAuthorityCapability:u}:{},...P?{taskSuggestionDeliveryMode:`gateway`}:{},expectedActiveReplyOperation:r.expectedActiveReplyOperation,...e.getSessionInitializationOptions(),onSessionPrepared:e=>{Q?.mark(`preparation`);r.onSessionPrepared(e);q.notePreparedSession(e);recordSessionOperatorSource({agentId:T,sessionKey:j,storePath:e.storePath??k,authority:r.operatorAuthority,log:o.logGateway})},onTranscriptStartPreparation:()=>t.scope(`snapshot`)?.finish,abortSignal:y.controller.signal,getProviderLoginConfig:o.getRuntimeConfig,assertProviderLoginAuthority:()=>{a?.connectionSignal?.throwIfAborted();if(a?.invalidated||!a?.connect.scopes?.includes(`operator.admin`))throw new Error(`Provider login authority is no longer active.`)},onFollowupQueueDisposition:J.onQueueDisposition,onQueuedFollowupReplyBatch:J.onQueuedFollowupReplyBatch,turnAdoptionLifecycle:J.lifecycle,images:B,imageOrder:_.length>0?_:void 0,media:V,...N.timeoutMs!==void 0?{timeoutOverrideMs:N.timeoutMs}:{},thinkingLevelOverride:N.thinking,normalizeThinkingLevelOverride:p.normalizeThinkingLevelOverride,fastModeOverride:N.fastMode,queueModeOverride:N.queueMode,userTurnTranscriptRecorder:H,...ae.replyOptions(N.queueMode===`steer`&&Boolean(C)),fastModeAutoOnSecondsOverride:N.fastAutoOnSeconds,onAgentRunStart,onPreparedAgentRunStart:({runId:e,executionIdentityToken:t,options:n,transcriptStart:r})=>onAgentRunStart(e,t,n,r),onModelSelected:e=>{updateChatRunProvider({runId:D,resolveGatewayContext:o.resolveGatewayContext,providerId:e.provider,authProviderId:resolveProviderIdForAuth(e.provider,{config:E})});q.onModelSelected(e);se(`model-selected`,{provider:e.provider,model:e.model},le)}},r.sourceRef.input)})};const dispatchWithRetry=()=>withExecRequestTurn({identity:{runId:D,...getRpcSourceIdentity(r.sourceRef),ownerConnId:r.sourceRef.adapter.requester?.connectionId,ownerDeviceId:r.sourceRef.adapter.requester?.deviceId,initiatingPersonalOperator:r.sourceRef.adapter.initiatingPersonalOperator,controlUiVisible:r.sourceRef.adapter.controlUiVisible,turnKind:r.sourceRef.adapter.turnKind},abortSignal:y.controller.signal},()=>Z(()=>withDiagnosticsTimelineObserver(t.observeSpan,()=>withCurrentUserTurnInput(H,dispatchInbound))));const runDispatch=async()=>{try{var n=_usingCtx();const r=n.u(t.scope(`detail.dispatch.external_handoff`));return await runChatSendExternalDispatch(e,()=>{r?.finish();return dispatchWithRetry()})}catch(e){n.e=e}finally{n.d()}};const x=await runWithAgentWorkspaceReadiness(i,async()=>{try{return await runDispatch()}finally{if(i)try{var e=_usingCtx();const n=e.u(t.scope(`detail.dispatch.workspace_readiness`));await i.waitUntilReady();n?.finish()}catch(t){e.e=t}finally{e.d()}}});if(x.beforeAgentRunBlocked===true)H.markBlocked();return x},{phase:`agent-turn`,config:E,attributes:x}).catch(X.captureUnstartedFailure)).then(async e=>{t.finish(oe);if(e.deferredToActiveRun===`followup`&&J.isEnqueued()){const e=q.deliveredReplies.map(({input:e})=>readChatSendReplyPayload(e)).filter(isReplyPayloadStatusNotice);if(e.length>0)await J.onQueuedFollowupReplyBatch({kind:`queued-followup`,runId:D,originatingChannel:r.originatingRoute.originatingChannel,payloads:e,completion:{kind:`progress`}})}if(Y||J.isEnqueued()||J.isTerminal())return;se(`dispatch-completed`,void 0,le);const n=performance.now();await measureDiagnosticsTimelineSpan(`gateway.chat_send.post_dispatch`,async()=>{const t=K?.getResult();const n=t?.terminalOutcome;const{runtimeClassification:i,runtimeCancelled:a,runtimeFailed:s,returnedAgentErrorPayloads:c,hasOnlyFinalWarnings:l,hasReturnedAgentError:u,returnedAgentErrorMessage:d}=resolveChatSendReturnedOutcome({dispatchResult:e,runtimeOutcome:n,deliveredReplies:q.deliveredReplies,agentRunStarted:G,isInternalTextSlashCommandTurn:L,collaborativeSteeringRefused:e.collaborativeSteeringRefused});if(!H.hasPersisted()&&!H.isBlocked()&&(u||G&&c.length===0&&H.hasRuntimePersistencePending()))await ne();const f={terminalEntry:r.sourceRef,requesterContext:I,abortSignal:y.controller.signal,accountId:F,context:o,deliveredReplies:q.deliveredReplies,emitFirstAssistantServerTiming:ce,session:m};let p=false;if(!v&&(!G||K||l)&&!u&&!o.chatRunState.hasAbortMarker(D))await finalizeChatSendDispatchedReplies({...f,foldCommandBlocks:L||K!==void 0,persistUserTurnTranscript:ne,suppressReplies:!K&&q.hasAppendedWebchatAgentMedia(),runtimeOwnsTranscript:t?.assistantTranscript?.agentId===T&&t.assistantTranscript.sessionKey===j&&t.assistantTranscript.sessionId===getRpcSourceIdentity(y.entry).sessionId,state:a?`aborted`:`final`,stopReason:n?.stopReason});else if(!v&&!o.chatRunState.hasAbortMarker(D))p=await finalizeChatSendSourceReplies({...f,hasReturnedAgentErrorPayloads:u,suppressFinal:s});const h=e.collaborativeSteeringRefused||u&&(s||!p);await X.settleTerminalPersistence();if(!o.chatRunState.hasAbortMarker(D)){if(h&&!e.collaborativeSteeringRefused){await X.recordUnstartedFailure({error:d??`agent returned an error payload`,notice:d});X.broadcastError({errorMessage:d,errorKind:i===`timeout`?`timeout`:void 0,stopReason:n?.stopReason})}const s=h?errorShape(ErrorCodes.UNAVAILABLE,d??`agent returned an error payload`):void 0;setGatewayDedupeEntry({dedupe:o.dedupe,key:`chat:${D}`,session:captureAgentJobSession({...getRpcSourceIdentity(r.sourceRef),lifecycleGeneration:r.lifecycleGeneration}),entry:{ts:Date.now(),ok:!h,payload:h?{runId:D,status:i===`timeout`?`timeout`:`error`,summary:d??`agent returned an error payload`,...n?{endedAt:n.endedAt}:{},...n?.stopReason?{stopReason:n.stopReason}:{}}:a?buildAbortedChatSendPayload({runId:D,endedAt:n?.endedAt??Date.now(),stopReason:n?.stopReason}):{runId:D,status:v&&!J.isSteered()?`completed`:`ok`,...t?.terminalOutcome?.stopReason?{stopReason:t.terminalOutcome.stopReason}:{}},...s?{error:s}:{}}})}},{phase:`agent-turn`,config:E,attributes:x});se(`post-dispatch-completed`,{postDispatchMs:roundedChatSendTimingMs(performance.now()-n)},le)}).catch(e=>{t.finish(oe);return X.handleError(e)});trackSessionControllerSourceWork(r.sourceRef.input,fe);const pe=(async()=>{try{await fe}finally{ie.resolve();await X.finalize();emitSessionsChanged(o,{sessionKey:j,agentId:T,reason:`agent.input.settled`},{accessChanged:false,rowScope:`runtime`});if(H.isBlocked()&&i.offloadedRefs.length>0)discardPreparedInboundMedia(i.offloadedRefs)}})();pe.catch(e=>{o.logGateway.warn(`webchat dispatch settlement failed: ${formatForLog(e)}`)});return pe}
//!src/gateway/server-methods/chat-send-attachments.ts
async function prepareChatSendAttachments(e){const{request:t,session:n,admission:r,respond:i,context:a}=e;const{inboundMessage:o,normalizedAttachments:s,explicitOrigin:c}=t;const{cfg:l,agentId:u,resolvedSessionModel:d,clientRunId:f}=n;const{activeRunAbort:p,chatSendTraceAttributes:m,cleanupAdmittedRun:h,finishAbortedChatSend:g,lifecycleGeneration:_}=r;const assertInputCurrent=()=>{p.controller.signal.throwIfAborted();r.assertWorkAdmissionCurrent();r.assertClientUploadAllowed?.()};let v=o;let y=[];let b=[];let x=[];let S=[];let C=false;let w;try{const e=await resolveExplicitOriginBindingTargets(c);assertInputCurrent();C=e.plugin;const t=readQueuedChatInputAdmission(f);if(t)S=readPersistedMediaFacts(t.target.message)??[];if(s.length>0){if((r.initialSessionEntry??r.admittedSessionEntry??n.entry)?.deviceFolder)throw new Error(DEVICE_FOLDER_ATTACHMENTS_UNSUPPORTED);const t=performance.now();await measureDiagnosticsTimelineSpan(`gateway.chat_send.prepare_attachments`,async()=>{const t={value:e.acp||C?true:void 0};const resolveSupportsImages=async()=>{t.value??=await resolveGatewayModelSupportsImages({loadGatewayModelCatalog:a.loadGatewayModelCatalog,loadGatewayModelCatalogSnapshot:a.loadGatewayModelCatalogSnapshot,agentId:u,provider:d.provider,model:d.model});return t.value};const n=await parseMessageWithAttachments(o,s,{maxBytes:resolveChatAttachmentMaxBytes(l),log:a.logGateway,supportsImages:t.value??resolveSupportsImages,acceptNonImage:true,signal:p.controller.signal,assertCurrent:assertInputCurrent});const r=t.value!==false;v=r?n.message:stripImageMediaMarkers(n.message,n.offloadedRefs);y=n.images;b=n.imageOrder;x=n.offloadedRefs;S=x.filter(e=>!r||!e.mimeType.startsWith(`image/`)).map(e=>({path:e.path,url:e.mediaRef,contentType:e.mimeType,fileName:e.label}))},{phase:`agent-turn`,config:l,attributes:{...m,attachmentCount:s.length}});assertInputCurrent();p.controller.signal.throwIfAborted();w=roundedChatSendTimingMs(performance.now()-t)}}catch(e){const t=p.controller.signal.aborted&&(a.chatRunState.hasAbortMarker(f)||Object.is(e,p.controller.signal.reason));if(!t)p.cleanup();await discardPreparedInboundMedia(x);if(t){g();return{ok:false}}h();clearAgentRunContext(f,_);logAttachmentFailure(a.logGateway,`chat.send attachment offload failed`,e);i(false,void 0,e instanceof SessionMutationAuthorizationChangedError?e.error:errorShape(e instanceof MediaOffloadError?ErrorCodes.UNAVAILABLE:ErrorCodes.INVALID_REQUEST,String(e)));return{ok:false}}return{ok:true,value:{explicitOriginTargetsPlugin:C,imageOrder:b,mediaPathOffloads:S,offloadedRefs:x,parsedImages:y,parsedMessage:v,prepareAttachmentsMs:w}}}function bindChatSendPreparedMediaCustody(e){let t;e.admission.setDiscardAbandonedPreparedMedia(()=>{if(!t||!retainsUserTurnTranscriptMedia(t))discardPreparedInboundMedia(e.attachments.offloadedRefs)});return e=>{t=e}}
//!src/gateway/server-methods/chat-send-goal-ack.ts
async function acknowledgeCodexGoal(e){const{context:t,session:n,request:r,client:i,userTurn:a}=e.dispatch;try{await Promise.race([e.committed,e.dispatched]);const o=a.recorder.hasPersisted()?await a.persist():void 0;const s=o?.sessionTurnMutationResult?.result;if(!s||!o?.sessionEntry||!r.goalOperation)throw new Error(`Codex Goal input was not committed; inspect the run before retrying.`);await publishCommittedSessionGoalChange(t,{sessionKey:n.sessionKey,agentId:n.agentId,entry:o.sessionEntry,actor:gatewayClientSessionCreator(i),summary:`goal ${r.goalOperation.action}`});e.respond(true,{...e.ackPayload,...s},void 0,{runId:n.clientRunId})}catch(i){if(!a.recorder.hasPersisted()&&r.goalOperation)t.dedupe.set(`chat:${n.clientRunId}`,{ts:Date.now(),ok:true,requestIdentity:r.goalOperation.requestFingerprint});e.respond(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,String(i),{retryable:true}))}}
//!src/gateway/server-methods/chat-send-goal-admission.ts
function requiresRuntimeApprovedChatInput(e){return hasGlobalHooks(`before_agent_run`)||isAcpBridgeClient(e)}function resolveCodexGoalAdmission(e,t,n,r){const{session:i,request:a,context:o,client:s}=e;const c=o.getRuntimeConfig();const l=getRegisteredAgentHarness(`codex`)?.harness;const u=!n||n.state===`local`;return Boolean(a.goalOperation&&t.entry&&isDirectGatewayUserClient(s)&&l&&(u?!c.cloudWorkers?.requiredProfile:n.executionMode===`remote-exec`&&l.cloudPlacement?.mode===`remote-exec`)&&isDirectChatGoalSession({entry:t.entry,allowAborted:a.goalOperation.action===`resume`,allowVisibleSpawn:true,acpMeta:r,requestedSessionId:i.requestedSessionId,sessionKey:t.canonicalKey})&&resolveEffectiveAgentRuntime({cfg:c,agentId:i.agentId,sessionKey:t.canonicalKey,sessionEntry:t.entry,provider:i.resolvedSessionModel.provider,modelId:i.resolvedSessionModel.model})===`codex`)?u?`local`:`worker`:void 0}function isDirectChatGoalSession(e){const t=e.entry;return Boolean(t?.sessionId&&e.sessionKey!==`global`&&(t.abortedLastRun!==true||e.allowAborted===true)&&t.archivedAt===void 0&&t.initializationPending!==true&&t.pendingFinalDelivery===void 0&&t.pluginOwnerId===void 0&&(t.spawnedBy===void 0&&(t.spawnDepth??0)===0||e.allowVisibleSpawn===true&&isVisibleSpawnedSession(e.sessionKey,{entry:t}))&&t.subagentRole===void 0&&e.acpMeta==null&&t.cronRunContinuation===void 0&&!isSubagentSessionKey(e.sessionKey)&&!isCronSessionKey(e.sessionKey)&&!isAcpSessionKey(e.sessionKey)&&!isAgentHarnessSessionKey(e.sessionKey)&&(e.requestedSessionId===void 0||e.requestedSessionId===t.sessionId))}function isLocalChatInputAdmission(e,t,n,r,i){const{session:a,request:o,context:s}=e;const c=s.getRuntimeConfig();const l=t.entry??n;if(c.cloudWorkers?.requiredProfile||requiresRuntimeApprovedChatInput(e.client)||o.goalOperation&&hasGlobalHooks(`reply_dispatch`,{dispatchKind:`agent`})||r&&r.state!==`local`||!l||!isDirectChatGoalSession({entry:l,acpMeta:i,sessionKey:t.canonicalKey,requestedSessionId:a.requestedSessionId,allowAborted:o.goalOperation?.action===`resume`,allowVisibleSpawn:Boolean(o.goalOperation)})||l.agentHarnessId!==void 0&&l.agentHarnessId!==`openclaw`)return false;if(n)return true;const u={agentId:a.agentId,now:Date.now(),resetOverride:resolveChannelResetConfig({sessionCfg:c.session,channel:sessionDeliveryChannel(t.entry)}),resetType:resolveSessionResetType({sessionKey:t.canonicalKey}),sessionCfg:c.session,sessionKey:t.canonicalKey,storePath:t.storePath};if(isIncognitoSessionKey(t.canonicalKey))return resolveSessionEntryResetFreshness(u).state===`fresh`;if(!t.lifecycleTimestamps)throw new Error(`Chat session freshness was not prepared; retry.`);return resolvePreparedSessionEntryResetFreshness(u,l,t.lifecycleTimestamps).state===`fresh`}async function withGoalChatPlacement(e,t,n){if(!e.prepareSessionPlacement)throw new Error(`Worker placement admission reader is unavailable; retry.`);const r=await e.prepareSessionPlacement(t);try{await n({sessionId:t,facts:r})}finally{r.release()}}function createChatSendGoalCommitGuard(e){const{admission:t,session:n,client:r,context:i,sessionMutationAuthorization:a,sessionMutationCommitGuard:o}=e;const s=t.initialSessionEntry?{config:structuredClone(i.getRuntimeConfig()),key:n.sessionLoadKey,agentId:n.sessionLoadOptions.agentId,storePath:n.storePath,canonicalKey:n.sessionKey}:void 0;const check=e=>{e();const a=i.getRuntimeConfig();const o=t.initialSessionEntry;if(o){t.assertInitialSkillSelection?.();if(!isDeepStrictEqual(a,s?.config))throw new Error(`Session routing changed before Goal admission; refresh and retry.`);const e=authorizeGatewaySessionCreation({cfg:a,client:r,agentId:n.agentId});if(e)throw new SessionMutationAuthorizationChangedError(e);const i=resolveOperatorSessionCreation(r);if(i.actor?.id!==o.createdActor?.id||resolveCreatorSandbox(a,i)!==o.sandbox)throw new Error(`Session creation policy changed before Goal admission; retry.`)}if(t.activeRunAbort.controller.signal.aborted||t.lifecycleGeneration!==getAgentEventLifecycleGeneration()||n.sessionRoutingChanged(a))throw new Error(`Goal admission changed before commit; refresh and retry.`)};const c=[o,a?.assertCurrent];return{assertCurrent:t.codexGoalAdmission?composeSessionSourceAssertion(c,check):()=>check(()=>c.forEach(e=>e?.())),routingPredicate:s}}
//!src/gateway/server-methods/chat-send-retry-comparison.ts
function chatSendRequestConflictError(e=false){return errorShape(ErrorCodes.INVALID_REQUEST,e?`The previous mention selections cannot be verified. Check the conversation history and use a new message ID to send again.`:`This message ID was already used for different input. Check the conversation history and use a new message ID to send again.`,{details:{reason:`chat-request-conflict`}})}function readChatSendRetryComparison(e){if(!e.entry?.sessionId)return;const{agentId:t,storePath:n,sessionKey:r,clientRunId:i}=e;const{sessionId:a,lifecycleRevision:o}=e.entry;return readSessionSubmittedInput({agentId:t,storePath:n,sessionKey:r,sessionId:a},`${i}:user`,{includeSource:true,strictRetryComparison:true}).then(e=>({agentId:t,storePath:n,sessionKey:r,sessionId:a,lifecycleRevision:o,clientRunId:i,submitted:e?.message,source:e?.source,messageSeq:e?.messageSeq,disposition:e?.disposition}),e=>{if(e instanceof SessionTranscriptProjectionUnavailableError)throw e;throw new SessionTranscriptProjectionUnavailableError(a,`rebuilding`,{cause:e})})}function compareChatSendSubmittedInput(e,t,n){if(!n&&t.entry?.sessionId||n&&(n.agentId!==t.agentId||n.storePath!==t.storePath||n.sessionKey!==t.sessionKey||n.sessionId!==t.entry?.sessionId||n.lifecycleRevision!==t.entry?.lifecycleRevision||n.clientRunId!==t.clientRunId))throw new SessionTranscriptProjectionUnavailableError(t.entry?.sessionId??n?.sessionId??t.clientRunId,`window-changed`);const r=n?.submitted;if(!r)return e.mentions?.length||e.workContext||e.appContext?`unverifiable`:false;const i=r[`__openclaw`]?.chatRequestIdentity;if(typeof i===`string`)return i!==e.requestIdentity;const a=r[`__openclaw`]?.humanMentions;const o=r[`__openclaw`]?.workContext;const s=extractTextFromChatContent(r.content,{joinWith:`
`,normalizeText:e=>e})??``;if(n?.source===`pending`&&s!==e.rawMessage)return`unverifiable`;if(!e.mentions?.length&&!a?.length&&!e.workContext&&!o&&!e.appContext&&!r[`__openclaw`]?.appContext)return false;return s!==e.rawMessage||!isDeepStrictEqual(a??[],e.mentions??[])||!isDeepStrictEqual(o,e.workContext)||!isDeepStrictEqual(r[`__openclaw`]?.appContext,e.appContext)}
//!src/gateway/server-methods/chat-send-session-binding.ts
function bindChatSendPreparedSession(e){const{sourceRef:t}=e;let n=getRpcSourceIdentity(t).sessionId;return r=>{const i=t.input;const a=i.claim?.operation;if(r.sessionKey!==e.sessionKey)return;if(!isRpcSourceRegistered(t)||e.lifecycleGeneration!==getAgentEventLifecycleGeneration()||!e.admission.isActive()||i.abortSignal.aborted||i.phase===`consumed`||i.retirementRequested||i.custody.cancellationRetired||i.withdrawalHolds>0||a?.abortFrozen||a?.result||t.adapter.projectSessionTerminalPending||t.adapter.projectSessionTerminalPersisted)throw createAbortError(`chat session preparation no longer owns its admission`);adoptExecRequestSession({runId:e.runId,previousSessionId:n,sessionId:r.sessionId});const o=i.mailbox.owner;const s=o.target;if(!s)throw new Error(`Prepared RPC source lost its physical target`);bindSessionControllerEntryTarget(o,captureSessionTarget({storeScope:s.storeScope,sessionKey:s.sessionKey,aliases:s.aliases,agentId:s.agentId,incarnation:r.sessionId}));updateRpcSourceSessionId(t,r.sessionId);n=r.sessionId}}function createChatSendSessionInitialization(e){const{authorization:t}=e;const n={sessionKey:e.sessionKey,agentId:e.agentId};return()=>({...e.getSessionInitializationOptions(),onDatabaseRegistration:t?.followRegistration?e=>t.followRegistration?.(n,e):void 0,...e.needsCreationBinding&&t?.bindCreation?{bindSessionCreation:e=>{t.bindCreation?.(n,e);return t.assertCurrent},onSessionCreated:t.recordCreatedSession}:{}})}
//!src/gateway/server-methods/chat-send-admission-context.ts
function prepareChatSendAdmissionContext(e){const{request:t,session:n,client:r}=e;const{p:i,explicitOrigin:a,normalizedAttachments:o}=t;const{cfg:s,entry:c,sessionKey:l,selectedAgent:u,agentId:d,clientRunId:f,resolvedSessionModel:p}=n;return{chatSendTraceAttributes:{runId:f,sessionKey:l,agentId:u.agentId??d,provider:p.provider,model:p.model,hasAttachments:o.length>0,hasExplicitOrigin:a!==void 0,hasConnectedClient:r?.connect!==void 0},originatingRoute:resolveChatSendOriginatingRoute({client:t.clientInfo,deliver:i.deliver,entry:c,explicitOrigin:a,hasConnectedClient:r?.connect!==void 0,mainKey:s.session?.mainKey,sessionKey:l})}}async function prepareChatSendAcpMetadata({session:e,diagnostics:t},n){try{var r=_usingCtx();const i=n??{canonicalKey:e.sessionTarget.canonicalKey,binding:e.entry?captureAcpSessionEntryBinding(e.entry):null};r.u(t?.scope(`detail.admission.acp_metadata`));const[a]=await readAcpSessionMetaForEntries({cfg:e.cfg,entries:[{agentId:e.agentId,sessionKey:i.canonicalKey,entry:i.binding??void 0}]});return{binding:i.binding,meta:a??null}}catch(e){r.e=e}finally{r.d()}}function prepareChatSendAcpRefresh(e,t,n){if(!t)return;const r=n.entry?captureAcpSessionEntryBinding(n.entry):null;return isDeepStrictEqual(t.binding,r)?void 0:()=>prepareChatSendAcpMetadata(e,{binding:r,canonicalKey:n.canonicalKey})}function assertChatSendSessionTargetOrRespond(e){try{e.assertSessionTargetCurrent();return true}catch(t){e.cleanup();respondChatSendAdmissionError(t,e.respond);return false}}
//!src/gateway/server-methods/chat-send-goal-retry.ts
async function prepareGoalChatSendRetry({request:e,session:t,context:n}){if(!e.goalOperation)return;const r=n.dedupe.get(`chat:${t.clientRunId}`);try{const n={sessionKey:t.sessionKey,storePath:t.storePath,agentId:t.agentId,expectedSessionId:t.entry?.sessionId??t.backingSessionId??t.clientRunId,operation:e.goalOperation};let i=await lookupSessionGoalOperation(n);const a=i?void 0:await readChatSendRetryComparison(t);if(a?.submitted)i=await lookupSessionGoalOperation(n);return{receipt:i,dedupe:r,comparison:a}}catch(e){if(!(e instanceof SessionGoalOperationError))throw e;return{receipt:e,dedupe:r}}}
//!src/gateway/server-methods/chat-send-reservation.ts
function createPendingChatSendReservationAccess(e){const{pendingChatSendKey:t,clientRunId:n}=e.session;const{now:r,sessionKey:i,backingSessionId:a,rawSessionKey:o,selectedAgent:s,timeoutMs:c}=e.session;const{turnKind:l}=e.request;const read=()=>readPreRegisteredRun({key:t,entry:e.context.dedupe.get(t)});return{read,abort:t=>writePreRegisteredChatAbort({context:e.context,runId:n,stopReason:t,attemptId:e.attemptId,requestIdentity:e.requestIdentity}),reserve:()=>{const{context:u,request:d,attemptId:f}=e;u.dedupe.set(t,{ts:r,ok:true,requestIdentity:e.requestIdentity,payload:{runId:n,attemptId:f,status:`accepted`,sessionKey:i,...a?{sessionId:a}:{},...o===i?{}:{sessionKeyAliases:[o]},...s.agentId?{agentId:s.agentId}:{},ownerConnId:normalizeOptionalString(e.client?.connId),ownerDeviceId:normalizeOptionalString(e.client?.connect?.device?.id),expiresAtMs:resolveChatRunExpiresAtMs({now:r,timeoutMs:c}),turnKind:l,...d.goalOperation?{goalFingerprint:d.goalOperation.requestFingerprint}:{}}})},clear:()=>{const r=read();if(r?.runId===n&&normalizeOptionalString(r.payload.attemptId)===e.attemptId)e.context.dedupe.delete(t)},markInputAccepted:()=>{const t=e.context.dedupe.get(`chat:`+n);if(t?.ok!==true||t.requestIdentity!==e.requestIdentity||t.payload!==void 0||t.error!==void 0)throw new Error(`Chat input acceptance marker changed before acknowledgment`);t.effectAccepted=true}}}function readChatSendDedupeResponse(e,t){const n=e.get(`chat:${t}`);return n?.ok&&n.payload===void 0&&n.error===void 0?void 0:n}function inspectGoalChatSendRetry({request:e,session:t,respond:n,context:r,assertCurrent:i,prepared:a}){i?.();const{clientRunId:o,pendingChatSendKey:s}=t;if(!e.goalOperation)return{kind:`new`};try{const t=a?.receipt;if(t instanceof SessionGoalOperationError)throw t;if(t)return{kind:`replay`,receipt:t};const i=readPreRegisteredRun({key:s,entry:r.dedupe.get(s)});const c=r.dedupe.get(`chat:${o}`)?.requestIdentity;const l=a?.comparison?.submitted;const u=l?.[`__openclaw`]?.chatRequestIdentity;const d=c!==void 0&&typeof u===`string`&&c!==u;if(l&&!i?.payload.goalFingerprint&&!d){n(false,void 0,chatSendRequestConflictError());return{kind:`settled`}}const f=c!==void 0&&c!==e.goalOperation.requestFingerprint;const p=readChatSendDedupeResponse(r.dedupe,o);const m=c===e.goalOperation.requestFingerprint&&p!==void 0&&p!==a?.dedupe;if(!f&&(i?.payload.goalFingerprint===e.goalOperation.requestFingerprint||m||!i&&getRpcSourceForGateway(o,r.resolveGatewayContext))){n(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`Goal is being admitted; retry the same request.`,{retryable:true}));return{kind:`settled`}}if(f||i||p||r.chatRunState.hasAbortMarker(o)||getRpcSourceForGateway(o,r.resolveGatewayContext))throw new SessionGoalOperationError(`operation-conflict`,`Goal operation ID is already used by another request.`);return{kind:`new`}}catch(e){if(!(e instanceof SessionGoalOperationError))throw e;n(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,e.message,{details:{reason:`goal-${e.code}`}}));return{kind:`settled`}}}
//!src/gateway/server-methods/chat-send-pre-admission.ts
function resolveChatSendRequestConflict({request:e,session:t,context:n},r,i){if(e.goalOperation)return;const a=[n.dedupe.get(`chat:${t.clientRunId}`),n.dedupe.get(t.pendingChatSendKey)];if(a.some(t=>t?.requestIdentity!==void 0&&t.requestIdentity!==e.requestIdentity))return chatSendRequestConflictError();const o=i!==void 0&&readPreRegisteredRun({key:t.pendingChatSendKey,entry:a[1]})?.payload.attemptId===i;const s=o?a.slice(0,1):a;if(!(r?.submitted!==void 0||s.some(Boolean)||n.chatRunState.hasAbortMarker(t.clientRunId)||!o&&getRpcSourceForGateway(t.clientRunId,n.resolveGatewayContext)))return;const c=compareChatSendSubmittedInput(e,t,r);if(!r?.submitted&&e.requestIdentity!==void 0&&s.some(t=>t?.requestIdentity===e.requestIdentity))return;return c?chatSendRequestConflictError(c===`unverifiable`):void 0}function prepareChatSendRetryComparison(e,t){try{resolveChatSendRequestConflict(e,void 0,t);return}catch(t){if(!isSessionTranscriptProjectionUnavailableError(t))throw t;return readChatSendRetryComparison(e.session)}}async function consumeChatSendCurrent(e,t){const invoke=()=>{e.assertCurrent?.();return t()};if(e.withCurrent)return e.withCurrent(invoke);if(e.assertCurrentAsync)await e.assertCurrentAsync();return invoke()}async function respondPreparedChatSendRetry(e){const t=await readChatSendRetryComparison(e.session)?.catch(e=>({error:e}));try{return await consumeChatSendCurrent(e,()=>{if(t&&`error`in t)throw t.error;return respondChatSendRetry(e,t)})}catch(t){if(!isSessionTranscriptProjectionUnavailableError(t))throw t;respondChatSendAdmissionError(t,e.respond);return true}}function respondUnconsumedQueuedRetry({context:e,respond:t,session:n},r){const{agentId:i,clientRunId:a,entry:o,sessionKey:s,storePath:c}=n;const matchesStore=e=>e===c||sameSessionTranscriptStorePath(e,n.readSource?.path);const matchesSession=e=>e.agentId===i&&e.sessionKey===s&&e.sessionId===o?.sessionId;const l=readQueuedChatInputAdmission(a)?.target;if(l&&matchesSession(l)&&matchesStore(l.storePath))return false;const u=getRpcSourceForGateway(a,e.resolveGatewayContext);const d=u?.input.target?.storeScope;const f=u&&d&&!u.input.abortSignal.aborted&&matchesStore(d)&&matchesSession(getRpcSourceIdentity(u));const p=o?.resumeAfterRestart;if(f||p?.queuedInputIds.includes(r)&&p.queuedInputSources?.[r])t(true,{runId:a,status:`in_flight`},void 0,{cached:true,runId:a});else t(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`Chat input is still queued, but its delivery cannot be confirmed. Retry the same request.`,{retryable:true}));return true}function respondChatSendRetry(e,t){e.assertCurrent?.();const{session:n,context:r,respond:i}=e;const{clientRunId:a,pendingChatSendKey:o}=n;const s=resolveChatSendRequestConflict(e,t);if(s){i(false,void 0,s);return true}const c=t?.disposition;const l=r.chatRunState.runs.get(a)?.abortMarker;const u=t?.source!==`transcript`&&!c?.consumed&&chatAbortPendingInputEndCause(l,n)===`user-stop`;if(u||c?.state===`cancelled`&&!c.consumed){const e=u||c?.userStopped;i(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,e?`Chat input was stopped before it ran. Use a new message ID to send again.`:`Chat input was cancelled before it ran. Use a new message ID to send again.`,{details:{reason:`chat-input-cancelled`,...e?{endCause:`user-stop`}:{}}}));return true}if(c?.state===`queued`&&!c.consumed)return respondUnconsumedQueuedRetry(e,c.inputId);const d=readChatSendDedupeResponse(r.dedupe,a);if(d){i(d.ok,d.payload,d.error,{cached:true});return true}if(l!==void 0){const e=chatAbortMarkerTimestampMs(l);const t=buildAbortedChatSendPayload({runId:a,endedAt:e});setGatewayDedupeEntry({dedupe:r.dedupe,key:`chat:${a}`,entry:{ts:e,ok:true,payload:t}});i(true,t,void 0,{cached:true,runId:a});return true}const f=r.dedupe.get(`chat:${a}`)?.effectAccepted===true;const p=readPreRegisteredRun({key:o,entry:r.dedupe.get(o)})||getRpcSourceForGateway(a,r.resolveGatewayContext);if(f||p&&t?.submitted){i(true,{runId:a,status:`in_flight`},void 0,{cached:true,runId:a});return true}if(p){i(false,void 0,errorShape(ErrorCodes.UNAVAILABLE,`Chat input is being admitted; retry the same request.`,{retryable:true}));return true}if(t?.submitted){i(true,{runId:a,status:`ok`,...t.messageSeq!==void 0?{messageSeq:t.messageSeq}:{}},void 0,{cached:true,runId:a});return true}return false}async function runChatSendPreAdmission(e){const{request:t,session:n,respond:r,context:i,client:a}=e;const{stopCommand:o}=t;const{cfg:s,entry:c,sessionKey:l,rawSessionKey:u,selectedAgent:d,clientRunId:f,storePath:p,sessionRoutingChanged:m}=n;const consumeNewDispatchDecision=()=>{if(m(s)){respondChatSessionRoutingChanged(r);return false}const e=resolveSessionWorkStartError(l,c,{allowPendingWorkspace:true,providerReviewAcknowledgment:t.providerReviewAcknowledgment,runId:f});if(e){r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,e));return false}return true};const consumeInitialDecision=()=>{if(resolveSendPolicy({cfg:s,entry:c,sessionKey:l,channel:sessionDeliveryChannel(c),chatType:c?.chatType})===`deny`){r(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`send blocked by session policy`));return false}if(!t.goalOperation)try{if(respondChatSendRetry(e))return false}catch(e){if(!isSessionTranscriptProjectionUnavailableError(e))throw e}return true};if(!(o?consumeInitialDecision():await consumeChatSendCurrent(e,consumeInitialDecision)))return false;if(t.goalOperation){const t=await prepareGoalChatSendRetry(e);const n=await consumeChatSendCurrent(e,()=>inspectGoalChatSendRetry({...e,prepared:t}));if(n.kind===`settled`)return false;if(n.kind===`replay`){r(true,{...n.receipt,replayed:true},void 0,{cached:true,runId:f});return false}}if(o){const t=resolveChatAbortRequester(a);const o=n.readSource?.path??p;const f={};const assertCurrent=()=>{if(f.failure)throw f.failure.error;try{e.assertCurrent?.()}catch(e){f.failure={error:e};throw e}};let h;try{if(await respondPreparedChatSendRetry(e))return false;if(m(s)){respondChatSessionRoutingChanged(r);return false}assertCurrent();h=await abortChatRunsForSessionKeyWithPartials({context:i,ops:createChatAbortOps(i),sessionKey:l,sessionKeyAliases:l===u?void 0:[u],agentId:d.agentId,sessionId:c?.sessionId,session:{ok:true,value:{cfg:s,storePath:o,entry:c,canonicalKey:l,agentId:n.agentId}},defaultAgentId:tryResolveSessionCompatibilityOwnerAgentId(s,l),abortOrigin:`stop-command`,stopReason:`stop`,requester:t,stopSource:`channel-user`,controllerTargets:[captureSessionTarget({storeScope:p,sessionKey:l,aliases:[u],agentId:d.agentId,incarnation:c?.sessionId})],hookContext:{sessionKey:l,sessionEntry:c,sessionId:c?.sessionId,commandSource:`gateway:chat.send`,senderId:t.deviceId??t.connId},assertCurrent,cascadeDescendants:true,announceRunStopped:true});try{assertCurrent()}catch(e){throw abortedPartialPersistenceError(e,h.warning)}}catch(e){const t=f.failure?f.failure.error:e;const n=f.failure&&e instanceof AggregateError&&e.cause instanceof Error?e.cause:e;if(t instanceof SessionMutationAuthorizationChangedError)throw n instanceof SessionMutationAuthorizationChangedError?n:new SessionMutationAuthorizationChangedError({...t.error,message:n instanceof Error?n.message:t.message});respondChatSendAdmissionError(t,(e,i,a)=>{r(e,i,a&&n instanceof Error&&n.cause===t?{...a,message:n.message}:a)});return false}const g=h.unauthorized?errorShape(ErrorCodes.INVALID_REQUEST,`unauthorized`):h.error??descendantAbortError(h.descendants,`Session`);if(g){r(false,void 0,withAbortedPartialPersistenceWarning(g,h.warning));return false}r(true,{ok:true,aborted:h.aborted,runIds:h.runIds,...h.warning?{warning:h.warning}:{}});return false}if(!t.goalOperation&&await respondPreparedChatSendRetry(e))return false;return consumeChatSendCurrent(e,consumeNewDispatchDecision)}
//!src/gateway/server-methods/chat-send-preparation-config.ts
function chatSendPreparationConfig(e,t,n,r,i,a){const o=e.agents?.defaults;const s=resolveAgentEntry(e,t);const c=a??resolveSessionModelRef(e,n,t);const{refs:l,repairConfigPath:u}=resolveConfiguredModelPolicyAllow({cfg:e,agentId:t});const d=[c,...(modelFallbackOverrideFromAvailability(resolveModelFallbackAvailability({cfg:e,agentId:t,sessionKey:i,selectedModel:c,hasSessionModelOverride:Boolean(n?.modelOverride),modelOverrideSource:n?.modelOverrideSource==="default"?void 0:n?.modelOverrideSource,modelSelectionLocked:n?.modelSelectionLocked}))??[]).flatMap(e=>{const t=parseModelRef(e,c.provider);return t?[t]:[]})];const f=Object.fromEntries([...new Set(d.map(({provider:e})=>e))].map(t=>{const n=findNormalizedProviderValue(e.models?.providers,t);return[t,n?{...n,models:n.models?.filter(({id:e})=>d.some(n=>n.provider===t&&n.model===e))}:void 0]}));const p=[...new Set([`webchat`,r?.explicitOrigin?.originatingChannel,sessionDeliveryChannel(n)].filter(e=>Boolean(e)))];return{defaultModel:o?.model,agentModel:s?.model,defaultModels:o?.models,agentModels:s?.models,modelPolicy:{refs:l,owner:l.length>0?u:null},runtime:s?.runtime,models:{mode:e.models?.mode,providers:f},auth:e.auth,workspace:s?.workspace??o?.workspace,agentDir:s?.agentDir,timeoutSeconds:o?.timeoutSeconds,defaultSandbox:o?.sandbox,agentSandbox:s?.sandbox,tools:e.tools,agentTools:s?.tools,plugins:{enabled:e.plugins?.enabled,allow:e.plugins?.allow,deny:e.plugins?.deny,load:e.plugins?.load,slots:e.plugins?.slots,entries:Object.fromEntries(Object.entries(e.plugins?.entries??{}).map(([e,{enabled:t,hooks:n,subagent:r,llm:i}])=>[e,{enabled:t,hooks:n,subagent:r,llm:i}]))},channels:{defaults:e.channels?.defaults,selected:Object.fromEntries(p.map(t=>[t,e.channels?.[t]]))},roles:e.gateway?.roles,nodeCommands:e.gateway?.nodes?.commands,commands:e.commands,sendPolicy:e.session?.sendPolicy,reset:e.session?.reset,resetByType:e.session?.resetByType,resetByChannel:e.session?.resetByChannel}}
//!src/gateway/server-methods/chat-send-session.ts
async function prepareChatSendSessionEntry(e){const{cfg:t,client:n,agentId:r,getRuntimeConfig:i}=e;const a=authorizeGatewaySessionCreation({cfg:t,client:n,agentId:r});if(a)throw new Error(a.message);const o=await prepareSkillLibrarySessionCreation(n,i,resolveOperatorSessionCreation(n));const assertSkillSelection=()=>assertPreparedSkillLibrarySelection(o.skillLibrarySelections);const s=Date.now();const c=randomUUID();return{entry:{...buildSessionCreationStamp({...o,sandbox:resolveCreatorSandbox(t,o),now:s}),sessionId:c,lifecycleRevision:randomUUID(),updatedAt:s,sessionStartedAt:s,lastInteractionAt:s,chatType:`direct`},assertSkillSelection}}async function loadChatSendSessionContext(e){const{request:t,context:n}=e;const{p:r,explicitOrigin:i,normalizedAttachments:a}=t;const o=r.sessionKey;if(!o.trim())return{ok:false,error:`sessionKey must not be blank`};const s=normalizeOptionalString(r.agentId);const c=r.idempotencyKey;const l=pendingChatSendDedupeKey(c);const u=n.getRuntimeConfig();const d=resolveRequestedSessionAgentId(u,o,s);if(!d.ok)return{ok:false,error:d.error};const f=d.agentId;const p=resolveChatSendSessionKey(u,o,f);const m={agentId:f};const h=captureSessionMutationRouting(u,void 0,[{sessionKey:o,agentId:f}]);const assertConfigCurrent=()=>h(n.getRuntimeConfig());if(!t.stopCommand)await waitForAgentInputAdmission(f,{cfg:u,sessionKey:p,owner:n.agentDatabaseStartup});const g=performance.now();const _=await measureDiagnosticsTimelineSpan(`gateway.chat_send.load_session`,()=>t.stopCommand?loadGatewaySessionEntryReadOnlyInWorker({excludeInternalEffects:true,cfg:u,key:p,...m}):withGatewaySessionEntry(p,m,e=>e,u,assertConfigCurrent),{phase:`agent-turn`,attributes:{runId:c,hasAttachments:a.length>0,hasExplicitOrigin:i!==void 0}});assertConfigCurrent();const preparationFor=e=>chatSendPreparationConfig(e,f,_.entry,t,p);if(!isDeepStrictEqual(preparationFor(u),preparationFor(n.getRuntimeConfig())))throw new Error(`Session preparation changed; retry.`);const{cfg:v,agentId:y,storePath:b,entry:x,canonicalKey:S,legacyKey:C}=_;const w=normalizeOptionalString(r.expectedSessionRoutingContract);const T=r.expectedLeafEntryId===null?null:normalizeOptionalString(r.expectedLeafEntryId);const sessionRoutingChanged=e=>w!==void 0&&w.toLowerCase()!==resolveSessionRoutingContract(e);return{ok:true,value:{rawSessionKey:o,sessionLoadKey:p,clientRunId:c,pendingChatSendKey:l,sessionLoadOptions:m,sessionLoadMs:roundedChatSendTimingMs(performance.now()-g),cfg:v,agentId:y,selectedAgent:d,...t.explicitOrigin?{preparationOrigin:t.explicitOrigin}:{},storePath:b,..._.readSource?{readSource:_.readSource}:{},..._.capturedReadSource?{capturedReadSource:_.capturedReadSource}:{},..._.capturedReadSources?{capturedReadSources:_.capturedReadSources}:{},entry:x,sessionKey:S,legacyKey:C,sessionRoutingChanged,expectedLeafEntryId:T,agentIdOverride:s,requestedAgentId:f}}}async function prepareChatSendSession(e){const t=await loadChatSendSessionContext(e);if(!t.ok)return t;const n=t.value;const{request:r,client:i}=e;const{p:a}=r;const{cfg:o,agentId:s,sessionKey:c,entry:l,legacyKey:u}=n;if(isIncognitoSessionKey(c)&&!l)return{ok:false,error:`Incognito session "${c}" was not found.`};const d=resolveMissingAgentHarnessSessionError(c,l);if(d)return{ok:false,error:d};const f=prepareDeletedAgentSessionCheck({cfg:o,sessionKey:c,entry:l,acpMetadataSessionKey:u,assertCurrent:e.assertCurrent});const p=f instanceof Promise?await f:f;if(f instanceof Promise)e.assertCurrent?.();if(p!==null)return{ok:false,error:`Agent "${p}" no longer exists in configuration`};const m=normalizeOptionalString(a.sessionId);const h=l?.sessionId??m;if(!l){const e=authorizeGatewaySessionCreation({cfg:o,client:i,agentId:s});if(e)return{ok:false,error:e}}const g=r.stopCommand?void 0:await resolveGatewaySessionTurnModelRef({cfg:o,agentId:s,sessionKey:c,entry:l});const _=g?.modelRef??resolveSessionModelRef(o,l,s);const v=g?.inherited?g.modelRef:void 0;if(v&&!isDeepStrictEqual(chatSendPreparationConfig(o,s,l,r,c,v),chatSendPreparationConfig(e.context.getRuntimeConfig(),s,l,r,c,v)))throw new Error(`Session preparation changed; retry.`);const y=resolveProviderIdForAuth(_.provider,{config:o});const b=resolveAgentTimeoutMs({cfg:o,overrideMs:a.timeoutMs});const x=Date.now();return{ok:true,value:{...n,requestedSessionId:m,backingSessionId:h,resolvedSessionModel:_,...v?{inheritedModel:v}:{},resolvedSessionAuthProvider:y,timeoutMs:b,now:x}}}async function qualifyChatSendSession(e,t){const n=await prepareQualifiedSessionEntryTarget({...e,canonicalKey:e.sessionKey,requestedKey:e.sessionLoadKey,storeKey:e.legacyKey??e.sessionKey,readSource:e.capturedReadSource},e.capturedReadSources);return{...e,sessionTarget:n,releaseSessionStorage:t,activeRunScopeKey:n.canonicalKey,readSource:n.readSource}}function assertCurrentChatSendSession(e,t){if(e.sessionRoutingChanged(t.cfg))throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON);const{agentId:n,storeKey:r,readSource:i}=e.sessionTarget;const a=t.agentId!==n&&`agent`||(t.legacyKey??t.canonicalKey)!==r&&`store key`||i&&!isDeepStrictEqual(t.capturedReadSource,i)&&`store source`;if(a)throw new Error(`Session storage changed while starting work (${a}). Retry.`)}function withCurrentChatSendSession(e){const{session:t}=e;const n=captureSessionMutationRouting(t.cfg,void 0,[t]);const r={explicitOrigin:t.preparationOrigin};const i=chatSendPreparationConfig(t.cfg,t.agentId,t.entry,r,t.sessionKey,t.inheritedModel);const assertConfigCurrent=()=>{const a=e.getRuntimeConfig();n(a);if(t.sessionRoutingChanged(a))throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON);if(!isDeepStrictEqual(i,chatSendPreparationConfig(a,t.agentId,t.entry,r,t.sessionKey,t.inheritedModel)))throw new Error(`Session preparation changed; retry.`)};const consume=(n,r,i)=>{assertCurrentChatSendSession(t,n);return e.consume(n,r,i)};if(isIncognitoSessionKey(t.sessionKey)){const n=t.expectedLeafEntryId;const readEntry=n=>withGatewaySessionEntry(t.sessionLoadKey,{...t.sessionLoadOptions,includeMembership:e.includeMembership},n?(e,t,r)=>{const i={...e,transcript:n};return consume(i,t,r)}:consume,t.cfg,assertConfigCurrent);return e.includeActivePath&&n!==void 0?readIncognitoActivePath({canonicalKey:t.sessionTarget.storeKey,entry:t.entry,storePath:t.storePath},t.agentId,n).then(readEntry):readEntry()}return withQualifiedGatewaySessionEntry({cfg:t.cfg,target:t.sessionTarget,logicalStorePath:t.storePath,includeMembership:e.includeMembership,includeLifecycle:true,transcript:e.includeActivePath&&t.expectedLeafEntryId!==void 0?{sessionKey:t.sessionTarget.storeKey,agentId:t.agentId,entryIds:[],activePathEntryId:t.expectedLeafEntryId,includeSession:true}:void 0,consume,assertConfigCurrent}).catch(e=>{if(isSessionTranscriptProjectionUnavailableError(e))startSessionTranscriptIndexReconcile({agentId:t.agentId,path:t.sessionTarget.storePath,preferredSessionId:e.sessionId});throw e})}async function prepareChatSendNativeRuntimeRestriction(e){const{request:t,session:n,client:r,context:i}=e;const{entry:a,cfg:o,agentId:s,sessionKey:c,resolvedSessionModel:l}=n;if(t.turnKind!==`main`||t.stopCommand||!a&&n.requestedSessionId||!t.suppressCommandInterpretation&&resolveTextCommand(t.inboundMessage,o))return;const u=resolveEffectiveAgentRuntime({cfg:o,agentId:s,sessionKey:c,sessionEntry:a,provider:l.provider,modelId:l.model});if(u===`openclaw`)return;const d=getRegisteredAgentHarness(u)?.harness;if(!d||d.executionEnvironment!==`host-only`)return;const restrictionFor=(e,t,n,i)=>resolveSessionNativeRuntimeRestriction({operation:`send`,cfg:e,agentId:s,sessionKey:c,entry:t,persistedEntry:i,preparedSessionCapabilityEntry:{sessionKey:c,entry:t},harness:d,provider:n.provider,modelId:n.model,callerCanConsent:hasGatewayAdminScope(r)});const f=resolveOperatorSessionCreation(r);const p=a??buildSessionCreationStamp({...f,sandbox:resolveCreatorSandbox(o,f),now:n.now});const m=await withPreparedSessionCapabilityRead(()=>restrictionFor(o,p,l,a));const h=readAgentRuntimeRestrictionErrorDetails(m?.details);if(a||!m||!hasGatewayAdminScope(r)||!h||h.reason===`sandbox-required`||h.reason===`remote-execution`)return m;const[{loadReplySessionInitializationSnapshot:g,commitReplySessionInitialization:_},{recordSessionCreated:v}]=await Promise.all([import(`./session-accessor.reset-Cu1MhkWR.mjs`),import(`./session-created-B8GJoe1Z.mjs`)]);await(e.assertCurrentAsync?e.assertCurrentAsync():e.assertCurrent?.());const y={agentId:s,sessionKey:c,storePath:n.storePath};const b=await g(y);await(e.assertCurrentAsync?e.assertCurrentAsync():e.assertCurrent?.());const sessionChanged=()=>errorShape(ErrorCodes.INVALID_REQUEST,`Session changed before native confirmation. Retry.`);if(b.currentEntry)return sessionChanged();const x=await prepareChatSendSessionEntry({cfg:o,client:r,agentId:s,getRuntimeConfig:i.getRuntimeConfig});const currentModelFor=e=>n.inheritedModel??resolveSessionModelRef(e,void 0,s);const S=await prepareSessionCapabilityRead(()=>{const e=i.getRuntimeConfig();const t=currentModelFor(e);return readAgentRuntimeRestrictionErrorDetails(restrictionFor(e,x.entry,t)?.details)});let C;try{C=await _({...y,activeSessionKey:c,expectedRevision:b.revision,databaseSource:b.databaseSource,sessionEntry:x.entry,commitGuard:()=>{e.assertCurrent?.();x.assertSkillSelection();const t=i.getRuntimeConfig();const a=resolveOperatorSessionCreation(r);const o=currentModelFor(t);const d=authorizeGatewaySessionCreation({cfg:t,client:r,agentId:s});const f=S.read();if(d||!hasGatewayAdminScope(r)||n.sessionRoutingChanged(t)||a.actor?.id!==x.entry.createdActor?.id||resolveCreatorSandbox(t,a)!==x.entry.sandbox||o.provider!==l.provider||o.model!==l.model||f?.reason!==h.reason||resolveEffectiveAgentRuntime({cfg:t,agentId:s,sessionKey:c,provider:o.provider,modelId:o.model})!==u)throw new Error(d?.message??`Native session creation changed before commit.`)}})}finally{S.release()}if(!C.ok)return sessionChanged();await v(o,{agentId:s,sessionKey:c,entry:C.sessionEntry});emitSessionsChanged(i,{agentId:s,sessionKey:c,reason:`create`});return withPreparedSessionCapabilityRead(()=>restrictionFor(i.getRuntimeConfig(),C.sessionEntry,l,C.sessionEntry))}
//!src/gateway/server-methods/chat-send-work-admission.ts
function assertChatSendWorkAdmissionCurrent(e){if(!e.retainedWork.isActive()||!e.admission.isActive()||e.lifecycleGeneration!==getAgentEventLifecycleGeneration()||e.controller.signal.aborted&&!(isRpcSourceRegistered(e.sourceRef)&&e.sourceRef.input.custody.cancellationRetired))throw new Error(`Chat admission ended or was cancelled; submit a new turn.`)}function prepareChatSendAdmissionRetry(e){try{return prepareChatSendRetryComparison(e)?.catch(e=>({error:e}))}catch(e){return{error:e}}}function consumeChatSendAdmissionRetry(e,t){try{if(t&&`error`in t)throw t.error;if(readPreRegisteredRun({key:e.session.pendingChatSendKey,entry:e.context.dedupe.get(e.session.pendingChatSendKey)})?.payload.goalFingerprint){respondError(e.respond,ErrorCodes.INVALID_REQUEST,`Run ID is reserved by a Goal request; use a new ID.`);return false}return!e.request.goalOperation&&respondChatSendRetry(e,t)?false:t}catch(t){if(t instanceof SessionMutationAuthorizationChangedError)throw t;respondChatSendAdmissionError(t,e.respond);return false}}async function withCurrentChatSendRetry(e,t,n){const withCurrent=t=>withCurrentChatSendSession({session:e.session,getRuntimeConfig:e.context.getRuntimeConfig,includeMembership:Boolean(e.withPreparedCurrent),includeActivePath:e.request.p.queueMode!==`steer`,consume:(n,r,i)=>{const consumeCurrent=()=>t(n);if(e.withPreparedCurrent)return e.withPreparedCurrent({agentId:n.agentId,storePath:n.storePath,sessionKey:n.canonicalKey,entry:n.entry,readSource:n.capturedReadSource,members:r.get(n.legacyKey??n.canonicalKey)??[]},consumeCurrent,i);i();return consumeCurrent()}});const r=await withCurrent(r=>{const i=prepareChatSendRetryComparison({...e,session:{...e.session,entry:r.entry}},t);if(i)return observeChatSendWork(i);n(r,void 0)});if(r){const e=await r();await withCurrent(t=>n(t,e))}}function respondChatSendWorkAdmissionFailure(e,t,n,r){if(t instanceof ExpectedProfileMismatchError)throw t;const{context:i,respond:a,session:o}=e;const{clientRunId:s}=o;const c=n.pendingReservation;const l=normalizeOptionalString(c?.payload.attemptId);if(!readChatSendDedupeResponse(i.dedupe,s)&&(!l||l===n.attemptId)){const e=n.runAbort.controller.signal.aborted?n.runAbort.entry?.adapter.abortStopReason??`rpc`:n.lifecycleGeneration!==getAgentEventLifecycleGeneration()?`restart`:!c||!isFutureDateTimestampMs(c.payload.expiresAtMs,{nowMs:Date.now()})?`timeout`:void 0;if(e&&e!==`restart`)writePreRegisteredChatAbort({context:i,runId:s,stopReason:e,attemptId:n.attemptId,requestIdentity:n.requestIdentity})}try{const t=resolveChatSendRequestConflict(e,r);if(t){a(false,void 0,t);return}}catch{}const u=i.chatRunState.hasAbortMarker(s)&&readChatSendDedupeResponse(i.dedupe,s);if(u){a(u.ok,u.payload,u.error,{cached:true,runId:s});return}respondChatSendAdmissionError(t,a,t=>{if(isProgressCardRefreshInputProvenance(e.request.systemInputProvenance))return;broadcastChatError({context:i,terminalEntry:n.runAbort.entry,runId:s,sessionKey:o.sessionKey,agentId:o.agentId,errorMessage:t})})}function admitChatSendUploads({params:e,client:t,context:n,respond:r}){try{const r=captureGatewayClientUploadCommitGuard({method:`chat.send`,requestParams:e,client:t,context:n});r?.();return{ok:true,assertClientUploadAllowed:r}}catch(e){if(!(e instanceof SessionMutationAuthorizationChangedError))throw e;r(false,void 0,e.error);return{ok:false}}}function observeChatSendWork(e){e.catch(()=>{});return()=>e}function createChatSendWorkAdmission(e){const t=e.terminal;const n=t&&getSessionActorStorageBinding({agentId:t.target.agentId,sessionKey:t.target.canonicalKey,storePath:t.storePath});const inStorage=e=>n?runWithSessionActorStorage(n,e):e();let r=1;const i=[];let a=t?.target.readSource;let o=t?.lifecycleRevision;let isCommittedDestinationCurrent;let s;let c;let l;let u;let d=true;const releaseAdmission=()=>{for(const e of i.splice(0))try{e()}catch(e){warnCleanupFailure(e)}try{e.admission.release()}finally{try{e.releaseCallerAuthority?.()}finally{e.releaseGatewayRootContinuation?.()}}};const warnCleanupFailure=t=>{e.logGateway.warn(`Failed to finish pending chat input: ${formatForLog(t)}`)};const finishRelease=()=>{if(!u){d=false;releaseAdmission();return}const close=async()=>{try{await(await u)?.actor.release()}finally{d=false;releaseAdmission()}};close().catch(warnCleanupFailure)};const release=()=>{if(r===0)return;r-=1;if(r!==0)return;let e=void 0;try{e=inStorage(()=>l?.())}catch(e){warnCleanupFailure(e)}if(e)e.then(finishRelease,e=>{warnCleanupFailure(e);finishRelease()});else finishRelease()};const hold=()=>{let e=false;return()=>{if(e)return;e=true;release()}};const retain=()=>{if(r===0)throw new Error(`cannot retain a released chat work admission`);r+=1;return hold()};return{acquireInputActor(){if(!u){if(!t||r===0)throw new Error(`Chat input actor has no live admission`);const assertCurrent=()=>{if(!d||!t.isActive())throw new Error(`Chat input actor admission ended`)};const n=e.followRegistration;u=inStorage(()=>acquireSessionInputActor({agentId:t.target.agentId,storePath:t.storePath,readSource:t.target.readSource,target:{canonicalKey:t.target.canonicalKey,storeKeys:[...t.target.storeKeys]}},{assertCurrent,assertReadable:assertCurrent},n&&(e=>n({sessionKey:t.target.canonicalKey,agentId:t.target.agentId},e))))}return u},addCleanup:e=>i.push(e),isActive:()=>r>0,assertCommittedDestinationCurrent(){if(isCommittedDestinationCurrent&&(r===0||!t?.isActive()||!isCommittedDestinationCurrent()))throw new Error(`Committed chat input session changed`)},recordFailureNotice(e){if(!t)throw new Error(`Failed input notice requires its original admission target`);const n=o;const i={agentId:t.target.agentId,storePath:t.target.storePath,sessionKey:t.target.storeKey,sessionId:getRpcSourceIdentity(t.sourceRef).sessionId,expectedOwner:{lifecycleRevision:n}};const assertCommitAllowed=()=>{if(r===0||!t.isActive())throw new Error(`Failed input notice admission ended`)};return inStorage(()=>withOwnedSessionTranscriptWrites({sessionTarget:i,assertCommitAllowed,withTranscriptWrite:trackAsyncWork},()=>recordGatewaySessionRunFailure({...e,target:i,assertCommitAllowed,sessionEntryCurrent:a?{source:{...a,sessionKey:i.sessionKey},assertCurrent(e){assertCommitAllowed();if(e?.sessionId!==i.sessionId||e.lifecycleRevision!==n)throw new Error(`Failed input notice session changed`)}}:void 0})))},release:hold(),retain,withInputCommitPublication(e,r){if(!t)throw new Error(`Chat input publication requires its original admission target`);return inStorage(()=>withSessionTranscriptSourcePublication({agentId:t.target.agentId,sessionId:getRpcSourceIdentity(t.sourceRef).sessionId,sessionKey:t.target.storeKey,storePath:t.target.storePath},(e,l)=>{if(a&&(a.agentId!==e.agentId||a.path!==e.path||a.databaseIdentity!==e.databaseIdentity||a.databaseBirthtime!==e.databaseBirthtime))throw new Error(`Committed chat input changed its admitted physical source`);a??=e;if(!isCommittedDestinationCurrent){const bindDestination=r=>{c?.();s=r;const{sessionId:i,lifecycleRevision:a}=r;const matches=e=>e!==void 0&&e.archivedAt===void 0&&e.lifecycleRevision===a&&(a!==void 0||e.sessionId===i);if(n)isCommittedDestinationCurrent=()=>matches(n.actor.storage.readCurrent({type:`session.entry.read`,input:{sessionKey:t.target.storeKey}},n.authority));else{const n=retainPreparedSessionEntryPredicate({databaseIdentity:`file:${e.databaseIdentity}`,sessionKey:t.target.storeKey,entry:r,matches:(e,t)=>matches(t)});c=n.release;isCommittedDestinationCurrent=n.isCurrent}};bindDestination(l);i.push(()=>c?.());bindSessionEffectTransition(captureSessionTarget({storeScope:t.storePath,sessionKey:t.target.canonicalKey,agentId:t.target.agentId}),t,({previous:e,current:t})=>{if(e?.sessionId===s?.sessionId&&e?.lifecycleRevision===s?.lifecycleRevision){bindDestination({...l,...t});o=t.lifecycleRevision}})}o=l.lifecycleRevision;r?.(e,l)},e))},setPendingInputCleanup:e=>{l=e}}}function assertChatSendExclusiveAdmission(e,t){if(!e.goalOperation&&!e.providerReviewAcknowledgment)return;const{storePath:n,sessionKey:r,backingSessionId:i,activeRunScopeKey:a}=t;if(isCompetingSessionControllerWorkActive(n,[r,i],t.agentId)||hasPendingFollowupQueueWork([r,i,a],{storeScope:n,agentId:t.agentId}))throw new Error(e.providerReviewAcknowledgment?`The session still has active work. Review its status before continuing.`:`goal-session-busy`)}function createChatSendPendingInputAdmission({runId:e,expectedProfileId:t,sessionMutationAuthorization:n,sessionMutationCommitGuard:r,assertCustodyLifetimeCurrent:i,assertClientUploadAllowed:a}){const assertCustodyCurrent=()=>{i();if(n?.assertAdmittedInputCurrent)n.assertAdmittedInputCurrent();else{r?.();n?.assertCurrent()}};let o;const s=t===void 0?assertCustodyCurrent:createMessageInjectionAuthority(()=>{if(o)throw o.cause;assertCustodyCurrent();return true});return{runId:e,authority:n?.admittedInputAuthority?withSessionPendingInputAuthorityGuard(n.admittedInputAuthority,i,t===void 0?void 0:e=>{o??={cause:e};s();throw e}):void 0,assertCurrent:()=>{a?.();r?.();assertCustodyCurrent()},assertAdmittedCurrent:s}}
//!src/gateway/server-methods/chat-send-admission-cleanup.ts
async function prepareAdmittedChatSendDispatch({params:e,runAbort:t,admission:n,releaseCaller:r,assertSessionTargetCurrent:i}){const{respond:a}=e;let releaseGatewayRootContinuation=()=>{};let o=r;const cleanup=()=>{try{t.cleanup();n.release();releaseGatewayRootContinuation()}finally{o?.();o=void 0}};let s;try{if(!assertChatSendSessionTargetOrRespond({assertSessionTargetCurrent:i,cleanup,respond:a}))return;const r=await consumeChatSendCurrent(e,()=>{t.controller.signal.throwIfAborted();releaseGatewayRootContinuation=retainGatewayRootWorkAdmissionContinuation()??(()=>{});const r=e.onAdmissionOwned?observeChatSendWork(n.run(e.onAdmissionOwned)):void 0;s=r;return{admission:r}});if(r.admission){if(!await r.admission()){cleanup();return}await consumeChatSendCurrent(e,()=>true)}if(!assertChatSendSessionTargetOrRespond({assertSessionTargetCurrent:i,cleanup,respond:a}))return}catch(e){if(s)await Promise.allSettled([s()]);cleanup();throw e}return{releaseCallerAuthority:o,releaseGatewayRootContinuation}}function createAdmittedChatSendCleanup(e){let t;return{cleanup:()=>{e.cleanupAbort();e.releaseRetainedWork();t?.();t=void 0},setDiscardPreparedMedia:e=>{t=e}}}function finishAbortedChatSend(e){const t=Date.now();const n=buildAbortedChatSendPayload({runId:e.runId,stopReason:e.stopReason??`rpc`,endedAt:t});setGatewayDedupeEntry({dedupe:e.context.dedupe,key:`chat:${e.runId}`,session:captureAgentJobSession({...getRpcSourceIdentity(e.sourceRef),lifecycleGeneration:e.lifecycleGeneration}),entry:{ts:t,ok:true,payload:n}});e.cleanup();clearAgentRunContext(e.runId,e.lifecycleGeneration);e.respond(true,n,void 0,{runId:e.runId})}function releaseChatSendCallerAuthority(e){try{e.operator.release?.()}finally{if(e.request.providerReviewAcknowledgment)retireProviderReviewAcknowledgment(e.request.providerReviewAcknowledgment)}}
//!src/gateway/server-methods/chat-send-interrupt-admission.ts
async function prepareChatSendInterruptAdmission(e){const{sessionMutationAuthorization:t,...n}=e.operator;const r=n.client?.internal?.operatorRunAuthority?void 0:t;const i=r?.retainForRun?.()??(r?{assertCurrent:r.assertAdmittedInputCurrent??r.assertCurrent,release:r.retain?.()}:void 0);let a=i?.release;try{const t=await retainGatewayOperatorRun({...n,entry:e.entry,invocationAuthority:i});if(t.authority)a=void 0;const assertCurrent=()=>{e.assertCurrent?.();e.abortSignal.throwIfAborted();t.authority?.assertCurrent();if(e.interruptCapture)e.assertSessionTargetCurrent()};try{assertCurrent();return{operator:t,interrupt:()=>{assertCurrent();if(!e.interruptCapture)return false;const t=stopSession({source:`interrupt`,capture:e.interruptCapture,assertCurrent,onError:()=>`continue`});assertCurrent();return t.aborted||t.queuedCancelled>0}}}catch(e){t.release();throw e}}finally{a?.()}}
//!src/gateway/server-methods/chat-send-admission.ts
async function admitChatSend(e){const{request:t,session:n,respond:r,context:i,client:a,diagnostics:o}=e;const{p:s,turnKind:c}=t;const l=t.goalOperation?.requestFingerprint??t.requestIdentity;const u=isProgressCardRefreshInputProvenance(t.systemInputProvenance);const{rawSessionKey:d,clientRunId:f,cfg:p,storePath:m,entry:h,sessionKey:g,selectedAgent:_,requestedSessionId:v,backingSessionId:y,agentId:b,resolvedSessionModel:x,resolvedSessionAuthProvider:S,activeRunScopeKey:C,timeoutMs:w,expectedLeafEntryId:T}=n;const assertSessionTargetCurrent=()=>{if(n.sessionRoutingChanged(i.getRuntimeConfig()))throw new Error(SESSION_ROUTING_CHANGED_ERROR_REASON)};const E={cached:true,runId:f};const{chatSendTraceAttributes:D,originatingRoute:O}=prepareChatSendAdmissionContext(e);const k=getAgentEventLifecycleGeneration();const A=randomUUID();const j=createPendingChatSendReservationAccess({context:i,client:a,attemptId:A,requestIdentity:l,request:t,session:n});const M=t.goalOperation?await prepareGoalChatSendRetry(e):void 0;const N=prepareChatSendAdmissionRetry(e);const P=N instanceof Promise?await N:N;const clearReservationAndThrow=e=>{j.clear();throw e};const F=await consumeChatSendCurrent(e,()=>{e.assertCurrent?.();const t=inspectGoalChatSendRetry({...e,prepared:M});if(t.kind!==`new`){if(t.kind===`replay`)r(true,{...t.receipt,replayed:true},void 0,E);return}const n=consumeChatSendAdmissionRetry(e,P);if(n===false)return;const o=readSessionControllerAdmissionError({scope:m,identities:[g,d,y],agentId:b});if(o){if(isAgentRunDirectAbortReason(o)){j.abort(`rpc`);const e=readChatSendDedupeResponse(i.dedupe,f);r(e.ok,e.payload,e.error,E)}else respondChatSendAdmissionError(o,r);return}const c=admitChatSendUploads({params:s,client:a,context:i,respond:r});if(!c.ok)return;j.reserve();return{retryComparison:n,uploadAdmission:c}}).catch(clearReservationAndThrow);if(!F)return{ok:false};let I=F.retryComparison;const L=F.uploadAdmission;const R=t.goalOperation?.action===`start`&&!h&&!v?await prepareChatSendSessionEntry({cfg:n.cfg,client:a,agentId:b,getRuntimeConfig:i.getRuntimeConfig}).catch(clearReservationAndThrow):void 0;let z=R?.entry.sessionId??y??f;let ee;let B=false;let V;let te=false;let ne=false;let H=false;let re;let U;let W;let ie;let G;let K;let q=false;let J;let assertSourceAuthority=e.assertCurrent;let assertAcceptedInputAuthority;const ae=captureSessionTarget({storeScope:m,sessionKey:g,aliases:[d,n.sessionTarget.storeKey],agentId:b,incarnation:z});const Y=registerChatAbortController({target:ae,policy:resolveQueueSettings({cfg:p,channel:O.originatingChannel,sessionEntry:h,inlineMode:s.queueMode}),authority:{assertCurrent:()=>assertSourceAuthority?.()},runId:f,sessionId:z,sessionKey:g,agentId:_.agentId,timeoutMs:w,ownerConnId:normalizeOptionalString(a?.connId),ownerDeviceId:normalizeOptionalString(a?.connect?.device?.id),providerId:x.provider,authProviderId:S,resolveTerminalProducer:e=>resolveActiveReplyRunOwnerForSignal(e.input.abortSignal),kind:`chat-send`,turnKind:c,...u?{controlUiVisible:false,projectSessionActive:false}:{},lifecycleGeneration:k});const oe=Y.entry?.input.policy.mode===`interrupt`&&!t.humanAddressed?captureSessionControllerInterruptBefore(Y.entry.input):void 0;const X=i.workerSessionPlacementService;const isPendingReservationCurrent=()=>{if(i.chatRunState.hasAbortMarker(f))return false;const e=j.read();if(e&&normalizeOptionalString(e.payload.attemptId)!==A){q=true;return false}if(!e){const e=readChatSendDedupeResponse(i.dedupe,f);if(e||Y.entry&&!isRpcSourceRegistered(Y.entry)&&hasRpcSourceForController(f,Y.entry)){q=true;J=e;return false}}if(k!==getAgentEventLifecycleGeneration()){Y.controller.abort(createAgentRunRestartAbortError());j.abort(`restart`);return false}if(!isFutureDateTimestampMs(e?.payload.expiresAtMs,{nowMs:Date.now()})){Y.controller.abort(`timeout`);j.abort(`timeout`);return false}return true};const commitChatWorkAdmission=async(r,a)=>{let c=r;if(i.workerSessionPlacementService!==X)throw new Error(`Worker placement owner changed during chat admission; retry.`);if(X&&a?.sessionId!==z)try{var l=_usingCtx();const e=l.u(o?.scope(`detail.admission.placement_prepare`));return await withGoalChatPlacement(X,z,t=>{e?.finish();return commitChatWorkAdmission(c,t)})}catch(e){l.e=e}finally{l.d()}let u=false;for(;;)try{var d=_usingCtx();let r;let l;const p=d.u(o?.scope(`detail.admission.current_session`));await withCurrentChatSendRetry(e,A,(o,d)=>{I=d;e.assertCurrent?.();const p=resolveChatSendRequestConflict(e,I,A);if(p)throw new Error(p.message);if(!isPendingReservationCurrent())return;const m=o.entry;const _=m?.sessionId;W=m;const x=resolveChatSendRequestConflict({...e,session:{...n,entry:m}},I,A);if(x)throw new Error(x.message);ie=captureAdmittedChatSendSessionSettings({commit:true,entry:m,expectedPermissionMode:s.expectedPermissionMode,expectedToolOverrides:s.expectedToolOverrides});assertChatSendExclusiveAdmission(t,n);if(h&&!m)throw new Error(`Session "${g}" was deleted while starting work. Retry.`);if(s.queueMode!==`steer`&&T!==void 0)assertExpectedLeafActive(o,T);if(y&&_!==y)throw new Error(`Session "${g}" changed while starting work. Retry.`);l=prepareChatSendAcpRefresh(e,c,o);if(l)return;const S=resolveSessionWorkStartError(g,m,{allowPendingWorkspace:true,providerReviewAcknowledgment:t.providerReviewAcknowledgment,runId:f});if(S)throw new Error(S);z=_??y??f;if(!B){K=s.queueMode===`steer`&&!t.humanAddressed?captureCurrentReplyMessageInjectionTarget(Y.entry?.input.mailbox.owner.id??C):void 0;ee=Y.entry?.input.mailbox.owner.active;B=true}if(t.goalOperation?.action===`start`&&!m&&!v){const e=R;U=e.entry;G=e.assertSkillSelection;z=U.sessionId}if(i.workerSessionPlacementService!==X)throw new Error(`Worker placement owner changed during chat admission; retry.`);const w=a?.sessionId!==z;if(X&&w){u=true;return}const E=a?.facts.prepareRead();if(E){r=observeChatSendWork(E);return}const D=a?.facts.current();const O=c?.meta??null;re=resolveCodexGoalAdmission(e,o,D,O);const k=!re&&isLocalChatInputAdmission(e,o,U,D,O);const j=(k||e.sessionCreate===true)&&ee===void 0&&resolveProjectedAgentRunProgressState({agentId:b,sessionId:z,sessionKeys:[g]})===void 0;ne=k&&j;H=e.sessionCreate===true&&j;te=Boolean(t.goalOperation&&ne);if(t.goalOperation&&!te&&!re)throw new SessionGoalOperationError(`invalid`,`Goal start or resume requires an idle built-in local session with recoverable history or a supported local or cloud-worker Codex session.`)}).catch(e=>{if(isSessionTranscriptProjectionUnavailableError(e))isPendingReservationCurrent();throw e});if(l){p?.finish();c=await l();continue}if(!r)break;p?.mark(`detail.admission.placement_refresh`);await r()}catch(e){d.e=e}finally{d.d()}return u?commitChatWorkAdmission(c):void 0};let Z;let releaseCapturedOperator=()=>{};let se=false;let ce;try{try{var le=_usingCtx();const r=le.u(o?.scope(`detail.admission.work`));const a=le.u(o?.scope(`detail.admission.operator`));const s=await prepareChatSendInterruptAdmission({operator:{...e,runId:f},interruptCapture:oe,entry:Y.entry,assertCurrent:e.assertCurrent,assertSessionTargetCurrent,abortSignal:Y.controller.signal});Z=s.operator;releaseCapturedOperator=Z.release;const c=await prepareChatSendAcpMetadata(e);a?.mark(`detail.admission.lifecycle_prepare`);V=await beginSessionEffect({agentId:b,sourceInput:Y.entry?.input,isSettling:()=>Y.entry?.adapter.terminalOutcomeObserved===true,target:ae,storeWriterIdentities:[g,n.sessionTarget.storeKey],assertAllowed:()=>{e.assertCurrent?.();assertSessionTargetCurrent();assertChatSendExclusiveAdmission(t,n)},revalidateAllowed:async()=>{try{var e=_usingCtx();a?.finish();e.u(o?.scope(`detail.admission.revalidate`));return await commitChatWorkAdmission(c)}catch(t){e.e=t}finally{e.d()}},onInterrupt:e=>{Y.controller.abort(e)}});if(re&&!Z.authority)throw new Error(`Codex Goals require a current authenticated operator request.`);Y.initializeTiming({now:Date.now(),timeoutMs:w});r?.finish();if(Y.controller.signal.aborted&&!readChatSendDedupeResponse(i.dedupe,f))j.abort(Y.entry?.adapter.abortStopReason??`rpc`);Y.controller.signal.throwIfAborted();e.assertCurrent?.();ce=await consumeChatSendCurrent(e,()=>resolveChatSendRequestConflict(e,I,A));if(oe&&!ce&&!q&&isPendingReservationCurrent()&&Y.registered)se=s.interrupt()}catch(e){le.e=e}finally{le.d()}}catch(t){const n=j.read();j.clear();Y.cleanup();V?.release();releaseCapturedOperator();respondChatSendWorkAdmissionFailure(e,t,{attemptId:A,lifecycleGeneration:k,pendingReservation:n,requestIdentity:l,runAbort:Y},I);return{ok:false}}if(ce){j.clear();Y.cleanup();V.release();Z.release();r(false,void 0,ce);return{ok:false}}if(Y?.registered&&!q&&!readChatSendDedupeResponse(i.dedupe,f))i.dedupe.set(`chat:${f}`,{ts:Date.now(),ok:true,requestIdentity:l});j.clear();const releaseAdmissionOwners=()=>{V.release();Z.release()};if(q){Y.cleanup();releaseAdmissionOwners();const e=J??readChatSendDedupeResponse(i.dedupe,f);if(e){r(e.ok,e.payload,e.error,E);return{ok:false}}r(true,{runId:f,status:`in_flight`},void 0,E);return{ok:false}}if(k!==getAgentEventLifecycleGeneration()){if(Y.entry)Y.entry.adapter.abortStopReason=`restart`;Y.controller.abort();Y.cleanup();releaseAdmissionOwners();if(!readChatSendDedupeResponse(i.dedupe,f))j.abort(Y.entry?.adapter.abortStopReason??`restart`);const e=readChatSendDedupeResponse(i.dedupe,f);r(e?.ok??true,e?.payload,e?.error,E);return{ok:false}}if(!Y.registered){releaseAdmissionOwners();r(true,{runId:f,status:`in_flight`},void 0,E);return{ok:false}}assertSourceAuthority=()=>{Z.authority?.assertCurrent();assertAcceptedInputAuthority?.();assertSessionTargetCurrent();if(!V?.isActive())throw new Error(`Chat source preparation custody ended`)};const ue=await prepareAdmittedChatSendDispatch({params:e,assertSessionTargetCurrent,runAbort:Y,admission:V,releaseCaller:()=>{try{releaseChatSendCallerAuthority({operator:Z,request:t})}finally{n.releaseSessionStorage?.()}}});if(!ue)return{ok:false};const{releaseCallerAuthority:de,releaseGatewayRootContinuation:Q}=ue;const fe=V;const pe=Y.entry;let me=true;const he=bindChatSendPreparedSession({runId:f,sessionKey:g,sourceRef:pe,lifecycleGeneration:k,admission:{isActive:()=>me&&fe.isActive()}});const $=createChatSendWorkAdmission({admission:fe,followRegistration:e.followRegistration,releaseCallerAuthority:de,releaseGatewayRootContinuation:Q,logGateway:i.logGateway,terminal:{target:n.sessionTarget,storePath:m,sourceRef:pe,lifecycleRevision:W?.lifecycleRevision??U?.lifecycleRevision,isActive:()=>fe.isActive()}});const{cleanup:ge,setDiscardPreparedMedia:_e}=createAdmittedChatSendCleanup({cleanupAbort:()=>{me=false;Y.cleanup()},releaseRetainedWork:$.release});const rejectSessionRoutingChanged=()=>{ge();clearAgentRunContext(f,k);respondChatSessionRoutingChanged(r)};claimAgentRunContext(f,{agentId:_.agentId??b,sessionKey:g,sessionId:z,lifecycleGeneration:k,...progressCardRefreshRunProjection(t.systemInputProvenance)});return{ok:true,value:{activeRunAbort:Y,operatorAuthority:Z.authority,armOperatorRunCancellation:Z.armCancellation,retireOperatorRunCancellation:Z.retireCancellation,admittedSessionSettings:ie,admittedSessionId:z,...ee?{expectedActiveReplyOperation:ee}:{},sourceRef:pe,bindAcceptedInputAuthority:e=>{assertAcceptedInputAuthority=()=>{$.assertCommittedDestinationCurrent();e()}},onSessionPrepared:he,initialSessionEntry:U,admittedSessionEntry:W,chatSendTraceAttributes:D,assertInitialSkillSelection:G,cleanupAdmittedRun:ge,finishAbortedChatSend:()=>finishAbortedChatSend({context:i,respond:r,runId:f,lifecycleGeneration:k,stopReason:Y.entry?.adapter.abortStopReason,sourceRef:pe,cleanup:ge}),gatewayWorkAdmission:V,lifecycleGeneration:k,markInputAccepted:j.markInputAccepted,interruptedActiveRun:se,messageInjectionTarget:K,originatingRoute:O,rejectSessionRoutingChanged,releaseSourceWorkAdmission:$.release,retainGatewayWorkAdmission:$.retain,recordFailureNotice:$.recordFailureNotice,withInputCommitPublication:$.withInputCommitPublication,acquireInputActor:()=>$.acquireInputActor(),setPendingInputCleanup:$.setPendingInputCleanup,assertClientUploadAllowed:L.assertClientUploadAllowed,assertWorkAdmissionCurrent:()=>assertChatSendWorkAdmissionCurrent({retainedWork:$,admission:fe,lifecycleGeneration:k,controller:Y.controller,sourceRef:pe}),localGoalAdmission:te,localInputAdmission:ne,commitInitialInput:H,codexGoalAdmission:re,setDiscardAbandonedPreparedMedia:_e}}}
//!src/gateway/server-methods/chat-send-setup.ts
async function prepareAndAdmitChatSend({params:e,respond:t,context:n,client:r,hasCurrentClientAuthority:i,sessionMutationAuthorization:a},o,s,c,l){const u=c?.scope(`admission`);const d=a||i?()=>{a?.assertCurrent();if(i?.()===false)throw new Error(`Gateway caller authority is no longer active.`)}:void 0;const f=a?.withCurrent;const assertCurrentAsync=async()=>f?f(()=>d?.()):d?.();const p=normalizeChatSendRequest({params:e,client:r,...s?.trustedSystemInput?{trustedSystemInput:true}:{},...s?.spawningParentOpening?{spawningParentOpening:true}:{},...s?.goalResume?{goalResume:s.goalResume}:{},...s?.providerReviewAcknowledgment?{providerReviewAcknowledgment:s.providerReviewAcknowledgment}:{}});const m=p instanceof Promise?await p:p;if(!m.ok){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,m.error,m.reason?{details:{reason:m.reason}}:void 0));return}if(p instanceof Promise||m.value.goalOperation)try{d?.()}catch(e){respondChatSendAdmissionError(e,t);return}const h=await prepareChatSendSession({request:m.value,context:n,client:r,assertCurrent:d});if(!h.ok){t(false,void 0,typeof h.error===`string`?errorShape(ErrorCodes.INVALID_REQUEST,h.error):h.error);return}let g=m.value;if(g.mentions){const e=await n.mentionInbox?.validateRecipientsAsync(r,h.value.entry?{sessionKey:h.value.sessionKey,agentId:h.value.agentId}:{agentId:h.value.agentId},g.mentions.map(e=>e.profileId));if(!e?.ok){t(false,void 0,e?.error??errorShape(ErrorCodes.UNAVAILABLE,`Human mentions are unavailable; reconnect and retry.`));return}if(isHumanAddressedChatMessage({cfg:h.value.cfg,agentId:h.value.agentId,text:g.workContext?.text??g.rawMessage,mentions:g.mentions}))g={...g,humanAddressed:true}}u?.mark(`authority`);const _={request:g,session:h.value,respond:t,context:n,client:r,assertCurrent:d,assertCurrentAsync,withCurrent:f};if(!await runChatSendPreAdmission(_))return;let v;try{v=await qualifyChatSendSession(h.value,l)}catch(e){respondChatSendAdmissionError(e,t);return}const y=await prepareChatSendNativeRuntimeRestriction({..._,session:v});if(y){t(false,void 0,y);return}u?.mark(`runAdmission`);const b=await admitChatSend({..._,session:v,sessionCreate:s?.sessionCreate,onAdmissionOwned:o,hasCurrentClientAuthority:i,sessionMutationAuthorization:a,withPreparedCurrent:a?.withPreparedCurrent,followRegistration:a?.followRegistration,diagnostics:c});if(!b.ok)return;u?.finish();return{request:g,session:v,admission:b.value}}
//!src/gateway/server-methods/chat-user-turn-recorder.ts
function createGatewayChatUserTurnController(e){const{admission:t,request:n,session:r}=e;const i=readQueuedChatInputAdmission(r.clientRunId);const a=r.entry;const o=a?.modelOverrideFallbackOriginProvider;const s=a?.modelOverrideFallbackOriginModel;const c=(o&&s&&hasSessionActiveAutoModelFallback(a)?{provider:o,model:s}:void 0)??r.resolvedSessionModel;const l=resolveSessionSubmittedModelRef(a);const u={...c,...l?{previous:l}:{}};const d=isProgressCardRefreshInputProvenance(n.systemInputProvenance);const f=n.goalOperation?.action===`resume`?void 0:gatewayClientSenderFields(e.client).sender;const p=i?i.requesterProfile?.id:e.client?.authenticatedUserProfile?.profileId;const m=e.client?.internal?.agentToolCaller;const h=captureRequesterOrigin({requesterOrigin:m?.requesterOrigin,sessionKey:r.sessionKey,operatorProfileId:m?void 0:t.operatorAuthority?.profileId,messageProvider:INTERNAL_MESSAGE_CHANNEL,agentAccountId:t.originatingRoute.accountId,chatType:`direct`,messageThreadId:t.originatingRoute.messageThreadId,senderId:m?void 0:f?.id,senderName:m?void 0:f?.name});const g=e.mentionInbox;const _=buildRunUserTurnIdempotencyKey(r.clientRunId);const v=i?.target.message[`__openclaw`]?.humanMentions??n.mentions;const y=!e.client?.internal?.syntheticClient&&(!n.systemInputProvenance||n.systemInputProvenance.kind===`external_user`)?normalizeMessageClientSources([n.clientInfo]):[];const b={...e.transcript,...n.goalOperation?.action===`resume`?{display:false}:{},text:n.rawMessage,requesterOrigin:h,...n.workContext?{workContext:n.workContext}:{},...n.appContext?{appContext:n.appContext}:{},...n.mentions?{mentions:n.mentions}:{},...n.humanAddressed?{humanAddressed:true}:{},timestamp:r.now,idempotencyKey:_,...n.p.replyToId?{replyToId:n.p.replyToId}:{},...f?{sender:f}:{},...y.length?{transport:{clients:y}}:{},...hasGatewayAdminScope(e.client)?{senderIsOwner:true}:{},provenance:n.systemInputProvenance??(e.client?.internal?.syntheticClient?void 0:{kind:`external_user`})};const x=n.p.replyToId?resolveChatSendReplyContext({replyToId:n.p.replyToId,cfg:r.cfg,agentId:r.agentId,sessionKey:r.sessionKey,sessionEntry:r.entry,storePath:r.storePath,userSenderLabel:n.clientInfo?.displayName,warn:e.warn}):void 0;let S=x?x.then(e=>({...b,...e.ReplyToBody?{replyToPreview:{text:e.ReplyToBody,...e.ReplyToSender?{senderLabel:e.ReplyToSender}:{}}}:{}})):Promise.resolve(b);let C=false;let w;const onPersistenceError=t=>e.warn(`gateway user transcript persistence failed: ${formatForLog(t)}`);const captureWorkerGoalSource=()=>captureWorkerTurnInputSource({agentId:r.agentId,sessionId:getRpcSourceIdentity(t.sourceRef).sessionId,sessionKey:r.sessionKey});const prepareWorkerGoalSource=async()=>prepareSessionSourceAuthority(captureWorkerGoalSource());const T=t.codexGoalAdmission===`worker`?Object.assign(()=>captureWorkerGoalSource()(),{prepareSessionSource:prepareWorkerGoalSource,prepareSessionSourceScope:prepareWorkerGoalSource}):void 0;const E=createUserTurnTranscriptRecorder({onMessagePersisted:e.onMessagePersisted,...i?{message:i.target.message}:{},pendingInputRequestFingerprint:i?.requestFingerprint??n.goalOperation?.requestFingerprint??(f?.id?sha256Hex(stableStringify([{...n.p,sessionId:getRpcSourceIdentity(t.sourceRef).sessionId,expectedLeafEntryId:void 0},f.identity??f.id,hasGatewayAdminScope(e.client)])):void 0),...n.goalOperation?{sessionTurnMutation:{kind:`goal`,operation:n.goalOperation,runId:r.clientRunId,...e.goalCommitGuard,assertCurrent:t.codexGoalAdmission===`worker`?composeSessionSourceAssertion([e.goalCommitGuard?.assertCurrent,T]):e.goalCommitGuard?.assertCurrent}}:{},input:b,resolveInput:async()=>{try{var e=_usingCtx();e.u(observeDiagnosticsTimelinePhases(`persist.resolveInput`));return await S}catch(t){e.e=t}finally{e.d()}},target:()=>{const e=r.sessionTarget;const n=getRpcSourceIdentity(t.sourceRef).sessionId;return{sessionId:n,expectedSessionId:n,initialSessionEntry:t.initialSessionEntry,sessionKey:e.storeKey,sessionEntry:void 0,storePath:e.storePath,agentId:r.agentId,config:r.cfg}},...(t.localInputAdmission||e.commitInitialInput)&&!d?{sessionLifecyclePatch:{lastInteractionAt:e.startedAt}}:{},errorContext:`gateway chat user turn transcript`,assertOriginalInputCommit:composeSessionSourceAssertion([e.assertOriginalInputCommit,t.operatorAuthority?.assertCurrent]),beforeMessageWrite:t=>{if(i)return t.message;const r=t.message.idempotencyKey===_;const a=runAgentHarnessBeforeMessageWriteHook(t);if(r&&a?.role===`user`){const t=a;const r={...asOptionalRecord(Reflect.get(a,`__openclaw`))};delete r.chatRequestIdentity;delete r.suppressCommandInterpretation;delete r.chatSendDelivery;delete r.chatSendRuntime;delete r.modelSelection;const i=!e.client?.internal?.syntheticClient&&!C&&t.display!==false&&t.excludeFromContext!==true&&(!t.provenance||t.provenance.kind===`external_user`);return{...a,...C?{excludeFromContext:true}:{},__openclaw:{...r,...n.requestIdentity?{chatRequestIdentity:n.requestIdentity}:{},...n.suppressCommandInterpretation?{suppressCommandInterpretation:true}:{},...n.p.deliver!==void 0||n.explicitOrigin?{chatSendDelivery:{deliver:n.p.deliver,originatingChannel:n.p.originatingChannel,originatingTo:n.p.originatingTo,originatingAccountId:n.p.originatingAccountId,originatingThreadId:n.p.originatingThreadId}}:{},...n.p.thinking!==void 0||n.p.fastMode!==void 0||n.p.fastAutoOnSeconds!==void 0||n.p.timeoutMs!==void 0?{chatSendRuntime:{thinking:n.p.thinking,fastMode:n.p.fastMode,fastAutoOnSeconds:n.p.fastAutoOnSeconds,timeoutMs:n.p.timeoutMs}}:{},...i?{modelSelection:u}:{},...C?{contextFreeCommand:true}:{}}}}return a},onPersistenceError,...v&&p&&g?{onOriginalInputCommitted:({message:t,anchor:a})=>{const o=t[`__openclaw`]?.humanMentions;const s=extractTextFromChatContent(t.content,{joinWith:`
`,normalizeText:e=>e})??``;const c=i?v:v.filter(e=>Array.isArray(o)&&o.some(t=>{const r=asOptionalRecord(t);return r?.profileId===e.profileId&&r.start===e.start&&r.end===e.end&&s.slice(e.start,e.end)===n.rawMessage.slice(e.start,e.end)}));if(!c.length){e.warn(`Human mentions skipped because the committed text no longer contains the selected tokens.`);return}w=g.recordCommittedInputAsync({sourceId:_,committedSource:{generation:a.generation,sequence:a.rawSeq,timestamp:t.timestamp},agentId:a.agentId,sessionKey:r.sessionKey,sessionId:a.sessionId,messageId:a.entryId,senderProfileId:p,recipientProfileIds:c.map(e=>e.profileId),excerpt:s});w.catch(onPersistenceError)}}:{}});bindUserTurnInputActor(E,{phase:`acceptInput`,acquire:t.acquireInputActor});const persist=async e=>{try{var n=_usingCtx();if(e?.contextFreeCommand===true&&!E.hasPersisted())C=true;if(t.codexGoalAdmission&&!E.hasPersisted())return;const i=await measureDiagnosticsTimelineSpan(`gateway.chat_send.persist_user_transcript`,()=>E.persistFallback({sessionLifecyclePatch:e?.sessionLifecyclePatch}),{phase:`agent-turn`,config:r.cfg,attributes:t.chatSendTraceAttributes});n.u(observeDiagnosticsTimelinePhases(`persist.mentionPublication`));await w;return i}catch(e){n.e=e}finally{n.d()}};return{baseInput:b,persist,persistBestEffort:async e=>{return await persist(e).catch(()=>void 0)},recorder:E,replyContextFieldsPromise:x,getSessionInitializationOptions:()=>({requestedSessionId:r.requestedSessionId,resumeRequestedSession:n.reconnectResumeRequested,...t.localInputAdmission||t.codexGoalAdmission?{expectedExistingSessionId:t.admittedSessionId,pinExpectedExistingSession:true,newlyCreatedSessionId:t.initialSessionEntry?.sessionId,...E.hasPersisted()&&!d?{recordedSessionActivity:{sessionId:t.admittedSessionId,sessionKey:r.sessionKey,at:e.startedAt}}:{}}:r.entry?.sessionId?{expectedExistingSessionId:r.entry.sessionId}:{}}),setInputPromise:e=>{const t=S;S=Promise.all([t,e]).then(([e,t])=>({...e,...t,requesterOrigin:e.requesterOrigin}))}}}
//!src/gateway/server-methods/chat-send-input-dispatch.ts
const mediaDocumentContextLoader=createLazyImportLoader(()=>import(`./file-context-0ZZbVPci.mjs`));async function handleChatSendWithStorage(e,t,n,r,i){try{var a=_usingCtx();const{req:l,respond:u,context:d,client:f,hasCurrentClientAuthority:p,sessionMutationAuthorization:m,sessionMutationCommitGuard:h}=e;const g=m?.takeRelease?.()??m?.release;const _=a.u(readChatSendDiagnostics(e)??startChatSendDiagnostics(d.logGateway));const v=await prepareAndAdmitChatSend(e,t,{...r,sessionCreate:l.method===`sessions.create`},_,i?()=>i.release():void 0).catch(e=>{g?.();throw e});if(!v){g?.();return}i?.retain();const{request:y,session:b,admission:x}=v;x.setPendingInputCleanup(()=>g?.());const S=a.u({dispatched:false,[Symbol.dispose](){if(!this.dispatched)x.cleanupAdmittedRun()}});const{systemInputProvenance:C}=y;const{clientRunId:w,cfg:T,storePath:E,entry:D,sessionKey:O,sessionRoutingChanged:k,selectedAgent:A}=b;const{activeRunAbort:j,admittedSessionId:M,chatSendTraceAttributes:N,finishAbortedChatSend:P,interruptedActiveRun:F,lifecycleGeneration:I,messageInjectionTarget:L}=x;_.setRunIdentity(M,w);const R=_.scope(`attachments`);const z=await prepareChatSendAttachments({...v,respond:u,context:d});if(!z.ok)return;const ee=bindChatSendPreparedMediaCustody({admission:x,attachments:z.value});const settleInterruptedPreparation=()=>{if(j.controller.signal.aborted)P();else if(k(d.getRuntimeConfig()))x.rejectSessionRoutingChanged();else return false;return true};if(settleInterruptedPreparation())return;const{imageOrder:B,prepareAttachmentsMs:V}=z.value;R?.mark(`authority`);const te={runId:w,sessionKey:O,spawnedBy:D?.spawnedBy,isUncontrolledDashboardChild:Boolean(D?.spawnedBy&&parseAgentSessionKey(O)?.rest.startsWith(`dashboard:`)&&!resolveSessionChildController(O,D)),client:f,isCurrent:p,inputProvenance:C,hasExplicitOrigin:y.explicitOrigin!==void 0,hasRestoredCronContinuation:D?.cronRunContinuation!==void 0,isIncognitoEntry:D?.incognito===true,isSystemGenerated:y.suppressCommandInterpretation||y.systemProvenanceReceipt!==void 0,turnKind:y.turnKind};const ne=n?.resolve(te);const H=Date.now();const{commitInitialInput:re}=x;let U=x.localInputAdmission||re;let W=false;let ie;let G=void 0;let K;try{try{var o=_usingCtx();const assertCustodyLifetimeCurrent=()=>{x.assertWorkAdmissionCurrent();if(k(d.getRuntimeConfig()))throw new Error(`Session routing changed before input admission; refresh and retry.`)};let t;const i=createChatSendPendingInputAdmission({runId:w,expectedProfileId:l.expectedProfileId,sessionMutationAuthorization:m,sessionMutationCommitGuard:h,assertCustodyLifetimeCurrent,assertClientUploadAllowed:x.assertClientUploadAllowed});const a=composeSessionSourceAssertion([h],e=>{x.assertClientUploadAllowed?.();assertCustodyLifetimeCurrent();if(U)m?.assertCurrent();e()});const q=r?.stageCreatedInput?createDynamicSessionSourceAssertion(()=>t??a,()=>{throw new Error(`Chat input custody changed before admission`)}):a;q();const J=y.goalOperation?createChatSendGoalCommitGuard({admission:x,session:b,client:f,context:d,sessionMutationAuthorization:m,sessionMutationCommitGuard:h}):void 0;const ae=x.codexGoalAdmission?createDeferredCore():void 0;const Y=createGatewayChatUserTurnController({onMessagePersisted:ae?.resolve,...v,client:f,commitInitialInput:re,transcript:r?.transcript,startedAt:H,warn:e=>d.logGateway.warn(e),mentionInbox:d.mentionInbox,assertOriginalInputCommit:composeSessionSourceAssertion([q,re?m?.assertCurrent:void 0]),goalCommitGuard:J});const{persist:oe,recorder:X,replyContextFieldsPromise:Z}=Y;let se=!D;const withUserTurnInputPublication=e=>x.withInputCommitPublication(e,(e,n)=>{ie={sessionId:n.sessionId,lifecycleRevision:n.lifecycleRevision};if(!D){m?.recordCreatedSession?.({agentId:b.agentId,sessionKey:O,storePath:E,sessionId:M,lifecycleRevision:n.lifecycleRevision,readSource:e,entry:n});se=false}if(r?.stageCreatedInput)t=i.assertAdmittedCurrent;x.bindAcceptedInputAuthority(i.assertAdmittedCurrent)});const persistGatewayUserTurnTranscript=(...e)=>withDiagnosticsTimelineObserver(_.observeSpan,()=>withUserTurnInputPublication(()=>oe(...e)));const persistGatewayUserTurnTranscriptBestEffort=(...e)=>withUserTurnInputPublication(()=>Y.persistBestEffort(...e));ee(X);R?.mark(`preparation`);const ce=prepareChatSendUserTurn({...v,attachments:z.value,client:f,logGateway:d.logGateway,getConfig:d.getRuntimeConfig,assertInputCurrent:q,userTurn:Y});const{ctx:le,isInternalTextSlashCommandTurn:ue}=ce;U=!readQueuedChatInputAdmission(w)&&(re&&!requiresRuntimeApprovedChatInput(f)||x.localInputAdmission&&y.p.queueMode!==`steer`&&!L&&!ue&&(x.localGoalAdmission||Y.baseInput.display!==false&&(!C||C.kind===`external_user`)));x.setPendingInputCleanup(async()=>{try{const e=X.getPendingInputMessage?.()&&!X.isPendingInputConsumed?.();const t=`cancelled`;const n=j.controller.signal;const r=n.aborted?chatAbortPendingInputEndCause(d.chatRunState.runs.get(w)?.abortMarker,b)??resolveChatAbortDiagnosticReason(n,j.entry?.adapter):void 0;X.finishPendingInput?.(t,r===`user-stop`?true:void 0);if(e&&r)d.logGateway.info(`chat pending input aborted: ${r} (${t})`,{runId:w,sessionKey:O,sessionId:M,agentId:A.agentId,disposition:t,reason:r});await X.waitForPendingInputSettlement?.()}finally{K?.release();g?.();ce.discardUnreferencedMedia(X.getPendingInputMessage?.()).catch(e=>d.logGateway.warn(`Failed to discard unused chat media: ${String(e)}`))}});R?.mark(`persist`);let de;if(x.codexGoalAdmission||Boolean(D?.sessionId&&Y.baseInput.display!==false&&(!C||C.kind===`external_user`||r?.stageCreatedInput===true)&&!ue&&!y.goalOperation&&!U))try{var s=_usingCtx();W=true;const e=s.u(_.scope(`detail.persist.stage`));const n=await withDiagnosticsTimelineObserver(_.observeSpan,()=>X.stageApproved?.({...i,recoverySource:captureQueuedOperatorRecoverySource(x.operatorAuthority)}));e?.finish();if(X.isPendingInputConsumed?.()){const e=await readChatSendRetryComparison(b);q();x.cleanupAdmittedRun();clearAgentRunContext(w,I);u(true,{runId:w,status:`ok`,...e?.messageSeq!==void 0?{messageSeq:e.messageSeq}:{}},void 0,{cached:true,runId:w});return}if(!n)throw new Error(`Chat input was not durably admitted; refresh and retry.`);if(r?.stageCreatedInput)t=i.assertAdmittedCurrent;x.bindAcceptedInputAuthority(i.assertAdmittedCurrent);de=X.getPendingInputMessage?.();emitSessionsChanged(d,{sessionKey:O,agentId:A.agentId,reason:`send`},{accessChanged:false})}catch(e){s.e=e}finally{s.d()}let Q;if(U)try{var c=_usingCtx();W=true;const e=c.u(_.scope(`detail.persist.transcript`));const t=await persistGatewayUserTurnTranscript({sessionLifecyclePatch:ue?void 0:{...deriveGatewaySessionLifecycleSnapshot({event:{runId:w,ts:H,data:{phase:`start`}}}),activeWriterRunId:w,lifecycleRunId:w,lastRunId:void 0,lastInteractionAt:H}});e?.finish();de=t?.message;const n=y.goalOperation;if(n){const e=t?.sessionTurnMutationResult;Q=e?.result;if(!Q){Q=await lookupSessionGoalOperation({sessionKey:O,storePath:E,agentId:b.agentId,expectedSessionId:M,operation:n});q();J?.assertCurrent()}if(Q&&(!t||e?.replayed)){x.cleanupAdmittedRun();clearAgentRunContext(w,I);u(true,{...Q,replayed:true},void 0,{cached:true,runId:w});return}if(!Q||!t?.sessionEntry)throw new Error(`Goal and its input were not durably admitted.`);if(x.initialSessionEntry)await recordSessionCreated(b.cfg,{sessionKey:O,agentId:b.agentId,entry:t.sessionEntry});await publishCommittedSessionGoalChange(d,{sessionKey:O,agentId:b.agentId,entry:t.sessionEntry,actor:gatewayClientSessionCreator(f),summary:`goal ${n.action}`})}if(!t)throw new Error(`Chat input was not durably admitted; refresh and retry.`);if(I!==getAgentEventLifecycleGeneration()){if(j.entry)j.entry.adapter.abortStopReason=`restart`;j.controller.abort(createAgentRunRestartAbortError())}if(j.controller.signal.aborted){P();return}if(k(d.getRuntimeConfig())){x.rejectSessionRoutingChanged();return}}catch(e){c.e=e}finally{c.d()}await recordSessionOperatorSource({agentId:b.agentId,sessionKey:O,storePath:E,authority:x.operatorAuthority,log:d.logGateway});if(de)ce.applyApprovedText(extractTextFromChatContent(de.content,{joinWith:`
`,normalizeText:e=>e})??``);const fe=o.u(_.scope(`detail.persist.authority`));K=await createChatSendDashboardAuthority({admission:x,session:b,client:f,context:d,hasCurrentClientAuthority:p,sessionMutationCommitGuard:h,sessionMutationAuthorization:m,externalAuthorityAdmission:n,externalAdmissionParams:te});fe?.finish();const pe=K.assertReadCurrent;K.bindPromptRecorder(X);R?.mark(`preparation`);if(L)invalidateSkillAuthoringForOtherRequester(O,f?.internal?.syntheticClient?void 0:f?.authenticatedUserProfile?.profileId);const me=L&&!ue&&le.media?.length?await mediaDocumentContextLoader.load().then(async e=>({status:`rendered`,...await e.renderInboundDocumentContext({ctx:le,cfg:b.cfg})})).catch(e=>{mediaDocumentContextLoader.clear();logVerbose(`steer document render failed, injecting raw content: ${formatErrorMessage(e)}`);return{status:`failed`}}):void 0;if(settleInterruptedPreparation())return;const he=createChatSendMessageInjectionStarter({diagnostics:_,operatorAuthority:x.operatorAuthority,target:L,sourceRef:x.sourceRef,abortSignal:j.controller.signal,request:y,session:b,admittedSessionSettings:x.admittedSessionSettings,turn:ce,imageOrder:B,documentContext:me,userTurnTranscriptRecorder:X,logGateway:d.logGateway,assertCurrent:l.expectedProfileId===void 0&&!x.assertClientUploadAllowed&&!isProgressCardRefreshInputProvenance(C)?void 0:q});R?.mark(`effects`);const{serverTiming:$,chatSendTiming:ge,ackReadyEvent:_e}=prepareChatSendAckTiming({client:f,request:y,session:b,prepareAttachmentsMs:V,chatSendTraceAttributes:N});if(r?.beforeDispatch){q();G=await r.beforeDispatch({runId:w,assertCurrent:q,assertWorkAdmissionCurrent:()=>{x.assertClientUploadAllowed?.();x.assertWorkAdmissionCurrent()}});q()}d.addChatRun(w,{sessionKey:O,agentId:A.agentId,clientRunId:w,...ge?{chatSendTiming:ge}:{}});const ve=X.getAdmissionReceipt?.();const ye={...Q,runId:w,status:`started`,...ve?{messageSeq:ve.activeMessagePosition+1}:{},...F?{interruptedActiveRun:true}:{},...$?{serverTiming:$}:{}};emitDiagnosticsTimelineEvent(_e(ye.status),{config:T});q();x.setDiscardAbandonedPreparedMedia(void 0);R?.mark(`response`);x.markInputAccepted();if(readGatewayRequestMutationAuthority(e).family===`worker`)acceptGatewayDeviceSourceAuthority(p);if(!x.codexGoalAdmission)u(true,ye,void 0,{runId:w});R?.finish();_.acknowledge();const be=o.u(_.scope(`detail.dispatch.accepted_handoff`));d.recordClientActivity?.(f);const xe=ge?.ackedAtMs??performance.now();G=void 0;const Se={...v,diagnostics:_,admissionStartedAt:H,attachments:z.value,client:f,context:d,toolsAllow:r?.toolsAllow,deferWorkspaceBootstrap:r?.deferWorkspaceBootstrap,prepareAssistantTranscriptMessage:r?.prepareAssistantTranscriptMessage,skillLibrary:{sessionKey:O,owner:{client:f,context:d,sessionMutationCommitGuard:()=>{h?.();x.assertWorkAdmissionCurrent()}},isHumanTurn:!r&&!C&&y.turnKind===`main`},cronCreatorAuthority:ne,assertDashboardReadCurrent:pe,getSessionInitializationOptions:createChatSendSessionInitialization({sessionKey:O,agentId:b.agentId,authorization:m,needsCreationBinding:se,getSessionInitializationOptions:Y.getSessionInitializationOptions}),externalAuthorityAdmission:n,injection:{beginCapturedMessageInjection:he,replyContextFieldsPromise:Z},timing:{chatSendAckedAtMs:xe,chatSendTiming:ge},turn:ce,userTurn:{...Y,persist:persistGatewayUserTurnTranscript,persistBestEffort:persistGatewayUserTurnTranscriptBestEffort}};const Ce=runOutsidePreparedModelRuntimePluginGenerationScope(()=>withoutGatewayToolCallerIdentity(()=>runOutsideOperatorToolGatewayAuthority(()=>startChatDispatch(Se))));be?.finish();S.dispatched=true;if(ae)await acknowledgeCodexGoal({dispatch:Se,committed:ae.promise,dispatched:Ce,ackPayload:ye,respond:u})}catch(e){o.e=e}finally{o.d()}}catch(e){K?.release();G?.();await handleChatSendSetupError({cacheResult:y.goalOperation===void 0&&!W,committedInput:ie,admission:x,context:d,error:e,respond:u,session:b})}}catch(e){a.e=e}finally{a.d()}}
//!src/gateway/server-methods/chat-send-storage.ts
async function runChatSendWithStorage(e,t){const n=e.params.sessionKey;if(typeof n!==`string`||!isIncognitoSessionKey(n))return t();const r=e.context.getRuntimeConfig();const i=resolveRequestedSessionAgentId(r,n,typeof e.params.agentId===`string`?e.params.agentId:void 0);if(!i.ok){e.respond(false,void 0,i.error);return}let a=true;let o=false;const assertCurrent=()=>{if(!a)throw new Error(`Chat session storage admission ended`)};const s=await acquireSessionActorStorage({sessionKey:resolveChatSendSessionKey(r,n,i.agentId),agentId:i.agentId},{lifetime:{assertCurrent,assertReadable:assertCurrent},authority:{assertCurrent,authorize:assertCurrent}});if(!s){respondError(e.respond,ErrorCodes.INVALID_REQUEST,`Incognito session "${resolveChatSendSessionKey(r,n,i.agentId)}" was not found.`);return}const release=()=>{if(!a)return;a=false;s.actor.release().catch(t=>{e.context.logGateway.warn(`Chat session storage cleanup failed: ${String(t)}`)})};try{await runWithSessionActorStorage(s,()=>t({release,retain(){o=true}}))}finally{if(!o)release()}}
//!src/gateway/server-methods/chat-send-handler.ts
async function handleChatSendWithOptions(e,t,n,r){await runChatSendWithStorage(e,i=>handleChatSendWithStorage(e,t,n,r,i))}async function handleChatSend(e,t,n){await handleChatSendWithOptions(e,t,n)}async function handleProviderReviewContinuationChat(e,t){let n=false;try{await handleChatSendWithOptions(e,async()=>{n=true;return true},void 0,{providerReviewAcknowledgment:t})}finally{if(!n)retireProviderReviewAcknowledgment(t)}}async function handleSessionGoalResumeChat(e,t){await handleChatSendWithOptions(e,void 0,void 0,{goalResume:t})}async function handleTrustedInternalChatSend(e,t,n){await handleChatSendWithOptions(e,t,n?.templateSetup?{allowsDashboardReads:()=>false,resolve:e=>{const t=resolveGatewayTemplateSetupCronAuthorityAdmission({...e,resolvedSessionKey:e.sessionKey});return t?createCronCreatorAuthorityCapability(t.runId,t.callerOrigin,t.managementEntitlement,t.isCurrent,void 0,t.requesterOwner,t.callerScopedCreation):void 0},run:(e,t,n)=>runWithCronCreatorAuthorityCapability(e,t,n)}:void 0,{...n,trustedSystemInput:true})}export{isDirectChatGoalSession as a,handleTrustedInternalChatSend as i,handleProviderReviewContinuationChat as n,lookupSessionGoalOperation as o,handleSessionGoalResumeChat as r,handleChatSend as t};