openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9,404 lines • 342 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { n as isTruthyEnvValue, s as isVitestRuntimeEnv } from "./env-HehwidXj.mjs";
import { a as getTrackedWorkerCpuSources } from "./worker-cpu-dNstslyu.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { r as runWithMainThreadTask, t as createMainThreadStallMonitor } from "./main-thread-stall-BhUfYJnA.mjs";
import { o as measureGatewayBootstrapStep } from "./startup-trace-DWZsuODq.mjs";
import { a as extractErrorCode, d as readErrorName, s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { b as uniqueStrings, d as normalizeSortedUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { c as isSecretRef } from "./ref-contract-b8L-9DrQ.mjs";
import "./types.secrets-BmNLLnHp.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as resolveConfigDir } from "./config-dir-DMqvtq2W.mjs";
import { S as resolveIsConfigReadOnly, c as isNamedProfile, l as isNixMode, u as normalizeStateDirEnv } from "./paths-DAcAg5aV.mjs";
import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs";
import { t as formatErrorMessage$1 } from "./errors-BKzCeTYb.mjs";
import { i as getActiveGatewayRootWorkCount } from "./gateway-work-admission-state-X3ZM0tLe.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { c as runOutsideAsyncWorkScope, o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { a as pluginInstanceInvocation } from "./plugin-instance-invocation-Bq_toGDw.mjs";
import { d as withPluginRuntimeRegistryScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { i as hasRetainedPluginRuntimeCloseError } from "./runtime-close-error-Ak-r7PLO.mjs";
import { a as getGatewayContextLifetime, t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs";
import { n as bindLegacyPluginSdkResourceHost, t as LegacyPluginSdkResourceHost } from "./legacy-sdk-resource-host-BiedXayN.mjs";
import { t as bumpSkillsSnapshotVersion } from "./refresh-state-C65GsLnU.mjs";
import { n as ok, t as err } from "./result-CV1-31DB.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { t as isControlUiFocusPath } from "./focus-DDcKuIiJ.mjs";
import { F as buildControlUiSessionPath, j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as resolveIncognitoSessionExpiresAt } from "./incognito-session-key-DEZTpgjh.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { a as isSameOpenClawAgentDatabasePath, s as resolveIncognitoOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { u as getPluginMetadataSnapshotCache } from "./plugin-cache-B_eRuqTM.mjs";
import { i as getGatewayPluginMetadataSnapshot, s as selectCurrentPluginMetadataCache } from "./current-plugin-metadata-state-BmYo9Q7A.mjs";
import { I as hasInternalDiagnosticEventInterest, o as emitInternalDiagnosticEvent, p as isDiagnosticsEnabled, t as areDiagnosticsEnabledForProcess, y as setDiagnosticsEnabledForProcess, z as onInternalDiagnosticEventInterest } from "./diagnostic-events-BjAH1Kbx.mjs";
import { T as runWithDiagnosticTraceContext, g as createDiagnosticTraceContext, i as flushDiagnosticsTimeline } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as applyLoggingConfig } from "./logger-1QDNfT7Y.mjs";
import { n as runtimeForLogger, t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { l as resolveRuntimeServiceVersion, o as resolveRuntimeServiceBuildId } from "./version-GlxUMdxI.mjs";
import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { t as GatewayScheduler } from "./gateway-scheduler-BApPBa3S.mjs";
import { r as resolveDatabasePath, s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { _ as withSqliteReadOnlyWorkerScope, y as captureSqliteReadOnlyWorkerScope } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { a as getRecordedChildRuntimeViability, c as prepareChildRuntimeViability } from "./child-runtime-viability-DFyU3D5D.mjs";
import { n as runWithSpawnBroker, t as getSpawnBroker } from "./context-Btn9lVDh.mjs";
import { d as ModelAccountConnectAuthorityError, f as ModelAccountConnectInputError } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { r as createLazyPromiseLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { i as createLazyRuntimeNamedExport, n as createLazyRuntimeMethodBinder, r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { b as registerOpenClawStateDatabaseAsyncResource, m as openClawStateDatabaseCache, x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { c as initializePublishedConfigRuntimeEnv, i as collectConfigRuntimeEnvOwnership, l as prepareConfigRuntimeEnv } from "./config-env-vars-ByeGN-9N.mjs";
import { n as withGatewayServiceInstallation, t as getGatewayServiceInstallation } from "./gateway-service-installation-context-CHlb7Eod.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { n as registerPluginMetadataProcessMemoLifecycleClear, r as retainGatewayPluginMetadata } from "./plugin-metadata-lifecycle-C9EqhiS5.mjs";
import { i as copyConfigResolutionFacts } from "./resolution-facts-xaIKuREs.mjs";
import { c as setGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { s as captureConfigOverrideApplier } from "./io.recovery-BpeT7cx2.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { i as hashConfigRaw } from "./io.read-helpers-qAcqsRC0.mjs";
import { p as assertOpenClawStateWriteAllowedAtPath } from "./openclaw-state-db-ARhwdPJg.mjs";
import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs";
import { a as sessionChangeScopeAffectsStoredRows, o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { E as setAppliedRuntimeConfigSnapshot, a as getRuntimeConfigSnapshot, c as getRuntimeConfigSourceSnapshot, h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { a as hasGatewayClientCap, l as normalizeGatewayClientName, n as GATEWAY_CLIENT_IDS, t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs";
import { c as onUserProfilesChanged, g as readUserProfileVersion, r as captureUserProfileModelAccountLinksAuthority } from "./user-profile-events-BhLFevt9.mjs";
import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { f as pluginInvocationContext, r as getPluginInstance } from "./plugin-instance-scope-oezVdCr2.mjs";
import { A as pluginHttpRouteChanges, a as createPluginRegistryOwner } from "./runtime-ezCEpumg.mjs";
import { o as listLoadedChannelPluginsForRegistry } from "./registry-loaded-NYWUyLLC.mjs";
import { a as READ_SCOPE, c as TALK_SCOPE, i as QUESTIONS_SCOPE, n as APPROVALS_SCOPE, o as SESSION_READ_SCOPE, r as PAIRING_SCOPE, t as ADMIN_SCOPE, u as WRITE_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { o as prepareRemoteModelCatalogStartupSnapshot } from "./remote-overlay-ifi3kxLn.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { n as assertGatewayConfigEnvSelectionUnchanged } from "./gateway-env-selection-yOcr26em.mjs";
import { c as readConfigFileSnapshotForRuntimeTransaction, i as promoteConfigSnapshotToLastKnownGood, u as readConfigFileSnapshotWithPluginMetadata, y as registerConfigWriteListener } from "./io.runtime-DsJ2dLCQ.mjs";
import "./io-4QsrsWTJ.mjs";
import { s as subscribeSecretStoreChanges } from "./secret-store-hidden-github-qvQ-BJHF.mjs";
import { i as purgeExpiredSecretStoreEntries, n as getSecretStoreExpiryDeadline } from "./secret-store-BZfjrX_2.mjs";
import { t as installGatewayDatabaseEngine } from "./server-database-engine-PSSSKs3N.mjs";
import { i as closePreparedModelRuntimeSnapshots } from "./prepared-model-runtime.lifecycle-zeMqOys6.mjs";
import { i as prepareGatewayAgentCliShim, t as clearGatewayAgentCliShim } from "./openclaw-cli-shim-spskOd_w.mjs";
import { t as ensureOpenClawCliOnPath } from "./path-env-BdB9UQFN.mjs";
import { d as isGatewayRestartDraining, i as beginGatewayShutdownCleanup, l as getGatewaySuspendAdmissionPhase, p as isGatewayWorkAdmissionClosed, w as runWithGatewayIndependentRootWorkAdmission } from "./gateway-work-admission-79pid1hQ.mjs";
import { _ as listAgentDatabaseAdmissionRefusals, i as canIsolateAgentDatabase } from "./agent-database-admission-CL6wHJ_N.mjs";
import { i as onInternalSessionTranscriptUpdate } from "./transcript-events-BHwlF03q.mjs";
import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs";
import { t as resolveSharedMainAuthAgentDir } from "./shared-main-dir-C2ynhf4g.mjs";
import { a as getActiveSecretsRuntimeConfigSnapshot, i as clearSecretsRuntimeSnapshotState } from "./runtime-state-Dq_fFDZp.mjs";
import { n as getAgentDatabaseStartupAdmission, t as AgentDatabaseStartupSupersededError } from "./agent-database-startup-C_V1xkCB.mjs";
import { t as isCoreCanvasHostEnabled } from "./config-7gJAwGAJ.mjs";
import { i as withCoreCanvasNodeCapability, n as isCanvasDocumentHttpPath, r as resolveCanvasNodeCapability } from "./constants-D5OpegQk.mjs";
import { t as adoptPluginHttpRouteHandoffs } from "./http-registry-BssL0T_Y.mjs";
import { t as extractAssistantPhaseText } from "./chat-message-content-DNUdbbJ8.mjs";
import { t as createAgentRuntimeApprovalAuthorityValidator } from "./agent-runtime-approval-authority-C0rhCYlf.mjs";
import { C as GatewayOperatorAccessUnavailableError } from "./admitted-run-context-D3Jvk_f_.mjs";
import { d as revokeAttachGrantsForSession, t as GatewayConnectionWork } from "./server-connection-work-BcD-l4Tl.mjs";
import { n as operatorScopeSatisfied } from "./operator-scope-compat-CpFHu-FC.mjs";
import { n as authorizeOperatorScopesForMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import { c as listCoreGatewayMethodNames, n as createCoreGatewayMethodDescriptors, r as isCoreGatewayMethodClassified, t as STARTUP_UNAVAILABLE_GATEWAY_METHODS } from "./core-method-policy-CcbxxGLc.mjs";
import { n as createGatewayMethodRegistry, t as createGatewayMethodDescriptorsFromHandlers } from "./registry-Dp_VYYNS.mjs";
import { t as isContainerEnvironment } from "./container-environment-BQP66a3c.mjs";
import { _ as resolveGatewayListenHosts, d as isTrustedProxyAddress, r as isLocalDirectRequest, s as isLoopbackHost } from "./net-BgRayX-P.mjs";
import { n as isBrowserOperatorUiClient } from "./message-channel-DTYVLJT1.mjs";
import { l as withSystemEventOwner } from "./system-event-ownership-zDxyv2EM.mjs";
import { i as publishSystemEventStoreConfig } from "./session-store-path-BIJyO4vM.mjs";
import { t as notifyGatewayWorkMetricsChanged } from "./gateway-work-metrics-events-DG6KfFxk.mjs";
import { l as enqueueSystemEvent } from "./system-events-BFJiZPP0.mjs";
import { t as createCronExecutionId } from "./run-id-Be9gQ-r9.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { g as resolveOperatorRolePolicyForProfile, r as authorizeGatewaySessionCreation, x as readGatewayAccessRevision } from "./operator-role-policy-DhcqVpmG.mjs";
import { r as onSessionIdentityMutation } from "./session-lifecycle-events-DWKmeEvQ.mjs";
import { c as resolveSystemMainSessionTarget } from "./main-session-BNL3-mRV.mjs";
import { o as runWithSessionActorStorage } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { t as flattenMarkdownToPlainText } from "./markdown-plain-text-B3XtgPwD.mjs";
import { _ as stripInternalRuntimeContext } from "./internal-runtime-context-BEUlDNuI.mjs";
import { s as resolveConfiguredAgentDatabaseTargets, t as isConfiguredAgentDatabaseTarget } from "./targets-BVE0__Jb.mjs";
import { u as sanitizeAssistantVisibleTextWithProfile } from "./assistant-visible-text-fPqh5m9O.mjs";
import { l as isTranscriptOnlyOpenClawAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs";
import { x as updateSessionProfileInvolvementAsync } from "./session-accessor-CizTbDQj.mjs";
import { t as memorySessionActorOwners } from "./session-actor-memory-owner-BkB9Vtu4.mjs";
import { i as decodeSandboxHostCsp, n as buildSandboxHostDocument, o as resolveSandboxHostPort, t as SANDBOX_HOST_PATH } from "./sandbox-host-C-9vv4vO.mjs";
import { t as warnSessionPersistenceDeprecation } from "./session-persistence-deprecation-B7LsOH2X.mjs";
import { t as beginSessionEffect } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { F as MAX_HUMAN_MENTIONS, I as MAX_MENTIONABLE_USERS, L as MENTION_INBOX_MAX_ITEMS } from "./logs-chat-C8_2M86E.mjs";
import { t as GATEWAY_RESTART_UNAVAILABLE_REASON } from "./restart-unavailable-CqvsgSBG.mjs";
import { o as resolveSessionEventAgentScope, r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { i as tryLoadActivatedBundledPluginPublicSurfaceModule } from "./facade-runtime-B7RI0rKM.mjs";
import { o as upsertPresence, r as listSystemPresence, t as commitPresence } from "./system-presence-Dj1W_mp4.mjs";
import { f as buildRateLimitIdentityKey, p as createGatewayAuthRateLimiter, s as AUTH_RATE_LIMIT_SCOPE_NODE_REAPPROVAL, u as AUTH_RATE_LIMIT_SCOPE_WORKER_ADMISSION } from "./auth-rate-limit-DGfPTrXr.mjs";
import { a as getRemoteControlUiIngressContext, c as prepareGatewayIngressAttribution, i as createGatewayUnattributableProxyReporter, n as PROXY_ATTRIBUTION_REQUIRED_REASON, r as assertRemoteControlUiIngressCurrent, s as markGatewayIngressTransport, t as PROXY_ATTRIBUTION_GUIDANCE, u as readPreparedGatewayIngressAttribution } from "./ingress-attribution-DAAQgd6y.mjs";
import { t as resolveGatewayPublicOrigin } from "./gateway-public-origin-SLjx6A2a.mjs";
import { a as resolveControlUiAllowedOrigins, n as ensureControlUiAllowedOriginsForNonLoopbackBind } from "./gateway-control-ui-origins-jPuz3g3d.mjs";
import { n as mergeGatewayAuthConfig, r as resolveGatewayAuth } from "./auth-resolve-C6_i-P4T.mjs";
import { r as authorizeHttpGatewayConnect } from "./auth-dV1bLOjr.mjs";
import { a as GATEWAY_EVENT_UPDATE_RUN_CHANGED, n as GATEWAY_EVENT_DEVICE_PAIR_CHANGED, r as GATEWAY_EVENT_NODE_RUNNER_INVENTORY_CHANGED, t as GATEWAY_EVENTS } from "./events-BxTs-VBE.mjs";
import { t as authenticatedProfileUnavailableError } from "./gateway-client-identity-BkzV3v8p.mjs";
import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs";
import { m as isSessionVisibilityAllowed, v as resolveSessionSharingTargetAsync, y as resolveSessionVisibility } from "./session-sharing-policy-3TAaxC-R.mjs";
import { n as runWithProcessCleanupBudget, t as getProcessCleanupBudget } from "./cleanup-budget-DzfwYwHL.mjs";
import { i as prepareTalkConnectionClose } from "./session-registry-WMICe7rH.mjs";
import { n as createProfileSessionEntryFilter, o as prepareProjectedSessionSharing, s as prepareSessionSharing, t as canReceiveSessionEvent } from "./session-sharing-read-BqjuH16A.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { n as prepareSessionSharingRead } from "./session-sharing-target-read-Gmjqaux8.mjs";
import { a as incrementPresenceVersion, c as createPresenceRecipientProjection, i as getPresenceVersion, o as refreshGatewayHealthSnapshot, r as getHealthVersion } from "./health-state-C4YLLrF7.mjs";
import { a as MAX_PREAUTH_PAYLOAD_BYTES, i as MAX_BUFFERED_BYTES } from "./server-constants-CYohpfLc.mjs";
import { i as onGatewayPolicyClientInvalidated } from "./ws-policy-close-Cspv0w92.mjs";
import { c as normalizePluginNodeCapabilityScopedUrl, d as reconcileClientPluginNodeCapabilities, o as indexPluginNodeCapabilitySurfaces } from "./plugin-node-capability-DIz0zxpb.mjs";
import { n as resolvePluginRoutePathContext, t as isProtectedPluginRoutePathFromContext } from "./path-context-7uf9WsoW.mjs";
import { t as findMatchingPluginHttpRoutes } from "./route-match-qEuQOF9X.mjs";
import { n as listPluginNodeCapabilities, t as findMatchingPluginNodeCapabilityRoute } from "./route-capability-BJpMXoa1.mjs";
import { t as SerializedGatewayFrame } from "./serialized-json-Ji3ULdJD.mjs";
import { n as invalidateSharedReadResponses } from "./shared-read-responses-DEdZ_cYp.mjs";
import { t as resolveGrantExpiryDaysConfig } from "./standing-grant-expiry-config-DuoF0kTN.mjs";
import { i as retireQuestionChannelGateway } from "./question-channel-runtime-9JTnl8rq.mjs";
import { i as closeGatewayDeviceRevocation } from "./device-revocation-Cbich35f.mjs";
import { t as shouldUseGatewayOwnerProfile } from "./gateway-owner-profile--usQDxAz.mjs";
import { t as deriveSessionTitle } from "./session-utils-core-GPDhMqaX.mjs";
import { n as createGatewayChatMetadataLifecycle, t as broadcastChatMetadataChanged } from "./server-chat-metadata-lifecycle-DyGY76_o.mjs";
import { d as runHttpConnectionRequest } from "./http-body-B9w7rzPz.mjs";
import { n as installActiveGitHubOAuthLifecycle, t as createGitHubOAuthLifecycle } from "./github-oauth-lifecycle-6AnTmFkw.mjs";
import { a as prepareWorktreeRunEndClose } from "./run-end-lifecycle-CvtGWdnp.mjs";
import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs";
import { n as startGitHubPublicationDiscovery } from "./github-publication-discovery-DgQJ4lzA.mjs";
import { h as closeAuthProfileUsage } from "./store-Bh2lUvOT.mjs";
import { a as listUserModelAccounts, d as readUserModelAccountSummary, h as setUserProfileAuthLink, o as listUserProfileAuthLinks, s as listUserProfileAuthLinksAsync, t as clearUserProfileAuthLink } from "./user-model-accounts-DdCvjiOp.mjs";
import { r as getPluginRuntimeLoadContext } from "./load-context-CwTU1iXB.mjs";
import { a as classifyMcpAppStandalonePath, c as classifyWorkerBootstrapArtifactTransferPath, i as classifyGatewayProbePath, l as classifyWorkerGatewayPath, o as classifyNodeWorkerBundleTransferPath, r as WORKER_BOOTSTRAP_ARTIFACT_TRANSFER_PATH, s as classifyNodeWorkspaceTransferPath } from "./gateway-http-route-contracts-DIOh6f_o.mjs";
import { a as isPreparedModelRuntimePluginLifecycleFailure } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import "./operator-access-policy-BWvd6twL.mjs";
import { a as resolveDiscoverableProviderOwnerPluginIds } from "./providers-B9AkUbSZ.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, s as ensureAuthProfileStoreWithoutExternalProfiles } from "./store-runtime-dW0pXLJI.mjs";
import { i as resolveManifestProviderAuthChoices } from "./provider-auth-choices-BfC_56hU.mjs";
import { t as runProviderPluginAuthMethodUnpersisted } from "./provider-auth-method-Bgbv8Sbe.mjs";
import { c as readUserModelAccountSummaryAsync, i as listUserModelAccountsAsync, l as setUserProfileAuthLinkAsync, n as connectUserModelAccountAsync, o as readSelectedUserModelAccountAsync, t as clearUserProfileAuthLinkAsync } from "./user-model-account-operations-DmkXXwRf.mjs";
import { n as sanitizeWizardStepForClient, t as WizardSession } from "./session-beMMG7GW.mjs";
import { r as queuePluginSessionsChanged } from "./gateway-events-vda1-yYc.mjs";
import { c as isCustomPluginUiEnabled, u as controlUiPluginAssetRoot } from "./control-ui-plugin-tabs-C_6CJE64.mjs";
import { n as resolveControlUiWebPushUrl, t as normalizeControlUiBasePath } from "./control-ui-shared-_tUmz6W8.mjs";
import { a as parseControlUiUserAvatarPath, i as parseControlUiResourcePath, o as resolveAssistantMediaRoutePath } from "./control-ui-resource-routes-DgXN5Axb.mjs";
import "./control-ui-contract-DTmt_Jww.mjs";
import { n as expectSessionAutomationSource } from "./session-automation-index-DBEXanrD.mjs";
import { t as resolveCurrentUserProfileDisplay } from "./current-user-profile-display-BvqB5fqy.mjs";
import { t as closeHttpServers } from "./http-server-lifecycle-DYMZqwqs.mjs";
import "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import { o as resolveAssistantAgentId } from "./assistant-avatar-DjDH3za_.mjs";
import { n as ConnectionSessionRows, t as prepareSessionEventProjection } from "./session-event-projection-C70IcEm0.mjs";
import { n as createVisibleActiveSessionRunProjector } from "./session-active-runs-ENHF8ERS.mjs";
import { t as attachSessionChangeEventLifetime } from "./session-change-event-DFgDuXAu.mjs";
import { n as readPreparedServerMethodModelCatalogs } from "./optional-model-catalog-D8GNpUVH.mjs";
import { r as prepareSandboxRegistryClose } from "./registry-lifecycle-DLOlVYoU.mjs";
import { r as fenceSessionSuspensionWritesForGatewayShutdown } from "./session-suspension-DpEUvu5N.mjs";
import "./command-queue-BenRlAaO.mjs";
import { t as createGatewayActiveWorkSnapshot } from "./gateway-active-work-2EmwaczJ.mjs";
import { a as markGatewaySuspendExiting, i as isGatewaySuspendControlAvailable } from "./gateway-suspend-coordinator-DwPh5h96.mjs";
import { d as startGatewayDiagnosticHeartbeat, f as stopGatewayDiagnosticHeartbeat } from "./diagnostic-C-GjPJGO.mjs";
import { i as roundDiagnosticMetric } from "./diagnostic-phase-B2sTxKxe.mjs";
import { o as resolveCronJobsStorePathFromConfigAsync } from "./paths-CY4cvrR6.mjs";
import { o as readDevicePairingNodeSnapshot } from "./device-pairing-store-readonly-CIEEZowO.mjs";
import { c as removeRemoteNodeInfoForConnection, i as recordRemoteNodeInfo, s as removeRemoteNodeInfo } from "./remote-BFNOi3gh.mjs";
import { f as requestNodePairing, p as reusePendingNodePairingForReconnect, r as finalizeNodePairingCleanupClaim } from "./device-pairing-node-CoZTLZY1.mjs";
import { t as createControlUiSessionPrRead } from "./control-ui-session-pr-read-DJu6I6Wb.mjs";
import { t as createControlUiSessionPullRequestSubscriptions } from "./control-ui-session-pr-subscriptions-Ck2vpW-r.mjs";
import { a as startNodeConnectionNotifications, o as retireDeviceTokenClients, r as projectHealthSummary, t as disconnectDisallowedGatewayPolicyClients } from "./ws-origin-policy-CWX73XV0.mjs";
import { f as publishHooksTokenEnvKey } from "./hooks-CCWUVSIu.mjs";
import { h as waitForNodeWorkerSupervisor } from "./node-registry-private-Bz6rjvDD.mjs";
import { i as clearNodeWakeState } from "./node-wake-state-i9g313wk.mjs";
import { f as resumeGatewayRestartTraceFromEnv, i as finishGatewayRestartTrace, n as collectGatewayProcessMemoryUsageMb, p as resumeGatewayRestartTraceFromHandoff, s as measureGatewayCloseStep } from "./restart-trace-B73rkxbv.mjs";
import { i as reconcileOrphanedMemoryDreamingJobs, n as applyGatewayLaneConcurrency, r as resolveGatewayLaneConcurrency, t as resolveHookClientIpConfig } from "./hook-client-ip-config-D5Ogoc6h.mjs";
import { r as waitForMediaCleanupDrains, t as MEDIA_CLEANUP_STOP_TIMEOUT_MS } from "./server-media-cleanup-lifecycle-CLvUNPN_.mjs";
import { t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import { c as runGatewayCloseSteps, o as resolveGatewayShutdownNotice, s as rethrowGatewayStartupError } from "./server-shutdown-BGFtNoiM.mjs";
import { n as createGatewayReadyAnnouncer, t as beginMacOSSystemCaWarmupOnce } from "./system-ca-warmup-BRKZBe1G.mjs";
import { t as recordClientPresenceActivity } from "./client-presence-CBSqWMVE.mjs";
import { r as registerGatewayModelCatalogPrivateAccess } from "./server-model-catalog-auth-DPSO0-N0.mjs";
import { t as createDefaultDeps } from "./deps-CeXkTZma.mjs";
import { i as loadOrCreateProcessDeviceIdentityAsync } from "./device-identity-async-B1EfjFkw.mjs";
import { n as loadGatewayTlsServerRuntime } from "./gateway-XogH1jHE.mjs";
import { r as createDesktopSessionRegistry } from "./session-registry-0QrwKuF4.mjs";
import { _ as webPushAgentAllowed, f as isWebPushQuietHours, m as normalizeWebPushDisplayLabel, v as webPushCategoryEnabled } from "./push-web-store.records-DmO63TGG.mjs";
import { r as prepareWebPushNotificationSender, s as hasBoundWebPushSubscriptions } from "./push-web-mW2cYpXA.mjs";
import { a as webPushTargetClient, i as webPushSessionAccess, n as prepareWebPushAgentIcon, o as withCurrentWebPushAuthority, r as listCurrentWebPushTargets, t as currentWebPushAgentIcon } from "./web-push-avatar-DRCFhXBk.mjs";
import { i as readUserProfileDirectory } from "./user-profile-reads-B8FZQ8ed.mjs";
import { r as resolveOperatorSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs";
import { n as MENTION_RETENTION_MS, r as getMentionStoreHeadAdmission, t as MAX_MENTION_SOURCES } from "./mention-inbox-store-YCmXh6N0.mjs";
import { n as logRejectedLargePayload } from "./diagnostic-payload-KWldAlR0.mjs";
import { r as preparePresenceDelivery, t as acceptsPresenceDeltas } from "./presence-delivery-B8RRk1pE.mjs";
import { t as isLiveTextAppend } from "./live-text-continuity-XF213psQ.mjs";
import { t as closeGatewayTransportWithGrace } from "./connection-transport-close-C7HyHuZq.mjs";
import { n as logWs, r as summarizeAgentEventForWsLog } from "./ws-log-CbOV6uhk.mjs";
import { a as createSessionMessageSubscriberRegistry, i as createSessionEventSubscriberRegistry, r as createChatRunState } from "./server-chat-state-hXRKEuCM.mjs";
import { i as respondPlainText, r as respondNotFound } from "./control-ui-http-utils-DH5C3tE0.mjs";
import { t as createGatewayControlUiRootLifecycle } from "./server-control-ui-root-DHOn05WY.mjs";
import { t as SharedGatewaySessionGenerationState } from "./server-shared-auth-generation-BosbfyX3.mjs";
import { t as isChannelStartupSuppressedByEnvironment } from "./server-sidecar-startup-mode-7oxoS28V.mjs";
import { r as createWizardSessionTracker } from "./server-wizard-sessions-COEvU-5i.mjs";
import { c as parseNativeCpuProfile, l as sanitizeDiagnosticProfileFrame, s as hasProfilerConflict } from "./diagnostic-profile-2SXDazNA.mjs";
import { n as DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS, r as evaluateChannelHealth, t as DEFAULT_CHANNEL_CONNECT_GRACE_MS } from "./channel-health-policy-Czg3cLcH.mjs";
import { t as resolveSharedGatewaySessionGeneration } from "./ws-shared-generation-BWsSp-Zl.mjs";
import { n as isRestartEnabled } from "./commands.flags-bgyYi4vf.mjs";
import { r as readGatewayRestartHandoff } from "./restart-handoff-Cby-pPDg.mjs";
import { d as setGatewayRestartPolicy, f as setPreRestartDeferralCheck } from "./restart-LzysM26p.mjs";
import { n as resolveGatewayReloadPluginActivationCandidate, t as mergeActivationSectionsIntoRuntimeConfig } from "./plugin-activation-runtime-config-CqOZTBHN.mjs";
import { t as resolveGatewayStartupSourceConfig } from "./server-startup-secret-surfaces-Dwoc7qgm.mjs";
import { t as createGatewayStartupTrace } from "./server-startup-trace-CsogKICW.mjs";
import { n as WebSocketServer } from "./websocket-CGHaToS5.mjs";
import { s as readTailscaleWhoisIdentity } from "./tailscale-6NHccc09.mjs";
import { t as rejectWebSocketUpgrade } from "./websocket-upgrade-reject-DmyU-6p3.mjs";
import { i as listenGatewayHttpServer, t as createGatewayPortalService } from "./portal-service-X1hWO5QI.mjs";
import { t as bindGatewayControlUiIngressHost } from "./remote-control-ui-ingress-host-DcGokR4Q.mjs";
import { r as NODE_PORTAL_ATTACH_PATH, t as NODE_DESKTOP_ATTACH_PATH } from "./node-desktop-stream-BZM2AiRA.mjs";
import { a as runWithGatewayHttpWorkAdmission, i as rejectGatewayUpgradeServiceUnavailable, r as shouldEnforceGatewayAuthForPluginPath, t as isPluginAuthenticatedRoutePath } from "./route-auth-CcifwYUn.mjs";
import { i as markPublicWorkerIngress, t as GATEWAY_WS_CONNECTION_KIND_PROPERTY } from "./ws-types-BpZoXr07.mjs";
import { t as ARTIFACT_DOWNLOAD_PATH } from "./artifact-download-CXaDlLGk.mjs";
import { n as parseDevicePairingJoinRequestPath } from "./join-code-zMzzNXYS.mjs";
import { r as markPluginHttpLegacyListener, t as getWebhookLegacyListener } from "./http-legacy-listener-Cujc9G0x.mjs";
import { n as NODE_WORKER_BUNDLE_TRANSFER_PATH } from "./node-bundle-install-protocol-BtZLgZMr.mjs";
import { t as parseControlUiUserBackgroundPath } from "./control-ui-user-background-route-CHvXWjlI.mjs";
import { n as isControlUiApprovalDocumentPath, r as isControlUiPluginManagerRequest, t as classifyControlUiRequest } from "./control-ui-routing-X6jysl9I.mjs";
import { t as parseControlUiSessionPath } from "./parse-Byrz2Lb6.mjs";
import { a as parseControlUiPublicSessionShareUrl, i as parseControlUiPublicSessionCardUrl, n as buildControlUiPublicSessionCardPath, r as buildControlUiPublicSessionSharePath } from "./public-share-B-H7sO_M.mjs";
import { t as buildPublicSessionMediaBaseUrl } from "./control-ui-public-session-attachments-DauqtHb5.mjs";
import { t as isSecurePublicSessionIngress } from "./control-ui-public-session-ingress-BMb0UKvP.mjs";
import { n as controlUiSessionEntryPath } from "./control-ui-session-entry-path-DeICmSyS.mjs";
import { n as resolveControlUiShareOrigin, t as isControlUiSharePath } from "./control-ui-share-V2WSYnX0.mjs";
import { t as isTerminalConfigEnabled } from "./enabled-B07Lihbx.mjs";
import { g as setDefaultSecurityHeaders, i as isWebSocketUpgradeRequest, l as sendGatewayAuthFailure, n as finishFailedGatewayHttpResponse, r as finishGatewayHttpDatabaseAdmissionError } from "./http-common-FfhIIwOW.mjs";
import { a as finishGatewayHttpAuthorityError, o as runGatewayHttpRequest } from "./http-request-authority-CYXIvBHo.mjs";
import { a as handleProviderOAuthCallback, t as PROVIDER_OAUTH_CALLBACK_PATH } from "./provider-browser-auth-CczEsRoa.mjs";
import { t as resolveRemoteControlUiHttpRoute } from "./remote-control-ui-http-routing-CDY2U6yG.mjs";
import { r as getGatewayRecentCrashes } from "./gateway-crash-D22VnCOp.mjs";
import { n as handleArtifactTransferHttpRequest } from "./artifact-transfer-http-B3zgn06S.mjs";
import { n as handleNodeWorkspaceTransferHttpRequest } from "./node-workspace-transfer-http-COEgqKt8.mjs";
import { t as GATEWAY_PER_MESSAGE_DEFLATE } from "./ws-compression-BlKVWwRd.mjs";
import { r as listConfigReloadRefinementPrefixes, s as diffGatewayReloadPaths, t as buildGatewayReloadPlan } from "./config-reload-plan-BWeZCeX8.mjs";
import { t as clearGatewayMaintenanceHandles } from "./server-maintenance-lifecycle-DU9m0X5h.mjs";
import { n as refreshConnectedNodeSurfaceCaches } from "./nodes.read-DYMngc6W.mjs";
import { t as assertGatewayRuntimeSecurityConfig } from "./server-runtime-config-CG0ZvhCy.mjs";
import { t as collectGatewayWorkerPoolMetrics } from "./process-vitals-dDZiP3Lo.mjs";
import { n as DEFAULT_TERMINAL_DETACH_SECONDS } from "./session-limits-BqiIRDwa.mjs";
import { closeSync, openSync, readFileSync, readSync, unwatchFile, watchFile } from "node:fs";
import { versions } from "node:process";
import { createHash, randomUUID } from "node:crypto";
import { cpus } from "node:os";
import { Worker, isMainThread } from "node:worker_threads";
import * as v8 from "node:v8";
import { AsyncLocalStorage } from "node:async_hooks";
import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
import { isDeepStrictEqual } from "node:util";
import { isProxy } from "node:util/types";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
import { TLSSocket } from "node:tls";
import { createServer as createServer$1 } from "node:http";
import { Server, createServer as createServer$2 } from "node:https";
//#region src/gateway/server-core-runtime.ts
function approvalRequestTargetsSession(e, t, n) {
if (typeof e !== "object" || e === null) return false;
const r = e;
return typeof r.sessionId === "string" && r.sessionId === n || typeof r.sessionKey === "string" && t.has(r.sessionKey);
}
async function startGatewayCoreRuntime(e) {
const { lifecycleRuntime: t, port: n, log: r, logDiscovery: i, logHealth: a, logChannels: o, loadGatewayModelCatalog: s, loadGatewayModelCatalogSnapshot: c, readPreparedGatewayModelCatalog: l, readPreparedGatewayModelCatalogBatch: u } = e;
const { minimalTestGateway: d, cfgAtStart: f, gatewayTls: p, bindHost: m, tailscaleMode: h, nodeRegistry: g, pluginRuntime: _, broadcast: v, nodeSendToAllSubscribed: y, refreshGatewayHealthSnapshotWithRuntime: b, dedupe: x, chatRunState: S, removeChatRun: C, agentRunSeq: w, nodeHasSessionSubscribers: T, nodeSendToSession: E, runtimeState: D, kernel: O, startupTrace: k, channelManager: A, readinessEventLoopHealth: j, workerDispatchAuthority: M, clients: N, sharedGatewaySessionGenerationState: P, resolveSharedGatewaySessionGenerationForConfig: F, sessionMessageSubscribers: I, sessionEventSubscribers: L, toolEventRecipients: R, broadcastToConnIds: z, controlUiBasePath: B, workerEnvironmentService: V, workerPlacementControlAvailable: H, desktopSessionRegistry: U, gatewayComputerService: W, listStartupChannelGatewayMethods: G, workerEnvironmentStartup: K, activateRuntimeSecrets: q } = t;
t.registerGatewayLifetimeSidecars({
name: "computer-and-desktop-sessions",
preparePluginReload: W.preparePluginReload,
stop: async () => {
await W.close();
await U.stopAll();
}
});
const J = f.secrets?.egressProxy?.enabled === true ? await import("./runtime-ClzVh8ge.mjs").then((e) => e.startGatewaySecretEgressProxy({
...f.secrets?.egressProxy?.allowedHosts !== void 0 ? { allowedHosts: f.secrets.egressProxy.allowedHosts } : {},
...f.secrets?.egressProxy?.bypassHosts ? { bypassHosts: f.secrets.egressProxy.bypassHosts } : {}
})) : void 0;
if (J) t.registerGatewayLifetimeSidecars({
name: "secret-egress-proxy",
...J
});
const sendNodeSessionEvent = (e, t, n, r) => {
E(e, t, n, r);
};
let Y;
const startEarlyRuntime = () => Y ??= k.measure("runtime.early", () => import("./server-startup-early-OjkDAox8.mjs").then(({ startGatewayEarlyRuntime: e }) => e({
scheduler: t.scheduler,
getCronStorePath: () => D.cronState.storePath,
minimalTestGateway: d,
isClosing: () => t.lifecycle.closePreludeStarted,
updateCanary: t.opts.updateCanary,
cfgAtStart: f,
port: n,
gatewayTls: p,
gatewayDirectReachable: !isLoopbackHost(m),
tailscaleMode: h,
log: r,
logDiscovery: i,
nodeRegistry: g,
swapDiscovery: O.swapDiscovery,
pluginRegistry: _.registry,
getPluginMetadataSnapshot: () => t.pluginMetadataSnapshot,
broadcast: v,
maintenance: {
nodeSendToAllSubscribed: y,
getPresenceVersion,
getHealthVersion,
refreshGatewayHealthSnapshot: b,
channelManager: A,
refreshPresence: t.publishPresence,
resetEventLoopHealth: j.reset,
logHealth: a,
clients: N,
dedupe: x,
chatRunState: S,
removeChatRun: C,
agentRunSeq: w,
nodeSendToSession: sendNodeSessionEvent
},
getRuntimeConfig: readRuntimeConfig,
startupTrace: k
}))).then((e) => {
O.setEarlyRuntimeHandles(e);
return e;
});
const [{ startGatewayEventSubscriptions: ee }, { startGatewayChannelHealthMonitor: X }] = await k.measure("runtime.post-early-imports", () => Promise.all([import("./server-runtime-subscriptions-Dy22-VAS.mjs"), import("./server-runtime-startup-services-DhGHAMHn.mjs")]));
const { sessionCompanion: te, sessionObserver: ne, sessionActivitySummaries: re, channelAdmissionAudit: ie, ...ae } = await k.measure("runtime.subscriptions", () => ee({
resolveGatewayContext: t.resolvePluginGatewayContext,
scheduler: t.scheduler,
signal: t.connectionWork.signal,
getSessionRowProjection: t.getSessionRowProjection,
log: r,
broadcast: v,
broadcastToConnIds: z,
nodeHasSessionSubscribers: T,
nodeSendToSession: sendNodeSessionEvent,
agentRunSeq: w,
chatRunState: S,
toolEventRecipients: R,
sessionEventSubscribers: L,
sessionMessageSubscribers: I,
refreshConnectedUserProfiles: () => t.resolvePluginGatewayContext()?.refreshConnectedUserProfile?.()
}));
Object.assign(D, ae);
await k.measure("runtime.services", () => O.setChannelHealthMonitor(X({
channelManager: A,
scheduler: t.scheduler
})));
const { createOperatorApprovalSessionEventRuntime: oe } = await import("./operator-approval-session-events-ByoV5Gje.mjs");
const Z = /* @__PURE__ */ new Map();
const Q = oe({
clients: N,
sessionMessageSubscribers: I,
broadcastToConnIds: z,
controlUiBasePath: B,
reconcileTerminal: (e) => {
return Z.get(e.kind)?.reconcileDurableTerminal(e) ?? false;
},
getLiveManager: (e) => Z.get(e),
isCurrent: () => !t.connectionWork.signal.aborted
});
const se = createAgentRuntimeApprovalAuthorityValidator(K?.placementStore);
const { beginCloseApprovalObservers: ce, stopOperatorInteractions: le, extraHandlers: $, coreGatewayHandlers: ue, ...de } = await k.measure("gateway.handlers", async () => {
const [{ createGatewayAuxHandlers: e }, { coreGatewayHandlers: n }] = await Promise.all([import("./server-aux-handlers-Dq3lfkqK.mjs"), import("./server-methods-8SJxE8_X.mjs")]);
return {
...e({
scheduler: t.scheduler,
log: r,
hasRunAbortMarker: (e) => S.hasAbortMarker(e),
getNativeApprovalRouteCoordinator: () => t.gatewayInstanceRuntimeRef.current?.nativeApprovals.routeCoordinator,
resolveGrantDefaultExpiresAtMs: (e) => {
const t = resolveGrantExpiryDaysConfig(readRuntimeConfig());
return t !== null ? e + t * 864e5 : null;
},
activateRuntimeSecrets: q,
sharedGatewaySessionGenerationState: P,
resolveSharedGatewaySessionGenerationForConfig: F,
clients: N,
channelManager: A,
getChannelAutostartSuppression: A.getAutostartSuppression,
logChannels: o,
registerWorkerTurnClaimClosedHandler: K?.placementStore ? (e) => K.placementStore.registerTurnClaimClosedHandler(e) : void 0,
validateAgentRuntimeDelegatedAuthority: (e) => se({
kind: "agentRuntime",
agentId: "approval-manager",
sessionKey: "approval-manager",
operationalRunInstance: e.operationalRunInstance,
delegatedAuthority: e
}),
onApprovalLifecycle: Q.publish,
onAgentRunAuthorityClosed: (e) => {
W.revokeRunAuthority(e);
}
}),
coreGatewayHandlers: n
};
});
const { execApprovalManager: fe, pluginApprovalManager: pe, systemAgentApprovalManager: me } = de;
const he = t.connectionWork.signal;
he.addEventListener("abort", ce, { once: true });
if (he.aborted) ce();
t.registerGatewayLifetimeSidecars({
name: "operator-interactions",
stop: async () => {
he.removeEventListener("abort", ce);
await le();
}
});
await de.ready;
Z.set("exec", fe);
Z.set("plugin", pe);
Z.set("system-agent", me);
M.revoke = ({ sessionId: e, sessionKeys: t }) => {
const n = new Set(t);
for (const e of n) revokeAttachGrantsForSession(e);
const i = {
kind: "system",
id: "worker-dispatch"
};
for (const t of [fe, pe]) for (const a of t.listLocalPendingRecords()) if (approvalRequestTargetsSession(a.request, n, e)) t.forceDenyDetailed(a.id, "run-aborted", i, "cancelled").catch((e) => {
r.error(`approval dispatch-fence settlement failed: ${String(e)}`);
});
};
const ge = {
..._.registry.gatewayHandlers,
...$
};
let _e = new Set(Object.keys(_.registry.gatewayHandlers));
const buildAttachedGatewayMethodRegistry = (e) => {
const t = { ...ue };
const n = {};
for (const [e, r] of Object.entries($)) if (isCoreGatewayMethodClassified(e)) t[e] = r;
else n[e] = r;
const r = createCoreGatewayMethodDescriptors(t).filter((e) => (V || e.name !== "environments.create" && e.name !== "environments.destroy" && !e.name.startsWith("environments.session.")) && (H || e.name !== "sessions.dispatch") && (H || e.name !== "sessions.reclaim" && e.name !== "sessions.move") && (V || e.name !== "desktop.launch" && e.name !== "worker.desktop.observe" && e.name !== "worker.desktop.launch"));
return createGatewayMethodRegistry([
...r,
...e.gatewayMethodDescriptors,
...createGatewayMethodDescriptorsFromHandlers({
handlers: n,
owner: {
kind: "aux",
area: "gateway-extra"
},
defaultScope: ADMIN_SCOPE
})
], e);
};
let ve = buildAttachedGatewayMethodRegistry(_.registry);
const listAttachedGatewayMethods = () => {
const e = ve.listAdvertisedMethods();
e.push(...G());
return uniqueStrings(e);
};
O.publishMethodSurface(listAttachedGatewayMethods());
const getPluginNodeCapabilities = () => withCoreCanvasNodeCapability(listPluginNodeCapabilities(_.registry), isCoreCanvasHostEnabled(readRuntimeConfig()));
const prepareAttachedPluginRuntime = async (e, n) => {
const { activatePluginRegistry: r } = await import("./loader-shared-GHYZmbCN.mjs");
const i = buildAttachedGatewayMethodRegistry(e.pluginRegistry);
const a = uniqueStrings([...i.listAdvertisedMethods(), ...G(e.pluginRegistry)]);
const o = new Set(Object.keys(e.pluginRegistry.gatewayHandlers));
return {
publish: () => {
adoptPluginHttpRouteHandoffs(_.registry, e.pluginRegistry);
r(e.pluginRegistry, null, "gateway-bindable", t.pluginWorkspaceDir, _.registry, n);
_.publish(e.pluginRegistry);
_.baseGatewayMethods = e.gatewayMethods;
for (const e of _e) delete ge[e];
Object.assign(ge, e.pluginRegistry.gatewayHandlers);
_e = o;
ve = i;
invalidateSharedReadResponses(v);
O.publishMethodSurface(a);
},
afterCommit: () => {
g.refreshRuntimePolicy();
}
};
};
const refreshAttachedGatewayDiscovery = async (e) => {
if (d) return;
try {
await D.discovery?.update({ gatewayDiscoveryServices: e.gatewayDiscoveryServices });
} catch (e) {
i.warn(`gateway discovery refresh failed after plugin load: ${String(e)}`);
}
};
const reloadAttachedGatewayPlugins = async (e) => {
const { reloadGatewayPlugins: i } = await import("./server-plugin-reload-Dsy-m98A.mjs");
return i({
runtime: t,
port: n,
log: r,
loadGatewayPluginBootstrapModule: () => import("./server-plugin-bootstrap-BOnSKxcv.mjs"),
prepareAttachedPluginRuntime
}, e);
};
return {
...t,
kernel: {
...O,
reloadPlugins: reloadAttachedGatewayPlugins
},
startEarlyRuntime,
sessionCompanion: te,
sessionObserver: ne,
sessionActivitySummaries: re,
channelAdmissionAudit: ie,
approvalSessionEvents: Q,
...de,
validateAgentRuntimeApprovalAuthority: se,
attachedGatewayExtraHandlers: ge,
getAttachedGatewayMethodRegistry: () => ve,
getPluginNodeCapabilities,
prepareAttachedPluginRuntime,
refreshAttachedGatewayDiscovery,
loadGatewayModelCatalog: s,
loadGatewayModelCatalogSnapshot: c,
readPreparedGatewayModelCatalog: l,
readPreparedGatewayModelCatalogBatch: u,
getPluginMetadataSnapshot: () => t.pluginMetadataSnapshot
};
}
//#endregion
//#region src/plugins/compat/model-account-connect-deprecation.ts
function warnModelAccountConnectDeprecation(e) {
const t = pluginInstanceInvocation.getStore()?.instance.pluginId;
warnSessionPersistenceDeprecation(`modelAccountConnectService.${e}`, `modelAccountConnectService.${e}Async`, {
pluginId: t,
family: "model-account-connect"
});
}
//#endregion
//#region src/plugins/personal-account-auth.ts
/** Personal auth is opt-in; discovery never enables, installs, or imports host credentials. */
function listPersonalAccountAuthChoices(e) {
const t = resolvePluginMetadataSnapshot({ config: e });
const n = resolveManifestProviderAuthChoices({
config: e,
metadataSnapshot: t,
includeUntrustedWorkspacePlugins: false
}).filter((e) => e.personalAccount);
const r = new Set(resolveDiscoverableProviderOwnerPluginIds({
config: e,
pluginIds: n.map((e) => e.pluginId),
registry: t.index,
manifestRegistry: t.manifestRegistry,
normalizePluginId: t.normalizePluginId,
includeUntrustedWorkspacePlugins: false
}));
return n.filter((e) => r.has(e.pluginId));
}
async function resolvePersonalAccountAuthMethod(e, t, n) {
const r = listPersonalAccountAuthChoices(e).find((e) => e.providerId === t && e.methodId === n);
if (!r) return;
const { resolvePluginProvidersCore: i } = await import("./providers.runtime.js");
return i({
config: e,
onlyPluginIds: [r.pluginId],
mode: "setup",
cache: true,
activate: false,
includeUntrustedWorkspacePlugins: false
}).find((e) => e.pluginId === r.pluginId && e.id === t)?.auth.find((e) => e.id === n);
}
//#endregion
//#region src/gateway/model-account-connect.ts
const CONNECT_TTL_MS = 9e5;
const MAX_ACTIVE_CONNECTS = 8;
const MAX_RETAINED_CONNECTS = 64;
function matchesLiteralCredential(e, t) {
if (e.provider !== t.provider) return false;
return e.type === "api_key" && t.type === "api_key" ? e.key === t.key : e.type === "token" && t.type === "token" && e.token === t.token;
}
async function resolveOwnedAccountProvider(e, t, n) {
return requireOwnedAccountProvider(await readUserModelAccountSummaryAsync({
profileId: e,
authProfileId: t
}, { context: n }));
}
function requireOwnedAccountProvider(e) {
if (!e) throw new ModelAccountConnectInputError("Select an account from your personal account list, or add it first.");
return e.provider;
}
async function resolveLinkableAuthProfileProvider(e, t, n, r) {
if (isUserModelAuthProfileId(n)) return resolveOwnedAccountProvider(t, n, r);
return (await ensureAuthProfileStoreWithoutExternalProfilesAsync(resolveSharedMainAuthAgentDir(), { readOnly: true })).profiles[n]?.provider ?? e.auth?.profiles?.[n]?.provider;
}
function resolveSharedAuthProfileProvider(e, t) {
return ensureAuthProfileStoreWithoutExternalProfiles(resolveSharedMainAuthAgentDir(), { readOnly: true }).profiles[t]?.provider ?? e.auth?.profiles?.[t]?.provider;
}
function requireLinkableProvider(e, t) {
if (!e) throw new ModelAccountConnectInputError(`unknown auth profile "${t}"; sign the account in first with "openclaw models auth login --provider <id> --profile-id ${t}", then link it`);
return e;
}
/** One Gateway lifetime owns sign-in steps and authority; provider methods only stage credentials. */
function createModelAccountConnectService(e) {
const t = /* @__PURE__ */ new Map();
let n = false;
const r = /* @__PURE__ */ new Set();
let i = Promise.resolve();
const retainWrite = (e) => {
const t = runOutsideAsyncWorkScope(() => i.then(e));
i = t.catch(() => {});
r.add(t);
t.finally(() => r.delete(t)).catch(() => {});
return t;
};
const finish = (e, t) => {
if (e.terminal && t.status !== "connected") return e.terminal;
e.terminal = t;
clearTimeout(e.timeout);
e.session?.cancel();
return t;
};
const snapshot = (e, t) => {
if (e.terminal) return e.terminal;
if (e.expiresAtMs <= Date.now()) return finish(e, { status: "expired" });
try {
e.action.assertCurrent(t);
e.answerAction?.assertCurrent(t);
} catch {
return finish(e, {
status: "failed",
reason: "authority"
});
}
};
const assertRunning = (e) => {
if (n) throw new ModelAccountConnectAuthorityError();
e.assertCurrent();
};
const assertLive = (e, r) => {
if (n && !e.settlement || t.get(e.id) !== e || snapshot(e, r)) throw new ModelAccountConnectAuthorityError();
};
const resultSnapshot = (e) => {
const t = snapshot(e);
if (!t) {
const t = e.session?.getCurrentStep();
return {
status: "pending",
...t ? { step: sanitizeWizardStepForClient(t) } : {}
};
}
return t;
};
const projectResult = (e, t) => {
const n = resultSnapshot(t);
if (n.status !== "connected") return n;
assertRunning(e);
return {
...n,
links: listUserProfileAuthLinks(t.owner)
};
};
const projectResultAsync = async (e, t) => {
const n = resultSnapshot(t);
if (n.status !== "connected") return n;
assertRunning(e);
const r = await listUserProfileAuthLinksAsync(t.owner);
assertRunning(e);
return {
...n,
links: r
};
};
const findOperation = (e, n) => {
assertRunning(e);
const r = t.get(n);
return r?.owner === e.owner ? r : void 0;
};
const supersede = (e, n, r = t.values()) => {
for (const t of r) if (t.owner === e && t.provider === n) finish(t, { status: "cancelled" });
};
const changeLink = async (n, r, i) => {
assertRunning(n);
const a = captureOpenClawStateWorkerContext();
const o = [...t.values()];
return retainWrite(async () => {
const t = r === "unlink" ? i : r === "select" ? await resolveOwnedAccountProvider(n.owner, i, a) : requireLinkableProvider(await resolveLinkableAuthProfileProvider(e.getConfig(), n.owner, i, a), i);
if (r !== "unlink") n.assertCurrent();
const s = {
profileId: n.owner,
provider: t,
authorityProfileIds: n.actorProfileId ? [n.actorProfileId] : [],
assertCurrent: n.assertCurrent
};
const c = r !== "unlink" ? await setUserProfileAuthLinkAsync({
...s,
authProfileId: i
}, { context: a }) : await clearUserProfileAuthLinkAsync(s, { context: a });
supersede(n.owner, t, o);
e.onChanged?.();
n.assertCurrent();
return { links: c };
});
};
const setLinkNative = (t, n, r) => {
const i = setUserProfileAuthLink({
profileId: t.owner,
provider: n,
authProfileId: r,
assertCurrent: () => assertRunning(t)
});
supersede(t.owner, n);
e.onChanged?.();
return { links: i };
};
const cancelOperation = (e, t) => {
const n = findOperation(e, t);
if (n) {
snapshot(n);
finish(n, { status: "cancelled" });
}
return n;
};
const beginClose = () => {
n = true;
for (const e of t.values()) if (e.settlement) e.session?.cancel();
else finish(e, { status: "cancelled" });
};
return {
/** @deprecated Await listLinksAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
listLinks(e) {
warnModelAccountConnectDeprecation("listLinks");
assertRunning(e);
return { links: listUserProfileAuthLinks(e.owner) };
},
/** @deprecated Await linkAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
link(t, n) {
warnModelAccountConnectDeprecation("link");
assertRunning(t);
const r = isUserModelAuthProfileId(n) ? requireOwnedAccountProvider(readUserModelAccountSummary({
profileId: t.owner,
authProfileId: n
})) : resolveSharedAuthProfileProvider(e.getConfig(), n);
return setLinkNative(t, requireLinkableProvider(r, n), n);
},
/** @deprecated Await unlinkAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
unlink(t, n) {
warnModelAccountConnectDeprecation("unlink");
assertRunning(t);
const r = clearUserProfileAuthLink({
profileId: t.owner,
provider: n,
assertCurrent: () => assertRunning(t)
});
supersede(t.owner, n);
e.onChanged?.();
return { links: r };
},
/** @deprecated Await listAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
list(e, t) {
warnModelAccountConnectDeprecation("list");
assertRunning(e);
return {
profileId: e.owner,
...listUserModelAccounts({
profileId: e.owner,
cursor: t
}),
links: listUserProfileAuthLinks(e.owner)
};
},
/** @deprecated Await selectAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
select(e, t) {
warnModelAccountConnectDeprecation("select");
assertRunning(e);
return setLinkNative(e, requireOwnedAccountProvider(readUserModelAccountSummary({
profileId: e.owner,
authProfileId: t
})), t);
},
/** @deprecated Await statusAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
status(e, t) {
warnModelAccountConnectDeprecation("status");
const n = findOperation(e, t);
return n ? projectResult(e, n) : { status: "expired" };
},
/** @deprecated Await cancelAsync; final compatibility day: 2026-12-31; removal in the first January 2027 stable release. */
cancel(e, t) {
warnModelAccountConnectDeprecation("cancel");
const n = cancelOperation(e, t);
return n ? projectResult(e, n) : { status: "expired" };
},
async listLinksAsync(e) {
assertRunning(e);
const t = await listUserProfileAuthLinksAsync(e.owner);
assertRunning(e);
return { links: t };
},
async linkAsync(e, t) {
return changeLink(e, "link", t);
},
unlinkAsync(e, t) {
return changeLink(e, "unlink", t);
},
async listAsync(e, t) {
assertRunning(e);
const n = captureOpenClawStateWorkerContext();
const r = captureUserProfileModelAccountLinksAuthority(n.admission, e.owner);
const i = await listUserModelAccountsAsync({
profileId: e.owner,
cursor: t
}, { context: n });
const a = await listUserProfileAuthLinksAsync(e.owner, { context: n });
assertRunning(e);
if (!r()) throw new Error("Personal account selection changed while listing accounts; retry the request.");
return {
profileId: e.owner,
...i,
links: a
};
},
catalog(t) {
assertRunning(t);
const n = /* @__PURE__ */ new Map();
for (const t of listPersonalAccountAuthChoices(e.getConfig())) {
let e = n.get(t.providerId);
if (!e) {
e = {
id: t.providerId,
label: t.groupLabel ?? t.providerId,
methods: []
};
n.set(t.providerId, e);
}
if (!e.methods.some((e) => e.id === t.methodId)) e.methods.push({
id: t.methodId,
label: t.choiceLabel,
...t.choiceHint ? { hint: t.choiceHint } : {}
});
}
assertRunning(t);
return { providers: [...n.values()] };
},
async selectAsync(e, t) {
return changeLink(e, "select", t);
},
async start(n, r, i) {
assertRunning(n);
const a = captureOpenClawStateWorkerContext();
for (const e of t.values()) snapshot(e);
supersede(n.owner, r);
if ([...t.values()].filter((e) => !e.terminal).length >= MAX_ACTIVE_CONNECTS) throw new Error("Too many model-account sign-ins are in progress; try again shortly.");
for (const [e, n] of t) {
if (t.size < MAX_RETAINED_CONNECTS) break;
if (n.terminal) t.delete(e);
}
const o = randomUUID();
const s = {
id: o,
owner: n.owner,
provider: r,
action: n,
expiresAtMs: Date.now() + CONNECT_TTL_MS,
timeout: setTimeout(() => finish(s, { status: "expired" }), CONNECT_TTL_MS)
};
s.timeout.unref();
t.set(o, s);
let c;
try {
c = await resolvePersonalAccountAuthMethod(e.getConfig(), r, i);
assertLive(s);
if (!c) throw new ModelAccountConnectInputError("This sign-in method is unavailable for personal accounts. Choose a method from Connected accounts.");
} catch (e) {
snapshot(s);
finish(s, {
status: "failed",
reason: "unavailable"
});
throw e;
}
const l = c;
s.session = new WizardSession(async (t, n) => {
await Promise.resolve();
let i = "exchange";
try {
assertLive(s);
const o = await readSelectedUserModelAccountAsync(s.owner, r, { context: a });
assertLive(s);
const c = await runProviderPluginAuthMethodUnpersisted({
config: {},
env: {},
existingProfiles: o ? [{
profileId: o.id,
credential: o.credential
}] : [],
method: l,
prompter: t,
signal: n,
assertCurrent: () => assertLive(s),
isRemote: true,
secretInputMode: "plaintext",
allowSecretRefPrompt: false,
runtime: {
log: () => {},
error: () => {},
exit: () => {
throw new Error("Provider sign-in stopped.");
}
}
});
assertLive(s);
const u = c.profiles[0];
if (c.profiles.length !== 1 || !u || u.credential.provider !== r || u.secretStorage) {
finish(s, {
status: "failed",
reason: "identity"
});
return;
}
i = "unavailable";
s.settlement = retainWrite(async () => {
const t = await connectUserModelAccountAsync({
ownerProfileId: s.owner,
credential: u.credential,
matchesCredential: (e) => (l.matchesPersonalAccount ?? matchesLiteralCredential)(u.credential, e),
authorityProfileIds: [...new Set([s.action, s.answerAction].flatMap((e) => e?.actorProfileId ? [e.actorProfileId] : []))],
assertCurrent: (e) => assertLive(s, e)
}, { context: a });
finish(s, {
status: "connected",
authProfileId: t.authProfileId
});
e.onChanged?.();
});
await s.settlement;
} catch {
snapshot(s);
finish(s, {
status: "failed",
reason: i
});
}
});
return {
connectId: o,
expiresAtMs: s.expiresAtMs
};
},
async statusAsync(e, t) {
const n = findOperation(e, t);
return n ? projectResultAsync(e, n) : { status: "expired" };
},
async answer(e, t, n, r) {
const i = findOperation(e, t);
if (!i) return { status: "expired" };
if (snapshot(i)) return projectResultAsync(e, i);
const a = i.session?.getCurrentStep();
if (!i.session || a?.id !== n || a.type === "progress") {
const t = await projectResultAsync(e, i);
return t.status === "pending" ? {
...t,
error: "This step has changed. Follow the current sign-in instructions."
} : t;
}
if (a.sensitive && typeof r === "string") registerSecretValueForRedaction(r);
i.answerAction = e;
const o = await i.session.answer(n, r);
assertRunning(e);
const s = await projectResultAsync(e, i);
if (o && s.status === "pending" && s.step?.id === n) return {
...s,
error: "That answer is not valid. Check the sign-in instructions and try again."
};
return s;
},
async cancelAsync(e, t) {
const n = cancelOperation(e, t);
return n ? projectResultAsync(e, n) : { status: "expired" };
},
supersede: (e, t) => supersede(e, t),
async stop() {
beginClose();
await Promise.allSettled(r);
t.clear();
}
};
}
//#endregion
//#region src/gateway/session-incognito-lifetime.ts
const CLEANUP_RETRY_MS = 6e4;
/** Deadlines come from committed actor state; deletion owns transport and session cleanup. */
function startIncognitoActorSessionLifetime(e) {
const { owner: t } = e;
const n = e.scheduler.scope();
const r = {
assertCurrent() {},
authorize() {}
};
const i = /* @__PURE__ */ new Map();
let a = true;
const forget = (e) => {
i.get(e)?.job?.cancel();
i.delete(e);
};
const schedule = (o, s) => {
const c = { ...o };
i.set(o.sessionKey, c);
c.job = n.schedule({
id: `incognito-expiry:${o.sessionKey}`,
...s === void 0 ? { atMs: o.expiresAt } : { delayMs: s },
run: async () => {
let n;
try {
n = await t.acquireExisting(o.sessionKey, {
assertCurrent() {},
assertReadable() {}
});
if (!n) {
if (i.get(o.sessionKey) === c) forget(o.sessionKey);
return;
}
const a = {
actor: n,
authority: r,
agentId: t.agentId,
path: t.path
};
await runWithSessionActorStorage(a, () => e.deleteSession(o, a));
if (i.get(o.sessionKey) === c) forget(o.sessionKey);
} catch {
let n;
try {
n = t.readSession(o.sessionKey, r)?.entry;
} catch {}
if (i.get(o.sessionKey) !== c) return;
if (a && n?.sessionId === o.sessionId) {
e.logWarning("Incognito session expiry could not finish cleanup; will retry.");
schedule(o, CLEANUP_RETRY_MS);
} else forget(o.sessionKey);
} finally {
await n?.release();
}
}
});
};
const observeSession = (e, n) => {
const r = n && resolveIncognitoSessionExpiresAt(n);
if (!n || r === void 0) {
forget(e);
return;
}
if (i.get(e)?.sessionId === n.sessionId) return;
forget(e);
schedule({
sessionKey: e,
sessionId: n.sessionId,
agentId: t.agentId,
expiresAt: r
});
};
const observe = (e) => {
if (!a) return;
if (e && "sessionKey" in e) {
if (e.agentId === t.agentId && e.storePath === t.path) observeSession(e.sessionKey, t.readSession(e.sessionKey, r)?.entry);
return;
}
const n = t.listSessions(r);
const o = new Set(n.map((e) => e.target.sessionKey));
for (const e of i.keys()) if (!o.has(e)) forget(e);
for (const e of n) observeSession(e.target.sessionKey, e.entry);
};
const o = AsyncLocalStorage.snapshot();
const s = sessionChanges.subscribeProjection((e) => o(() => observe(e)));
observe();
return { async stop() {
a = false;
s();
n.beginClose();
await n.stop();
i.clear();
} };
}
/** Follow existing memory owners without creating sessions or retaining database workers. */
function startIncognitoSessionLifetime(e) {
const t = {
...e.env ?? process.env,
OPENCLAW_STATE_DIR: resolveStateDir(e.env ?? process.env)
};
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Set();
const retire = (t, i) => {
n.delete(t);
const a = Promise.resolve(i.stop()).catch(() => {
e.logWarning("Incognito expiry could not finish stopping its memory owner.");
});
r.add(a);
a.finally(() => r.delete(a));
};
const observe = () => {
const r = memorySessionActorOwners.list().filter((e) => e.path === resolveIncognitoOpenClawAgentSqlitePath({
agentId: e.agentId,
env: t
}));
for (const [e, t] of n) if (!r.includes(e)) retire(e, t);
for (const t of r) {
if (n.has(t)) continue;
n.set(t, startIncognitoActorSessionLifetime({
...e,
owner: t,
async deleteSession(t) {
const { deleteGatewaySession: n } = await import("./sessions-delete-CjCoVuoK.mjs");
const r = await n({
params: {
key: t.sessionKey,
agentId: t.agentId,
expectedSessionId: t.sessionId
},
client: null,
context: e.context
});
if (!r.ok) throw new Error(r.error.message);
}
}));
}
};
const i = AsyncLocalStorage.snapshot();
const a = sessionChanges.subscribeProjection(() => i(observe));
observe();
return {
name: "incognito-sessions",
async stop() {
a();
for (const [e, t] of n) retire(e, t);
await Promise.all(r);
}
};
}
//#endregion
//#region src/gateway/server-lifetime-sidecars.ts
async function attachInitialGatewayLifetimeSidecars(e) {
e.publishSidecars(startIncognitoSessionLifetime({
scheduler: e.scheduler,
context: e.gatewayRequestContext,
logWarning: e.logWarning
}));
await e.chatMetadataLifecycle.attachContext(e.gatewayRequestContext, e.publishSidecars);
if (!e.minimalTestGateway) {
const { startSessionCostUsageProjectionLifetime: t } = await import("./session-cost-usage-lifetime-DTb7JtHF.mjs");
e.publishSidecars(t({
getConfig: e.gatewayRequestContext.getRuntimeConfig,
warn: e.logWarning
}));
}
const t = createModelAccountConnectService({
getConfig: e.gatewayRequestContext.getRuntimeConfig,
onChanged: () => broadcastChatMetadataChanged(e.gatewayRequestContext)
});
e.gatewayRequestContext.modelAccountConnectService = t;
e.publishSidecars({
name: "model-account-connect",
stop: async () => {
await t.stop();
if (e.gatewayRequestContext.modelAccountConnectService === t) delete e.gatewayRequestContext.modelAccountConnectService;
}
});
const n = createGitHubOAuthLifecycle({
scheduler: e.scheduler,
getConfig: e.gatewayRequestContext.getRuntimeConfig,
getPersistedConfig: () => createConfigIO().loadConfigAsync(),
warn: e.logWarning
});
e.gatewayRequestContext.githubOAuthService = n;
const r = installActiveGitHubOAuthLifecycle(n);
if (!e.minimalTestGateway) {
e.publishSidecars(startGitHubPublicationDiscovery({
scheduler: e.scheduler,
projection: getSessionRowProjection(e.gatewayRequestContext)
}));
n.start();
}
e.publishSidecars({
name: "github-oauth",
stop: async () => {
r();
await n.stop();
if (e.gatewayRequestContext.githubOAuthService === n) delete e.gatewayRequestContext.githubOAuthService;
}
});
if (!e.minimalTestGateway) {
const t = e.scheduler.scope();
let n = false;
let r = false;
const scheduleExpiry = (e) => {
if (!t.signal.aborted) t.schedule({
id: "maintenance:secret-expiry",
atMs: e,
mode: "earliest",
run: sweep
});
};
const sweep = async () => {
if (r) return;
r = true;
try {
await purgeExpiredSecretStoreEntries();
n = false;
const e = getSecretStoreExpiryDeadline();
if (e !== null) scheduleExpiry(e ?? t.now());
} catch {
if (!n) {
e.logWarning("Secret store expiry cleanup failed; will retry.");
n = true;
}
scheduleExpiry(t.now() + 6e4);
} finally {
r = false;
}
};
const i = subscribeSecretStoreChanges(() => scheduleExpiry(t.now()));
const a = registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind !== "opened") scheduleExpiry(t.now());
});
t.signal.addEventListener("abort", () => {
i();
a();
}, { once: true });
e.publishSidecars({
name: "secret-expiry",
stop: t.stop
});
scheduleExpiry(t.now());
}
const i = e.reconcileGitHubPublications;
if (i) e.publishSidecars({
name: "github-publication-recovery",
...e.scheduler.schedule({
id: "maintenance:github-publication",
atMs: e.scheduler.now(),
everyMs: 6e4,
run: () => i().catch(() => e.logWarning("GitHub publication recovery failed; will retry."))
})
});
attachSessionChangeEventLifetime(e.gatewayRequestContext, () => e.publishSidecars({
name: "session-change-events",
stop: async () => {
await e.flushPendingSessionsChangedEvents(e.gatewayRequestContext);
}
}));
}
//#endregion
//#region src/gateway/server-kernel-request-runtime.ts
/** Prepares request bindings and the one-shot initializer shared by startup and transports. */
async function prepareGatewayKernelRequestRuntime(e) {
const { coreRuntime: t, log: n, logHealth: r } = e;
const { minimalTestGateway: i, runtimeState: a, bindApprovalPublicationContext: o, startupTrace: s, workerPlacementRuntime: c, githubPublicationRuntime: l, pluginGatewayContext: u, getAttachedGatewayMethodRegistry: d, gatewayInstanceRuntimeRef: f, startupState: p, shutdownRuntime: m } = t;
const [h, g] = await Promise.all([s.measure("gateway.chat-metadata-lifecycle", () => createGatewayChatMetadataLifecycle({
getConfig: readRuntimeConfig,
log: n,
getPluginMetadataSnapshot: t.getPluginMetadataSnapshot
})), s.measure("gateway.config-revision-key", async () => {
const { loadGatewayConfigRevisionProjector: e } = await import("./config-revision-token-BnXSwmhx.mjs");
return e({ env: process.env });
})]);
const _ = await s.measure("gateway.request-context", async () => {
const { createGatewayRequestContext: e } = await import("./server-request-context-FzapEdH1.mjs");
return e({
runtime: t,
configRevisionProjector: g,
chatMetadataLifecycle: h,
log: n,
logHealth: r
});
});
const v = t.opts.updateCanary ? void 0 : s.measure("sessions.projection", async () => {
const { createSessionRowProjection: e } = await import("./session-row-projection-Dny-dCXp.mjs");
return e({
cfg: readRuntimeConfig(),
getConfig: readRuntimeConfig,
getPolicyConfig: _.getCommittedRuntimeConfig ?? readRuntimeConfig,
getModelCatalog: () => readPreparedServerMethodModelCatalogs(_, listAgentIds(readRuntimeConfig())),
context: _,
placementFactsReader: t.workerEnvironmentStartup?.placementStore
});
});
v?.catch(() => {});
let y;
const b = { closing: false };
t.registerGatewayLifetimeSidecars({
name: "request-runtime",
stop: async () => {
b.closing = true;
retireQuestionChannelGateway(t.connectionWork.signal);
closeGatewayDeviceRevocation(_);
await _.scopeUpgradeCoordinator?.close();
const e = await v?.catch(() => void 0);
await m.flushPendingSessionsChangedEvents(_);
if (e) await m.drainSessionEventPublications(e);
b.detach?.();
e?.dispose();
}
});
const x = AsyncLocalStorage.bind(async () => {
const e = await v;
if (b.closing) throw new Error("Gateway closed during session projection startup");
if (e) {
b.detach = t.attachSessionRowProjection(e);
if (shouldUseGatewayOwnerProfile({
role: "operator",
authMethod: t.getResolvedAuth().mode,
rolesConfigured: Boolean(readRuntimeConfig().gateway?.roles)
})) try {
await s.measure("gateway.owner-profile", async () => {
const [{ ensureCanonicalGatewayOwnerProfile: e }, { resolveHostAccountName: t }] = await Promise.all([import("./user-profile-writes-D1DnWcE8.mjs"), import("./host-account-name-ymJn3k-8.mjs")]);
await e(t);
});
} catch (e) {
n.warn(`Gateway owner profile preparation failed: ${formatErrorMessage$1(e)}`);
}
await s.measure("sessions.materialize", () => e.ensureMaterialized());
if (b.closing) throw new Error("Gateway closed during session projection startup");
if (t.opts.controlUiEnabled ?? readRuntimeConfig().gateway?.controlUi?.enabled ?? true) t.connectionWork.track(() => runWithGatewayIndependentRootWorkAdmission(async () => {
const { listProjectedSessions: n } = await import("./session-utils-list-BtgAJ_ds.mjs");
t.connectionWork.signal.throwIfAborted();
await s.measure("sessions.first-page", () => n({
projection: e,
opts: {
limit: 100,
archived: false,
rowMode: "sidebar"
},
acceptsSerializedJson: true
}));
}, "startup:session-row-prewarm", t.connectionWork.signal)).catch((e) => {
if (!t.connectionWork.signal.aborted) n.warn(`Session first-page preparation failed: ${formatErrorMessage$1(e)}`);
});
}
if (!t.opts.updateCanary) await s.measure("gateway.lifetime-sidecars", () => attachInitialGatewayLifetimeSidecars({
scheduler: t.scheduler,
chatMetadataLifecycle: h,
gatewayRequestContext: _,
flushPendingSessionsChangedEvents: m.flushPendingSessionsChangedEvents,
minimalTestGateway: i,
logWarning: (e) => n.warn(e),
...!c && l ? { reconcileGitHubPublications: l.reconcilePublications } : {},
publishSidecars: a.gatewayLifetimeSidecars.publish
}));
});
const ensureRequestRuntimeReady = () => y ??= x();
_.requestEntryLifetime = t.requestEntryLifetime;
o(_);
u.current = _;
_.dispatchHookAgentTurn = async (e, n) => {
const r = t.transportBridge.current();
if (!r) throw new Error("Gateway listener must start before plugin hook dispatch");
return await r.dispatchHookAgentTurn(e, n);
};
const { createGatewayInstanceRuntime: S } = await s.measure("gateway.instance-runtime-import", () => import("./server-instance-runtime-BURHuhnk.mjs"));
const C = S({
getContext: () => _,
getMethodRegistry: () => d(),
isDispatchAvailable: () => p.dispatchReady,
logError: (e) => n.error(e)
});
f.current = C;
_.resolveGatewayContext = () => C.isAvailable() ? _ : void 0;
bindLegacyPluginSdkResourceHost(_.resolveGatewayContext, t.sdkResourceHost);
bindGatewayContextResolver(_.resolveGatewayContext, t.resolvePluginGatewayContext);
const w = e.hostLifecycle;
if (w) _.hostLifecycle = {
externalRestart: w.externalRestart,
getShutdownBudget: () => w.getShutdownBudget?.(),
request: (e, n) => w.request(e, () => {
if (t.requestEntryLifetime.signal.aborted || !C.isAvailable()) throw new Error("Gateway lifecycle is unavailable for this closed instance. Reconnect and retry.");
n();
})
};
_.approvalEvents = C.approvalEvents;
_.lifecycleRuntime = C.lifecycle;
bindGatewayContextResolver(C.lifecycle, _.resolveGatewayContext);
_.createAgentTurnFacade = C.createAgentTurnFacade;
return {
...t,
chatMetadataLifecycle: h,
gatewayRequestContext: _,
gatewayInstanceRuntime: C,
ensureRequestRuntimeReady
};
}
//#endregion
//#region src/gateway/server-cron-lazy.ts
/** Creates a cron state proxy that imports the real cron service on first use. */
function createLazyGatewayCronState(e) {
const t = getSpawnBroker();
const n = { installation: getGatewayServiceInstallation() };
const r = captureSqliteReadOnlyWorkerScope();
const i = e.env ?? process.env;
const a = e.storePath;
const o = i.OPENCLAW_SKIP_CRON !== "1" && (e.cfg.cron?.enabled ?? true);
if (o) expectSessionAutomationSource();
let s = null;
let c = false;
let l = false;
let u = 0;
let d;
let f;
let p = false;
const assertOpen = () => {
if (l) throw new Error("Cron service is closed");
};
const m = createLazyPromiseLoader(() => import("./server-cron-Wz5Qk2HG.mjs").then(({ buildGatewayCronService: i }) => {
assertOpen();
s = runWithSpawnBroker(t, () => r(() => withGatewayServiceInstallation(n, () => i(e))));
if (p) s.cron.pauseScheduling();
return s;
}), { cacheRejections: true });
const load = async () => {
assertOpen();
if (s) return s;
return await m.load();
};
const runWithInstallation = (e) => withGatewayServiceInstallation(n, e);
const bindOwnedCron = (e) => {
const t = createLazyRuntimeMethodBinder(e);
return (e) => {
const n = t(e);
return (...e) => runWithInstallation(() => n(...e));
};
};
const h = bindOwnedCron(load);
const g = bindOwnedCron(async () => {
const e = await load();
if (!c) await _.start();
return e;
});
const stopResolvedCron = async (e) => runWithInstallation(async () => {
if (d) await (f ??= d.stopOwner());
else if (e.cron.stopAndDrain) await e.cron.stopAndDrain();
else {
e.cron.stop();
await e.stopStreamWatchers();
}
});
const stopLoadedCronAndDrain = async (e) => {
l = true;
c = true;
u += 1;
d ??= e;
const t = s;
if (t) await measureGatewayCloseStep("restart.close.cron-owner", () => stopResolvedCron(t));
};
const _ = {
async start() {
c = false;
const e = await load();
if (!c) await runWithInstallation(() => e.cron.start());
},
stop() {
c = true;
u += 1;
if (s) {
runWithInstallation(() => s?.cron.stop());
return;
}
const e = m.peek();
if (e) e.then((e) => {
if (!c) return;
runWithInstallation(() => e.cron.stop());
}).catch(() => {});
},
async stopAndDrain() {
await stopLoadedCronAndDrain();
},
pauseScheduling() {
p = true;
if (s) runWithInstallation(() => s?.cron.pauseScheduling());
},
resumeScheduling() {
p = false;
runWithInstallation(() => s?.cron.resumeScheduling());
},
getSuspensionBlockerCount() {
return s?.cron.getSuspensionBlockerCount?.() ?? 0;
},
status: h((e) => e.cron.status.bind(e.cron)),
list: h((e) => e.cron.list.bind(e.cron)),
listPage: h((e) => e.cron.listPage.bind(e.cron)),
add: h((e) => e.cron.add.bind(e.cron)),
update: h((e) => e.cron.update.bind(e.cron)),
updateWithPrecondition: h((e) => e.cron.updateWithPrecondition.bind(e.cron)),
remove: h((e) => e.cron.remove.bind(e.cron)),
removeStaleJobFamily: h((e) => e.cron.removeStaleJobFamily.bind(e.cron)),
async removeAgentJobsTransactional(e, t) {
const n = await load();
return await runWithInstallation(() => n.cron.removeAgentJobsTransactional(e, t));
},
quiesceJobs: h((e) => e.cron.quiesceJobs.bind(e.cron)),
run: g((e) => e.cron.run.bind(e.cron)),
enqueueRun: g((e) => e.cron.enqueueRun.bind(e.cron)),
waitForManualRun: h((e) => e.cron.waitForManualRun.bind(e.cron)),
readEventSources: h((e) => e.cron.readEventSources.bind(e.cron)),
runEvent: h((e) => e.cron.runEvent.bind(e.cron)),
getStoreKey() {
const e = s?.cron.getStoreKey?.();
if (!e) throw new Error("Cron store is not prepared; read cron jobs first");
return e;
},
getJob(e) {
return s?.cron.getJob(e);
},
getLoadedJobs() {
return s?.cron.getLoadedJobs();
},
readJob: h((e) => e.cron.readJob.bind(e.cron)),
async readScratch(e, t) {
t?.assertCurrent?.();
const n = await load();
t?.assertCurrent?.();
return await runWithInstallation(() => n.cron.readScratch(e, t));
},
writeScratch: h((e) => e.cron.writeScratch.bind(e.cron)),
getDefaultAgentId() {
return s?.cron.getDefaultAgentId();
},
async prepareWake() {
await load();
},
async wake(e) {
if (l) return { ok: false };
if (!s) {
load().catch(() => {});
return { ok: false };
}
const t = s;
return runWithInstallation(() => t.cron.wake(e));
}
};
return {
cron: _,
get readHeartbeatSummary() {
return s?.readHeartbeatSummary;
},
deferHookWake: async (e) => {
const t = u;
const commitGuard = () => {
e.commitGuard();
if (c || u !== t) throw new Error("Scheduled Hook wake owner changed; retry the request");
};
commitGuard();
const n = await load();
commitGuard();
const r = n.deferHookWake;
if (!r) throw new Error("Scheduled Hook wake admission is unavailable; restart the Gateway");
return await runWithInstallation(() => r({
...e,
commitGuard
}));
},
storePath: a,
cronEnabled: o,
prepareExitWatcherHandoff: async () => {
if (l) return;
const e = m.peek();
const t = s ?? (e ? await e : null);
const n = await runWithInstallation(() => t?.prepareExitWatcherHandoff?.());
if (!n) return;
return {
...n,
stopOwner: async () => {
await stopLoadedCronAndDrain(n);
}
};
},
reconcileExitWatchers: h((e) => e.reconcileExitWatchers.bind(e)),
reconcileStreamWatchers: h((e) => e.reconcileStreamWatchers.bind(e)),
async stopStreamWatchers() {
await runWithInstallation(() => s?.stopStreamWatchers());
}
};
}
//#endregion
//#region src/gateway/server-cron-reconciled.ts
function createGatewayCronReconciliation(e) {
let t;
const supersedeActive = () => {
t?.abort();
t = void 0;
};
return {
arm: ({ reason: n, config: r, cronState: i }) => {
supersedeActive();
const a = new AbortController();
t = a;
const o = i.cron;
const s = o;
const c = {
reason: n,
enabled: i.cronEnabled
};
let l = false;
return { complete: async () => {
if (l) return;
l = true;
if (e.isClosing() || a.signal.aborted) return;
const t = e.getConfig();
const n = e.getPluginRegistry();
await reconcileOrphanedMemoryDreamingJobs({
cron: o,
cfg: t,
logger: e.logger,
manifestRegistry: getPluginRuntimeLoadContext(n)?.manifestRegistry,
isCurrent: () => !e.isClosing() && !a.signal.aborted && t === e.getConfig() && n === e.getPluginRegistry()
});
if (e.isClosing() || a.signal.aborted) return;
await e.runHook(c, {
port: e.port,
config: r,
workspaceDir: e.workspaceDir,
getCron: () => s,
abortSignal: a.signal
});
} };
},
invalidate: supersedeActive
};
}
//#endregion
//#region src/gateway/server-diagnostics.ts
const QA_DIAGNOSTIC_ABORT_MS_ENV = "QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS";
const MIN_QA_DIAGNOSTIC_ABORT_MS = 3e4;
/** The Gateway lifetime owns diagnostics configuration and its heartbeat job. */
function createGatewayDiagnosticsConfigurator(e) {
stopGatewayDiagnosticHeartbeat();
return (t) => {
if (e.isClosing()) return;
setDiagnosticsEnabledForProcess(isDiagnosticsEnabled(t));
notifyGatewayWorkMetricsChanged();
const n = process.env.OPENCLAW_ENABLE_PRIVATE_QA_CLI === "1" && process.env.OPENCLAW_GATEWAY_HOST_LIFELINE?.trim() === "stdin" ? process.env[QA_DIAGNOSTIC_ABORT_MS_ENV]?.trim() : void 0;
const r = n && /^\d+$/.test(n) ? Number(n) : void 0;
const i = r !== void 0 && Number.isSafeInteger(r) && r >= MIN_QA_DIAGNOSTIC_ABORT_MS ? {
stuckSessionWarnMs: Math.max(15e3, Math.floor(r / 2)),
stuckSessionAbortMs: r
} : void 0;
startGatewayDiagnosticHeartbeat(e.scheduler, void 0, {
getConfig: readRuntimeConfig,
startupGraceMs: 6e4,
testTimings: i,
sampleLiveness: () => {
const t = e.sampleLiveness();
if (!t || t.degradedSinceMs == null) return null;
return {
reasons: t.reasons,
intervalMs: t.intervalMs,
degradedSinceMs: t.degradedSinceMs,
eventLoopDelayP99Ms: t.delayP99Ms,
eventLoopDelayMaxMs: t.delayMaxMs,
eventLoopUtilization: t.utilization,
cpuCoreRatio: t.cpuCoreRatio
};
}
});
};
}
//#endregion
//#region src/gateway/server-lifecycle-close.ts
/** Shutdown owns core persistence independently of the plugin that requested it. */
function createGatewayCloseEntrypoints(e, t, n) {
const run = (t) => pluginInvocationContext.exit(() => pluginInstanceInvocation.exit(() => e.run(t)));
return {
runClose: run,
prepareClose: async (e) => {
const n = await run(() => t(e));
return () => run(n);
},
closeOnStartupFailure: (e) => run(() => n(e))
};
}
//#endregion
//#region src/gateway/server-sidecar-owners.ts
function createGatewaySidecarStopOwner() {
let e = /* @__PURE__ */ new Set();
let t = null;
let n;
let r = "open";
let i;
const remove = (t) => {
e.delete(t);
};
const publish = (...t) => {
if (r === "sealed") throw new Error("cannot publish a Gateway sidecar after shutdown sealed its owner");
for (const n of t) e.add(n);
if (r === "closing") stop();
return () => t.forEach(remove);
};
const beginClose = () => {
i ??= getProcessCleanupBudget();
if (r === "open") r = "closing";
};
const stop = () => {
beginClose();
if (t) return t;
const r = Promise.resolve().then(async () => {
const r = /* @__PURE__ */ new Set();
n = void 0;
try {
for (;;) {
const t = [...e].filter((e) => !r.has(e));
if (t.length === 0) break;
t.forEach(remove);
const a = await Promise.allSettled(t.map(async (e) => await measureGatewayCloseStep(`shutdown.sidecar.${e.name ?? e.stop.name}`, () => runWithProcessCleanupBudget(i, () => e.stop()))));
const o = t.filter((e, t) => a[t]?.status === "rejected");
t.forEach(remove);
if (o.length > 0) {
const e = a.find((e) => e.status === "rejected");
n ??= e?.reason instanceof Error ? e.reason : new Error(String(e?.reason));
materializeErrorStack(n);
for (const e of o) r.add(e);
}
}
if (n) {
e = /* @__PURE__ */ new Set([...r, ...e]);
throw n;
}
} finally {
t = null;
}
});
t = r;
r.catch(() => {});
return r;
};
const sealAndJoin = async () => {
for (let e = t; e; e = t) try {
await e;
} catch (e) {
n ??= e instanceof Error ? e : new Error(String(e));
materializeErrorStack(n);
}
r = "sealed";
if (n || e.size > 0) throw n ?? /* @__PURE__ */ new Error("Gateway sidecar cleanup did not complete");
};
return {
publish,
remove,
snapshot: () => [...e],
beginClose,
stop,
sealAndJoin,
async stopAndJoin() {
try {
await stop();
} finally {
await sealAndJoin();
}
}
};
}
//#endregion
//#region src/gateway/server-runtime-handles.ts
/** Creates gateway mutable state with inert handles that are safe to stop before startup finishes. */
function createGatewayServerMutableState() {
return {
discovery: null,
maintenance: null,
stopMediaCleanup: () => waitForMediaCleanupDrains({ timeoutMs: MEDIA_CLEANUP_STOP_TIMEOUT_MS }),
stopScheduledServices: async () => {},
stopDeliveryRecovery: async () => {},
stopGatewayUpdateCheck: async () => {},
tailscaleCleanup: null,
postReadySidecars: createGatewaySidecarStopOwner(),
gatewayLifetimeSidecars: createGatewaySidecarStopOwner(),
skillsChangeUnsub: async () => {},
channelHealthMonitor: null,
configReloader: {
stop: async () => {},
applyPluginLifecycleChange: async () => {
throw new Error("Plugin lifecycle is unavailable before Gateway startup completes.");
},
isConfigReloadSettled: () => false
},
reconcileAuditPolicy: null,
agentUnsub: null,
transcriptUnsub: null,
lifecycleUnsub: null
};
}
//#endregion
//#region src/gateway/server-live-state.ts
function createGatewayServerLiveState(e) {
return {
...createGatewayServerMutableState(),
hooksConfig: e.hooksConfig,
hookClientIpConfig: e.hookClientIpConfig,
cronState: e.cronState,
controlUiSessionPullRequests: void 0,
sessionViewerPresence: void 0,
pluginServices: null,
gatewayMethods: e.gatewayMethods
};
}
//#endregion
//#region src/gateway/server-plugin-runtime-generation.ts
/** Plugin service publication and operator-visible reload diagnostics. */
function createGatewayPluginRuntimeGeneration(e) {
let t;
return {
getReloadStatus: () => t,
currentServices: e.getServices,
setServices: e.setServices,
setReloadStatus: (e) => {
t = e;
},
finishReload: (e, n, r, i, a, o) => {
if (n === "unchanged") {
t = e;
return;
}
const s = n === "restored" ? new Set(i.plugins.filter((e) => e.status === "loaded" && (e.format === "bundle" || getPluginInstance(e)?.acceptingCalls)).map((e) => e.id)) : r;
const c = new Set(e?.phase === "failed" ? e.pluginIds.filter((e) => !r.has(e) || !s.has(e)) : []);
for (const e of r) if (n === "failed" || n === "restored" && a.has(e) && !s.has(e)) c.add(e);
t = c.size ? {
phase: "failed",
pluginIds: [...c].toSorted(),
reason: "Plugin activation or recovery failed. Retry openclaw plugins reload <id> after admitted work settles, or restart the Gateway. Inspect the Gateway log for the failure."
} : void 0;
if (n === "failed" && t?.reason) o?.(t.reason);
}
};
}
//#endregion
//#region src/gateway/server-request-entry.ts
function isPendingNodeCompletion({ req: e, client: t, context: n }) {
if (t?.connect.role !== "node" || !t.connId || !isRecord(e.params)) return false;
const r = e.method === "node.invoke.progress" ? e.params.invokeId : e.method === "node.invoke.result" ? e.params.id : void 0;
return typeof r === "string" && typeof e.params.nodeId === "string" && n.nodeRegistry.isInvokeCurrent(r, e.params.nodeId, t.connId);
}
/** One Gateway's preparation leases; handler execution belongs to its existing runtime owner. */
var GatewayRequestEntryLifetime = class {
constructor() {
this.stopping = new AbortController();
this.retained = new AbortController();
this.active = /* @__PURE__ */ new Set();
this.sealed = false;
this.signal = this.stopping.signal;
this.retainedSignal = this.retained.signal;
}
enter(e) {
let t = false;
const assertOpen = () => {
if (t || this.sealed || this.signal.aborted && !isPendingNodeCompletion(e)) throw new GatewayClientRequestError({
code: ErrorCodes.UNAVAILABLE,
message: "Gateway request entry is closed",
retryable: true,
retryAfterMs: 1e3,
details: { reason: GATEWAY_RESTART_UNAVAILABLE_REASON }
});
};
assertOpen();
const n = createDeferredCore();
this.active.add(n.promise);
return {
assertOpen,
release: () => {
if (t) return;
t = true;
this.active.delete(n.promise);
n.resolve();
}
};
}
beginClose() {
this.stopping.abort();
}
/** Accepted ingress authority outlives admission until restart custody is recorded. */
retire(e) {
this.retained.abort(e);
}
async waitForPendingEntries() {
await Promise.all(this.active);
}
async sealAndJoin() {
this.sealed = true;
this.retire();
await this.waitForPendingEntries();
}
};
//#endregion
//#region src/gateway/session-viewer-presence.ts
/** Owns one replace-set per websocket connection until empty declaration or disconnect. */
function createSessionViewerPresenceDeclarations(e) {
const t = /* @__PURE__ */ new Map();
let n = false;
const replace = (r, i) => {
if (n) return [];
const a = r.trim();
const o = e.clients.getByConnectionId(a);
if (!o || o.invalidated || o.socket.readyState !== 1) return [];
const s = [...new Set(i.map((e) => e.trim()).filter(Boolean))].toSorted();
const c = t.get(a) ?? [];
if (c.length === s.length && c.every((e, t) => e === s[t])) return s;
if (s.length === 0) t.delete(a);
else t.set(a, s);
if (o.presenceKey) {
upsertPresence(o.presenceKey, { watchedSessions: s.length > 0 ? [...s] : void 0 });
if (s.length > 0) recordClientPresenceActivity(e.clients, o);
e.publishPresence();
}
return s;
};
const unsubscribe = (e) => {
const n = e.trim();
if (n) t.delete(n);
};
/** True only while an open connection of this paired device currently renders the session. */
const isViewedOnDevice = (n, r) => {
for (const [i, a] of t) {
if (!a.includes(r)) continue;
const t = e.clients.getByConnectionId(i);
if (t && !t.invalidated && !t.connectionSignal?.aborted && t.socket.readyState === 1 && normalizeOptionalString(t.connect.device?.id) === n) return true;
}
return false;
};
const stop = () => {
n = true;
t.clear();
};
return {
replace,
unsubscribe,
isViewedOnDevice,
stop
};
}
//#endregion
//#region src/gateway/terminal/open-admission.ts
/** Gateway lifecycle custody includes pending spawns until their backend settles. */
async function withAgentTerminalOpenAdmission(e, t) {
const n = new AbortController();
const r = e.signal ? AbortSignal.any([e.signal, n.signal]) : n.signal;
let i;
try {
i = await beginSessionEffect({
agentId: e.agentId,
scope: `agent:${e.agentId}`,
identities: e.owner.kind === "agent" ? [e.owner.agentSessionKey, e.owner.agentSessionId] : [e.owner.connId],
signal: r,
assertAllowed: () => r.throwIfAborted(),
onInterrupt: (e) => n.abort(e)
});
} catch (e) {
return {
ok: false,
code: "closed",
message: e instanceof Error ? e.message : String(e)
};
}
try {
return await i.run(() => t({
...e,
signal: r
}));
} finally {
i.release();
}
}
//#endregion
//#region src/gateway/server-lifecycle.ts
async function prepareGatewayLifecycle(e) {
const { runtime: t, port: n, log: r, logCron: i, shutdownRuntime: a } = e;
const o = new GatewayRequestEntryLifetime();
const s = prepareWorktreeRunEndClose();
const c = prepareSandboxRegistryClose();
const l = prepareTalkConnectionClose(t.clients, r);
const { transportBridge: u, sessionMessageSubscribers: d, isConnectionActive: f, clients: p, mentionInbox: m, broadcast: h, cfgAtStart: g, cronStorePath: _, pluginRuntime: v, authRateLimiter: y, nodeReapprovalCoordinator: b, channelManager: x, deps: S, initialHooksConfig: C, initialHookClientIpConfig: w, runtimeStateRef: T, gatewayInstanceRuntimeRef: E, startupState: D, unavailableGatewayMethods: O, readinessEventLoopHealth: k, browserAuthRateLimiter: A, chatRunState: j, listActiveGatewayMethods: M, broadcastToConnIds: N, getBufferedAmount: P, sessionEventSubscribers: F, watchNodeRequestHandler: I, defaultWorkspaceDir: L, desktopSessionRegistry: R, nodeDesktopStreamBroker: z, bindDeviceNodeControl: B, bindWorkerNodeDesktopControl: V, workerPlacementRuntime: H, lifecycle: U } = t;
const W = {};
const { createGatewayNodeSessionRuntime: G } = await import("./server-node-session-runtime-CY3ByFQW.mjs");
const { nodeWorkerSupervisorTransport: K, closeHostStats: q, ...J } = G({
broadcast: h,
sessionEventSubscribers: F,
sessionMessageSubscribers: d,
listRegisteredNodePluginToolCommands: () => v.registry.nodeHostCommands,
getConfig: readRuntimeConfig,
onRunnerStateChanged: (e, t) => {
if (t.availabilityChanged) {
H?.runnerAvailability.markChanged(e);
H?.scheduleNodeWorkspaceRetention(e);
}
},
onPairingInvalidated: ({ nodeId: e, connId: n }) => {
W.current?.stopNode(e);
upsertPresence(e, { reason: "disconnect" });
commitPresence(e, n);
t.publishPresence();
removeRemoteNodeInfoForConnection(e, n);
},
onPairingGenerationChanged: ({ nodeId: e }) => {
W.current?.stopNode(e);
}
});
const { nodeRegistry: Y, nodeUnsubscribeAll: ee } = J;
const X = startNodeConnectionNotifications(Y, t.scheduler);
const te = (await import("./node-source-Cc0m7z_T.mjs")).createNodeDesktopService({
getConfig: readRuntimeConfig,
nodeRegistry: Y,
desktopRegistry: R,
streamBroker: z
});
W.current = te;
H?.bindNodeWorkerAvailability((e, t) => waitForNodeWorkerSupervisor(Y, e, t));
B?.(K);
V?.(K);
const { createWatchNodeHttpRuntime: ne } = await import("./watch-node-http-D8PSGFHr.mjs");
const re = ne({
nodeRegistry: Y,
getConfig: readRuntimeConfig,
broadcast: h,
rateLimiter: y,
nodeReapprovalCoordinator: b,
onDeviceTokensReplaced: (e, n) => {
const r = t.resolvePluginGatewayContext();
if (!r) throw new Error("Gateway request context is unavailable during device setup");
retireDeviceTokenClients(r, e, n, "device-token-rotated");
},
onNodeConnected: (e) => {
upsertPresence(e.nodeId, {
connectionId: e.connId,
host: e.displayName ?? e.clientId ?? e.nodeId,
clientId: e.clientId,
ip: e.remoteIp,
version: e.version,
platform: e.platform,
deviceFamily: e.deviceFamily,
modelIdentifier: e.modelIdentifier,
mode: e.clientMode,
deviceId: e.nodeId,
roles: ["node"],
scopes: [],
instanceId: e.nodeId,
reason: "connect"
}, { pending: false });
t.publishPresence();
recordRemoteNodeInfo({
nodeId: e.nodeId,
connId: e.connId,
displayName: e.displayName,
platform: e.platform,
deviceFamily: e.deviceFamily,
commands: e.commands,
remoteIp: e.remoteIp,
pairingGeneration: e.pairingGeneration
});
},
onNodeDisconnected: (e) => {
upsertPresence(e, { reason: "disconnect" });
t.publishPresence();
removeRemoteNodeInfo(e);
ee(e);
clearNodeWakeState(e);
},
onError: (e, t) => r.warn(`${e}: ${String(t)}`)
});
I.current = re.handleRequest;
const { TerminalSessionManager: ie, DEFAULT_TERMINAL_DETACH_SECONDS: ae } = await import("./session-manager-Bcn5BKt2.mjs");
const { TERMINAL_EVENT_DATA: oe } = await import("./session-types-j_Rhlbzz.mjs");
const Z = new ie({
disableGatewayLocalTerminals: isTruthyEnvValue(process.env.OPENCLAW_DISABLE_GATEWAY_LOCAL_TERMINALS),
withOpenAdmission: withAgentTerminalOpenAdmission,
emit: (e, t, n) => N(t, n, /* @__PURE__ */ new Set([e]), { dropIfSlow: t === oe }),
getBufferedAmount: P,
detachGraceMs: (g.gateway?.terminal?.detachedSessionTimeoutSeconds ?? ae) * 1e3
});
applyGatewayLaneConcurrency(resolveGatewayLaneConcurrency(g), { gatewayStart: true });
T.current = createGatewayServerLiveState({
hooksConfig: C,
hookClientIpConfig: w,
cronState: createLazyGatewayCronState({
scheduler: t.scheduler,
storePath: _,
cfg: g,
deps: S,
broadcast: h,
resolveGatewayContext: t.resolvePluginGatewayContext,
resolvePluginRegistry: () => v.registry
}),
gatewayMethods: M(v.baseGatewayMethods)
});
const Q = T.current;
const se = createGatewayPluginRuntimeGeneration({
getServices: () => Q.pluginServices,
setServices: (e) => {
Q.pluginServices = e;
}
});
const ce = createDeferredCore();
if (O.size === 0) ce.resolve();
const le = createGatewayReadyAnnouncer({
getReadiness: t.getReadiness,
isClosing: () => U.closePreludeStarted,
isChatSendAvailable: () => !O.has("chat.send"),
areSidecarsReady: () => D.sidecarsReady,
startupTrace: t.startupTrace,
log: r
});
const $ = {
startupMethodsReady: ce.promise,
pluginRuntimeGeneration: se,
pluginMetadata: e.pluginMetadata,
setDispatchReady: (e) => {
D.dispatchReady = e;
},
markSidecarsReady: () => {
D.sidecarsReady = true;
},
unlockStartupMethods: () => {
for (const e of STARTUP_UNAVAILABLE_GATEWAY_METHODS) O.delete(e);
ce.resolve();
return le();
},
publishMethodSurface: (e) => {
Q.gatewayMethods.splice(0, Q.gatewayMethods.length, ...e);
},
setEarlyRuntimeHandles: (e) => {
Q.skillsChangeUnsub = e.skillsChangeUnsub;
},
swapDiscovery: (e) => {
const t = Q.discovery;
Q.discovery = e;
return t;
},
setScheduledServiceHandles: (e) => {
Q.stopScheduledServices = e.stopScheduledServices;
Q.stopDeliveryRecovery = e.stopDeliveryRecovery;
},
setPostAttachHandles: (e) => {
Q.stopGatewayUpdateCheck = e.stopGatewayUpdateCheck;
},
setTailscaleCleanup: (e) => {
Q.tailscaleCleanup = e;
},
setConfigReloaderHandle: (e) => {
Q.configReloader = e;
},
getReloadState: () => ({
hooksConfig: Q.hooksConfig,
hookClientIpConfig: Q.hookClientIpConfig,
cronState: Q.cronState
}),
setReloadHookState: (e) => {
Q.hooksConfig = e.hooksConfig;
publishHooksTokenEnvKey(e.hooksConfig);
Q.hookClientIpConfig = e.hookClientIpConfig;
},
getCronService: () => Q.cronState.cron,
swapCronState: (e) => {
const t = Q.cronState;
Q.cronState = e;
S.cron = e.cron;
return t;
},
setChannelHealthMonitor: (e) => {
Q.channelHealthMonitor = e;
},
applyPluginLifecycleChange: (e) => Q.configReloader.applyPluginLifecycleChange(e),
getConfigReloaderHotReloadStatus: () => Q.configReloader.hotReloadStatus?.(),
setMaintenanceHandles: (e) => {
Q.maintenance = e;
Q.stopMediaCleanup = e.stopMediaCleanup;
}
};
Q.controlUiSessionPullRequests = createControlUiSessionPullRequestSubscriptions({
scheduler: t.scheduler,
getSessionRowProjection: t.getSessionRowProjection,
broadcastToConnIds: N,
isConnectionActive: f,
prepareRead: async (e, n) => {
const r = p.getByConnectionId(e);
return r ? createControlUiSessionPrRead({
allowOwnImportedPullRequest: true,
client: r,
...n,
getRuntimeConfig: readRuntimeConfig,
getSessionRowProjection: t.getSessionRowProjection,
isCurrentClient: () => p.getByConnectionId(e) === r
}) : void 0;
}
});
Q.sessionViewerPresence = createSessionViewerPresenceDeclarations({
clients: p,
publishPresence: t.publishPresence
});
t.attachSessionViewerPresence(Q.sessionViewerPresence);
S.cron = Q.cronState.cron;
const ue = createGatewayCronReconciliation({
port: n,
workspaceDir: L,
isClosing: () => U.closePreludeStarted,
getConfig: readRuntimeConfig,
getPluginRegistry: () => v.registry,
logger: i,
runHook: async (e, t) => {
try {
const n = (await import("./hooks-C5niPW1e.mjs")).createHookRunner(v.registry);
if (n.hasHooks("cron_reconciled")) await n.runCronReconciled(e, t);
} catch (e) {
i.error(`cron_reconciled hook failed: ${String(e)}`);
}
}
});
let de = null;
const stopMediaCleanupForClose = () => de ??= Q.stopMediaCleanup();
let fe;
const stopModelAccountsForClose = () => fe ??= t.resolvePluginGatewayContext()?.modelAccountConnectService?.stop();
const pe = new AsyncWorkScope();
let me = false;
const markClosePreludeStarted = (n) => {
if (me) return e.pluginMetadata.beginClose();
me = true;
beginGatewayShutdownCleanup();
const r = e.pluginMetadata.beginClose();
const i = resolveGatewayShutdownNotice(n);
markGatewaySuspendExiting();
y.dispose();
A.dispose();
s.beginClose();
c.beginClose();
l.beginClose();
closeAuthProfileUsage(e.sdkResourceHost);
Q.maintenance?.stopPeriodicTasks();
pe.beginClose();
h("shutdown", i);
Se.beginClose();
Q.stopDeliveryRecovery();
stopMediaCleanupForClose();
Q.stopGatewayUpdateCheck().catch(() => {});
stopConfigReloaderForClose().catch(() => {});
Q.controlUiSessionPullRequests?.stop();
Q.sessionViewerPresence?.stop();
t.stopPresencePublications();
return r;
};
let he = null;
const stopConfigReloaderForClose = () => he ??= Q.configReloader.stop();
const step = (e, t) => measureGatewayCloseStep(`restart.close.${e}`, t);
const drainClosePersistence = () => Promise.all([
step("auth-profile-usage", () => closeAuthProfileUsage(e.sdkResourceHost)),
step("model-accounts", stopModelAccountsForClose),
step("mention-inbox", () => m.dispose()),
step("sandbox-registry", () => c.drain())
]);
const beginClosePrelude = async (e) => {
await step("prelude-fence", () => markClosePreludeStarted(e));
await Promise.all([
drainClosePersistence(),
step("pending-request-entries", () => o.waitForPendingEntries()),
step("delivery-recovery", Q.stopDeliveryRecovery),
step("media-cleanup", stopMediaCleanupForClose),
step("update-check", () => Q.stopGatewayUpdateCheck()),
step("config-reloader", () => stopConfigReloaderForClose().catch(() => {})),
step("periodic-maintenance", () => Q.maintenance?.stopPeriodicTasks().catch(() => {})),
step("session-pull-requests", () => Q.controlUiSessionPullRequests?.stop()),
step("health-work", () => pe.drain())
]);
};
let ge = false;
const runClosePrelude = async () => {
await beginClosePrelude();
await step("talk-persistence", () => l.drain());
X();
await re.close();
await a.runGatewayClosePrelude({
stopDiagnostics: stopGatewayDiagnosticHeartbeat,
skillsChangeUnsub: () => Q.skillsChangeUnsub({ exitAfterClose: ge }),
disposeNodeReapproval: () => b.dispose(),
stopChannelHealthMonitor: async () => {
const e = Q?.channelHealthMonitor;
e?.shutdown();
await e?.waitForIdle();
},
stopReadinessEventLoopHealth: k.stop,
closeMcpServer: a.closeMcpLoopbackServer
});
};
const { getRuntimeSnapshot: _e, startChannels: ve, startChannel: ye, stopChannel: be, markChannelLoggedOut: xe } = x;
const refreshGatewayHealthSnapshotWithRuntime = (e) => {
if (pe.isClosing) return Promise.reject(/* @__PURE__ */ new Error("Gateway health refresh owner is closed"));
return pe.track(() => refreshGatewayHealthSnapshot({
...e,
getRuntimeSnapshot: _e,
getEventLoopHealth: k.snapshot,
getConfigReloaderHotReloadStatus: $.getConfigReloaderHotReloadStatus,
getSessionRowProjection: t.getSessionRowProjection,
getCronState: () => Q.cronState
}));
};
const Se = createGatewaySidecarStopOwner();
const Ce = Se.stopAndJoin;
const we = Q.postReadySidecars;
const Te = Q.gatewayLifetimeSidecars;
const sealAndJoinRegisteredSidecarStops = async () => {
const e = (await Promise.allSettled([we.sealAndJoin(), Te.sealAndJoin()])).find((e) => e.status === "rejected");
if (e) throw e.reason;
};
const prepareClose = async (n) => {
ge = n?.exitAfterClose === true;
fenceSessionSuspensionWritesForGatewayShutdown();
U.closePreludeStarted = true;
o.beginClose();
t.scheduler.fence();
stopModelAccountsForClose();
m.dispose();
ue.invalidate();
t.resolvePluginGatewayContext()?.scopeUpgradeCoordinator?.close();
const r = await a.prepareGatewayClose({
resolveGatewayContext: t.resolvePluginGatewayContext,
preparePluginRegistryClose: () => v.prepareClose(),
persistRunningSessionsForRestart: async (e) => {
const t = Q.configReloader.getCommittedRuntimeConfig?.();
if (!t) return;
const { persistRunningSessionsForRestart: n } = await import("./session-restart-resume-BNbJMTu5.mjs");
await n({
cfg: t,
signal: e
});
},
terminateRunningSubagentsForShutdown: async () => {
Promise.resolve(markClosePreludeStarted(n)).catch(() => {});
const { terminateLiveSubagentsForShutdown: e } = await import("./subagent-registry-DxTolEfW.mjs");
await e(t.resolvePluginGatewayContext);
},
cancelReceivedWork: (e) => {
o.retire(e);
t.scheduler.beginClose();
t.connectionWork.beginClose(e);
},
disposeAllCodeModeRuns: a.disposeAllCodeModeRuns,
updateCheckStop: Q.stopGatewayUpdateCheck,
configReloader: { stop: stopConfigReloaderForClose }
}, n);
await beginClosePrelude(n);
return async () => {
$.setDispatchReady(false);
E.current?.close();
const i = listLoadedChannelPluginsForRegistry(v.registry).map((e) => e.id);
const c = u.current();
const l = getGatewayContextLifetime(t.resolvePluginGatewayContext);
try {
await measureGatewayCloseStep("restart.close.portal-service", () => c?.portalService.closeAll());
} finally {
await withPluginRuntimeRegistryScope(v.registry, () => a.completeGatewayClose({
retainSharedState: n?.retainSharedState,
resolveGatewayContext: t.resolvePluginGatewayContext,
closePluginRegistry: (e) => v.close(e),
pluginMetadata: {
beginClose: e.pluginMetadata.beginClose,
close: async (...t) => {
try {
return await e.pluginMetadata.close(...t);
} finally {
l.abort(/* @__PURE__ */ new Error("Gateway closed; plugin runtime unavailable."));
}
}
},
bonjourStop: $.swapDiscovery(null)?.stop ?? null,
tailscaleCleanup: Q.tailscaleCleanup,
clearSecretsRuntimeSnapshot: clearSecretsRuntimeSnapshotState,
channelIds: i,
stopChannel: be,
pluginServices: Q.pluginServices,
cron: Q.cronState.cron,
stopCronMaintenance: a.stopCronMaintenance,
stopScheduledServices: Q.stopScheduledServices,
maintenance: Q.maintenance,
stopMediaCleanup: stopMediaCleanupForClose,
agentUnsub: Q.agentUnsub,
transcriptUnsub: Q.transcriptUnsub,
lifecycleUnsub: Q.lifecycleUnsub,
chatRunState: j,
clients: p,
finishRequestEntries: async () => {
await o.sealAndJoin();
await q();
},
drainSdkWork: () => e.sdkResourceHost.drainWork(),
stopScheduler: () => t.scheduler.stop(),
closeSdkResources: () => e.sdkResourceHost.close(),
...c ? {
wss: c.wss,
httpServer: c.httpServer,
httpServers: c.httpServers
} : {},
drainActiveSessionsForShutdown: a.drainActiveSessionsForShutdown,
disposeAllBundleLspRuntimes: a.disposeAllBundleLspRuntimes,
drainWorktreeRunEnd: () => s.drain(),
drainRetainedOpenAiEmbeddingProviders: a.drainRetainedOpenAiEmbeddingProviders,
stopGmailWatcher: a.stopGmailWatcher,
closeProviderTransportDispatcherPool: a.closeProviderTransportDispatcherPool
}, r));
}
await o.sealAndJoin();
await a.waitForPluginCacheRetirement();
};
};
const Ee = {
connectionWork: t.connectionWork,
stopConnectionDependentSidecars: Ce,
stopRegisteredGatewayLifetimeSidecars: Te.stop,
stopRegisteredPostReadySidecars: we.stop,
runClosePrelude,
sealAndJoinRegisteredSidecarStops
};
let De;
const closeOnStartupFailure = (e) => De ??= closeStartupFailure(e).catch((e) => {
De = void 0;
throw e;
});
const closeStartupFailure = async (n) => {
const i = {
reason: "gateway startup failed",
exitAfterClose: e.exitAfterStartupFailure?.(n) === true
};
t.startupTrace.close();
await runGatewayCloseSteps({
owner: Ee,
exitAfterClose: i.exitAfterClose,
close: await prepareClose(i),
onError: (e) => r.error(e)
});
};
const Oe = createGatewayDiagnosticsConfigurator({
scheduler: t.scheduler,
isClosing: () => U.closePreludeStarted,
sampleLiveness: k.persistentDegradationSnapshot
});
Oe(g);
return {
...t,
...Ee,
sdkResourceHost: e.sdkResourceHost,
configureDiagnostics: Oe,
requestEntryLifetime: o,
subscribeSessionMessageEvents: d.subscribe,
unsubscribeSessionMessageEvents: d.unsubscribe,
...J,
nodeDesktopService: te,
watchNodeHttpRuntime: re,
terminalSessions: Z,
runtimeState: Q,
unavailableGatewayMethods: O,
kernel: $,
pluginHostServices: { get cron() {
return $.getCronService();
} },
shutdownRuntime: a,
lifecycle: U,
cronReconciliation: ue,
getRuntimeSnapshot: _e,
startChannels: ve,
startChannel: ye,
stopChannel: be,
markChannelLoggedOut: xe,
refreshGatewayHealthSnapshotWithRuntime,
registerConnectionDependentSidecars: Se.publish,
unregisterConnectionDependentSidecar: Se.remove,
registerPostReadySidecars: we.publish,
registerGatewayLifetimeSidecars: Te.publish,
...createGatewayCloseEntrypoints(e.sdkResourceHost, prepareClose, closeOnStartupFailure)
};
}
//#endregion
//#region src/gateway/node-reapproval-coordinator.ts
const pendingNodeReapprovalAttempts = new KeyedAsyncQueue();
function buildRequestFingerprint(e) {
const t = e.permissions ? Object.fromEntries(Object.entries(e.permissions).toSorted(([e], [t]) => e.localeCompare(t))) : void 0;
return JSON.stringify({
nodeId: e.nodeId.trim(),
clientId: e.clientId,
clientMode: e.clientMode,
displayName: e.displayName,
platform: e.platform,
version: e.version,
coreVersion: e.coreVersion,
uiVersion: e.uiVersion,
deviceFamily: e.deviceFamily,
modelIdentifier: e.modelIdentifier,
caps: e.caps && normalizeSortedUniqueTrimmedStringList(e.caps),
commands: e.commands && normalizeSortedUniqueTrimmedStringList(e.commands),
permissions: t,
remoteIp: e.remoteIp,
silent: Boolean(e.silent)
});
}
/** Creates the gateway-lifetime owner for paired-node reapproval write limits. */
function createNodeReapprovalCoordinator(e, { scheduler: t }) {
const n = createGatewayAuthRateLimiter({
...e,
exemptLoopback: false
}, {
scheduler: t,
id: "auth/node-reapproval"
});
const r = /* @__PURE__ */ new Map();
let i = false;
const executeRequest = async ({ input: e, cleanupClaim: t, baseDir: r }) => {
if (i) return null;
const a = await reusePendingNodePairingForReconnect(e, t, r);
if (a) return a;
const o = e.nodeId.trim();
const s = buildRateLimitIdentityKey("node", o);
if (!n.check(s, "node-reapproval").allowed) return null;
const c = await requestNodePairing(e, r);
n.recordFailure(s, AUTH_RATE_LIMIT_SCOPE_NODE_REAPPROVAL);
return c;
};
const enqueueRequest = (e, t, n) => {
pendingNodeReapprovalAttempts.enqueue(`node-reapproval:${e}`, async () => {
const i = n ?? t.queued;
if (!n) t.queued = void 0;
if (!i) return;
try {
const e = await executeRequest(i.params);
for (const [t, n] of i.waiters.entries()) n.resolve(t === 0 ? e : null);
} catch (e) {
for (const t of i.waiters) t.reject(e);
} finally {
if (r.get(e) === t && !t.queued) r.delete(e);
}
});
};
return {
updateConfig: (e) => n.updateConfig({
...e,
exemptLoopback: false
}),
request(e) {
if (i) return Promise.resolve(null);
const t = e.input.nodeId.trim();
const n = buildRequestFingerprint(e.input);
let a = r.get(t);
const o = createDeferredCore();
if (a?.queued?.fingerprint === n) {
a.queued.params = e;
a.queued.waiters.push(o);
} else {
const i = {
fingerprint: n,
params: e,
waiters: [o]
};
if (!a) {
a = {};
r.set(t, a);
enqueueRequest(t, a, i);
} else {
const e = a.queued;
a.queued = i;
if (e) for (const t of e.waiters) t.resolve(null);
else enqueueRequest(t, a);
}
}
return o.promise;
},
async finalizeCleanup(e) {
return await pendingNodeReapprovalAttempts.enqueue(`node-reapproval:${e.nodeId}`, async () => await finalizeNodePairingCleanupClaim(e));
},
dispose() {
i = true;
for (const e of r.values()) for (const t of e.queued?.waiters ?? []) t.resolve(null);
r.clear();
n.dispose();
}
};
}
//#endregion
//#region src/gateway/event-web-push.ts
const EVENT_PUSH_TTL_SECONDS = 300;
const log$8 = createSubsystemLogger("gateway/web-push");
function resolveEventWebPushNotification(e, t) {
const n = isRecord(t) ? t : null;
if (!n) return null;
if (e === "question.requested") {
const e = normalizeWebPushDisplayLabel(n.id) ?? "pending";
const t = normalizeOptionalString(n.id);
return {
category: "agent-question",
title: "OpenClaw needs an answer",
body: "An agent has a question for you.",
tag: `openclaw-question-${e}`,
...t ? { path: `ask/${encodeURIComponent(t)}` } : {}
};
}
if (e === "chat" && n.state === "final" && n.yielded !== true && !isTranscriptOnlyOpenClawAssistantMessage(n.message)) return {
category: "agent-finished",
title: "OpenClaw agent finished",
body: "An agent completed its response.",
tag: `openclaw-agent-finished-${normalizeWebPushDisplayLabel(n.runId) ?? "finished"}`
};
if (e === "cron" && n.action === "finished" && n.status === "error") {
const e = isRecord(n.job) ? n.job : null;
const t = normalizeOptionalString(n.jobId);
const r = normalizeWebPushDisplayLabel(t) ?? "failed";
const i = normalizeWebPushDisplayLabel(e?.name);
const a = new URLSearchParams();
if (t) {
a.set("job", t);
const e = normalizeOptionalString(n.runId) ?? (typeof n.runAtMs === "number" && Number.isSafeInteger(n.runAtMs) && n.runAtMs >= 0 ? createCronExecutionId(t, n.runAtMs) : void 0);
if (e) a.set("run", e);
}
return {
category: "scheduled-task-failed",
title: "OpenClaw scheduled task failed",
body: "A scheduled task needs attention.",
...i ? { identifiedBody: `${i} needs attention.` } : {},
tag: `openclaw-cron-failed-${r}`,
path: `automations${a.size ? `?${a}` : ""}`
};
}
return null;
}
/** Routes attention events to offline browsers without expanding live session visibility. */
function createEventWebPushDelivery(e, t, n) {
const deliver = (r, i, a, o, s) => {
let c = "subscriptions";
(async () => {
if (!await hasBoundWebPushSubscriptions()) return;
c = "sender";
const l = await prepareWebPushNotificationSender();
c = "authority";
const u = normalizeOptionalString(o?.agentId ?? (isRecord(a) ? a.agentId : void 0));
const d = o?.sessionKeys ?? [];
const f = s ? void 0 : await prepareWebPushAgentIcon(e(), u);
const p = await withCurrentWebPushAuthority({
getRuntimeConfig: e,
sessionKeys: d,
agentId: u,
preparePublication: s?.prepare
}, (e) => {
const { cfg: o } = e;
const p = s && e.profile?.readCurrentIdentity(s.recipientProfileId)?.profileId;
if (s && !p) return;
const m = s?.sessionKey ?? d[0];
const h = m ? buildControlUiSessionPath({
namespace: "chat",
sessionKey: m,
fallbackAgentId: u,
mainKey: o.session?.mainKey,
exactKey: true
}) : void 0;
if (s && !h) return;
const g = r.path ?? h?.slice(1) ?? "sessions";
const _ = resolveControlUiWebPushUrl(o, g);
const v = listCurrentWebPushTargets({
...e,
requiredScopes: r.category === "agent-question" ? [READ_SCOPE, QUESTIONS_SCOPE] : [READ_SCOPE],
...s ? { visibilityScopes: [ADMIN_SCOPE] } : {}
});
const y = d.length === 1 ? d[0] : void 0;
const b = normalizeWebPushDisplayLabel(u);
const x = currentWebPushAgentIcon(o, f);
const S = /* @__PURE__ */ new Map();
for (const c of v) {
if (s && c.userProfileId !== p) continue;
const { preferences: l } = c;
if (!webPushCategoryEnabled(l, r.category) || isWebPushQuietHours(l) || !webPushAgentAllowed(l, u)) continue;
const f = webPushTargetClient(c);
if (d.length > 0 && !canReceiveSessionEvent({
cfg: o,
client: f,
prepared: webPushSessionAccess(e, f),
sessionKeys: d,
...u ? { agentId: u } : {},
event: i,
payload: a
})) continue;
if (o.gateway?.roles && d.length === 0) continue;
if (r.category === "agent-finished" && y !== void 0 && t?.isViewedOnDevice(c.subscription.deviceId, y) === true) continue;
let h = r.identifiedBody;
if (r.category === "agent-finished" && l.detailLevel !== "private" && d.length === 1 && m) {
const t = e.sessions.get(m)?.target;
const i = t ? n?.()?.readCapabilityEntry({
agentId: t.agentId,
storePath: t.storePath,
key: t.canonicalKey
})?.entry : void 0;
const a = normalizeWebPushDisplayLabel(i?.sessionId === t?.entry.sessionId ? i?.label : void 0);
if (a) h = `${a}: ${r.body}`;
}
const g = `${l.label ? `${l.label} · ` : ""}${r.title}`;
const _ = l.detailLevel === "private" ? r.body : h ?? (b ? `${b}: ${r.body}` : r.body);
const v = l.detailLevel === "private" ? void 0 : x;
const C = JSON.stringify({
title: g,
body: _,
icon: v
});
const w = S.get(C) ?? {
title: g,
body: _,
icon: v,
subscriptions: []
};
w.subscriptions.push(c.subscription);
S.set(C, w);
}
if (s && !s.isCurrent()) return;
const C = createHash("sha256").update(r.tag).digest("base64url").slice(0, 32);
return { start: () => {
c = "delivery";
return Promise.all([...S.values()].map((e) => l({
subscriptions: e.subscriptions,
payload: {
title: e.title,
body: e.body,
...e.icon ? { icon: e.icon } : {},
tag: r.tag,
renotify: false,
url: _
},
deliveryOptions: {
TTL: EVENT_PUSH_TTL_SECONDS,
urgency: r.category.includes("failed") ? "high" : "normal",
topic: C
}
})));
} };
});
if (!p) return;
const m = p.flat();
const h = m.filter((e) => !e.ok).length;
if (h > 0) log$8.warn("event Web Push delivery failed", {
category: r.category,
attempted: m.length,
failed: h
});
})().catch((e) => {
log$8.warn("event Web Push delivery could not complete", {
category: r.category,
stage: c,
error: formatErrorMessage(e),
errorName: readErrorName(e),
errorCode: extractErrorCode(e),
stack: e instanceof Error ? e.stack : void 0,
retry: false
});
});
};
return {
handleEvent(e, t, n) {
const r = resolveEventWebPushNotification(e, t);
if (r) deliver(r, e, t, n);
},
deliverMention(e) {
const t = normalizeWebPushDisplayLabel(e.senderLabel) ?? "Someone";
const n = normalizeWebPushDisplayLabel(e.sessionTitle);
const r = createHash("sha256").update(e.id).digest("base64url");
deliver({
category: "human-mentioned",
title: "OpenClaw mention",
body: "Someone mentioned you in a conversation.",
identifiedBody: `${t} mentioned you${n ? ` in ${n}` : ""}.`,
tag: `openclaw-mention-${r}`
}, "human-mentioned", void 0, {
agentId: e.agentId,
sessionKeys: [e.sessionKey]
}, e);
}
};
}
//#endregion
//#region src/plugins/compat/mention-inbox-deprecation.ts
function warnMentionInboxDeprecation(e) {
const t = pluginInstanceInvocation.getStore()?.instance.pluginId;
warnSessionPersistenceDeprecation(`mentionInbox.${e}`, `mentionInbox.${e}Async`, {
pluginId: t,
family: "mention-inbox",
compatibility: "Legacy recording queues work after commit; await recordCommittedInputAsync for completion. Synchronous reads, dismissals, and invalidation reject calls with async migration guidance."
});
}
//#endregion
//#region src/gateway/human-mention-policy.ts
const MAX_DIRECTORY_PROFILES = 1e4;
/** UI labels are text, never identity or an email-address fallback. */
function humanMentionDisplayLabel(e, t) {
const n = e?.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/gu, " ").trim();
return truncateUtf16Safe(n || `Person ${t.slice(0, 8)}`, 256);
}
function createHumanMentionPolicy(e) {
let t = true;
let n = -1;
const r = /* @__PURE__ */ new Map();
let i;
let a;
function synchronizeProfileVersion() {
const e = readUserProfileVersion();
if (n !== e) {
n = e;
r.clear();
i = void 0;
a = void 0;
}
}
function needsDirectoryPreparation() {
synchronizeProfileVersion();
return t && !i;
}
async function prepareDirectory() {
if (!needsDirectoryPreparation()) return;
const e = n;
const r = await readUserProfileDirectory(MAX_DIRECTORY_PROFILES);
if (t && e === readUserProfileVersion()) i = r;
}
function readProfile(e) {
synchronizeProfileVersion();
let t = r.get(e);
if (!t) {
t = resolveCurrentUserProfileDisplay(e);
if (t.kind === "resolved") {
pruneMapToMaxSize(r, 9999);
r.set(e, t);
}
}
return t.kind === "resolved" ? t : void 0;
}
function identify(e, t) {
if (!e?.connect || e.invalidated === true || e.internal?.syntheticClient || (e.connect.role ?? "operator") !== "operator" || !operatorScopeSatisfied("operator.sessions.read", e.connect.scopes ?? [])) return err(errorShape(ErrorCodes.FORBIDDEN, "Human mentions require a signed-in operator."));
const n = e.authenticatedUserProfile;
if (!n?.profileId) return err(e.authenticatedGitHubIdentitySync ? authenticatedProfileUnavailableError() : errorShape(ErrorCodes.FORBIDDEN, "Human mentions require a verified user profile. Sign in to use mentions."));
const r = readProfile(n.profileId);
if (!r) return err(authenticatedProfileUnavailableError());
const i = resolveOperatorRolePolicyForProfile(r.profileId, t);
if (i && !operatorScopeSatisfied("operator.sessions.read", i.scopes)) return err(errorShape(ErrorCodes.FORBIDDEN, "Your operator role cannot read mentions."));
const a = e.connect.scopes?.includes("operator.admin") && (!i || i.scopes.includes("operator.admin"));
const { entryFilter: o } = prepareSessionSharing({
cfg: t,
client: {
connect: {
...e.connect,
scopes: a ? [ADMIN_SCOPE] : [SESSION_READ_SCOPE]
},
internal: { operatorRoleActor: {
kind: "operator",
profileId: r.profileId
} }
}
});
return ok({
profile: r,
canRead: (e) => o?.(e.sessionKey, e.entry) ?? true
});
}
function recipientProfile(e, t, n) {
const r = readProfile(e);
if (!r || t.entry.incognito === true || isIncognitoSessionKey(t.sessionKey)) return;
const i = resolveOperatorRolePolicyForProfile(r.profileId, n);
const a = i?.scopes ?? ["operator.read"];
if (!operatorScopeSatisfied("operator.sessions.read", a)) return;
if (a.includes("operator.admin")) return r;
return createProfileSessionEntryFilter({
profileId: r.profileId,
sessionCap: i?.sessions.others
})(t.sessionKey, t.entry) ? r : void 0;
}
function resolveContext(t, n, r, i) {
const a = identify(t, r);
if (!a.ok) return a;
const o = a.value;
if ("sessionKey" in n) {
const t = resolveRequestedSessionAgentId(r, n.sessionKey, n.agentId);
if (!t.ok) return err(t.error);
const a = i ? i.readTarget() : e.readSessionTarget(n.sessionKey, t.agentId);
const s = a && {
agentId: a.agentId,
sessionKey: a.canonicalKey,
entry: {
createdActor: a.entry.createdActor,
visibility: a.entry.visibility,
incognito: a.entry.incognito
}
};
if (!s || !o.canRead(s)) return err(errorShape(ErrorCodes.INVALID_REQUEST, "Session was not found."));
return ok({
target: s,
profile: o.profile
});
}
const s = resolveRequestedSessionAgentId(r, void 0, n.agentId);
if (!s.ok) return err(s.error);
const c = authorizeGatewaySessionCreation({
cfg: r,
profileId: o.profile.profileId,
agentId: s.agentId
});
if (c) return err(c);
const l = resolveSessionVisibility({ visibility: n.visibility });
if (!isSessionVisibilityAllowed(r, l)) return err(errorShape(ErrorCodes.INVALID_REQUEST, "This session visibility is disabled."));
return ok({
profile: o.profile,
target: {
agentId: s.agentId,
entry: {
visibility: l,
createdActor: resolveOperatorSessionCreation({ authenticatedUserProfile: o.profile }).actor
}
}
});
}
function involvedProfiles(e, t, n) {
if (t?.entry.sessionId === e.sessionId && t.entry.incognito !== true && !isIncognitoSessionKey(t.canonicalKey)) {
const r = readProfile(e.senderProfileId);
return e.recipientProfileIds.flatMap((e) => {
const i = recipientProfile(e, {
agentId: t.agentId,
sessionKey: t.canonicalKey,
entry: t.entry
}, n);
return r && i && r.profileId !== i.profileId ? [i.profileId] : [];
});
}
return [];
}
return {
async prepareContext(t) {
if (!("sessionKey" in t)) return {
readTarget: () => null,
release() {}
};
const n = e.getRuntimeConfig();
const r = resolveRequestedSessionAgentId(n, t.sessionKey, t.agentId);
if (!r.ok) return {
readTarget: () => null,
release() {}
};
const i = await prepareSessionSharingRead({
cfg: n,
sessionKey: t.sessionKey,
agentId: r.agentId
});
return {
readTarget: () => i.readCurrent(e.getRuntimeConfig()).target,
release: i.release
};
},
async recordCommittedInvolvementAsync(n, r) {
const i = e.getRuntimeConfig();
if (!resolveRequestedSessionAgentId(i, n.sessionKey, n.agentId).ok || isIncognitoSessionKey(n.sessionKey)) return;
const a = r.readCurrent(e.getRuntimeConfig()).target;
const o = involvedProfiles(n, a, e.getRuntimeConfig());
if (!a || !o.length) return;
if (!await updateSessionProfileInvolvementAsync({
agentId: a.agentId,
sessionKey: a.storeKey,
storePath: a.storePath
}, {
expectedSessionId: n.sessionId,
expectedEntry: a.entry,
profileIds: o,
change: {
kind: "mention",
source: n.committedSource
},
assertCurrent() {
const i = e.getRuntimeConfig();
const a = r.readCurrent(i).target;
if (!t || !isDeepStrictEqual(involvedProfiles(n, a, i), o)) throw new Error("Committed mention authority changed before involvement commit");
}
})) throw new Error("Committed mention involvement was refused for a changed session");
},
identify,
prepareDirectory,
needsDirectoryPreparation,
readProfile,
recipientProfile,
invalidateDirectory() {
a = void 0;
},
dispose() {
t = false;
r.clear();
i = void 0;
a = void 0;
},
mentionable(t, r, o) {
const s = e.getRuntimeConfig();
const c = resolveContext(t, r, s, o);
if (!c.ok) return c;
const { target: l, profile: u } = c.value;
if (!i) throw new Error("The mention directory has not been prepared.");
const d = JSON.stringify([
n,
l,
s.gateway?.roles
]);
if (a?.key !== d) a = {
key: d,
users: i.profiles.flatMap(({ id: e, logins: t }) => {
const n = recipientProfile(e, l, s);
return n ? [{
profileId: n.profileId,
displayName: humanMentionDisplayLabel(n.label ?? t[0], n.profileId),
avatarUrl: n.avatarUrl,
logins: t,
online: false
}] : [];
}),
truncated: i.truncated
};
const f = r.query?.trim().toLocaleLowerCase() ?? "";
const p = a.users.filter((e) => e.profileId !== u.profileId && (!f || e.displayName.toLocaleLowerCase().includes(f) || e.logins.some((e) => e.toLocaleLowerCase().includes(f))));
const m = /* @__PURE__ */ new Map();
for (const e of p) m.set(e.displayName, (m.get(e.displayName) ?? 0) + 1);
const h = /* @__PURE__ */ new Set();
for (const t of e.getClients()) {
const e = t.authenticatedUserProfile?.profileId;
if (e && !t.internal?.syntheticClient) {
const t = readProfile(e);
if (t) h.add(t.profileId);
}
}
const g = p.map((e) => ({
profileId: e.profileId,
displayName: (m.get(e.displayName) ?? 0) > 1 ? `${truncateUtf16Safe(e.displayName, 244)} (${e.profileId.slice(0, 8)})` : e.displayName,
avatarUrl: e.avatarUrl,
online: h.has(e.profileId)
}));
g.sort((e, t) => Number(t.online) - Number(e.online) || e.displayName.localeCompare(t.displayName) || e.profileId.localeCompare(t.profileId));
return ok({
users: g.slice(0, 100),
truncated: a.truncated || g.length > 100
});
},
validateRecipients(t, n, r, i) {
if (r.length === 0) return ok([]);
const a = e.getRuntimeConfig();
const o = resolveContext(t, n, a, i);
if (!o.ok) return o;
const { target: s, profile: c } = o.value;
const l = /* @__PURE__ */ new Set();
for (const e of r) {
const t = recipientProfile(e, s, a);
if (!t || t.profileId === c.profileId || r.length > 10) return err(errorShape(ErrorCodes.INVALID_REQUEST, "One or more mentioned people are unavailable. Select the recipients again."));
l.add(t.profileId);
}
return ok([...l]);
}
};
}
//#endregion
//#region src/gateway/mention-inbox-presentation.ts
function formatMentionSessionTitle(e) {
return truncateUtf16Safe((deriveSessionTitle(e) ?? "Conversation").replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/gu, " ").trim(), 256) || "Conversation";
}
function formatMentionExcerpt(e) {
return e ? truncateUtf16Safe(flattenMarkdownToPlainText(truncateUtf16Safe(e, 2048)).replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/gu, " ").trim(), 280) : void 0;
}
function mentionInboxUnavailable(e) {
e?.warn("The mention Inbox could not read or save its current state. Reconnect to retry.");
return err(errorShape(ErrorCodes.UNAVAILABLE, "The mention Inbox is unavailable. Reconnect to retry.", { retryable: true }));
}
//#endregion
//#region src/gateway/mention-inbox-projection.ts
const MAX_GLOBAL_ITEMS = 1e4;
function mentionTargetKey(e, t) {
return JSON.stringify([t, e]);
}
function createMentionProjection(e) {
const t = {
head: { ...e.head },
items: /* @__PURE__ */ new Map(),
itemsByProfile: /* @__PURE__ */ new Map(),
processed: /* @__PURE__ */ new Map(),
dirtySources: /* @__PURE__ */ new Set(),
nextExpiryAt: Infinity,
profileVersion: -1
};
for (const n of e.sources) {
const e = {
key: n.key,
sequence: n.sequence,
expiresAt: n.expiresAt,
recipients: /* @__PURE__ */ new Map()
};
t.processed.set(e.key, e);
t.nextExpiryAt = Math.min(t.nextExpiryAt, e.expiresAt);
for (const [r, i] of n.recipients) {
const a = i && n.message ? {
id: i,
targetKey: mentionTargetKey(n.message.content.sessionKey, n.message.content.agentId),
recipientProfileId: r,
source: e,
message: n.message
} : null;
e.recipients.set(r, a);
if (a) {
t.items.set(a.id, a);
indexMentionItem(t, a, false);
}
}
}
return t;
}
function createMentionMutationProjection(e, t) {
if (!t) {
const t = createMentionProjection({
head: e.head,
sources: Array.from(e.processed.values(), serializeMentionSource)
});
t.profileVersion = e.profileVersion;
return {
draft: t,
sourceIndex: t.processed,
itemLimit: MAX_GLOBAL_ITEMS,
publish(e) {
t.head = e;
t.dirtySources.clear();
return t;
}
};
}
const n = {
...e,
head: { ...e.head },
processed: /* @__PURE__ */ new Map(),
items: /* @__PURE__ */ new Map(),
itemsByProfile: /* @__PURE__ */ new Map(),
dirtySources: /* @__PURE__ */ new Set()
};
const include = (e) => {
if (n.items.has(e.id)) return;
let t = n.processed.get(e.source.key);
if (!t) {
t = {
...e.source,
recipients: new Map(e.source.recipients)
};
n.processed.set(t.key, t);
}
const r = {
...e,
source: t
};
t.recipients.set(e.recipientProfileId, r);
n.items.set(e.id, r);
indexMentionItem(n, r, false);
};
const r = e.items.values();
for (let e = 0; e < 10; e++) {
const e = r.next().value;
if (!e) break;
include(e);
}
for (const n of t) for (const t of e.itemsByProfile.get(n) ?? []) include(t);
const i = e.items.size - n.items.size;
return {
draft: n,
sourceIndex: e.processed,
itemLimit: MAX_GLOBAL_ITEMS - i,
publish(t) {
for (const t of n.dirtySources) {
const r = n.processed.get(t);
const i = e.processed.get(t);
if (i) {
for (const [t, n] of i.recipients) if (n && r?.recipients.get(t)?.id !== n.id) removeMentionItem(e, n);
}
if (!r) {
e.processed.delete(t);
continue;
}
const a = i ?? r;
const o = /* @__PURE__ */ new Map();
for (const [t, n] of r.recipients) {
const r = i?.recipients.get(t);
if (n && r?.id === n.id) o.set(t, r);
else {
o.set(t, n);
if (n) {
n.source = a;
e.items.set(n.id, n);
indexMentionItem(e, n, false);
}
}
}
a.recipients = o;
a.sequence = r.sequence;
a.expiresAt = r.expiresAt;
e.processed.set(t, a);
}
e.head = t;
e.nextExpiryAt = n.nextExpiryAt;
e.profileVersion = n.profileVersion;
e.dirtySources.clear();
return e;
}
};
}
function serializeMentionSource(e) {
const t = [...e.recipients.values()].find((e) => e !== null)?.message;
return {
key: e.key,
sequence: e.sequence,
expiresAt: e.expiresAt,
recipients: Array.from(e.recipients, ([e, t]) => [e, t?.id ?? null]),
...t ? { message: t } : {}
};
}
function removeMentionItem(e, t) {
const { items: n, itemsByProfile: r, dirtySources: i } = e;
if (!t || !n.delete(t.id)) return;
const a = r.get(t.recipientProfileId);
a?.delete(t);
if (a?.size === 0) r.delete(t.recipientProfileId);
t.source.recipients.set(t.recipientProfileId, null);
i.add(t.source.key);
}
function trimMentionItems(e, t, n) {
const r = t.values();
while (t.size > n) removeMentionItem(e, r.next().value);
}
function indexMentionItem(e, t, n = true) {
const { itemsByProfile: r } = e;
const i = r.get(t.recipientProfileId) ?? /* @__PURE__ */ new Set();
i.add(t);
r.set(t.recipientProfileId, i);
if (n) trimMentionItems(e, i, 100);
}
function expireMentionItems(e, t) {
const { processed: n, dirtySources: r, nextExpiryAt: i } = e;
if (t < i) return;
let a = Infinity;
for (const [i, o] of n) {
if (o.expiresAt > t) {
a = Math.min(a, o.expiresAt);
continue;
}
for (const t of o.recipients.values()) removeMentionItem(e, t);
n.delete(i);
r.add(i);
}
e.nextExpiryAt = a;
}
function reconcileMentionProfiles(e, t, n) {
const { processed: r, dirtySources: i, items: a, itemsByProfile: o } = e;
if (t === e.profileVersion) return;
e.profileVersion = t;
for (const e of r.values()) {
const t = /* @__PURE__ */ new Map();
for (const [r, o] of e.recipients) {
const s = n(r);
if (s !== r || t.has(s)) i.add(e.key);
if (!t.has(s)) {
t.set(s, o);
if (o) o.recipientProfileId = s;
continue;
}
const c = t.get(s);
if (o === null && c) {
a.delete(c.id);
t.set(s, null);
} else if (o) a.delete(o.id);
}
e.recipients = t;
}
o.clear();
for (const t of a.values()) indexMentionItem(e, t);
}
//#endregion
//#region src/gateway/mention-inbox-input.ts
function hasValidMentionReferences(e) {
const t = [
e.sourceId,
e.sessionId,
e.messageId,
e.senderProfileId,
...e.recipientProfileIds
];
return e.recipientProfileIds.length <= 10 && e.sessionKey.length <= 512 && t.every((e) => Boolean(e) && e.length <= 256);
}
//#endregion
//#region src/gateway/mention-inbox-recording.ts
const log$7 = createSubsystemLogger("gateway/mentions");
function prepareCommittedMentionInput(e) {
if (e.recipientProfileIds.length === 0 || isIncognitoSessionKey(e.sessionKey)) return false;
if (!hasValidMentionReferences(e)) {
log$7.warn("Skipped mention delivery with invalid committed references.");
return false;
}
return true;
}
function createMentionInputRecorder(e) {
const { policy: t } = e;
return function applyCommittedInput(n, r, i, a, o) {
const { processed: s, head: c, dirtySources: l, items: u } = r;
const d = e.getRuntimeConfig();
const f = o();
if (!f || f.entry.sessionId !== n.sessionId || f.entry.incognito === true || isIncognitoSessionKey(f.canonicalKey)) {
log$7.debug("Skipped mention delivery because its committed session changed.");
return [];
}
i.push(() => {
const e = o();
if (!e || e.entry.sessionId !== n.sessionId || e.entry.incognito === true || e.canonicalKey !== f.canonicalKey || e.storePath !== f.storePath || e.entry.visibility !== f.entry.visibility) throw new Error("Committed mention session changed before commit");
});
const p = createHash("sha256").update(JSON.stringify([
f.agentId,
f.canonicalKey,
n.sessionId,
n.sourceId
])).digest("hex");
if (a.sourceIndex.has(p)) return [];
if (a.sourceIndex.size >= 1e4) {
e.onCapacityReached();
return [];
}
const m = e.now();
const h = {
key: p,
sequence: c.nextSequence++,
expiresAt: m + MENTION_RETENTION_MS,
recipients: /* @__PURE__ */ new Map()
};
s.set(p, h);
l.add(p);
r.nextExpiryAt = Math.min(r.nextExpiryAt, h.expiresAt);
const g = t.readProfile(n.senderProfileId);
const _ = {
agentId: f.agentId,
sessionKey: f.canonicalKey,
entry: f.entry
};
const v = formatMentionExcerpt(n.excerpt);
const y = {
sessionId: n.sessionId,
content: {
senderProfileId: g?.profileId ?? n.senderProfileId,
sessionKey: _.sessionKey,
agentId: _.agentId,
messageId: n.messageId,
createdAt: m,
...v ? { excerpt: v } : {}
}
};
const b = [];
let x = 0;
for (const e of n.recipientProfileIds) {
const n = t.recipientProfile(e, _, d);
const i = n?.profileId ?? e;
if (h.recipients.has(i)) continue;
h.recipients.set(i, null);
if (!g || !n || g.profileId === n.profileId) {
x += 1;
continue;
}
const o = {
id: randomUUID(),
targetKey: mentionTargetKey(_.sessionKey, _.agentId),
recipientProfileId: n.profileId,
source: h,
message: y
};
u.set(o.id, o);
h.recipients.set(n.profileId, o);
indexMentionItem(r, o);
trimMentionItems(r, u, a.itemLimit);
b.push(o);
}
if (x > 0) log$7.debug(`Skipped ${x} unavailable mention recipients for committed input.`);
return b;
};
}
//#endregion
//#region src/gateway/mention-inbox-targets.ts
/** One bounded set of retained sharing facts for the Inbox's current view. */
function createMentionTargetCache(e) {
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Map();
function readTarget(r) {
const i = t.get(n.get(r) ?? r);
if (!i) return null;
try {
const t = i.facts.readCurrent(e.getRuntimeConfig()).target;
if (!t) return null;
i.target = t;
return i;
} catch {
return null;
}
}
function prepareTarget(e, t, n = mentionTargetKey(e, t)) {
if (readTarget(n)) return;
return prepareMissingTarget(e, t, n);
}
async function prepareMissingTarget(r, i, a) {
removeTarget(n.get(a) ?? a);
const o = e.getRuntimeConfig();
const s = await resolveSessionSharingTargetAsync({
cfg: o,
sessionKey: r,
agentId: i
});
if (!s) return;
const c = mentionTargetKey(s.canonicalKey, s.agentId);
const l = readTarget(c);
if (l) {
n.set(a, c);
l.aliases.add(a);
return;
}
removeTarget(c);
if (t.size >= 1e4) pruneTargets();
const u = await prepareSessionSharingRead({
cfg: o,
sessionKey: r,
agentId: s.agentId
});
const d = {
sessionKey: r,
target: s,
sessionTitle: formatMentionSessionTitle(s.entry),
facts: u,
aliases: /* @__PURE__ */ new Set([a])
};
t.set(c, d);
n.set(a, c);
}
async function prepareTargets(t = e.readItems()) {
for (const e of t) {
const { sessionKey: t, agentId: n } = e.message.content;
const r = prepareTarget(t, n, e.targetKey);
if (r) await r;
}
}
function removeTarget(e) {
const r = t.get(e);
if (!r) return;
r.facts.release();
t.delete(e);
for (const e of r.aliases) n.delete(e);
}
function pruneTargets() {
const r = /* @__PURE__ */ new Set();
for (const t of e.readItems()) r.add(n.get(t.targetKey) ?? t.targetKey);
for (const e of t.keys()) if (!r.has(e)) removeTarget(e);
}
function invalidateTargets(e) {
if (!e) {
for (const e of t.values()) e.facts.release();
t.clear();
n.clear();
return;
}
for (const [n, r] of t) if (r.sessionKey === e || r.target.storeKeys.includes(e)) removeTarget(n);
}
return {
readTarget,
prepareTarget,
prepareTargets,
invalidateTargets
};
}
//#endregion
//#region src/gateway/mention-inbox-worker.ts
async function readMentionSnapshot(e, t) {
e.admission.assertCurrent();
if (t >= 0 && getMentionStoreHeadAdmission(e.admission.databasePath)?.revision === t) return;
const n = await executeExistingOpenClawStateRead({
path: e.admission.databasePath,
env: e.environment
}, {
type: "mentions.snapshot",
input: t
}, {
context: e,
current: true
});
e.admission.assertCurrent();
if (!n) return t === 0 ? void 0 : {
head: {
revision: 0,
nextSequence: 0
},
sources: []
};
return n.snapshot;
}
async function commitMentionChanges(e, t, n) {
const r = structuredClone(t);
let i;
try {
return await runOpenClawStateWorkerOperation(e, (e) => e.execute({
type: "mentions.mutate",
input: r
}), {
assertCurrent: n,
createAdmission: () => {
i = createSqliteWorkerOperationAdmission((t, r) => {
e.admission.assertCurrent();
n();
r();
});
return {
admission: i,
nativeLocations: [e.admission.databasePath]
};
}
});
} catch (e) {
const t = i?.committed?.facts;
if (isRecord(t) && t.kind === "committed" && isRecord(t.head) && t.head.revision === r.expectedHead.revision + (r.changes.length ? 1 : 0) && t.head.nextSequence === r.nextSequence) return {
kind: "committed",
head: {
revision: t.head.revision,
nextSequence: t.head.nextSequence
}
};
throw e;
}
}
//#endregion
//#region src/gateway/mention-inbox.ts
const log$6 = createSubsystemLogger("gateway/mentions");
/** Durable sources own retention and replay; each Gateway keeps disposable projection indexes. */
function createMentionInbox(e) {
const t = e.scheduler.scope();
const n = captureOpenClawStateWorkerContext();
const r = new AsyncWorkScope();
let i = createMentionProjection({
head: {
revision: -1,
nextSequence: 0
},
sources: []
});
const { readTarget: a, prepareTarget: o, prepareTargets: s, invalidateTargets: c } = createMentionTargetCache({
getRuntimeConfig: () => e.getRuntimeConfig(),
readItems: () => i.items.values()
});
const l = createHumanMentionPolicy({
...e,
readSessionTarget: (e, t) => a(mentionTargetKey(e, t))?.target ?? null
});
let u = Promise.resolve();
let d = false;
let f = true;
let p = 0;
let m = 0;
let h = 0;
const g = /* @__PURE__ */ new WeakMap();
const _ = /* @__PURE__ */ new WeakMap();
let v = false;
let y = false;
const b = createMentionInputRecorder({
getRuntimeConfig: () => e.getRuntimeConfig(),
now: () => t.now(),
policy: l,
onCapacityReached() {
if (!v) {
log$6.warn("Mention retention reached its replay budget; new mention alerts are skipped until retained sources expire.");
v = true;
}
}
});
function assertActive() {
if (d || t.signal.aborted) throw new Error("Mention Inbox is closed");
n.admission.assertCurrent();
}
async function enqueue(e) {
assertActive();
const t = runInDetachedAsyncContext(() => r.track(() => u.then(() => {
n.admission.assertCurrent();
return e();
})));
u = t.then(() => void 0, () => void 0);
return await t;
}
async function synchronize() {
const e = await readMentionSnapshot(n, f ? -1 : i.head.revision);
if (e) i = createMentionProjection(e);
f = false;
return Boolean(e);
}
async function mutate(r, a) {
try {
await synchronize();
for (;;) {
const o = { ...i.head };
const s = t.now();
const c = s >= i.nextExpiryAt || i.profileVersion !== readUserProfileVersion();
const u = createMentionMutationProjection(i, c ? void 0 : a?.());
const { draft: d } = u;
expireMentionItems(d, s);
if (u.sourceIndex.size < 1e4) v = false;
reconcileMentionProfiles(d, readUserProfileVersion(), (e) => l.readProfile(e)?.profileId ?? e);
const m = [];
const h = r(d, m, u);
if (d.dirtySources.size === 0) {
i = u.publish(o);
return h;
}
const g = readUserProfileVersion();
const _ = readGatewayAccessRevision();
const y = p;
const b = e.getRuntimeConfig();
const assertCurrent = () => {
n.admission.assertCurrent();
if (g !== readUserProfileVersion() || _ !== readGatewayAccessRevision() || y !== p || b !== e.getRuntimeConfig()) throw new Error("Mention authority changed before commit");
for (const e of m) e();
};
const x = await commitMentionChanges(n, {
expectedHead: o,
nextSequence: d.head.nextSequence,
changes: Array.from(d.dirtySources, (e) => {
const t = d.processed.get(e);
return [e, t ? serializeMentionSource(t) : void 0];
})
}, assertCurrent);
if (x.kind === "conflict") {
n.admission.assertCurrent();
i = createMentionProjection(x.snapshot);
continue;
}
n.admission.assertCurrent();
i = u.publish(x.head);
f = false;
return h;
}
} catch (e) {
f = true;
throw e;
}
}
async function maintain() {
const e = await synchronize();
const n = t.now() >= i.nextExpiryAt || i.profileVersion !== readUserProfileVersion();
if (n) await mutate(() => void 0);
return e || n;
}
function currentTarget(e, n, r = i) {
const { source: o, message: s } = e;
const { senderProfileId: c } = s.content;
if (r.items.get(e.id) !== e || o.expiresAt <= t.now()) return;
const u = a(e.targetKey);
if (!u || u.target.entry.sessionId !== s.sessionId) return;
const d = {
agentId: u.target.agentId,
sessionKey: u.target.canonicalKey,
entry: u.target.entry
};
const f = l.recipientProfile(e.recipientProfileId, d, n);
const p = l.readProfile(c);
return f && f.profileId !== p?.profileId ? {
target: d,
recipient: f,
sender: p,
sessionTitle: u.sessionTitle
} : void 0;
}
function projectItem(e, t) {
const n = _.get(e);
if (n && n.sender === t.sender && n.value.sessionTitle === t.sessionTitle && n.value.expiresAt === e.source.expiresAt) return n.value;
const { content: r } = e.message;
const i = {
...r,
id: e.id,
excerpt: r.excerpt,
expiresAt: e.source.expiresAt,
senderProfileId: t.sender?.profileId ?? r.senderProfileId,
senderLabel: humanMentionDisplayLabel(t.sender?.label, r.senderProfileId),
senderAvatarUrl: t.sender?.avatarUrl,
sessionTitle: t.sessionTitle
};
_.set(e, {
sender: t.sender,
value: i
});
return i;
}
function readView(t, n, r, a = i) {
const o = l.identify(t, n);
if (!o.ok) return o;
const s = o.value;
const c = [];
const u = a.itemsByProfile.get(s.profile.profileId);
for (const e of u ?? []) {
const t = currentTarget(e, n, a);
if (t && s.canRead(t.target)) c.push(projectItem(e, t));
}
c.reverse();
const d = t && g.get(t);
if (d?.profileId === s.profile.profileId && isDeepStrictEqual(d.result.items, c)) return ok(d.result);
const f = {
gatewayInstanceId: e.gatewayInstanceId,
revision: d ? d.result.revision + 1 : 0,
items: c
};
if (t && r) g.set(t, {
profileId: s.profile.profileId,
result: f
});
return ok(f);
}
function publishConnectedViews() {
if (t.signal.aborted) return;
const n = e.getRuntimeConfig();
for (const t of e.getClients()) {
if (!t.connId) continue;
const r = g.get(t);
const i = readView(t, n, true);
if (!i.ok || (r ? r.result.revision === i.value.revision : i.value.items.length === 0)) continue;
e.broadcastToConnIds("mentions.changed", {
gatewayInstanceId: e.gatewayInstanceId,
revision: i.value.revision
}, /* @__PURE__ */ new Set([t.connId]));
}
}
async function refreshConnectedViews() {
await s();
publishConnectedViews();
}
function scheduleExpiry() {
if (d || t.signal.aborted || i.processed.size === 0 && m === 0) return;
t.schedule({
id: `mentions:expiry:${e.gatewayInstanceId}`,
atMs: m || i.nextExpiryAt,
run: refresh
});
}
async function refresh() {
if (d || t.signal.aborted) return;
const e = performance.now();
let r = "admission";
try {
await enqueue(async () => {
if (t.now() < m) return;
r = "maintenance";
await maintain();
n.admission.assertCurrent();
r = "sharing";
await s();
r = "publication";
publishConnectedViews();
m = 0;
h = 0;
scheduleExpiry();
});
} catch (i) {
if (d || t.signal.aborted) return;
h = Math.min(h ? h * 2 : 6e4, 9e5);
m = t.now() + h;
log$6.warn(`Unable to refresh the mention Inbox; current reads will retry. phase=${r} error=${readErrorName(i) || "unknown"} code=${extractErrorCode(i) ?? "unknown"} elapsedMs=${Math.round(performance.now() - e)} retryAfterMs=${h} cause=${formatErrorMessage(i, { includeCode: true })}`, { source: n.admission.databasePath });
scheduleExpiry();
}
}
function invalidateAsync(e) {
c(e);
l.invalidateDirectory();
return refresh();
}
const x = sessionChanges.subscribeFacts((e) => {
if (!sessionChangeScopeAffectsStoredRows(e)) return;
if (!("facts" in e) || !e.facts || ![
"participants",
"category",
"owner",
"unchanged"
].includes(e.facts.kind) || e.factsInvalidated) p++;
c("sessionKey" in e ? e.sessionKey : void 0);
});
const S = onUserProfilesChanged(() => {
if (y) return;
y = true;
queueMicrotask(() => {
y = false;
invalidateAsync();
});
});
const C = onSessionIdentityMutation(() => {
p++;
invalidateAsync();
});
function readOperation(e) {
if (!d && !t.signal.aborted) try {
return e();
} catch {
return mentionInboxUnavailable(log$6);
}
return mentionInboxUnavailable();
}
function readResponse(t) {
const n = readOperation(() => readView(t, e.getRuntimeConfig(), true));
return n.ok ? ok({
...n.value,
items: n.value.items.map((e) => ({ ...e }))
}) : n;
}
function legacyError(e) {
warnMentionInboxDeprecation(e);
return errorShape(ErrorCodes.UNAVAILABLE, `mentionInbox.${e} is unavailable; await mentionInbox.${e}Async instead.`);
}
function dismissItems(t, n, r) {
const i = readView(n, e.getRuntimeConfig(), false, t);
if (i.ok) {
const e = new Set(i.value.items.map((e) => e.id));
for (const n of r) if (e.has(n)) removeMentionItem(t, t.items.get(n));
}
return i;
}
function publishCommittedMentions(n) {
if (t.signal.aborted || !e.onMentionCreated) return;
for (const r of n) {
const n = i.items.get(r.id);
const a = n && currentTarget(n, e.getRuntimeConfig());
if (!n || !a) continue;
const o = projectItem(n, a);
e.onMentionCreated({
id: r.id,
recipientProfileId: a.recipient.profileId,
sessionKey: o.sessionKey,
agentId: o.agentId,
senderLabel: o.senderLabel,
sessionTitle: o.sessionTitle,
prepare: () => enqueue(async () => {
await maintain();
await s();
}),
isCurrent: () => {
try {
if (t.signal.aborted) return false;
if (f) return false;
const n = i.items.get(r.id);
return Boolean(n && currentTarget(n, e.getRuntimeConfig()));
} catch {
return false;
}
}
});
}
}
async function dispose() {
d = true;
await u;
await r.drain();
t.beginClose();
S();
C();
x();
c();
l.dispose();
i.items.clear();
i.itemsByProfile.clear();
i.processed.clear();
await t.stop();
w();
}
const w = registerOpenClawStateDatabaseAsyncResource({ async close(e) {
if (!e || e.key === n.admission.identity.key || e.canonicalPath === n.admission.identity.canonicalPath) await dispose();
} });
refresh();
function recordCommittedInputAsync(t) {
const r = {
...t,
recipientProfileIds: [...t.recipientProfileIds],
committedSource: { ...t.committedSource }
};
return enqueue(async () => {
if (!prepareCommittedMentionInput(r)) return;
const t = e.getRuntimeConfig();
const { agentId: i } = resolveSessionStoreIdentity({
cfg: t,
sessionKey: r.sessionKey,
agentId: r.agentId
});
const a = await prepareSessionSharingRead({
cfg: t,
sessionKey: r.sessionKey,
agentId: i
});
try {
await l.recordCommittedInvolvementAsync(r, a);
const t = await mutate((t, n, i) => b(r, t, n, i, () => a.readCurrent(e.getRuntimeConfig()).target), () => r.recipientProfileIds.map((e) => l.readProfile(e)?.profileId ?? e));
n.admission.assertCurrent();
await refreshConnectedViews();
scheduleExpiry();
publishCommittedMentions(t);
} finally {
a.release();
}
}).catch(() => {
log$6.warn("Mention delivery could not be completed; the posted message is unchanged.");
});
}
return {
async mentionable(e, t, n) {
let r;
try {
while (l.needsDirectoryPreparation()) await l.prepareDirectory();
} catch {
r = mentionInboxUnavailable(log$6);
}
try {
if ("sessionKey" in t) await o(t.sessionKey, t.agentId);
} catch {
r = mentionInboxUnavailable(log$6);
}
n(r ?? readOperation(() => l.mentionable(e, t)));
},
validateRecipients(e, t, n) {
warnMentionInboxDeprecation("validateRecipients");
return readOperation(() => l.validateRecipients(e, t, n));
},
async validateRecipientsAsync(e, t, n) {
try {
const r = await l.prepareContext(t);
try {
return readOperation(() => l.validateRecipients(e, t, n, r));
} finally {
r.release();
}
} catch {
return mentionInboxUnavailable(log$6);
}
},
list: () => err(legacyError("list")),
dismiss: () => err(legacyError("dismiss")),
async listAsync(t, n) {
try {
await enqueue(async () => {
if (await maintain()) await refreshConnectedViews();
else {
const n = l.identify(t, e.getRuntimeConfig());
if (n.ok) await s(i.itemsByProfile.get(n.value.profile.profileId) ?? []);
}
scheduleExpiry();
});
} catch {
return n(mentionInboxUnavailable(log$6));
}
return n(readResponse(t));
},
async dismissAsync(t, n, r) {
let i;
try {
const r = [...n];
await enqueue(async () => {
await maintain();
await s();
const n = await mutate((e, n) => {
const i = dismissItems(e, t, r);
if (i.ok) {
const e = t?.authenticatedUserProfile?.profileId;
const r = JSON.stringify(t?.connect.scopes);
const i = t?.connect.role;
n.push(() => {
if (t?.invalidated || t?.internal?.syntheticClient || i !== t?.connect.role || e !== t?.authenticatedUserProfile?.profileId || r !== JSON.stringify(t?.connect.scopes)) throw new Error("Mention caller changed before dismissal");
});
}
return i;
}, () => {
const n = l.identify(t, e.getRuntimeConfig());
return n.ok ? [n.value.profile.profileId] : [];
});
await refreshConnectedViews();
scheduleExpiry();
if (!n.ok) i = n;
});
} catch {
i = mentionInboxUnavailable(log$6);
}
r(i ?? readResponse(t));
},
recordCommittedInput(e) {
warnMentionInboxDeprecation("recordCommittedInput");
if (d || t.signal.aborted) return;
const r = structuredClone(e);
const record = () => void recordCommittedInputAsync(r);
const i = openClawStateDatabaseCache.getOpenClawStateDatabaseIfOpenAtPath(n.admission.identity.canonicalPath);
if (!i || !deferSqlitePostCommitPublication(i.db, record)) record();
},
recordCommittedInputAsync,
invalidate() {
throw new Error(legacyError("invalidate").message);
},
invalidateAsync,
dispose
};
}
//#endregion
//#region src/gateway/server-broadcast-live-text.ts
const log$5 = createSubsystemLogger("gateway/broadcast");
/** Socket-owned queues and receipts share the run's retirement and subscription lifecycle. */
function createGatewayLiveTextDelivery(e) {
const t = /* @__PURE__ */ new WeakMap();
const n = /* @__PURE__ */ new WeakMap();
const deliveryFor = (e) => {
let n = t.get(e);
if (!n) {
n = {
socket: e.socket,
retired: false,
inFlight: 0,
draining: false,
bytes: 0,
groups: /* @__PURE__ */ new Map(),
pending: /* @__PURE__ */ new Set()
};
t.set(e, n);
}
return n;
};
const bufferedBytes = (e) => e.socket.bufferedAmount + e.bytes;
const takePending = (e, t) => {
e.pending.delete(t);
const n = e.groups.get(t.group);
n.entries.delete(t.key);
if (!n.entries.size && !n.receipts.size) {
t.group.removeEventListener("abort", n.retire);
e.groups.delete(t.group);
}
e.bytes -= t.bytes;
};
const retireDelivery = (e) => {
e.retired = true;
for (const [t, n] of e.groups) t.removeEventListener("abort", n.retire);
e.groups.clear();
e.pending.clear();
e.bytes = 0;
if (e.close) {
e.socket.off("close", e.close);
e.close = void 0;
}
};
const groupFor = (e, t) => {
if (!e.close) {
e.close = () => retireDelivery(e);
e.socket.once("close", e.close);
}
let n = e.groups.get(t);
if (!n) {
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
const retire = () => {
i.clear();
for (const t of r.values()) takePending(e, t);
e.groups.delete(t);
};
n = {
entries: r,
receipts: i,
retire
};
e.groups.set(t, n);
t.addEventListener("abort", retire, { once: true });
}
return n;
};
e.sessionMessageSubscribers?.onChange((n, r) => {
const i = e.clients.getByConnectionId(r);
const a = i && t.get(i);
for (const e of a?.groups.values() ?? []) for (const [t, r] of e.receipts) if (r.sessionKeys.includes(n)) e.receipts.delete(t);
});
const drain = (e, t) => {
if (e.retired || e.draining) return;
e.draining = true;
try {
for (const n of e.pending) {
if (t ? n.group !== t : e.inFlight !== 0) {
if (t) continue;
break;
}
takePending(e, n);
try {
n.send();
} catch (e) {
log$5.error(`broadcast pending send failed: ${formatErrorMessage$1(e)}`);
}
}
} finally {
e.draining = false;
}
};
const publish = (e) => {
if (!e?.projection || e.group.aborted) return;
let t = n.get(e.group);
if (!t) {
t = /* @__PURE__ */ new Map();
n.set(e.group, t);
e.group.addEventListener("abort", () => n.delete(e.group), { once: true });
}
const r = t.get(e.projection.key);
const i = r?.sourceEpoch === e.sourceEpoch ? r : void 0;
const a = {
key: e.projection.key,
sourceEpoch: e.sourceEpoch,
previous: i?.revision,
revision: {},
version: e.projection.version,
text: e.projection.text?.snapshot,
snapshot: e.projection.snapshot || !Object.is(i?.version, e.projection.version) || e.projection.text !== void 0 && !isLiveTextAppend(i?.text, e.projection.text)
};
t.set(a.key, a);
return a;
};
return {
deliveryFor,
bufferedBytes,
takePending,
retireDelivery,
drain,
publish,
pending: (e, t, n) => e.groups.get(t)?.entries.get(n),
enqueue: (e, t) => {
groupFor(e, t.group).entries.set(t.key, t);
e.pending.add(t);
e.bytes += t.bytes;
},
coalescePublication: (e, t) => e && {
...e,
previous: t ? t.previous : e.previous,
snapshot: e.snapshot || t?.snapshot || t !== void 0 && t.revision !== e.previous
},
canSendDelta: (e, t, n) => {
const r = n && t && e.groups.get(t.group)?.receipts.get(n.key);
return Boolean(n && r && r.revision === n.previous && Object.is(r.version, n.version) && !n.snapshot);
},
recordReceipt: (e, t, n, r) => {
if (r && n && !n.group.aborted) groupFor(e, n.group).receipts.set(r.key, {
revision: r.revision,
version: r.version,
sessionKeys: t
});
}
};
}
//#endregion
//#region src/gateway/server-broadcast-scopes.ts
const EVENT_SCOPE_GUARDS = {
agent: [SESSION_READ_SCOPE],
chat: [SESSION_READ_SCOPE],
"chat.metadata.changed": [SESSION_READ_SCOPE],
"board.changed": [SESSION_READ_SCOPE],
"board.command": [SESSION_READ_SCOPE],
"progressCard.changed": [SESSION_READ_SCOPE],
"ui.command": [READ_SCOPE],
"chat.send_timing": [READ_SCOPE],
"chat.side_result": [SESSION_READ_SCOPE],
cron: [READ_SCOPE],
"cron.inventory.changed": [READ_SCOPE],
health: [],
"exec.approval.requested": [APPROVALS_SCOPE],
"exec.approval.resolved": [APPROVALS_SCOPE],
"question.requested": [QUESTIONS_SCOPE],
"question.resolved": [QUESTIONS_SCOPE],
heartbeat: [],
"plugin.approval.requested": [APPROVALS_SCOPE],
"plugin.approval.resolved": [APPROVALS_SCOPE],
"openclaw.approval.requested": [APPROVALS_SCOPE],
"openclaw.approval.resolved": [APPROVALS_SCOPE],
presence: [READ_SCOPE],
shutdown: [],
"gateway.suspension": [],
tick: [],
"talk.event": [READ_SCOPE],
"talk.mode": [TALK_SCOPE],
"talk.voice.change": [TALK_SCOPE],
task: [READ_SCOPE],
"task.suggestion": [READ_SCOPE],
"update.available": [],
[GATEWAY_EVENT_UPDATE_RUN_CHANGED]: [ADMIN_SCOPE],
"config.changed": [READ_SCOPE],
"agent.identity.changed": [READ_SCOPE],
"users.prefs.changed": [SESSION_READ_SCOPE],
"mentions.changed": [SESSION_READ_SCOPE],
"mentions.failed": [SESSION_READ_SCOPE],
"skills.changed": [READ_SCOPE],
"plugins.changed": [READ_SCOPE],
"plugins.install.progress": [ADMIN_SCOPE],
"voicewake.changed": [READ_SCOPE],
"voicewake.routing.changed": [READ_SCOPE],
[GATEWAY_EVENT_DEVICE_PAIR_CHANGED]: [PAIRING_SCOPE],
"device.pair.requested": [PAIRING_SCOPE],
"device.pair.resolved": [PAIRING_SCOPE],
"device.pair.setup.completed": [PAIRING_SCOPE],
"device.pair.setup.deliveryUncertain": [PAIRING_SCOPE],
"node.pair.requested": [PAIRING_SCOPE],
"node.pair.resolved": [PAIRING_SCOPE],
"node.presence": [READ_SCOPE],
"node.hostStats": [READ_SCOPE],
[GATEWAY_EVENT_NODE_RUNNER_INVENTORY_CHANGED]: [READ_SCOPE],
"sessions.catalog.host": [READ_SCOPE],
"sessions.changed": [SESSION_READ_SCOPE],
"sessions.processes.changed": [SESSION_READ_SCOPE],
"controlUi.sessionPullRequests.changed": [SESSION_READ_SCOPE],
"plugins.controlUi.changed": [READ_SCOPE],
"mcp.app.resourceUpdated": [READ_SCOPE],
"mcp.app.hostContextChanged": [READ_SCOPE],
"session.approval": [APPROVALS_SCOPE],
"session.message": [SESSION_READ_SCOPE],
"session.narration": [SESSION_READ_SCOPE],
"session.observer": [SESSION_READ_SCOPE],
"session.operation": [READ_SCOPE],
"session.sharing": [READ_SCOPE],
"session.sharing.evidence": [READ_SCOPE],
"session.suggestion": [SESSION_READ_SCOPE],
"session.reaction": [SESSION_READ_SCOPE],
"session.typing": [SESSION_READ_SCOPE],
"session.tool": [SESSION_READ_SCOPE],
"socket.drain": [SESSION_READ_SCOPE],
"terminal.data": [ADMIN_SCOPE],
"terminal.exit": [ADMIN_SCOPE],
"portal.changed": [READ_SCOPE]
};
const SESSION_CATALOG_INVALIDATIONS = /* @__PURE__ */ new Set([
"delete",
"groups",
"sharing",
"profile-identity"
]);
/** Classify source envelopes without invoking getters, toJSON, or Proxy traps. */
function isPlainEventPayload(e) {
if (isProxy(e) || !isRecord(e)) return false;
const t = Object.getPrototypeOf(e);
return (t === null || t === Object.prototype) && !("toJSON" in e);
}
function isSessionReadInvalidation(e, t, n) {
if (!isPlainEventPayload(t)) return false;
const r = Object.entries(Object.getOwnPropertyDescriptors(t));
if (e === "mentions.changed") return n && Object.hasOwn(t, "gatewayInstanceId") && Object.hasOwn(t, "revision") && r.every(([e, t]) => "value" in t && (e === "gatewayInstanceId" && typeof t.value === "string" || e === "revision" && Number.isSafeInteger(t.value) && t.value >= 0));
return e === "sessions.changed" && n && Object.hasOwn(t, "reason") && r.every(([e, t]) => "value" in t && (e === "reason" && SESSION_CATALOG_INVALIDATIONS.has(t.value) || e === "ts" && typeof t.value === "number" && Number.isFinite(t.value)));
}
function modelMetadataInvalidationFragment(e) {
if (!isPlainEventPayload(e)) return;
const t = Reflect.ownKeys(e);
if (t.length === 0) return ",\"payload\":{}";
const n = {};
for (const r of t) {
if (r !== "modelSelectionChanged" && r !== "modelCatalogChanged" && r !== "authChanged") return;
const t = Object.getOwnPropertyDescriptor(e, r);
if (!t?.enumerable || !("value" in t) || typeof t.value !== "boolean" || r === "modelSelectionChanged" && !t.value) return;
n[r] = t.value;
}
return `,"payload":${JSON.stringify(n)}`;
}
function hasEventScope(e, t, n, r = false, i) {
if (e.connectionKind === "worker") return false;
const a = e.connect.role ?? "operator";
const o = e.connect.scopes ?? [];
const s = EVENT_SCOPE_GUARDS[t];
const c = n || (!s && t.startsWith("plugin.") ? "operator.write" : void 0);
if (c) return a === "operator" && operatorScopeSatisfied(c, o);
if (!s) return false;
return s.length === 0 || a === "operator" && (s.some((e) => operatorScopeSatisfied(e, o) && (e !== "operator.sessions.read" || operatorScopeSatisfied("operator.read", o) || i?.() === true)) || r && operatorScopeSatisfied("operator.sessions.write", o));
}
//#endregion
//#region src/gateway/server-broadcast-narration.ts
const NARRATION_INTERVAL_MS = 2e3;
/** Per-session pacing retains only the newest publication, never token queues. */
function createGatewayNarrationDelivery(e) {
const t = /* @__PURE__ */ new WeakMap();
const n = /* @__PURE__ */ new WeakMap();
const r = e.sessionMessageSubscribers;
const isNarration = (e, t) => {
let n = false;
for (const i of t) if (r?.get(i).has(e)) {
if (!r.getNarration(i).has(e)) return false;
n = true;
}
return n;
};
const cancelPending = (e) => {
clearTimeout(e.timer);
e.timer = void 0;
e.pending = void 0;
};
const connectionFor = (e) => {
const n = t.get(e);
if (n) return n;
const r = e.socket;
const i = /* @__PURE__ */ new Map();
const close = () => {
for (const e of i.values()) cancelPending(e);
i.clear();
r.off("close", close);
t.delete(e);
};
const a = {
sessions: i,
close
};
t.set(e, a);
r.once("close", close);
return a;
};
r?.onChange((n, r, i) => {
const a = e.clients.getByConnectionId(r);
const o = a && t.get(a);
if (i || !o) return;
for (const [e, t] of o.sessions) if (t.subscriptionKeys.includes(n)) {
cancelPending(t);
o.sessions.delete(e);
}
if (o.sessions.size === 0) o.close();
});
const projectionFor = (e, t, r) => {
const i = n.get(e);
if (i && i.explicitAgentId === r) return i;
const a = normalizeOptionalLowercaseString(r ?? e.agentId) ?? parseAgentSessionKey(t)?.agentId;
const o = {
explicitAgentId: r,
agentId: a,
key: `${t.length}:${t}${a ?? ""}`
};
n.set(e, o);
return o;
};
const project = (e, t) => {
if (t.digest) return t.digest;
const n = stripInternalRuntimeContext(sanitizeAssistantVisibleTextWithProfile(extractAssistantPhaseText(e.message) ?? "", "internal-scaffolding", e.state === "delta"), { streaming: e.state === "delta" });
const r = {
sessionKey: String(e.sessionKey),
runId: String(e.runId),
...t.agentId ? { agentId: t.agentId } : {},
text: sliceUtf16Safe(n, -16384)
};
t.digest = r;
return r;
};
const flush = (t, n) => {
const r = n.pending;
cancelPending(n);
if (!r || !e.clients.has(t)) return;
const { payload: i, projection: a, sessionKeys: o, opts: s } = r;
const c = s?.liveText;
if (!isNarration(t.connId, o) || c?.group.aborted) return;
try {
if (c?.isCurrent?.() === false) return;
} catch {
return;
}
const l = project(i, a);
if (n.last?.runId === l.runId && n.last.text === l.text) return;
n.lastSentAt = Date.now();
n.last = l;
e.send("session.narration", l, /* @__PURE__ */ new Set([t.connId]), {
sessionKeys: o,
agentId: a.agentId,
dropIfSlow: true,
sessionSubscriptionVerified: true
});
};
return {
isNarration,
prepareToolPayload: (e, t) => {
if (e !== "agent" && e !== "session.tool" || !isPlainEventPayload(t) || t.stream !== "tool" || !isPlainEventPayload(t.data)) return;
const n = t.data;
return () => {
const { args: e, diff: r, partialResult: i, result: a, ...o } = n;
return {
...t,
data: o
};
};
},
consume: (e, n, r, i, a) => {
if (n === "session.narration") return !isNarration(e.connId, i);
if (n !== "chat" && n !== "agent" && n !== "session.tool" && n !== "session.observer") return false;
if (!isRecord(r) || !isNarration(e.connId, i)) return false;
if (n === "agent") {
if (r.stream === "assistant" || r.stream === "thinking") return true;
if (r.stream === "item" && isRecord(r.data) && r.data.phase === "update" && (r.data.kind === "preamble" || r.data.kind === "answer_candidate" && r.data.status === "candidate")) return true;
}
if (typeof r.sessionKey !== "string") return false;
const o = projectionFor(r, r.sessionKey, a?.agentId);
const s = o.key;
const c = t.get(e)?.sessions.get(s);
if (c?.pending && (typeof r.runId === "string" && r.runId.trim().length > 0 && r.runId !== c.pending.payload.runId || (n === "agent" || n === "session.tool") && r.stream === "tool" && isRecord(r.data) && typeof r.data.name === "string" && r.data.name.trim().length > 0)) cancelPending(c);
if (n !== "chat" || typeof r.runId !== "string") return false;
const l = r.state === "delta";
const u = r.state === "final" || r.state === "error" || r.state === "aborted";
if (!l && !u) return false;
const d = connectionFor(e);
const f = d.sessions.get(s) ?? { subscriptionKeys: i };
f.subscriptionKeys = i;
d.sessions.set(s, f);
if (isRecord(r.message)) f.pending = {
payload: r,
projection: o,
sessionKeys: i,
opts: a
};
if (u) {
if (f.pending?.payload.runId === r.runId) flush(e, f);
} else if (f.pending) {
const t = NARRATION_INTERVAL_MS - (Date.now() - (f.lastSentAt ?? -Infinity));
if (t <= 0) flush(e, f);
else if (!f.timer) f.timer = setTimeout(() => flush(e, f), t).unref();
}
return l;
}
};
}
//#endregion
//#region src/gateway/session-event-metrics.ts
const sessionChangeReasons = /* @__PURE__ */ new Set([
"abort",
"activity-summary",
"agent.input.settled",
"agent.run.started",
"archive",
"board",
"branch-switch",
"chat.dispatch-error",
"chat.title",
"cleanup",
"compact",
"create",
"cron-continuation",
"cron-binding",
"cron-bindings-loaded",
"delete",
"dispatch",
"fork",
"github-publication",
"goal",
"groups",
"involvement",
"move",
"new",
"owner",
"participants",
"patch",
"placement",
"plugin-patch",
"progress-card-reset",
"project",
"reclaim",
"recovery",
"reset",
"rewind",
"run-capacity",
"send",
"sharing",
"steer",
"subagent-status",
"swarm-note",
"title",
"unarchive",
"update",
"updated",
"worker-disk-space",
"worker-runtime-install"
]);
const lifecyclePhases = /* @__PURE__ */ new Set([
"start",
"model",
"end",
"error",
"message"
]);
const messageRoles = /* @__PURE__ */ new Set([
"user",
"assistant",
"system",
"developer",
"tool",
"toolResult"
]);
function gatewaySessionEventReason(e, t) {
if (e !== "sessions.changed" && e !== "session.message") return;
const n = isRecord(t) ? t : void 0;
if (e === "session.message") {
const e = isRecord(n?.message) ? n.message.role : void 0;
return e === void 0 ? "message" : typeof e === "string" && messageRoles.has(e) ? e : "other";
}
const r = n?.reason ?? n?.phase;
return typeof r === "string" && (n?.reason !== void 0 ? sessionChangeReasons.has(r) : lifecyclePhases.has(r)) ? r : "other";
}
/** Resolve label values and subscription sets once; every recipient reuses the same two facts. */
function prepareSessionEventMetrics(e, t, n, r) {
const i = gatewaySessionEventReason(e, t);
if (i === void 0) return;
const a = n.map((e) => r?.get(e));
const o = {
reason: i,
delivery: "subscribed"
};
const s = {
reason: i,
delivery: "roster"
};
return (e) => a.some((t) => t?.has(e)) ? o : s;
}
//#endregion
//#region src/gateway/server-broadcast.ts
const log$4 = createSubsystemLogger("gateway/broadcast");
const SESSION_SUBSCRIPTION_EVENTS = /* @__PURE__ */ new Set([
"agent",
"chat",
"chat.side_result",
"session.observer",
"session.narration",
"session.tool",
"socket.drain"
]);
function serializeFrameField(e, t, n, r) {
const i = n ? t : void 0;
const a = i && !("toJSON" in i) && !("toJSON" in Object.prototype) ? i : void 0;
const o = a ? n?.() : void 0;
const s = a ? r?.() : void 0;
const c = a?.session;
const l = a?.message;
if (a) {
a.session = void 0;
if (s) a.message = void 0;
}
let u;
try {
u = JSON.stringify({ [e]: t });
} finally {
if (a) {
a.session = c;
if (s) a.message = l;
}
}
if (a) {
const e = u.endsWith("{}}") ? "" : ",";
const t = `,${u.slice(1, -2)}${e}`;
const n = `"session":${o}}`;
return s ? [
Buffer.from(t),
s,
Buffer.from(n)
] : [Buffer.from(`${t}${n}`)];
}
const d = u.startsWith(`{"${e}":`) ? `,${u.slice(1, -1)}` : "";
return n ? [Buffer.from(d)] : d;
}
function resolveBroadcastSessionScope(e, t, n) {
if (!e || typeof e !== "object" || Array.isArray(e)) return {
sessionKeys: t ?? [],
...n ? { agentId: n } : {}
};
const r = e;
const i = [
r,
r.suggestion,
r.request
].find((e) => typeof e?.sessionKey === "string" && e.sessionKey.trim());
const a = typeof i?.sessionKey === "string" ? i.sessionKey.trim() : "";
const o = n ?? (typeof i?.agentId === "string" ? i.agentId.trim() || void 0 : void 0);
return {
sessionKeys: t?.length ? t : a ? [a] : [],
...o ? { agentId: o } : {}
};
}
const MAX_SERVER_FRAME_HEADER_BYTES = 10;
const MAX_RECIPIENT_PROFILE_FIELD_BYTES = Buffer.byteLength(",\"recipientProfileId\":\"\"") + 128 * 6;
function frameWithSequence(e, t, n, r) {
const i = r === void 0 ? "" : `,"recipientProfileId":${JSON.stringify(r)}`;
const a = Buffer.from(`,"seq":${t}${e.stateVersionFragment}${i}}`);
if (Buffer.isBuffer(n)) return new SerializedGatewayFrame([
e.prefix,
n,
a
]);
const o = typeof n === "string" ? [Buffer.from(n)] : n;
if (o.length === 1) return new SerializedGatewayFrame([
e.prefix,
o[0],
a
]);
return new SerializedGatewayFrame([
Buffer.concat([e.prefix, o[0]]),
o[1],
Buffer.concat([o[2], a])
]);
}
function createGatewayBroadcaster(e) {
const t = /* @__PURE__ */ new WeakMap();
const n = /* @__PURE__ */ new WeakSet();
const deliveryLost = (t) => {
t.presenceSnapshot = void 0;
e.onSessionDeliveryLost?.(t);
};
const r = createGatewayLiveTextDelivery(e);
const i = createGatewayNarrationDelivery({
...e,
send: (e, t, n, r) => broadcastInternal(e, t, r, n)
});
const isCurrent = (e) => {
try {
return e?.() !== false;
} catch {
return false;
}
};
const broadcastInternal = (a, o, s, c, l, u) => {
if (!u) invalidateSharedReadResponses(broadcast, a);
if (!u && a === "sessions.changed") queuePluginSessionsChanged(o);
const d = s?.liveText;
const f = u ? u.publication : r.publish(d);
if (e.clients.size === 0 || !u && c?.size === 0) return;
const { sessionKeys: p, agentId: m } = resolveBroadcastSessionScope(o, s?.sessionKeys, s?.agentId);
let h = null;
const g = s?.sessionSubscriptionVerified === true;
const _ = SESSION_SUBSCRIPTION_EVENTS.has(a);
const v = e.sessionMessageSubscribers;
const y = a === "session.typing" || g;
let b;
let x = c;
if (!u && !x && (y || _)) {
const t = new Set(y ? void 0 : e.clients.unscopedSessionEventConnIds);
b = v ? p.map((e) => v.get(e)) : [];
for (const e of b) for (const n of e) t.add(n);
if (t.size === 0) return;
x = t;
}
const S = Boolean(c);
const C = a === "presence" ? o : void 0;
const w = a === "chat.metadata.changed" ? modelMetadataInvalidationFragment(o) : void 0;
const T = a === "chat" && isPlainEventPayload(o) && o.state === "status" && o.phase === "waiting_for_model";
const E = i.prepareToolPayload(a, o);
let D;
const hasSessionReadContext = () => D ??= a === "users.prefs.changed" && S || e.canReceiveSessionEvent !== void 0 && p.length > 0 && p.every((e) => e.trim().length > 0) || w !== void 0 || isSessionReadInvalidation(a, o, S);
let O;
let k;
let A;
let j;
let M = false;
let N = false;
let P = false;
const F = /* @__PURE__ */ new Map();
const I = u?.frames ?? {};
let L;
const getFrameFields = () => I.fields ??= {
prefix: Buffer.from(`{"type":"event","event":${JSON.stringify(a)}`),
stateVersionFragment: s?.stateVersion === void 0 ? "" : serializeFrameField("stateVersion", s.stateVersion)
};
const frameBaseFor = (e) => ({
...getFrameFields(),
payloadFragment: C ? "" : Buffer.from(e === o && w !== void 0 ? w : serializeFrameField("payload", e))
});
const R = u ? [u.client] : x ? e.clients.getByConnectionIds(x) : e.clients;
for (const x of R) {
if (!e.clients.has(x) || x.invalidated === true || x.socket.readyState !== 1 || T && !hasGatewayClientCap(x.connect.caps, GATEWAY_CLIENT_CAPS.MODEL_WAIT_STATUS) || s?.excludeClientCapability && hasGatewayClientCap(x.connect.caps, s.excludeClientCapability)) continue;
const D = a === "question.requested" || a === "question.resolved" ? s?.questionRecipient : void 0;
const R = D !== void 0 && !operatorScopeSatisfied("operator.questions", x.connect.scopes ?? []);
if (!hasEventScope(x, a, l, R, hasSessionReadContext)) continue;
if (a === "chat.metadata.changed" && !operatorScopeSatisfied("operator.read", x.connect.scopes ?? []) && w === void 0) continue;
if (D && !isCurrent(() => D(x))) continue;
if ((y || _ && !e.clients.unscopedSessionEventConnIds.has(x.connId)) && !(S && g && !u)) {
if (!p.length || !v) continue;
b ??= p.map((e) => v.get(e));
if (!b.some((e) => e.has(x.connId))) continue;
}
if (!D && p.length > 0 && e.canReceiveSessionEvent && !e.canReceiveSessionEvent(x, p, m, a, o)) continue;
if (u && !isCurrent(d?.isCurrent) || d?.coalesce && d.group.aborted) continue;
if (i.consume(x, a, o, p, s)) continue;
if (!P) {
P = true;
logWs("out", "event", () => {
const t = {
event: a,
seq: "per-client",
clients: e.clients.size,
targets: c ? c.size : void 0,
dropIfSlow: s?.dropIfSlow,
presenceVersion: s?.stateVersion?.presence,
healthVersion: s?.stateVersion?.health
};
if (a === "agent") Object.assign(t, summarizeAgentEventForWsLog(o));
return t;
});
}
const z = r.deliveryFor(x);
if (d && !d.coalesce) r.drain(z, d.group);
if (z.retired) continue;
const B = (t.get(x) ?? 0) + 1;
const V = r.bufferedBytes(z);
const H = V > MAX_BUFFERED_BYTES;
if (!H) n.delete(x);
else if (!n.has(x)) {
n.add(x);
logRejectedLargePayload({
surface: "gateway.ws.outbound_buffer",
bytes: V,
limitBytes: MAX_BUFFERED_BYTES,
reason: s?.dropIfSlow ? "ws_send_buffer_drop" : "ws_send_buffer_close"
});
}
if (H && s?.dropIfSlow) {
t.set(x, B);
deliveryLost(x);
continue;
}
if (H) {
deliveryLost(x);
r.retireDelivery(z);
closeGatewayTransportWithGrace(z.socket, 1008, "slow consumer");
continue;
}
if (!u && d?.coalesce && z.inFlight > 0) {
let e = r.pending(z, d.group, d.coalesce.key);
if (e && !isCurrent(e.isCurrent)) {
r.takePending(z, e);
e = void 0;
}
try {
const t = e ? L?.get(e.payload) : void 0;
const n = t ? t.payload : e ? d.coalesce.merge(e.payload, o) : o;
const i = t?.frames ?? (n === o ? I : {});
if (e && !t && n !== o) (L ??= /* @__PURE__ */ new Map()).set(e.payload, {
payload: n,
frames: i
});
if (i.reservedBytes === void 0) {
const e = d.projection;
const t = e?.snapshotBytes;
const r = t && e ? i.delta ??= frameBaseFor(e.delta(n)) : i.snapshot ??= frameBaseFor(n);
const a = Buffer.byteLength(r.payloadFragment);
const o = Buffer.byteLength(",\"payload\":");
i.fields = getFrameFields();
i.reservedBytes = frameWithSequence(r, Number.MAX_SAFE_INTEGER, "").byteLength + (t ? o + t(n, a - o) : a) + MAX_SERVER_FRAME_HEADER_BYTES + MAX_RECIPIENT_PROFILE_FIELD_BYTES;
}
const u = i.reservedBytes;
if (r.bufferedBytes(z) - (e?.bytes ?? 0) + u <= 52428800) {
if (e) r.takePending(z, e);
const t = r.coalescePublication(f, e?.publication);
const o = {
group: d.group,
key: d.coalesce.key,
payload: n,
bytes: u,
isCurrent: d.isCurrent,
publication: t,
send: () => broadcastInternal(a, n, s, c, l, {
client: x,
frames: i,
publication: t
})
};
r.enqueue(z, o);
continue;
}
} catch (e) {
deliveryLost(x);
log$4.error(`broadcast serialization failed for event ${a}: ${formatErrorMessage$1(e)}`);
return;
}
r.drain(z, d.group);
broadcastInternal(a, o, s, c, l, {
client: x,
frames: I,
publication: f
});
continue;
}
const U = r.canSendDelta(z, d, f);
const W = d?.projection;
const getDeliveryFrameBase = () => E && i.isNarration(x.connId, p) ? I.toolNarration ??= frameBaseFor(E()) : a === "health" && x.connect.caps?.includes(GATEWAY_CLIENT_CAPS.HEALTH_SUMMARY) ? I.healthSummary ??= frameBaseFor(projectHealthSummary(o)) : U && W ? I.delta ??= frameBaseFor(W.delta(o)) : I.snapshot ??= frameBaseFor(o);
let G;
let K;
let q;
try {
if (!N) {
getFrameFields();
const t = !u && (a === "session.message" || a === "sessions.changed") && isPlainEventPayload(o);
if (!t) getDeliveryFrameBase();
j = e.prepareSessionEventProjection?.(a, o, {
sessionKeys: p,
agentId: m,
...s?.prepareSessionProjection ? { prepareSessionProjection: s.prepareSessionProjection } : {}
});
M = t && j !== void 0;
N = true;
}
const t = M ? getFrameFields() : getDeliveryFrameBase();
let n = M ? "" : getDeliveryFrameBase().payloadFragment;
if (C) {
if (!e.preparePresenceProjection) throw new Error("presence recipient projection unavailable");
O ??= e.preparePresenceProjection(C.presence);
const t = {
...C,
presence: O(x)
};
if (acceptsPresenceDeltas(x) && s?.stateVersion?.presence !== void 0) {
q = preparePresenceDelivery(x, C.presence, t.presence, s.stateVersion.presence);
n = q.fragment;
} else {
const e = Object.keys(t).length === 1 && !("toJSON" in t);
n = (e ? k?.get(t.presence) : void 0) ?? serializeFrameField("payload", t);
if (e && typeof n === "string") {
n = Buffer.from(n);
(k ??= /* @__PURE__ */ new Map()).set(t.presence, n);
}
}
}
if (j) {
const e = j(x);
if (e === void 0) continue;
const t = e.serializeSession && (A ??= /* @__PURE__ */ new Map());
n = t?.get(e.payload) || e.serializePayload?.() || serializeFrameField("payload", e.payload, e.serializeSession, e.serializeMessage);
t?.set(e.payload, n);
K = e.delivered;
}
const r = (x.connect.role ?? "operator") === "operator" ? x.preparedRecipientProfileId : void 0;
let i = F.get(n);
if (!i) F.set(n, i = /* @__PURE__ */ new Map());
let c = i.get(r);
if (!c) i.set(r, c = /* @__PURE__ */ new Map());
G = c.get(B);
if (G === void 0) {
G = frameWithSequence(t, B, n, r);
c.set(B, G);
}
if (h === null) h = prepareSessionEventMetrics(a, o, s?.sessionEventSubscriptionKeys ?? p, e.sessionMessageSubscribers);
} catch (e) {
deliveryLost(x);
log$4.error(`broadcast serialization failed for event ${a}: ${formatErrorMessage$1(e)}`);
return;
}
t.set(x, B);
r.recordReceipt(z, p, d, f);
z.inFlight += 1;
let J = false;
const sent = (e) => {
if (J) return;
J = true;
z.inFlight -= 1;
if (z.retired) return;
if (e) {
deliveryLost(x);
r.retireDelivery(z);
log$4.error(`broadcast send failed conn=${x.connId}: ${formatErrorMessage$1(e)}`, { event: a });
z.socket.terminate();
} else r.drain(z);
};
try {
K?.(x);
z.socket.batchWrites?.();
const e = z.socket.send(G, { binary: false }, sent);
if (q && !z.retired) x.presenceSnapshot = q.snapshot;
z.socket.recordEventSent?.(a, G, h?.(x.connId), q?.mode ?? (C ? "legacy" : void 0), e);
} catch (e) {
sent(e instanceof Error ? e : new Error(String(e)));
}
}
};
const broadcast = (t, n, r) => {
e.onBroadcast?.(t, n, r);
broadcastInternal(t, n, r);
};
const broadcastToConnIds = (e, t, n, r) => broadcastInternal(e, t, r, n);
const getBufferedAmount = (t) => {
const n = e.clients.getByConnectionId(t);
if (!n || n.invalidated || n.socket.readyState !== 1) return;
const i = r.deliveryFor(n);
return i.retired ? void 0 : r.bufferedBytes(i);
};
const broadcastPluginEvent = (e, t, n) => {
if (!e.startsWith("plugin.") || e.startsWith("plugin.approval.")) throw new Error(`invalid plugin gateway event: ${e}`);
if (n !== "operator.read" && n !== "operator.write" && n !== "operator.admin") throw new Error("invalid plugin gateway event scope");
broadcastInternal(e, t, void 0, void 0, n);
};
return {
broadcast,
broadcastToConnIds,
broadcastPluginEvent,
getBufferedAmount
};
}
//#endregion
//#region src/gateway/server/client-registry.ts
var GatewayClientRegistry = class extends Set {
#e = /* @__PURE__ */ new Map();
#t = /* @__PURE__ */ new Set();
#n = 0;
#r;
#i = /* @__PURE__ */ new Map();
get unscopedSessionEventConnIds() {
return this.#t;
}
get authorityClients() {
return { [Symbol.iterator]: () => (/* @__PURE__ */ new Set([...this, ...this.#i.keys()])).values() };
}
retainRequest(e) {
this.#i.set(e, (this.#i.get(e) ?? 0) + 1);
let t = false;
return () => {
if (t) return;
t = true;
const n = this.#i.get(e) - 1;
if (n === 0) this.#i.delete(e);
else this.#i.set(e, n);
};
}
constructor(e, t) {
super();
this.#r = t;
for (const t of e ?? []) this.add(t);
}
add(e) {
if (!this.has(e)) {
this.#e.set(e.connId, {
client: e,
order: this.#n++
});
if (normalizeGatewayClientName(e.connect.client?.id) !== GATEWAY_CLIENT_IDS.BROWSER_COPILOT && !hasGatewayClientCap(e.connect.caps, GATEWAY_CLIENT_CAPS.SESSION_SCOPED_EVENTS)) this.#t.add(e.connId);
super.add(e);
this.onChange?.();
}
return this;
}
delete(e) {
if (!super.delete(e)) return false;
this.#r?.(e);
if (this.#e.get(e.connId)?.client === e) {
this.#e.delete(e.connId);
this.#t.delete(e.connId);
}
this.onChange?.();
return true;
}
clear() {
if (this.size === 0) return;
for (const e of this) this.#r?.(e);
super.clear();
this.#e.clear();
this.#t.clear();
this.onChange?.();
}
getByConnectionId(e) {
return this.#e.get(e)?.client;
}
getByConnectionIds(e) {
const t = [];
for (const n of e) {
const e = this.#e.get(n);
if (e) t.push(e);
}
if (t.length > 1) t.sort((e, t) => e.order - t.order);
return t.map((e) => e.client);
}
};
//#endregion
//#region src/gateway/server-connection-state.ts
/** Creates transport-independent connection, subscription, and run state. */
function createGatewayConnectionState(e) {
const t = e.getRuntimeConfig ?? (() => e.cfg);
let n;
const r = /* @__PURE__ */ new WeakMap();
const i = new GatewayClientRegistry(void 0, (e) => {
r.get(e)?.clear("close");
r.delete(e);
e.presenceSnapshot = void 0;
});
const forgetConnectionAncestors = (e) => {
const t = i.getByConnectionId(e);
if (t) r.get(t)?.clearAncestors();
};
const clearConnectionRows = () => {
const e = /* @__PURE__ */ new Map();
for (const t of i) r.get(t)?.clear("projection", e);
};
const clearAncestors = () => {
const e = /* @__PURE__ */ new Map();
for (const t of i) r.get(t)?.clearAncestors(e);
};
const forgetAncestor = (e) => {
const t = /* @__PURE__ */ new Map();
for (const n of i) r.get(n)?.forget(e, t);
};
const isConnectionActive = (e) => {
const t = i.getByConnectionId(e);
return Boolean(t && !t.invalidated && !t.connectionSignal?.aborted);
};
const a = createSessionEventSubscriberRegistry(isConnectionActive, forgetConnectionAncestors);
const o = createSessionMessageSubscriberRegistry(isConnectionActive, forgetConnectionAncestors);
let s;
const c = createEventWebPushDelivery(t, { isViewedOnDevice: (e, t) => s?.isViewedOnDevice(e, t) === true }, () => n);
const l = createGatewayBroadcaster({
clients: i,
preparePresenceProjection: (e) => createPresenceRecipientProjection({
cfg: t(),
presence: e,
projection: n
}),
sessionMessageSubscribers: o,
onSessionDeliveryLost: (e) => {
if (hasGatewayClientCap(e.connect.caps, GATEWAY_CLIENT_CAPS.SESSION_ROW_DELTAS)) r.get(e)?.clear("delivery-lost");
},
canReceiveSessionEvent: (e, r, i, a, o) => {
try {
const s = n;
const c = t();
const l = s?.getPolicyConfig() ?? c;
const u = s ? {
sharing: prepareProjectedSessionSharing({
cfg: l,
client: e,
isMember: (e, t) => s.hasMembership(e.storePath, e.storeKey, t)
}),
target: (e, t) => {
const n = resolveSessionEventAgentScope(c, e, t);
return n?.[1] ? s.sharingTarget({
key: e,
agentId: n[1]
}) : null;
}
} : void 0;
if (!u) return false;
return canReceiveSessionEvent({
cfg: c,
policyConfig: l,
client: e,
sessionKeys: r,
agentId: i,
event: a,
payload: o,
prepared: u
});
} catch {
return false;
}
},
prepareSessionEventProjection(i, a, o) {
const s = n;
if (!s) return;
return (o.prepareSessionProjection ?? prepareSessionEventProjection(s))(i, a, o, {
isCurrentProjection: (e) => e === n,
resolveAgentScope: (e, n) => resolveSessionEventAgentScope(t(), e, n),
forgetAncestors: (e) => {
if (e !== void 0) forgetAncestor(e);
else clearAncestors();
},
references: (e) => {
let t = r.get(e);
if (!t) {
t = new ConnectionSessionRows();
r.set(e, t);
}
return t;
},
createRunProjector: () => createVisibleActiveSessionRunProjector(s.state.rowContext.projectedAgentRuns, void 0, e.resolveGatewayContext, s.physicalPaths)
});
},
onBroadcast: (e, t, n) => c.handleEvent(e, t, n ? {
agentId: n.agentId,
sessionKeys: n.sessionKeys
} : void 0)
});
const u = createMentionInbox({
scheduler: e.scheduler,
gatewayInstanceId: e.bootId,
getRuntimeConfig: t,
*getClients() {
for (const e of i) if (!e.invalidated && e.socket.readyState === 1 && (e.connect.role ?? "operator") === "operator") yield e;
},
broadcastToConnIds: l.broadcastToConnIds,
onMentionCreated: c.deliverMention
});
const d = /* @__PURE__ */ new Map();
const f = /* @__PURE__ */ new Map();
const p = createChatRunState(isConnectionActive);
const m = p.registry;
const h = m.add;
const g = m.remove;
const _ = p.toolEventRecipients;
return {
getSessionRowProjection: () => n,
attachSessionRowProjection(e) {
n = e;
clearConnectionRows();
const t = sessionChanges.subscribeFacts((e) => {
if (!("all" in e) && e.scope === "acp") return;
if ("all" in e) clearAncestors();
else if (e.factsInvalidated || e.facts && e.facts.kind !== "unchanged") forgetAncestor(e.sessionKey);
});
return () => {
t();
if (n === e) {
n = void 0;
clearConnectionRows();
}
};
},
attachSessionViewerPresence(e) {
s = e;
},
clients: i,
forgetConnectionAncestors,
connectionWork: new GatewayConnectionWork(),
mentionInbox: u,
isConnectionActive,
...l,
agentRunSeq: d,
dedupe: f,
chatRunState: p,
addChatRun: h,
removeChatRun: g,
toolEventRecipients: _,
sessionEventSubscribers: a,
sessionMessageSubscribers: o
};
}
//#endregion
//#region src/gateway/server-transport-bridge.ts
/** Late-bound transport facts consumed by the socket-free Gateway kernel. */
function createGatewayTransportBridge() {
let e;
return {
attach: (t) => {
e = t;
},
current: () => e,
getPortalService: () => e?.portalService,
getTailscaleIngressEndpoint: () => e?.getTailscaleIngressEndpoint(),
getMcpAppSandboxPort: () => e?.getMcpAppSandboxPort(),
ensureSandboxHostPort: async () => {
if (!e) throw new Error("Gateway listener must start before the sandbox host");
return await e.ensureSandboxHostPort();
}
};
}
//#endregion
//#region src/logging/diagnostic-stall-flight-recorder.ts
const WINDOW_MS = 5e3;
const SAMPLE_MS = 25;
const MAX_SAMPLES = 1024;
const MAX_PROFILE_BYTES = 1048576;
/** Two short native profiles retain recent stacks without a listener or on-demand heap scan. */
function createStallFlightRecorder(e) {
let t;
let n;
let r = 0;
let i = !isMainThread || Boolean(versions.bun) || Number(versions.node.split(".")[0]) < 26;
let a = null;
const stop = () => {
i = true;
n = void 0;
const r = t;
t = void 0;
try {
r?.[Symbol.dispose]();
} catch {
e("stall flight recorder unavailable: profiler-cleanup-failed");
}
};
const start = () => v8.startCpuProfile({
sampleInterval: SAMPLE_MS,
maxBufferSize: MAX_SAMPLES
});
try {
if (!i) i = hasProfilerConflict() || Boolean(process.getBuiltinModule("inspector")?.url()) || Boolean(process.getBuiltinModule("trace_events")?.getEnabledCategories());
if (!i) {
a = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
t = start();
r = performance$1.now();
}
} catch {
i = true;
e("stall flight recorder unavailable: profiler-start-failed");
}
return {
sample(o) {
if (i || !t || !o && performance$1.now() - r < WINDOW_MS) return;
try {
const e = t;
t = start();
r = performance$1.now();
const i = performance$1.now();
const s = {
json: e.stop(),
endedAt: i
};
const c = n ? [n, s] : [s];
n = s.json.length <= MAX_PROFILE_BYTES ? s : void 0;
if (!o) return;
const l = /* @__PURE__ */ new Map();
let u = 0;
let d = false;
for (const e of c) {
if (e.json.length > MAX_PROFILE_BYTES) {
d = true;
continue;
}
const t = parseNativeCpuProfile(e.json);
const n = new Map(t.nodes.map((e) => [e.id, e]));
const r = /* @__PURE__ */ new Map();
for (const e of t.nodes) for (const t of e.children ?? []) r.set(t, e.id);
let i = t.startTime;
const s = t.endTime + (o.startedAt - e.endedAt) * 1e3;
const c = t.endTime + (o.endedAt - e.endedAt) * 1e3;
d ||= (t.samples?.length ?? 0) >= MAX_SAMPLES;
for (const [e, o] of (t.samples ?? []).entries()) {
i += t.timeDeltas?.[e] ?? 0;
if (i < s || i > c) continue;
u++;
const d = /* @__PURE__ */ new Set();
let f = o;
while (f !== void 0) {
const e = n.get(f);
if (!e) break;
const { callFrame: t } = sanitizeDiagnosticProfileFrame(e.callFrame, a);
if (t.url || t.functionName === "[native]" || t.functionName === "(garbage collector)") {
const e = `${t.functionName || "(anonymous)"}@${t.url}:${t.lineNumber + 1}`.slice(0, 240);
if (!d.has(e)) {
d.add(e);
l.set(e, (l.get(e) ?? 0) + 1);
}
}
f = r.get(f);
}
}
}
const f = [...l].toSorted((e, t) => t[1] - e[1]).slice(0, 8);
return `windowMs=${Math.round(o.endedAt - o.startedAt)} windowStartMs=${Math.round(performance$1.timeOrigin + o.startedAt)} windowEndMs=${Math.round(performance$1.timeOrigin + o.endedAt)} reportedAtMs=${Math.round(performance$1.timeOrigin + performance$1.now())} samples=${u} intervalMs=${SAMPLE_MS} truncated=${d} inclusive=${JSON.stringify(f)}`;
} catch {
stop();
e("stall flight recorder unavailable: profiler-capture-failed");
return;
}
},
stop
};
}
//#endregion
//#region src/gateway/server/event-loop-health.ts
const EVENT_LOOP_MONITOR_RESOLUTION_MS = 20;
const EVENT_LOOP_DELAY_WARN_MS = 1e3;
const EVENT_LOOP_UTILIZATION_WARN = .95;
const CPU_CORE_RATIO_WARN = .9;
const PERSISTENT_DEGRADATION_WARN_AFTER_MS = 6e4;
const LOAD_DEGRADATION_DELAY_COEVIDENCE_MS = 25;
const SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS = 1e3;
const IDLE_SAMPLE_INTERVAL_MS = 1e4;
const WORKER_CPU_SAMPLE_BUDGET_MS = 100;
const CPU_USAGE_ORIGIN = {
user: 0,
system: 0
};
const HOST_CPU_TIME_KEYS = [
"user",
"nice",
"sys",
"idle",
"irq"
];
const HOST_CPU_STAT_BUFFER = Buffer.alloc(256);
const log$3 = createSubsystemLogger("gateway/event-loop");
function nanosecondsToMilliseconds(e) {
return roundDiagnosticMetric(e / 1e6, 1);
}
function readMainThreadCpuUsage() {
try {
const e = isMainThread && typeof process.threadCpuUsage === "function" ? process.threadCpuUsage() : void 0;
return isValidCpuUsage(e) ? e : void 0;
} catch {
return;
}
}
function cpuUsageDelta(e, t) {
if (!e || !t) return;
const n = e.user - t.user;
const r = e.system - t.system;
return Number.isFinite(n + r) && n >= 0 && r >= 0 ? n + r : void 0;
}
function isValidCpuUsage(e) {
return cpuUsageDelta(e, CPU_USAGE_ORIGIN) !== void 0;
}
function readHostCpuTimes() {
try {
if (process.platform === "linux") {
const e = openSync("/proc/stat", "r");
let t;
try {
t = readSync(e, HOST_CPU_STAT_BUFFER, 0, HOST_CPU_STAT_BUFFER.length, 0);
} finally {
closeSync(e);
}
const n = HOST_CPU_STAT_BUFFER.indexOf(10);
if (n < 0 || n >= t) return;
const r = HOST_CPU_STAT_BUFFER.toString("ascii", 0, n).split(/\s+/);
if (r[0] !== "cpu" || r.length < 7) return;
const i = {
user: Number(r[1]),
nice: Number(r[2]),
sys: Number(r[3]),
idle: Number(r[4]),
irq: Number(r[6])
};
if (HOST_CPU_TIME_KEYS.some((e) => !Number.isFinite(i[e]) || i[e] < 0)) return;
let a = 0;
for (const e of readFileSync("/sys/devices/system/cpu/online", "utf8").trim().split(",")) {
const [t, n = t] = e.split("-").map(Number);
a += n - t + 1;
}
return a > 0 ? {
count: a,
cpus: [{ times: i }]
} : void 0;
}
const e = cpus();
return e.length ? {
count: e.length,
cpus: e
} : void 0;
} catch {
return;
}
}
function hostCpuUtilization(e, t) {
if (!e || !t || e.count !== t.count) return;
let n = 0;
let r = 0;
for (let i = 0; i < e.cpus.length; i++) {
const a = e.cpus[i].times;
const o = t.cpus[i].times;
for (const e of HOST_CPU_TIME_KEYS) {
const t = a[e] - o[e];
if (t < 0) return;
n += t;
if (e === "idle") r += t;
}
}
return n > 0 && Number.isFinite(n) ? roundDiagnosticMetric((n - r) / n) : void 0;
}
function classifyGatewayEventLoopHealthReasons(e) {
const t = [];
if (e.delayP99Ms >= EVENT_LOOP_DELAY_WARN_MS || e.delayMaxMs >= EVENT_LOOP_DELAY_WARN_MS) t.push("event_loop_delay");
if (e.intervalMs < SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS) return t;
if (!(e.delayP99Ms >= LOAD_DEGRADATION_DELAY_COEVIDENCE_MS || e.delayMaxMs >= LOAD_DEGRADATION_DELAY_COEVIDENCE_MS)) return t;
if (e.utilization >= EVENT_LOOP_UTILIZATION_WARN) t.push("event_loop_utilization");
if (e.cpuCoreRatio >= CPU_CORE_RATIO_WARN) t.push("cpu");
return t;
}
function createGatewayEventLoopHealthMonitor(e) {
const { scheduler: t } = e;
const n = performance$1.now.bind(performance$1);
const r = process.cpuUsage.bind(process);
const i = performance$1.eventLoopUtilization.bind(performance$1);
const a = createStallFlightRecorder((e) => log$3.warn(e));
const o = createMainThreadStallMonitor(n);
let s = null;
let c = true;
let l = 0;
let u = n();
let d = r();
let f = readMainThreadCpuUsage();
let p = readHostCpuTimes();
let m = i();
let h;
let g = null;
let _;
let cancelWorkerCpuSample;
const captureWorkerCpu = (e, t) => {
cancelWorkerCpuSample?.();
const r = _;
_ = void 0;
if (process.versions.bun || typeof Worker.prototype.cpuUsage !== "function") return;
const { workers: i, revision: a, currentRevision: o } = getTrackedWorkerCpuSources();
const accept = (n) => {
if (a !== o()) return;
_ = {
at: e,
revision: a,
usage: n
};
if (!t || h !== t || !r || r.revision !== a || e - r.at !== t.intervalMs) return;
let i = 0;
for (let e = 0; e < n.length; e++) {
const t = cpuUsageDelta(n[e], r.usage[e]);
if (t === void 0) return;
i += t;
}
const s = roundDiagnosticMetric(i / (t.intervalMs * 1e3));
const c = t.cpuBreakdown?.mainThreadCoreRatio;
h = {
...t,
cpuBreakdown: {
...t.cpuBreakdown,
workerCoreRatio: s,
...c === void 0 ? {} : { otherThreadsCoreRatio: roundDiagnosticMetric(Math.max(0, t.cpuCoreRatio - c - s)) }
}
};
};
if (!i.length) {
accept([]);
return;
}
let s = true;
cancelWorkerCpuSample = () => {
s = false;
};
const c = i.map((e) => e.cpuUsage());
Promise.all(c).then((t) => {
if (!s || n() - e > WORKER_CPU_SAMPLE_BUDGET_MS) return;
if (t.every(isValidCpuUsage)) accept(t);
});
};
try {
s = monitorEventLoopDelay({ resolution: EVENT_LOOP_MONITOR_RESOLUTION_MS });
s.enable();
} catch {
s = null;
}
const sample = () => {
if (!s) return;
const t = n();
const _ = o.drain();
if (_.stalls.length > 0 && areDiagnosticsEnabledForProcess() && hasInternalDiagnosticEventInterest("gateway.main_thread.stall")) {
const e = _.stalls.filter((e) => e.task !== "unattributed");
if (e.length > 0) runWithDiagnosticTraceContext(void 0, () => emitInternalDiagnosticEvent({
type: "gateway.main_thread.stall",
stalls: e.map((e) => ({
task: e.task,
durationMs: e.elapsedMs
})),
dropped: _.dropped
}));
}
const y = Math.max(c ? nanosecondsToMilliseconds(s.max) : Math.max(0, t - l), _.delayMaxMs);
if (!c && y > EVENT_LOOP_DELAY_WARN_MS && !_.stalls.length) _.stalls.push({
elapsedMs: t - l,
startedAt: l,
endedAt: t,
task: "unattributed",
taskMs: t - l
});
let b;
const x = Math.round(performance$1.timeOrigin + n());
for (const e of _.stalls) {
if (!b || e.elapsedMs > b.elapsedMs) b = e;
const t = e.task === "unattributed" ? "task=unattributed" : `task=${JSON.stringify(e.task.slice(0, 160))} taskMs=${Math.round(e.taskMs)}`;
log$3.warn(`main-thread stall: elapsedMs=${Math.round(e.elapsedMs)} ${t} stallStartMs=${Math.round(performance$1.timeOrigin + e.startedAt)} stallEndMs=${Math.round(performance$1.timeOrigin + e.endedAt)} reportedAtMs=${x}`);
}
const S = a.sample(b);
if (S) log$3.warn(`main-thread stall profile: ${S}`);
const C = Math.max(1, t - u);
const w = _.dropped + _.unattributedDropped;
if (w > 0) log$3.warn(`main-thread stall: omitted=${w} pendingLimit=8`);
if (y < EVENT_LOOP_DELAY_WARN_MS && C < SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS) {
v = scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS - C);
return;
}
const T = c ? nanosecondsToMilliseconds(s.percentile(99)) : 0;
const E = r(d);
const D = i();
const O = roundDiagnosticMetric(i(D, m).utilization);
const k = roundDiagnosticMetric((E.user + E.system) / 1e3, 1);
const A = roundDiagnosticMetric(k / C);
const j = readMainThreadCpuUsage();
const M = cpuUsageDelta(j, f);
f = j;
const N = readHostCpuTimes();
const P = hostCpuUtilization(N, p);
p = N;
const F = classifyGatewayEventLoopHealthReasons({
intervalMs: C,
delayP99Ms: T,
delayMaxMs: y,
utilization: O,
cpuCoreRatio: A
});
const I = F.length > 0;
if (I) g ??= t;
else g = null;
const L = {
degraded: I,
degradedSinceMs: g === null ? null : Math.max(0, Math.round(t - g)),
reasons: F,
intervalMs: C,
delayP99Ms: T,
delayMaxMs: y,
utilization: O,
cpuCoreRatio: A,
cpuBreakdown: {
...M === void 0 ? {} : { mainThreadCoreRatio: roundDiagnosticMetric(M / (C * 1e3)) },
...P === void 0 ? {} : { hostUtilization: P },
...N ? { hostCpuCount: N.count } : {}
}
};
s.reset();
u = t;
d = r();
m = D;
h = L;
captureWorkerCpu(t, L);
if (areDiagnosticsEnabledForProcess() && hasInternalDiagnosticEventInterest("gateway.event_loop.sample")) runWithDiagnosticTraceContext(void 0, () => emitInternalDiagnosticEvent({
type: "gateway.event_loop.sample",
intervalMs: C,
delayMaxMs: y
}));
v = scheduleSample(!I && e.isIdle?.() && !hasInternalDiagnosticEventInterest("gateway.event_loop.sample") ? IDLE_SAMPLE_INTERVAL_MS : SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS);
};
const scheduleSample = (e) => {
const r = e !== IDLE_SAMPLE_INTERVAL_MS;
o.setEventLoopSampling(r);
if (s && c !== r) {
c = r;
if (r) {
s.reset();
s.enable();
} else s.disable();
}
const i = t.schedule({
id: "event-loop-health",
delayMs: e,
phase: e === IDLE_SAMPLE_INTERVAL_MS ? "maintenance" : void 0,
run: () => queueMicrotask(sample)
});
l = n() + (i.atMs - t.now());
return i;
};
let v = s ? scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS) : void 0;
if (s) captureWorkerCpu(u);
const y = onInternalDiagnosticEventInterest("gateway.event_loop.sample", () => {
const e = n();
const t = Math.max(e, u + SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS);
if (s && t < l) v = scheduleSample(t - e);
});
const reset = () => {
o.reset();
s?.reset();
u = n();
d = r();
f = readMainThreadCpuUsage();
p = readHostCpuTimes();
m = i();
h = void 0;
g = null;
cancelWorkerCpuSample?.();
_ = void 0;
if (s) {
captureWorkerCpu(u);
v = scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS);
}
};
return {
snapshot: () => h,
persistentDegradationSnapshot: () => {
const e = h;
return e?.degradedSinceMs != null && e.degradedSinceMs >= PERSISTENT_DEGRADATION_WARN_AFTER_MS ? e : void 0;
},
reset,
stop: () => {
y();
a.stop();
o.stop();
v?.cancel();
s?.disable();
s = null;
cancelWorkerCpuSample?.();
_ = void 0;
h = void 0;
g = null;
}
};
}
//#endregion
//#region src/gateway/server/presence-events.ts
const log$2 = createSubsystemLogger("gateway/presence");
/** One Gateway owns fixed publication windows; authoritative reads never wait for them. */
function createPresencePublisher(e) {
const t = e.scheduler.scope();
let n = false;
let r = 0;
const schedule = () => {
if (!t.signal.aborted && !n) {
n = true;
t.schedule({
id: "presence/publication",
delayMs: 200,
run: flush
});
}
};
const flush = async () => {
let i = r;
try {
for (let n = e.prepare(); n; n = e.prepare()) {
await n;
if (t.signal.aborted) return;
}
i = r;
e.broadcast("presence", { presence: listSystemPresence() }, {
dropIfSlow: true,
stateVersion: {
presence: i,
health: e.getHealthVersion()
}
});
} catch (e) {
log$2.warn(`Presence publication failed: ${formatErrorMessage$1(e)}`);
} finally {
n = false;
if (r !== i) schedule();
}
};
return {
publish: () => {
if (!t.signal.aborted) {
r = e.incrementPresenceVersion();
schedule();
}
},
stop: t.beginClose
};
}
//#endregion
//#region src/gateway/server/readiness.ts
const DEFAULT_READINESS_CACHE_TTL_MS = 1e3;
/** Startup waits for admission settlement; readiness retains its own agent policy. */
function createStartupChecker(e, t) {
return () => {
const n = Date.now() - e.startedAt;
if (e.getGatewayDraining?.()) return {
ok: false,
status: "draining",
uptimeMs: n
};
const r = e.getStartupPending?.() ? e.getStartupPendingReason?.() ?? "startup-sidecars" : t?.().some((e) => e.code === "agent-database-inspection-pending") ? "agent-database-inspection" : void 0;
if (r !== void 0) return {
ok: false,
status: "starting",
uptimeMs: n,
pendingReason: r
};
return {
ok: true,
status: "started",
uptimeMs: n
};
};
}
function shouldIgnoreReadinessFailure(e, t) {
if (t.reason === "unmanaged" || t.reason === "stale-socket") return true;
const n = t.reason === "not-running" || t.reason === "ingress-unavailable";
const r = e.restartPending === true && e.running !== true;
return n && r;
}
function createReadinessChecker(e) {
const { channelManager: t, startedAt: n } = e;
const r = createStartupChecker(e);
let i = 0;
let a = null;
const readReadiness = (r, o, s) => {
const c = s.uptimeMs;
const l = n + c;
if (s.status === "starting") return {
ready: false,
coreReady: false,
failing: [s.pendingReason],
uptimeMs: c
};
if (s.status === "draining") return {
ready: false,
coreReady: false,
failing: ["gateway-draining"],
uptimeMs: c
};
if (!(o ?? getRecordedChildRuntimeViability()).available) return {
ready: false,
coreReady: false,
failing: ["child-runtime"],
uptimeMs: c
};
const u = e.getStateDatabaseFailure?.();
if (u) {
a = null;
return {
ready: false,
coreReady: false,
failing: ["state-database"],
stateDatabase: { reason: u.message },
uptimeMs: c
};
}
if (r?.length) {
a = null;
return {
ready: false,
coreReady: false,
failing: r.map(({ agentId: e }) => `agent-database:${e}`),
uptimeMs: c
};
}
const d = e.getPluginReloadStatus?.();
if (d) {
a = null;
return {
ready: false,
coreReady: false,
failing: ["plugin-reload"],
pluginReload: d,
uptimeMs: c
};
}
if (e.isChatSendAvailable?.() === false) {
a = null;
return {
ready: false,
coreReady: false,
failing: ["chat-startup"],
uptimeMs: c
};
}
if (a && !isFutureDateTimestampMs(i, { nowMs: l }) && l - i < DEFAULT_READINESS_CACHE_TTL_MS) return {
...a,
uptimeMs: c
};
if (e.shouldSkipChannelReadiness?.()) return {
ready: true,
coreReady: true,
failing: [],
uptimeMs: c
};
const f = t.getRuntimeSnapshot();
const p = t.getAutostartSuppression() !== null;
const m = [];
const h = [];
for (const [e, n] of Object.entries(f.channelAccounts)) {
if (!n) continue;
const r = p || t.isAmbientAutostartSuppressed(e);
for (const t of Object.values(n)) {
if (!t) continue;
const n = evaluateChannelHealth(t, {
now: l,
staleEventThresholdMs: DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,
channelConnectGraceMs: DEFAULT_CHANNEL_CONNECT_GRACE_MS,
channelId: e
});
if (!n.healthy && r && n.reason === "not-running") {
if (!h.includes(e)) h.push(e);
continue;
}
if (!n.healthy && !shouldIgnoreReadinessFailure(t, n)) {
m.push(e);
break;
}
}
}
i = l;
a = {
ready: m.length === 0,
coreReady: true,
failing: m,
...h.length > 0 ? { suppressed: h } : {}
};
return {
...a,
uptimeMs: c
};
};
const read = (t, n) => {
const i = e.getAgentDatabaseAdmissionRefusals?.();
const a = readReadiness(i, t, n ?? r());
const o = e.getEventLoopHealth;
const s = o?.();
return {
...a,
...i?.length ? { agentDatabases: i } : {},
...s ? { eventLoop: s } : {}
};
};
return Object.assign(read, { prepare: async () => {
const e = r();
if (e.status !== "started") return { publish: () => {
const t = r();
return read(void 0, t.status === "started" ? e : t);
} };
const t = await prepareChildRuntimeViability();
return { publish: () => read(t.publish()) };
} });
}
//#endregion
//#region src/gateway/server-runtime-state-prepare.ts
async function prepareGatewayKernelState(e) {
const { bootstrap: t, scheduler: n, bootId: r, port: i, opts: a, log: o, logChannels: s, logHooks: c, logPlugins: l, gatewayRuntime: u, resolveChannelRuntime: d } = e;
const { pluginBootstrap: f, workerEnvironmentStartup: p, startupTrace: m, cfgAtStart: h, resolvedStartupAuthOverride: g, startupTailscaleOverride: _, ambientAutostartSuppressedChannelIds: v, minimalTestGateway: y, pluginGatewayContext: b, resolvePluginGatewayContext: x } = t;
const S = Object.assign(e.pluginRegistryOwner, { baseGatewayMethods: f.baseGatewayMethods });
const listGatewayStartupChannelPlugins = (e = S.registry) => listLoadedChannelPluginsForRegistry(e);
const C = createDesktopSessionRegistry();
const w = (await m.measure("node-desktop.runtime-import", () => import("./node-stream-broker-Dbm5XqMy.mjs"))).createNodeDesktopStreamBroker();
const T = (await m.measure("host-desktop.runtime-import", () => import("./host-source-CwfCPmcO.mjs"))).createHostDesktopService({
getConfig: () => readRuntimeConfig().desktop?.host,
registry: C
});
const E = (await m.measure("computer.runtime-import", () => import("./computer-service-C827tJqB.mjs"))).createGatewayComputerService({
getConfig: readRuntimeConfig,
getPluginRegistry: () => S.registry,
hostDesktopService: T
});
await m.measure("device-identity", () => loadOrCreateProcessDeviceIdentityAsync().catch(() => {}));
await m.measure("device-pairing", () => readDevicePairingNodeSnapshot());
const D = p ? await m.measure("worker-environments.runtime-imports", async () => {
return await (await import("./server-worker-environment-startup-i4DVypHZ.mjs")).createGatewayWorkerEnvironmentRuntime({
scheduler: n,
getPluginRegistry: () => S.registry,
getPortalRuntime: () => b.current,
resolveGatewayContext: x,
desktopSessionRegistry: C,
nodeDesktopStreamBroker: w,
startup: p,
log: o
});
}) : {};
const { workerEnvironmentService: O, workerLiveEvents: k, nodeWorkerGatewayNamespace: A, nodeWorkerBundleRetention: j, runtimeInstall: M, bindDeviceNodeControl: N, bindWorkerNodeDesktopControl: P, bindNodeWorkspaceBindingResolver: F, handleNodeWorkerBundleTransferRequest: I, handleWorkerBootstrapArtifactTransferRequest: L, handleNodeWorkspaceTransferRequest: R } = D;
const z = { revoke: (e) => {
throw new Error("Worker dispatch authority revocation is not ready");
} };
const B = p ? await m.measure("worker-environments.placement-module", () => import("./server-worker-placement-startup-C7nTx6kW.mjs")) : void 0;
const getCommittedRuntimeConfig = () => {
const e = x();
if (!e) throw new GatewayOperatorAccessUnavailableError();
return (e.getCommittedRuntimeConfig ?? e.getRuntimeConfig)();
};
const V = p && B ? B.createGatewayGitHubPublicationRuntime({
placements: p.placementStore,
getCommittedRuntimeConfig,
warn: (e) => o.warn(e)
}) : void 0;
const H = O && p && A && B ? await m.measure("worker-environments.placement-runtime", async () => B.createGatewayWorkerPlacementRuntime({
scheduler: n,
placements: p.placementStore,
initialPlacements: await p.placementStore.listAsync(),
getCommittedRuntimeConfig,
environments: O,
gatewayNamespace: A,
nodeWorkerBundleRetention: j,
getSessionChangeContext: () => b.current,
persistAbandonedPartial: async (e) => {
const t = Re.chatRunState.resolveBuffer(e.runId, { final: true });
const n = t.displayText ?? t.text;
if (!n.trim() && !e.missingToolResultText) return;
const r = await import("./chat-transcript-persistence.runtime.js");
await r.persistAbortedPartials({
context: { logGateway: o },
missingToolResultText: e.missingToolResultText,
snapshots: [r.captureAbortedPartial({
...e,
text: n,
abortOrigin: "placement-abandon",
session: await r.prepareChatAbortSessionSnapshot({
cfg: getCommittedRuntimeConfig(),
key: e.sessionKey,
agentId: e.agentId
})
})]
});
},
cancelSessionWork: async (e) => {
const t = b.current;
if (!t) throw new Error("Worker session cancellation is not ready");
const { cancelGatewayWorkerSessionWork: n } = await import("./server-worker-placement-cancel-DcMY8sST.mjs");
await n(t, e);
},
revokeSessionAuthority: (e) => z.revoke(e),
info: (e) => o.info(e),
warn: (e) => o.warn(e),
...V ? { githubPublicationRuntime: V } : {}
})) : void 0;
const U = H ? {
...H,
runtimeInstall: M
} : void 0;
if (U && O) {
const { createDevicePlacementDemandReader: e, createDevicePlacementDemandReaderAsync: t } = await import("./device-placement-demand-MEwO0sN5.mjs");
const n = {
resolveGatewayContext: x,
placements: U.placements,
environments: O
};
Object.assign(U.dispatchService, {
getAdmittedDeviceSessionCounts: e(n),
getAdmittedDeviceSessionCountsAsync: t(n)
});
F?.(U.resolveNodeWorkspaceBinding);
D.bindWorkerSessionDispatch?.(U.dispatchService.dispatch, U.dispatchService.waitForInitialPlacement);
}
const W = N ? (e) => {
N(e);
U?.bindNodeWorkerSupervisorTransport(e);
} : void 0;
const G = U?.dispatchService;
const K = Object.fromEntries(listGatewayStartupChannelPlugins().map((e) => [e.id, s.child(e.id)]));
const q = Object.fromEntries(Object.entries(K).map(([e, t]) => [e, runtimeForLogger(t)]));
const listStartupChannelGatewayMethods = (e = S.registry) => {
const t = [];
for (const n of listGatewayStartupChannelPlugins(e)) {
t.push(...n.gatewayMethods ?? []);
for (const e of n.gatewayMethodDescriptors ?? []) t.push(e.name);
}
return t;
};
const listActiveGatewayMethods = (e) => uniqueStrings([...e, ...listStartupChannelGatewayMethods()]).filter((e) => (G || e !== "sessions.dispatch") && (G || e !== "sessions.reclaim" && e !== "sessions.move") && (O || e !== "desktop.launch" && e !== "worker.desktop.observe" && e !== "worker.desktop.launch"));
const J = await m.measure("runtime.config", async () => {
const { resolveGatewayRuntimeConfig: e } = await import("./server-runtime-config-hnL3sZOF.mjs");
return e({
cfg: h,
port: i,
bind: a.bind,
host: a.host,
controlUiEnabled: a.controlUiEnabled,
auth: g,
tailscale: _
});
});
const { bindHost: Y, controlUiEnabled: ee, controlUiBasePath: X, controlUiRoot: te, resolvedAuth: ne, tailscaleConfig: re, tailscaleMode: ie } = J;
if (t.generatedStartupAuthToken && isLoopbackHost(Y)) {
const { ensureStartupLocalCliPairing: e } = await m.measure("runtime.local-cli-pairing-import", () => import("./startup-local-cli-pairing-Z3x0Qg96.mjs"));
const t = await m.measure("runtime.local-cli-pairing", () => e());
if (t === "created") o.info("runtime-only gateway auth paired the local CLI device before readiness");
else if (t === "unavailable") o.warn("runtime-only gateway auth could not prepare local CLI device credentials; configure gateway.auth.token or gateway.auth.password for CLI access");
}
const getResolvedAuth = () => resolveGatewayAuth({
authConfig: getActiveSecretsRuntimeConfigSnapshot()?.config.gateway?.auth ?? readRuntimeConfig().gateway?.auth,
authOverride: g,
env: process.env,
tailscaleMode: ie
});
const resolveSharedGatewaySessionGenerationForConfig = (e) => resolveSharedGatewaySessionGeneration(resolveGatewayAuth({
authConfig: e.gateway?.auth,
authOverride: g,
env: process.env,
tailscaleMode: ie
}), e.gateway?.trustedProxies);
const resolveCurrentSharedGatewaySessionGeneration = () => resolveSharedGatewaySessionGeneration(getResolvedAuth(), readRuntimeConfig().gateway?.trustedProxies);
const resolveSharedGatewaySessionGenerationForRuntimeSnapshot = () => resolveSharedGatewaySessionGenerationForConfig(readRuntimeConfig());
const ae = new SharedGatewaySessionGenerationState({
current: resolveCurrentSharedGatewaySessionGeneration(),
required: null
});
const oe = J.hooksConfig;
publishHooksTokenEnvKey(oe);
const Z = resolveHookClientIpConfig(h);
const Q = h.gateway?.auth?.rateLimit;
const se = createGatewayAuthRateLimiter(Q, {
scheduler: n,
id: "auth/main"
});
const ce = createGatewayAuthRateLimiter({
...Q,
exemptLoopback: false
}, {
scheduler: n,
id: "auth/browser"
});
const le = createNodeReapprovalCoordinator(Q, { scheduler: n });
const $ = await m.measure("control-ui.root", () => createGatewayControlUiRootLifecycle({
controlUiRootOverride: te,
controlUiEnabled: ee,
gatewayRuntime: u,
log: o
}));
const { createTerminalLaunchPolicy: ue } = await m.measure("terminal.launch-import", () => import("./launch-BwaLLGNl.mjs"));
const de = ue(h);
const { runDefaultChannelSetupWizard: fe, runDefaultSetupWizard: pe } = await m.measure("gateway.wizard-imports", () => import("./wizard-0CzdpPGK.mjs"));
const me = a.wizardRunner ?? pe;
const he = a.channelWizardRunner ?? fe;
const { wizardSessions: ge, findRunningWizard: _e, purgeWizardSession: ve } = createWizardSessionTracker();
const ye = /* @__PURE__ */ new Map();
const be = createDefaultDeps();
const xe = { current: null };
const Se = { handled: false };
const Ce = await m.measure("tls.runtime", () => loadGatewayTlsServerRuntime(h.gateway?.tls, o.child("tls")));
const we = Date.now();
const Te = createGatewayEventLoopHealthMonitor({
scheduler: n,
isIdle: () => getActiveGatewayRootWorkCount({ excludeCurrent: true }) === 0
});
const Ee = {
sidecarsReady: y,
pendingReason: "startup-sidecars",
dispatchReady: false
};
const De = new Set(y ? [] : STARTUP_UNAVAILABLE_GATEWAY_METHODS);
const Oe = { closePreludeStarted: false };
const ke = createDeferredCore();
const Ae = { current: void 0 };
const { createChannelManager: je } = await m.measure("gateway.channel-manager-import", () => import("./server-channels-2gqBlxfG.mjs"));
const Me = je({
scheduler: n,
getRuntimeConfig: readRuntimeConfig,
resolveGatewayContext: x,
channelLogs: K,
channelRuntimeEnvs: q,
resolveChannelRuntime: d,
getPluginRegistry: () => S.registry,
startupTrace: m,
deferStartupAccountStartsUntil: ke.promise,
getNativeApprovalRuntime: () => Ae.current?.nativeApprovals,
ambientAutostartSuppressedChannelIds: v,
...a.tryRecoverChannelAutostartSuppression ? { tryRecoverAutostartSuppression: a.tryRecoverChannelAutostartSuppression } : {},
isClosing: () => Oe.closePreludeStarted
});
Me.setAutostartSuppression(a.channelAutostartSuppression ?? null);
const Ne = a.sidecarStartup ?? "start";
const isGatewayStartupPending = () => (!Ee.dispatchReady || !Ee.sidecarsReady || De.size > 0) && !Oe.closePreludeStarted;
const Pe = {
startedAt: we,
getStartupPending: isGatewayStartupPending,
getStartupPendingReason: () => Ee.pendingReason,
getGatewayDraining: () => Oe.closePreludeStarted || isGatewayWorkAdmissionClosed()
};
const Fe = createStartupChecker(Pe, listAgentDatabaseAdmissionRefusals);
const Ie = createReadinessChecker({
channelManager: Me,
...Pe,
getEventLoopHealth: Te.snapshot,
getStateDatabaseFailure: () => openClawStateDatabaseCache.getOpenClawStateDatabaseRecordedFailure(resolveDatabasePath()),
getAgentDatabaseAdmissionRefusals: () => {
const e = readRuntimeConfig();
return listAgentDatabaseAdmissionRefusals().filter((t) => !canIsolateAgentDatabase(e, t.agentId));
},
getPluginReloadStatus: e.getPluginReloadStatus,
isChatSendAvailable: () => !De.has("chat.send"),
shouldSkipChannelReadiness: isChannelStartupSuppressedByEnvironment
});
const Le = {};
o.info("starting HTTP server...");
const Re = await m.measure("runtime.state", () => createGatewayConnectionState({
resolveGatewayContext: x,
scheduler: n,
bootId: r,
cfg: h,
getRuntimeConfig: readRuntimeConfig
}));
const ze = createGatewayTransportBridge();
const Be = createPresencePublisher({
scheduler: n,
broadcast: Re.broadcast,
incrementPresenceVersion,
getHealthVersion,
prepare: () => {
const e = Re.getSessionRowProjection();
return e?.needsMembershipPreparation() ? e.prepareMembership() : void 0;
}
});
const createHttpTransportOptions = () => ({
scheduler: e.scheduler,
cfg: h,
getRuntimeConfig: readRuntimeConfig,
bindHost: Y,
port: i,
controlUiEnabled: a.controlUiEnabled,
controlUiBasePath: X,
controlUiRoot: $.state,
openAiChatCompletionsEnabled: a.openAiChatCompletionsEnabled,
openResponsesEnabled: a.openResponsesEnabled,
resolvedAuth: ne,
rateLimiter: se,
joinRateLimiter: ce,
isTerminalEnabled: de.isEnabled,
gatewayTls: Ce,
getResolvedAuth,
hooksConfig: () => xe.current === null ? oe : xe.current.hooksConfig,
getHookClientIpConfig: () => xe.current?.hookClientIpConfig ?? Z,
pluginRegistry: S.registry,
getPluginRouteRegistry: () => S.registry,
isStartupPluginRuntimeReady: () => Ee.sidecarsReady,
getGatewayRequestContext: x,
deps: be,
log: o,
logHooks: c,
logPlugins: l,
getReadiness: Ie,
getStartup: Fe,
isStartupPending: isGatewayStartupPending,
handleWatchNodeRequest: async (e, t) => await Le.current?.(e, t) ?? false,
handleNodeWorkerBundleTransferRequest: I,
handleWorkerBootstrapArtifactTransferRequest: L,
handleNodeWorkspaceTransferRequest: R,
workerIngressEnabled: Boolean(O),
desktopSessionRegistry: C,
nodeDesktopStreamBroker: w,
clients: Re.clients,
tailscaleMode: ie
});
return {
...t,
scheduler: n,
bootId: r,
pluginRuntime: S,
workerEnvironmentService: O,
workerLiveEvents: k,
bindDeviceNodeControl: W,
bindWorkerNodeDesktopControl: P,
workerDispatchAuthority: z,
workerPlacementRuntime: U,
githubPublicationRuntime: V,
githubPublicationService: V?.coordinator,
workerPlacementControlAvailable: G,
desktopSessionRegistry: C,
nodeDesktopStreamBroker: w,
hostDesktopService: T,
gatewayComputerService: E,
channelLogs: K,
channelRuntimeEnvs: q,
listStartupChannelGatewayMethods,
listActiveGatewayMethods,
bindHost: Y,
controlUiRootLifecycle: $,
controlUiBasePath: X,
resolvedAuth: ne,
tailscaleConfig: re,
tailscaleMode: ie,
getResolvedAuth,
resolveSharedGatewaySessionGenerationForConfig,
resolveSharedGatewaySessionGenerationForRuntimeSnapshot,
sharedGatewaySessionGenerationState: ae,
initialHooksConfig: oe,
initialHookClientIpConfig: Z,
authRateLimiter: se,
browserAuthRateLimiter: ce,
nodeReapprovalCoordinator: le,
terminalLaunchPolicy: de,
wizardRunner: me,
channelWizardRunner: he,
wizardSessions: ge,
findRunningWizard: _e,
purgeWizardSession: ve,
systemAgentSessions: ye,
deps: be,
runtimeStateRef: xe,
cronStartState: Se,
gatewayTls: Ce,
readinessEventLoopHealth: Te,
startupState: Ee,
unavailableGatewayMethods: De,
getReadiness: Ie,
lifecycle: Oe,
releaseStartupAccountStarts: ke.resolve,
gatewayInstanceRuntimeRef: Ae,
channelManager: Me,
sidecarStartup: Ne,
isGatewayStartupPending,
pluginGatewayContext: b,
watchNodeRequestHandler: Le,
createHttpTransportOptions,
transportBridge: ze,
...Re,
publishPresence: Be.publish,
stopPresencePublications: Be.stop
};
}
//#endregion
//#region src/gateway/startup-control-ui-origins.ts
/**
* Seeds runtime-only Control UI origins when a non-loopback gateway bind would
* otherwise reject the browser that just opened the local UI.
*/
function maybeSeedControlUiAllowedOriginsAtStartup(e) {
const t = ensureControlUiAllowedOriginsForNonLoopbackBind(e.config, {
isContainerEnvironment,
runtimeBind: e.runtimeBind,
runtimePort: e.runtimePort
});
if (!t.seededOrigins || !t.bind) return {
config: e.config,
seededAllowedOrigins: false
};
e.log.info(`gateway: seeded gateway.controlUi.allowedOrigins ${JSON.stringify(t.seededOrigins)} for bind=${t.bind} (required since v2026.2.26; see issue #29385). Applied for this runtime without writing config; add other origins to gateway.controlUi.allowedOrigins if needed.`);
return {
config: t.config,
seededAllowedOrigins: true
};
}
//#endregion
//#region src/gateway/server-startup-bootstrap.ts
async function prepareGatewayServerBootstrap(e) {
process.env.OPENCLAW_GATEWAY_PORT = String(e.port);
await installGatewayDatabaseEngine(e.opts.startupConfigSnapshotRead?.snapshot, e.opts.startupConfigSnapshotRead?.databaseEngineSelection);
return prepareGatewayServerBootstrapSelected(e);
}
async function prepareGatewayServerBootstrapSelected(e) {
try {
var t = _usingCtx();
const { port: n, opts: r, log: i, logSecrets: a, loadWorkerEnvironmentStartupModule: o } = e;
const { assertConfiguredWorkspaceStateReady: s } = await import("./workspace-state-dirs-H0UukwV6.mjs");
process.env.OPENCLAW_GATEWAY_PORT = String(n);
const c = { ...process.env };
const l = e.formatRuntimeGatewayAuthTokenWarning;
const u = r.processStartedAt ?? r.startupStartedAt;
const d = typeof u === "number" ? Math.max(0, Date.now() - u) : 0;
const f = createGatewayStartupTrace(i, performance$1.now() - d, r.updateCanary);
const p = t.u({
transferred: false,
[Symbol.dispose]() {
if (!this.transferred) f.close();
}
});
if (d > 0) f.mark("process.bootstrap");
const m = await withArtifactPreservingStateReads(async () => {
if (!resumeGatewayRestartTraceFromEnv(process.env, [["source", "env"]]) && isTruthyEnvValue(process.env.OPENCLAW_GATEWAY_RESTART_TRACE)) {
const e = await readGatewayRestartHandoff();
resumeGatewayRestartTraceFromHandoff(e?.restartTrace, [
["source", e?.source],
["restartKind", e?.restartKind],
["supervisorMode", e?.supervisorMode]
]);
}
const e = r.startupConfigSnapshotRead ?? await f.measure("config.snapshot.read", () => readConfigFileSnapshotWithPluginMetadata({
observe: false,
measure: (e, t) => f.measure(e, t)
}));
await s({ cfg: captureConfigOverrideApplier()(e.snapshot.config) });
return e;
});
const inspectStateOwnership = async (e) => {
normalizeStateDirEnv(process.env);
if (!process.env.OPENCLAW_STATE_DIR?.trim() && !isNamedProfile(process.env)) {
const e = resolveStateDir(process.env);
if (resolveConfigDir(process.env) === e) process.env.OPENCLAW_STATE_DIR = e;
}
await assertOpenClawStateWriteAllowedAtPath({
databasePath: resolveOpenClawStateSqlitePath(process.env),
env: process.env,
signal: e
});
};
await withSqliteReadOnlyWorkerScope(async () => {
await f.measure("state.ownership", () => r.startupOperation ? r.startupOperation(inspectStateOwnership) : inspectStateOwnership());
const { OPENCLAW_DATABASE_SCHEMA_DOCS_URL: e, OpenClawDatabaseSchemaPreflightError: t, preflightOpenClawDatabaseSchemas: n } = await f.measure("state.runtime-imports", () => import("./openclaw-database-preflight-BB0y4HYJ.mjs"));
const inspectDatabaseSchemas = (e) => n({
signal: e,
env: process.env,
reuseStartupSchemaPreparation: true,
agentAdmissionConfig: captureConfigOverrideApplier()(m.snapshot.config),
onAgentInspection: (e) => f.detail("state.schema-preflight", Object.entries(e))
});
const a = await f.measure("state.schema-preflight", () => r.startupOperation ? r.startupOperation(inspectDatabaseSchemas) : inspectDatabaseSchemas());
if (a.incompatible.length > 0) throw new t(a.incompatible);
for (const t of a.indeterminate) i.warn("database schema preflight could not inspect database; continuing to real open", {
kind: t.kind,
path: t.path,
reason: t.reason,
docsUrl: e
});
});
const { ensureGlobalUndiciEnvProxyDispatcher: h } = await f.measure("runtime.network-imports", () => import("./undici-global-dispatcher-qyMDs7M4.mjs"));
await f.measure("runtime.network-bootstrap", h);
const g = isVitestRuntimeEnv() && process.env.OPENCLAW_TEST_MINIMAL_GATEWAY === "1";
const _ = r.ambientEnvTriggers ?? "suppress";
if (!process.env.VITEST && true) {
if (process.env.OPENCLAW_RAW_STREAM?.trim()) i.info("raw stream logging flag configured via OPENCLAW_RAW_STREAM");
if (process.env.OPENCLAW_RAW_STREAM_PATH?.trim()) i.info("raw stream log path override configured via OPENCLAW_RAW_STREAM_PATH");
}
if (!g && !r.updateCanary) await f.measure("runtime.agent-cli", () => prepareGatewayAgentCliShim());
const v = f.measure("config.runtime-imports", () => import("./server-startup-config-mzsJm5wA.mjs"));
const { applyGatewayAuthOverridesForStartupPreflight: y, loadGatewayStartupConfigSnapshot: b } = await v;
const x = await f.measure("config.snapshot", () => b({
minimalTestGateway: g,
ambientEnvTriggers: _,
log: i,
measure: (e, t) => f.measure(e, t),
initialSnapshotRead: m
}));
const S = x.snapshot;
const C = r.auth ? structuredClone(r.auth) : void 0;
const w = r.tailscale ? structuredClone(r.tailscale) : void 0;
const T = g ? {
config: S.config,
seededAllowedOrigins: false
} : await f.measure("control-ui.seed", () => maybeSeedControlUiAllowedOriginsAtStartup({
config: S.config,
log: i,
runtimeBind: r.bind,
runtimePort: n
}));
if (T.seededAllowedOrigins) copyConfigResolutionFacts(S.config, T.config);
const E = T.seededAllowedOrigins ? {
...S,
runtimeConfig: T.config,
config: T.config
} : S;
const emitSecretsStateEvent = (e, t, n) => {
const r = `[${e}] ${t}`;
try {
const t = resolveSystemMainSessionTarget(n);
enqueueSystemEvent(r, withSystemEventOwner({
sessionKey: t.sessionKey,
contextKey: e
}, t.agentId));
} catch (e) {
a.warn(`${r} not delivered: ${formatErrorMessage$1(e)}`);
}
};
const { createRuntimeSecretsActivator: D } = await v;
const O = D({
logSecrets: a,
emitStateEvent: emitSecretsStateEvent,
beforeSnapshotPublication: async (e) => {
const { publishCanonicalUserChannelPolicy: t } = await import("./user-channel-identity-operations-31HWscOR.mjs");
await t(e?.gateway, e?.commands?.ownerAllowFrom);
},
...x.pluginMetadataSnapshot ? { pluginMetadataSnapshot: x.pluginMetadataSnapshot } : {}
});
const k = S.sourceConfig;
const A = captureConfigOverrideApplier()(E.config);
f.setConfig(A);
const { prepareGatewayStartupConfig: j } = await import("./server-startup-config-helpers-Df2-oRxf.mjs");
const M = await f.measure("config.auth", () => j({
configSnapshot: E,
authOverride: C,
tailscaleOverride: w,
activateRuntimeSecrets: O,
log: i,
measure: (e, t, n) => f.measure(e, t, n)
}), { omitErrorMessage: true });
const N = M.cfg;
f.setConfig(N);
if (!r.updateCanary) try {
const e = await f.measure("agents.github-profile-cleanup", async () => {
const { cleanupRetiredManagedGitHubProfiles: e } = await import("./github-tool-profile-cleanup-D01OjGrH.mjs");
return await e({
config: N,
env: process.env
});
});
for (const t of e.warnings) i.warn(`managed GitHub profile cleanup: ${t}`);
} catch (e) {
i.warn(`managed GitHub profile cleanup failed: ${formatErrorMessage$1(e)}`);
}
if (M.generatedToken) i.warn(l());
const P = N.gateway?.auth?.trustedProxy?.deviceAutoApprove;
if (N.gateway?.auth?.mode === "trusted-proxy" && P?.enabled === true && P.scopes?.some((e) => e.trim() === "operator.admin")) i.warn("SECURITY WARNING: gateway.auth.trustedProxy.deviceAutoApprove.scopes includes operator.admin; every proxy-authenticated user can auto-approve a new operator device with full admin, and requests without scopes receive full admin automatically. Remove operator.admin and grant admin per identity via gateway.auth.identityScopes instead.");
let F;
let I;
if (C) {
F = {};
I = {};
for (const e of [
"mode",
"token",
"password",
"allowTailscale",
"rateLimit",
"trustedProxy"
]) {
const t = C[e];
if (t === void 0) continue;
if ((e === "token" || e === "password") && isSecretRef(t)) {
I[e] = structuredClone(t);
continue;
}
const n = N.gateway?.auth?.[e];
if (n !== void 0) Object.assign(F, { [e]: structuredClone(n) });
}
}
const L = M.generatedToken ? mergeGatewayAuthConfig(F, { token: M.generatedToken }) : F;
setDiagnosticsEnabledForProcess(isDiagnosticsEnabled(N));
setGatewayRestartPolicy({ allowExternal: isRestartEnabled(N) });
setPreRestartDeferralCheck(() => createGatewayActiveWorkSnapshot().counts.totalActive);
const R = T.seededAllowedOrigins ? N.gateway?.controlUi?.allowedOrigins : void 0;
const applyFixedGatewayOverlays = (e) => {
const t = y(e, {
auth: M.generatedToken && e.gateway?.auth?.mode === void 0 ? {
mode: M.auth.mode,
...L
} : L,
tailscale: w
});
if (!R || t.gateway?.controlUi?.allowedOrigins !== void 0 || resolveControlUiAllowedOrigins(t).length > 0) return t;
const n = {
...t,
gateway: {
...t.gateway,
controlUi: {
...t.gateway?.controlUi,
allowedOrigins: R
}
}
};
copyConfigResolutionFacts(t, n);
return n;
};
const applyReloadableGatewayAuthRefs = (e) => I?.token || I?.password ? y(e, { auth: I }) : e;
const prepareReloadCandidate = async (e) => {
const t = e.previousSourceConfig ?? getRuntimeConfigSourceSnapshot() ?? S.sourceConfig;
assertGatewayConfigEnvSelectionUnchanged(t, e.sourceConfig);
const n = prepareConfigRuntimeEnv({
previousConfig: t,
nextConfig: e.sourceConfig
});
const r = x.pluginMetadataSnapshot;
const i = g ? e.sourceConfig : resolveGatewayReloadPluginActivationCandidate({
sourceConfig: e.sourceConfig,
env: n.env,
...r?.manifestRegistry ? { manifestRegistry: r.manifestRegistry } : {},
discovery: r?.discovery,
ambientEnvTriggers: _
});
const a = captureConfigOverrideApplier();
const reapplyCompareOverlays = (e) => {
const t = a(mergeActivationSectionsIntoRuntimeConfig({
runtimeConfig: e,
activationConfig: i
}));
copyConfigResolutionFacts(e, t);
return t;
};
const reapplyRuntimeOverlays = (e) => resolveGatewayStartupSourceConfig(applyFixedGatewayOverlays(applyReloadableGatewayAuthRefs(reapplyCompareOverlays(e))), n.env);
const o = reapplyRuntimeOverlays(e.runtimeConfig);
await s({
cfg: o,
env: n.env
});
return {
runtimeConfig: o,
compareConfig: reapplyCompareOverlays(e.sourceConfig),
runtimeEnv: n,
reapplyRuntimeOverlays,
reapplyCompareOverlays
};
};
await setAppliedRuntimeConfigSnapshot(N, S.sourceConfig);
applyLoggingConfig(N.logging);
initializePublishedConfigRuntimeEnv(S.sourceConfig, {
ownedEnv: collectConfigRuntimeEnvOwnership(S.sourceConfig, c, process.env),
preserveExistingOwnership: true
});
if (!g && !r.updateCanary) {
const { recoverConfiguredMcpDockerServers: e } = await import("./mcp-docker-recovery-BV1M3ZLg.mjs");
await e(N, x.pluginMetadataSnapshot?.manifestRegistry);
}
const z = [
g || r.updateCanary ? Promise.resolve(void 0) : f.measure("worker-environments.store-import", async () => {
return await (await o()).loadGatewayWorkerEnvironmentStartupState();
}),
(async () => {
if (r.updateCanary) i.warn("candidate gateway: session catalogs and maintenance deferred until activation");
if (g || r.updateCanary) return [];
await f.measure("state.desktop-approval-admission", async () => {
const { migrateLegacyDesktopStreamOptOuts: e } = await import("./device-pairing-node-desktop-migration-zoeNLPAx.mjs");
const t = await e(N);
if (t > 0) i.warn(`Preserved disabled desktop access for ${t} paired node(s); approve their updated desktop capability to enable sharing.`);
});
return f.measure("sessions.admission", async () => {
const { prepareGatewayStartupSessions: e } = await import("./server-startup-session-migration-BZABLvmL.mjs");
return e({
cfg: N,
env: process.env,
log: i
});
});
})(),
f.measure("plugins.bootstrap-imports", () => import("./server-startup-plugins-CpDU2lcS.mjs")),
f.measure("cron.store-path", () => resolveCronJobsStorePathFromConfigAsync(N))
];
await Promise.allSettled(z);
const [B, V, { prepareGatewayPluginBootstrap: H }, U] = await Promise.all(z);
const W = { current: void 0 };
const resolvePluginGatewayContext = () => W.current;
publishSystemEventStoreConfig(N);
const G = await f.measure("plugins.bootstrap", async () => {
if (!r.updateCanary) {
const { initSubagentRegistry: e } = await import("./subagent-registry-DxTolEfW.mjs");
await e();
}
return H({
cfgAtStart: N,
activationSourceConfig: k,
pluginMetadataSnapshot: x.pluginMetadataSnapshot,
workerProviderIds: B?.durableProviderIds ?? [],
minimalTestGateway: g,
ambientEnvTriggers: _,
log: i
});
});
const { gatewayPluginConfigAtStart: K, defaultWorkspaceDir: q, pluginWorkspaceDir: J, startupPluginIds: Y, pluginManifestRecords: ee, pluginMetadataSnapshot: X, pluginLookUpTable: te, baseMethods: ne, ambientAutostartSuppressedChannelIds: re } = G;
copyConfigResolutionFacts(N, K);
await setAppliedRuntimeConfigSnapshot(K, S.sourceConfig);
const ie = listCoreGatewayMethodNames();
const ae = getGatewayPluginMetadataSnapshot();
const oe = ae ?? X;
if (ae) selectCurrentPluginMetadataCache(getPluginMetadataSnapshotCache(ae));
else setGatewayPluginMetadataSnapshot(oe, {
config: k,
compatibleConfigs: [
A,
N,
K
],
env: process.env,
workspaceDir: J
});
if (te) {
const e = te.metrics;
f.detail("plugins.lookup-table", [
["registrySnapshotMs", e.registrySnapshotMs],
["manifestRegistryMs", e.manifestRegistryMs],
["startupPlanMs", e.startupPlanMs],
["ownerMapsMs", e.ownerMapsMs],
["totalMs", e.totalMs],
["indexPlugins", String(e.indexPluginCount)],
["indexPluginCount", e.indexPluginCount],
["manifestPlugins", String(e.manifestPluginCount)],
["manifestPluginCount", e.manifestPluginCount],
["startupPlugins", String(e.startupPluginCount)],
["startupPluginCount", e.startupPluginCount]
]);
}
p.transferred = true;
return {
opts: r,
minimalTestGateway: g,
ambientEnvTriggers: _,
startupTrace: f,
configSnapshot: S,
startupActivationSourceConfig: k,
startupSessionDatabases: V,
cronStorePath: U,
cfgAtStart: N,
generatedStartupAuthToken: M.generatedToken !== void 0,
resolvedStartupAuthOverride: F,
startupTailscaleOverride: w,
applyFixedGatewayOverlays,
prepareReloadCandidate,
workerEnvironmentStartup: B,
pluginGatewayContext: W,
resolvePluginGatewayContext,
pluginBootstrap: G,
gatewayPluginConfigAtStart: K,
defaultWorkspaceDir: q,
pluginWorkspaceDir: J,
startupPluginIds: Y,
pluginManifestRecords: ee,
pluginMetadataSnapshot: oe,
pluginLookUpTable: te,
baseMethods: ne,
ambientAutostartSuppressedChannelIds: re,
coreGatewayMethodNames: ie,
activateRuntimeSecrets: O
};
} catch (e) {
t.e = e;
} finally {
t.d();
}
}
//#endregion
//#region src/gateway/server-kernel.ts
const loadGatewayModelCatalogModule = createLazyRuntimeModule(() => import("./server-model-catalog-DG3mwjjz.mjs"));
const bindGatewayModelCatalog = createLazyRuntimeMethodBinder(loadGatewayModelCatalogModule);
const log$1 = createSubsystemLogger("gateway");
const logDiscovery = log$1.child("discovery");
const logTailscale$1 = log$1.child("tailscale");
const logChannels$1 = log$1.child("channels");
const logHealth$1 = log$1.child("health");
const logCron$1 = log$1.child("cron");
const logReload$1 = log$1.child("reload");
const logHooks$1 = log$1.child("hooks");
const logPlugins = log$1.child("plugins");
const logWsControl$1 = log$1.child("ws");
const logSecrets = log$1.child("secrets");
const gatewayKernelLogs = {
log: log$1,
logTailscale: logTailscale$1,
logChannels: logChannels$1,
logHealth: logHealth$1,
logCron: logCron$1,
logReload: logReload$1,
logHooks: logHooks$1,
logWsControl: logWsControl$1
};
const gatewayRuntime = runtimeForLogger(log$1);
const getChannelRuntime = createLazyRuntimeModule(() => import("./runtime-channel-C8FKrwt6.mjs").then(({ createRuntimeChannel: e }) => e()));
const loadGatewayModelCatalog = bindGatewayModelCatalog((e) => e.loadGatewayModelCatalog);
const loadGatewayModelCatalogSnapshot = bindGatewayModelCatalog((e) => e.loadGatewayModelCatalogSnapshot);
const readPreparedGatewayModelCatalog = bindGatewayModelCatalog((e) => e.readPreparedGatewayModelCatalog);
const readPreparedGatewayModelCatalogBatch = bindGatewayModelCatalog((e) => e.readPreparedGatewayModelCatalogBatch);
const loadPreparedGatewayModelCatalogSnapshot = bindGatewayModelCatalog((e) => e.loadPreparedGatewayModelCatalogSnapshot);
const readPreparedGatewayModelCatalogOwnerSnapshot = bindGatewayModelCatalog((e) => e.readPreparedGatewayModelCatalogOwnerSnapshot);
registerGatewayModelCatalogPrivateAccess(loadGatewayModelCatalogSnapshot, {
loadDeferred: (e) => loadPreparedGatewayModelCatalogSnapshot(e),
readPrepared: readPreparedGatewayModelCatalogOwnerSnapshot
});
function formatRuntimeGatewayAuthTokenWarning() {
const e = "Gateway auth token was missing. Generated a runtime token for this startup without changing config; restart will generate a different token.";
if (!isNixMode && resolveIsConfigReadOnly()) return `${e} Set gateway.auth.token in your external config source and redeploy.`;
if (!isNixMode) return `${e} Persist one with \`openclaw config set gateway.auth.mode token\` and \`openclaw config set gateway.auth.token <token>\`.`;
return [
e,
"In Nix mode, set gateway.auth.token in your Nix-managed OpenClaw config and rebuild.",
"For the first-party Nix flow, see https://github.com/openclaw/nix-openclaw#quick-start and https://docs.openclaw.ai/install/nix."
].join(" ");
}
/** Builds the Gateway kernel and internal dispatch surface without creating HTTP servers. */
async function createGatewayKernel(e = 18789, t = {}, n = {}) {
await installGatewayDatabaseEngine(t.startupConfigSnapshotRead?.snapshot, t.startupConfigSnapshotRead?.databaseEngineSelection);
const r = new GatewayScheduler();
const i = n.sdkResourceHost ?? new LegacyPluginSdkResourceHost();
i.bindScheduler(r);
return await i.run(() => createGatewayKernelWithSdkHost(e, t, n, i, r));
}
async function createGatewayKernelWithSdkHost(e, t, n, r, i) {
const a = t.bootId;
if (a !== void 0 && (a.trim() !== a || !a || a.length > 96)) throw new Error("Gateway boot ID must contain 1 to 96 characters");
const o = a ?? randomUUID();
const [, { cancelPreparedModelRuntimeRefresh: s }] = await Promise.all([measureGatewayBootstrapStep("gateway.catalog-startup-snapshot", () => prepareRemoteModelCatalogStartupSnapshot()), measureGatewayBootstrapStep("gateway.model-runtime-import", () => import("./prepared-model-runtime-D6x7ghYr.mjs"))]);
ensureOpenClawCliOnPath();
const c = retainGatewayPluginMetadata(i, async () => {
s();
});
let l;
let u;
let d;
let f;
let p;
try {
const a = await c.runBootstrap(() => prepareGatewayServerBootstrap({
port: e,
opts: t,
log: log$1,
logSecrets,
loadWorkerEnvironmentStartupModule: () => import("./server-worker-environment-startup-i4DVypHZ.mjs"),
formatRuntimeGatewayAuthTokenWarning
}));
f = a.startupTrace.close;
l = createPluginRegistryOwner(a.pluginBootstrap.pluginRegistry, a.pluginBootstrap.pluginWorkspaceDir);
c.publish(a.pluginMetadataSnapshot);
const s = l;
const p = await a.startupTrace.measure("gateway.kernel-state", () => prepareGatewayKernelState({
bootstrap: a,
scheduler: i,
bootId: o,
pluginRegistryOwner: s,
getPluginReloadStatus: () => u?.kernel.pluginRuntimeGeneration.getReloadStatus(),
port: e,
opts: t,
log: log$1,
logChannels: logChannels$1,
logHooks: logHooks$1,
logPlugins,
gatewayRuntime,
resolveChannelRuntime: getChannelRuntime
}));
d = p;
bindLegacyPluginSdkResourceHost(p.resolvePluginGatewayContext, r);
const m = await p.startupTrace.measure("gateway.shutdown-runtime-import", async () => (await import("./server-shutdown.runtime.js")).prepareGatewayShutdownRuntime());
const h = await p.startupTrace.measure("gateway.lifecycle", () => prepareGatewayLifecycle({
runtime: p,
sdkResourceHost: r,
pluginMetadata: c,
port: e,
log: log$1,
logCron: logCron$1,
shutdownRuntime: m,
exitAfterStartupFailure: t.exitAfterStartupFailure
}));
u = h;
const g = getAgentDatabaseStartupAdmission();
if (g) h.registerGatewayLifetimeSidecars({
name: "database-admission",
...g.adopt()
});
await setTimeout$1(0, void 0, { signal: p.connectionWork.signal });
p.connectionWork.signal.throwIfAborted();
if (a.cfgAtStart.gateway?.tls?.enabled && !p.gatewayTls.enabled) throw new Error(p.gatewayTls.error ?? "gateway tls: failed to enable");
const _ = await p.startupTrace.measure("gateway.core-runtime", () => startGatewayCoreRuntime({
lifecycleRuntime: h,
port: e,
log: log$1,
logDiscovery,
logHealth: logHealth$1,
logChannels: logChannels$1,
loadGatewayModelCatalog,
loadGatewayModelCatalogSnapshot,
readPreparedGatewayModelCatalog,
readPreparedGatewayModelCatalogBatch
}));
if (!n.deferEarlyRuntime) await _.startEarlyRuntime();
await c.waitForRetirement();
const v = await p.startupTrace.measure("gateway.request-runtime", () => prepareGatewayKernelRequestRuntime({
coreRuntime: _,
log: log$1,
logHealth: logHealth$1,
hostLifecycle: t.hostLifecycle
}));
if (!n.deferRequestRuntime) await v.ensureRequestRuntimeReady();
return v;
} catch (e) {
p = e;
}
return await rethrowGatewayStartupError(p, async () => {
const e = c.beginClose();
i.beginClose();
await e;
if (u) await u.closeOnStartupFailure(p);
else {
f?.();
await d?.mentionInbox.dispose();
await i.stop();
await r.drainWork();
const e = [];
const releaseMetadata = async (t) => {
try {
await r.close();
} catch (t) {
if (hasRetainedPluginRuntimeCloseError(t)) throw t;
e.push(t);
}
return c.close(async (t) => {
await closePreparedModelRuntimeSnapshots();
await t();
for (const t of [clearGatewayAgentCliShim, clearSecretsRuntimeSnapshotState]) try {
t();
} catch (t) {
e.push(t);
}
}, t);
};
try {
await (l ? l.close(releaseMetadata) : releaseMetadata());
} catch (t) {
e.push(t);
}
if (e.length === 1) throw e[0];
if (e.length > 1) throw new AggregateError(e, "Gateway startup cleanup failed", { cause: e[0] });
}
});
}
//#endregion
//#region src/gateway/mcp-app-sandbox-http.ts
function handleMcpAppSandboxHttpRequest(e, t) {
const n = URL.parse(e.url ?? "/", "http://localhost");
if (!n) {
respondPlainText(t, 400, "Bad Request");
return true;
}
if (n.pathname !== "/mcp-app-sandbox" || e.method !== "GET" && e.method !== "HEAD") return false;
let r;
try {
r = decodeSandboxHostCsp(n.searchParams.get("csp"));
} catch {
respondPlainText(t, 400, "invalid MCP App sandbox policy");
return true;
}
const i = getRemoteControlUiIngressContext(e);
assertRemoteControlUiIngressCurrent(i);
const { html: a, headers: o, version: s } = buildSandboxHostDocument(r, i ? [i.publicOrigin, ...i.frameAncestors] : void 0);
t.statusCode = 200;
for (const [e, n] of Object.entries(o)) t.setHeader(e, n);
t.setHeader("Cache-Control", n.searchParams.get("v") === s ? "public, max-age=31536000, immutable" : "no-store");
t.setHeader("Content-Length", String(Buffer.byteLength(a)));
t.end(e.method === "HEAD" ? void 0 : a);
return true;
}
/** Dedicated listener for the sandbox proxy, never Gateway data. */
function createSandboxHostHttpServer(e) {
const t = createSandboxHostHttpRequestHandler();
const listener = (e, n) => {
t(e, n);
};
return e ? createServer$2(e, listener) : createServer$1(listener);
}
/** Shared dedicated-surface owner for listener and virtual ingress transports. */
function createSandboxHostHttpRequestHandler() {
return async (e, t) => {
assertRemoteControlUiIngressCurrent(getRemoteControlUiIngressContext(e));
if (!handleMcpAppSandboxHttpRequest(e, t)) respondPlainText(t, 404, "Not Found");
};
}
//#endregion
//#region src/gateway/server-http-modules.ts
const getControlUiModule = createLazyRuntimeModule(() => import("./control-ui-kt1V6oyu.mjs"));
const getControlUiPluginAssetsModule = createLazyRuntimeModule(() => import("./control-ui-plugin-assets-ZUxE2s-C.mjs"));
const getCanvasServeModule = createLazyRuntimeModule(() => import("./serve.runtime.js"));
const getBoardHttpModule = createLazyRuntimeModule(() => import("./board-http-DuVf1-jU.mjs"));
const getEmbeddingsHttpModule = createLazyRuntimeModule(() => import("./embeddings-http-CXATlrqe.mjs"));
const getManagedMediaAttachmentsModule = createLazyRuntimeModule(() => import("./managed-image-attachments-L8xX6OIX.mjs"));
const getArtifactDownloadsModule = createLazyRuntimeModule(() => import("./artifact-downloads-_AafEW7V.mjs"));
const getMcpAppStandaloneModule = createLazyRuntimeModule(() => import("./mcp-app-standalone-D4PrD1lP.mjs"));
const getModelsHttpModule = createLazyRuntimeModule(() => import("./models-http-DWnCttgw.mjs"));
const getOpenAiHttpModule = createLazyRuntimeModule(() => import("./openai-http-DDdmZzKe.mjs"));
const getOpenResponsesHttpModule = createLazyRuntimeModule(() => import("./openresponses-http-DOGV7Dbl.mjs"));
const getSessionHistoryHttpModule = createLazyRuntimeModule(() => import("./sessions-history-http-B5bY7xfy.mjs"));
const getSessionKillHttpModule = createLazyRuntimeModule(() => import("./session-kill-http-BZWxuIk4.mjs"));
const getToolsInvokeHttpModule = createLazyRuntimeModule(() => import("./tools-invoke-http-DRGKAF8z.mjs"));
const getDevicePairingJoinHttpModule = createLazyRuntimeModule(() => import("./device-pairing-join-http-CBX6Ydbo.mjs"));
const getPluginNodeCapabilityAuthModule = createLazyRuntimeModule(() => import("./plugin-node-capability-auth-BuNv5gjk.mjs"));
const getHttpAuthUtilsModule = createLazyRuntimeModule(() => import("./http-auth-utils-oPUMOxUq.mjs"));
const getPluginRouteRuntimeScopesModule = createLazyRuntimeModule(() => import("./plugin-route-runtime-scopes-CZdjbmhU.mjs"));
const getNativeHookRelayModule = createLazyRuntimeModule(() => import("./native-hook-relay-http-BOh9xt3p.mjs"));
//#endregion
//#region src/channels/plugins/gateway-auth-bypass.ts
const GATEWAY_AUTH_API_ARTIFACT_BASENAME = "gateway-auth-api.js";
const MISSING_PUBLIC_SURFACE_PREFIX = "Unable to resolve bundled plugin public surface ";
/** Resolves to null when the plugin is not activated or ships no gateway auth artifact. */
async function loadChannelGatewayAuthApi(e) {
try {
return await tryLoadActivatedBundledPluginPublicSurfaceModule({
dirName: e,
artifactBasename: GATEWAY_AUTH_API_ARTIFACT_BASENAME
});
} catch (e) {
if (e instanceof Error && e.message.startsWith(MISSING_PUBLIC_SURFACE_PREFIX)) return null;
throw e;
}
}
/**
* Resolves configured gateway auth bypass paths from a channel plugin artifact.
*/
async function resolveBundledChannelGatewayAuthBypassPaths(e) {
return ((await loadChannelGatewayAuthApi(e.channelId))?.resolveGatewayAuthBypassPaths?.({ cfg: e.cfg }) ?? []).flatMap((e) => typeof e === "string" && e.trim() ? [e.trim()] : []);
}
//#endregion
//#region src/gateway/server-http-plugin-auth.ts
let pluginGatewayAuthBypassPathsCache = /* @__PURE__ */ new WeakMap();
registerPluginMetadataProcessMemoLifecycleClear(() => {
pluginGatewayAuthBypassPathsCache = /* @__PURE__ */ new WeakMap();
});
async function resolvePluginGatewayAuthBypassPaths(e) {
const t = /* @__PURE__ */ new Set();
for (const n of Object.keys(e.channels ?? {})) for (const r of await resolveBundledChannelGatewayAuthBypassPaths({
channelId: n,
cfg: e
})) t.add(r);
return t;
}
function getCachedPluginGatewayAuthBypassPaths(e) {
const t = pluginGatewayAuthBypassPathsCache;
const n = t.get(e);
if (n) return n;
const r = resolvePluginGatewayAuthBypassPaths(e).catch((n) => {
t.delete(e);
throw n;
});
t.set(e, r);
return r;
}
function shouldEnforceDefaultPluginGatewayAuth(e) {
return e.malformedEncoding || e.decodePassLimitReached || isProtectedPluginRoutePathFromContext(e);
}
//#endregion
//#region src/gateway/server-http-upgrades.ts
function rejectUpgradeAuth(e, t) {
if (t.rateLimited) {
const n = t.retryAfterMs && t.retryAfterMs > 0 ? Math.ceil(t.retryAfterMs / 1e3) : void 0;
const r = JSON.stringify({ error: {
message: "Too many failed authentication attempts. Please try again later.",
type: "rate_limited"
} });
rejectWebSocketUpgrade(e, {
status: 429,
body: {
contentType: "application/json; charset=utf-8",
text: r
},
headers: n ? { "Retry-After": String(n) } : void 0
});
return;
}
if (t.reason === "proxy_attribution_required") {
const t = JSON.stringify({ error: {
message: `Proxy client attribution is required. ${PROXY_ATTRIBUTION_GUIDANCE}`,
type: PROXY_ATTRIBUTION_REQUIRED_REASON
} });
rejectWebSocketUpgrade(e, {
status: 403,
body: {
contentType: "application/json; charset=utf-8",
text: t
}
});
return;
}
rejectWebSocketUpgrade(e, { status: 401 });
}
function handleBudgetedGatewayWebSocketUpgrade(e) {
const { req: t, socket: n, head: r, wss: i, preauthConnectionBudget: a, preauthBudgetKey: o, ingressName: s } = e;
const c = s === "Gateway" && isGatewayRestartDraining() && getGatewaySuspendAdmissionPhase() === "accepting" && e.isStartupPending?.() === true;
if (isGatewayWorkAdmissionClosed() && !c && (s === "Worker" || !isGatewaySuspendControlAvailable())) {
rejectGatewayUpgradeServiceUnavailable(n, `${s} websocket admission closed`);
return;
}
if (i.listenerCount("connection") === 0) {
rejectGatewayUpgradeServiceUnavailable(n, `${s} websocket handlers unavailable`);
return;
}
if (!a.acquire(o)) {
rejectGatewayUpgradeServiceUnavailable(n, "Too many unauthenticated sockets");
return;
}
let l = false;
const releaseUpgradeBudget = () => {
if (!l) {
l = true;
a.release(o);
}
};
n.once("close", releaseUpgradeBudget);
try {
if (readPreparedGatewayIngressAttribution(t)?.kind === "direct-local") delete t.headers["sec-websocket-extensions"];
i.handleUpgrade(t, n, r, (r) => {
const a = r;
a["__openclawPreauthBudgetKey"] = o;
e.prepareSocket?.(a);
i.emit("connection", r, t);
if (a["__openclawPreauthBudgetClaimed"]) {
l = true;
n.off("close", releaseUpgradeBudget);
}
});
} catch (e) {
n.off("close", releaseUpgradeBudget);
releaseUpgradeBudget();
throw e;
}
}
/** Physical and virtual transports share upgrade admission and route ownership. */
function attachGatewayUpgradeHandler(e) {
const { wss: t, handlePluginUpgrade: n, shouldEnforcePluginGatewayAuth: r, resolvePluginNodeCapabilityRoute: i, clients: a, preauthConnectionBudget: o, resolvedAuth: s, rateLimiter: c, publicRateLimiter: l, workerIngressEnabled: u, log: d } = e;
const f = e.getResolvedAuth ?? (() => s);
const handle = async (s, p, m) => {
p.once("error", () => p.destroy());
const h = getRemoteControlUiIngressContext(s);
if (!h) markGatewayIngressTransport(s, e.ingressTransport ?? { kind: "ordinary" });
const handleUpgrade = async () => {
await e.waitForRequestRuntime?.();
const d = readRuntimeConfig();
assertRemoteControlUiIngressCurrent(h);
if (h) {
const t = URL.parse(s.url ?? "/", h.publicOrigin)?.pathname;
const n = (e.controlUiBasePath ?? "") || "/";
if (s.headers.origin !== h.publicOrigin || !t || ![
n,
"/desktop/observe",
"/desktop/audio",
"/browser/screencast"
].includes(t)) {
rejectWebSocketUpgrade(p, { status: 403 });
return;
}
}
const g = d.gateway?.trustedProxies ?? [];
const _ = d.gateway?.allowRealIpFallback === true;
const v = prepareGatewayIngressAttribution({
req: s,
trustedProxies: g,
allowRealIpFallback: _
});
const y = v.kind === "unattributable-proxy" ? v.remoteAddress : v.clientIp;
const b = v.kind === "remote-forwarded" ? v.rateLimit.subject.key : y;
const x = URL.parse(s.url ?? "/", "http://localhost")?.pathname;
const S = x ? classifyWorkerGatewayPath(x) : "outside";
if (S !== "outside" && v.kind === "unattributable-proxy") {
e.reportUnattributableProxy?.(v);
rejectUpgradeAuth(p, {
ok: false,
reason: v.reason
});
return;
}
if (S === "worker" && !u) {
rejectGatewayUpgradeServiceUnavailable(p, "Worker websocket ingress unavailable");
return;
}
if (S === "worker") {
const e = l?.check(y, AUTH_RATE_LIMIT_SCOPE_WORKER_ADMISSION);
if (e && !e.allowed) {
rejectUpgradeAuth(p, {
ok: false,
reason: "rate_limited",
rateLimited: true,
retryAfterMs: e.retryAfterMs
});
return;
}
try {
handleBudgetedGatewayWebSocketUpgrade({
req: s,
socket: p,
head: m,
wss: t,
preauthConnectionBudget: o,
preauthBudgetKey: y,
ingressName: "Worker",
prepareSocket: (e) => {
e[GATEWAY_WS_CONNECTION_KIND_PROPERTY] = "worker";
markPublicWorkerIngress(e, {
clientIp: y,
rateLimiter: l
});
}
});
} catch {
throw new Error("public worker websocket upgrade failed");
}
return;
}
if (S !== "outside") {
rejectWebSocketUpgrade(p, { status: 404 });
return;
}
const C = normalizePluginNodeCapabilityScopedUrl(s.url ?? "/");
if (C.malformedScopedPath) {
rejectUpgradeAuth(p, {
ok: false,
reason: "unauthorized"
});
return;
}
if (C.rewrittenUrl) s.url = C.rewrittenUrl;
const w = f();
const T = C.pathname;
const E = resolvePluginRoutePathContext(T);
if (classifyWorkerGatewayPath(T) !== "outside") {
rejectWebSocketUpgrade(p, { status: 404 });
return;
}
const D = i?.(E);
if (v.kind === "unattributable-proxy") {
e.reportUnattributableProxy?.(v);
if (D || !e.isPluginAuthenticatedRoute?.(E)) {
rejectUpgradeAuth(p, {
ok: false,
reason: v.reason
});
return;
}
}
if (D) {
const { authorizePluginNodeCapabilityRequest: e } = await getPluginNodeCapabilityAuthModule();
const t = await e({
req: s,
auth: w,
trustedProxies: g,
allowRealIpFallback: _,
clients: a,
nodeCapability: D,
capability: C.capability,
malformedScopedPath: C.malformedScopedPath,
rateLimiter: c
});
if (!t.ok) {
rejectUpgradeAuth(p, t);
return;
}
}
if (n && (!h || T === "/browser/screencast")) {
let e = false;
let t;
let i;
if ((r ?? shouldEnforceDefaultPluginGatewayAuth)(E) && !(await getCachedPluginGatewayAuthBypassPaths(d)).has(T)) {
const { checkGatewayHttpRequestAuth: n } = await getHttpAuthUtilsModule();
const r = await n({
req: s,
auth: w,
trustedProxies: g,
allowRealIpFallback: _,
rateLimiter: c,
cfg: d,
getRuntimeConfig: readRuntimeConfig,
getResolvedAuth: f
});
if (!r.ok) {
rejectUpgradeAuth(p, r.authResult);
return;
}
e = true;
t = r.requestAuth;
const { resolvePluginRouteRuntimeOperatorScopes: a } = await getPluginRouteRuntimeScopesModule();
i = a(s, r.requestAuth);
}
if (t?.hasCurrentClientAuthority?.() === false) {
rejectUpgradeAuth(p, {
ok: false,
reason: "unauthorized"
});
return;
}
assertRemoteControlUiIngressCurrent(h);
if (await n(s, p, m, E, {
gatewayAuthSatisfied: e,
gatewayRequestAuth: t,
gatewayRequestOperatorScopes: i,
gatewayRequestClientIp: y
})) return;
}
if (v.kind === "unattributable-proxy") {
rejectUpgradeAuth(p, {
ok: false,
reason: v.reason
});
return;
}
if (T === "/desktop/observe" || T === "/desktop/audio") {
if (!e.desktopSessionRegistry) {
rejectGatewayUpgradeServiceUnavailable(p, "desktop observe unavailable");
return;
}
if (isGatewayWorkAdmissionClosed()) {
rejectGatewayUpgradeServiceUnavailable(p, "Gateway websocket admission closed");
return;
}
if (T === "/desktop/audio") {
const { handleDesktopAudioUpgrade: e } = await import("./audio-bridge-9ALRUW_y.mjs");
assertRemoteControlUiIngressCurrent(h);
e(s, p, m);
return;
}
const { handleDesktopObserveUpgrade: t } = await import("./observe-bridge-BNslmUCS.mjs");
assertRemoteControlUiIngressCurrent(h);
t(s, p, m, { registry: e.desktopSessionRegistry });
return;
}
if (T === "/node-desktop/attach" || T === "/node-portal/attach") {
const t = e.getGatewayRequestContext?.();
if (!e.nodeDesktopStreamBroker || !t) {
rejectGatewayUpgradeServiceUnavailable(p, `node ${T === "/node-desktop/attach" ? "desktop" : "portal"} attach unavailable`);
return;
}
if (isGatewayWorkAdmissionClosed()) {
rejectGatewayUpgradeServiceUnavailable(p, "Gateway websocket admission closed");
return;
}
await e.nodeDesktopStreamBroker.handleUpgrade(s, p, m, t.nodeRegistry);
return;
}
assertRemoteControlUiIngressCurrent(h);
if (h && T !== (e.controlUiBasePath || "/")) {
rejectWebSocketUpgrade(p, { status: 404 });
return;
}
try {
handleBudgetedGatewayWebSocketUpgrade({
req: s,
socket: p,
head: m,
wss: t,
preauthConnectionBudget: o,
preauthBudgetKey: b,
ingressName: "Gateway",
isStartupPending: e.isStartupPending
});
} catch {
throw new Error("gateway websocket upgrade failed");
}
};
await runHttpConnectionRequest(s, () => runWithDiagnosticTraceContext(createDiagnosticTraceContext(), handleUpgrade), "upgrade").catch((e) => {
const t = p.remoteAddress ?? "unknown";
const n = e instanceof Error ? e.message : String(e);
d?.warn(`ws upgrade error from ${t}: ${n}`);
rejectWebSocketUpgrade(p, { status: 503 });
});
};
e.httpServer.on("upgrade", (e, t, n) => {
handle(e, t, n);
});
return handle;
}
//#endregion
//#region src/gateway/control-ui-image-http-routes.ts
/** Resource owners stay lazy until their authenticated image route is requested. */
const CONTROL_UI_IMAGE_HTTP_ROUTES = [
[[
"pluginIcon",
"pluginActivityIcon",
"catalogIcon",
"linkFavicon"
], createLazyRuntimeNamedExport(() => import("./plugin-icon-http-CbPZ5otj.mjs"), "handlePluginIconHttpRequest")],
[["pluginThemeArt"], createLazyRuntimeNamedExport(() => import("./plugin-theme-art-http-CzbR4alS.mjs"), "handlePluginThemeArtHttpRequest")],
[["workspaceIcon"], createLazyRuntimeNamedExport(() => import("./workspace-icon-http-q5pIAVhz.mjs"), "handleWorkspaceIconHttpRequest")],
[["channelAvatar"], createLazyRuntimeNamedExport(() => import("./channel-avatar-http-lV7I3FqH.mjs"), "handleChannelAvatarHttpRequest")]
];
/** Personal images use their private authenticated owners even without dashboard hosting. */
const CONTROL_UI_USER_IMAGE_HTTP_ROUTES = [[parseControlUiUserBackgroundPath, createLazyRuntimeNamedExport(() => import("./user-background-http-B5pJlWuZ.mjs"), "handleUserBackgroundHttpRequest")], [parseControlUiUserAvatarPath, createLazyRuntimeNamedExport(() => import("./user-profiles-http-IaHiU6OH.mjs"), "handleUserProfileAvatarHttpRequest")]];
//#endregion
//#region src/gateway/control-ui-public-session-cache.ts
const MAX_ENTRIES = 128;
const MAX_BYTES = 16777216;
/** The route owns this bounded derived cache; publication authority is never cached here. */
function createPublicSessionRepresentationCache() {
const e = /* @__PURE__ */ new Map();
let t = 0;
const remove = (n, r) => {
t -= r.bytes;
e.delete(n);
};
const invalidate = (t, n = false) => {
for (const [r, i] of e) if ((!t || i.sessionKey === t) && (!n || i.kind === "card")) remove(r, i);
};
const n = [sessionChanges.subscribe((e) => {
const t = e.scope === "runtime" || e.scope === "agent-runs" || e.scope === "subagent-runs";
invalidate("sessionKey" in e ? e.sessionKey : void 0, t);
}), onInternalSessionTranscriptUpdate((e) => invalidate(e.target?.sessionKey ?? e.sessionKey))];
return {
get(t) {
const n = e.get(t);
if (!n) return;
if (n.representation) {
e.delete(t);
e.set(t, n);
}
return n.representation;
},
begin(n, r, i) {
const a = e.get(n);
if (a) remove(n, a);
while (e.size >= MAX_ENTRIES) {
const t = e.entries().next().value;
if (!t) break;
remove(...t);
}
const o = {
sessionKey: r,
kind: i,
bytes: 0
};
e.set(n, o);
const isCurrent = () => e.get(n) === o;
return {
isCurrent,
complete(r) {
if (!isCurrent()) return;
const i = {
body: r,
etag: `"${createHash("sha256").update(r).digest("base64url")}"`,
isCurrent
};
const a = Buffer.byteLength(r);
if (a > MAX_BYTES) {
remove(n, o);
return i;
}
e.delete(n);
e.set(n, o);
for (const [n, r] of e) {
if (t + a <= MAX_BYTES) break;
remove(n, r);
}
o.bytes = a;
o.representation = i;
t += a;
return i;
},
cancel() {
if (e.get(n) === o) remove(n, o);
}
};
},
dispose() {
for (const e of n) e();
invalidate();
}
};
}
//#endregion
//#region src/gateway/control-ui-public-session-admission.ts
const PUBLIC_SESSION_RATE_WINDOW_MS = 6e4;
const PUBLIC_SESSION_CLIENT_REQUEST_LIMIT = 120;
const PUBLIC_SESSION_PUBLICATION_REQUEST_LIMIT = 240;
const PUBLIC_SESSION_MAX_CLIENTS = 4096;
const PUBLIC_SESSION_MAX_PUBLICATIONS = 2048;
const PUBLIC_SESSION_MAX_CONCURRENT_READS = 8;
const PUBLIC_SESSION_MAX_CONCURRENT_READS_PER_PUBLICATION = 2;
const PUBLIC_SESSION_MAX_QUEUED_READS = 32;
function admitRateWindow(e, t, n, r, i) {
const a = i - PUBLIC_SESSION_RATE_WINDOW_MS;
let o = e.get(t);
if (!o) {
if (e.size >= r) for (const [t, n] of e) {
n.timestamps = n.timestamps.filter((e) => e > a);
if (n.timestamps.length === 0) e.delete(t);
}
if (e.size >= r) pruneMapToMaxSize(e, r - 1);
o = { timestamps: [] };
e.set(t, o);
}
o.timestamps = o.timestamps.filter((e) => e > a);
const s = o.timestamps[0];
if (o.timestamps.length >= n && s !== void 0) return Math.max(1, s + PUBLIC_SESSION_RATE_WINDOW_MS - i);
o.timestamps.push(i);
}
/** Creates the fixed, process-local abuse boundary for anonymous transcript reads. */
function createControlUiPublicSessionRequestGate() {
const e = /* @__PURE__ */ new Map();
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Map();
const i = createPublicSessionRepresentationCache();
let a = true;
const o = /* @__PURE__ */ new WeakMap();
let s = 1;
let c = 0;
const l = [];
const hasCapacity = (e) => c < PUBLIC_SESSION_MAX_CONCURRENT_READS && (n.get(e) ?? 0) < PUBLIC_SESSION_MAX_CONCURRENT_READS_PER_PUBLICATION;
const reserve = (e) => {
c++;
n.set(e, (n.get(e) ?? 0) + 1);
return () => {
c--;
const t = (n.get(e) ?? 1) - 1;
if (t) n.set(e, t);
else n.delete(e);
for (let e = 0; e < l.length;) {
if (!a || c >= PUBLIC_SESSION_MAX_CONCURRENT_READS) break;
const t = l[e];
if (!hasCapacity(t.publicationKey)) {
e++;
continue;
}
l.splice(e, 1);
t.resolve(reserve(t.publicationKey));
}
};
};
const acquire = (e) => {
if (!a) return Promise.resolve(void 0);
if (hasCapacity(e)) return Promise.resolve(reserve(e));
if (l.length >= PUBLIC_SESSION_MAX_QUEUED_READS) return Promise.resolve(void 0);
return new Promise((t) => {
l.push({
publicationKey: e,
resolve: t
});
});
};
const configId = (e) => {
const t = o.get(e);
if (t !== void 0) return t;
const n = s++;
o.set(e, n);
return n;
};
return {
dispose() {
a = false;
i.dispose();
for (const e of l.splice(0)) e.resolve(void 0);
e.clear();
t.clear();
},
admitClient(t) {
const n = admitRateWindow(e, t, PUBLIC_SESSION_CLIENT_REQUEST_LIMIT, PUBLIC_SESSION_MAX_CLIENTS, Date.now());
return n === void 0 ? { kind: "ok" } : {
kind: "rate-limited",
retryAfterSeconds: Math.ceil(n / 1e3)
};
},
async run(e) {
if (!a) return { kind: "unavailable" };
const n = Date.now();
const o = admitRateWindow(t, e.publicationKey, PUBLIC_SESSION_PUBLICATION_REQUEST_LIMIT, PUBLIC_SESSION_MAX_PUBLICATIONS, n);
if (o !== void 0) return {
kind: "rate-limited",
retryAfterSeconds: Math.ceil(o / 1e3)
};
const s = `${configId(e.config)}:${e.kind}:${e.requestKey}`;
const c = getAsyncWorkSignal();
const prepare = async () => {
const t = i.get(s);
if (t) return t;
const n = r.get(s);
if (n) try {
return await n.promise;
} catch (e) {
if (!n.signal?.aborted || c?.aborted) throw e;
return prepare();
}
const o = (async () => {
const t = await acquire(e.publicationKey);
if (!t) return;
try {
for (;;) {
if (!a) return;
c?.throwIfAborted();
const t = i.begin(s, e.sessionKey, e.kind);
try {
const n = await e.work();
if (n === null) {
t.cancel();
return null;
}
const r = t.complete(n);
if (r) return r.isCurrent() ? r : void 0;
} catch (e) {
t.cancel();
throw e;
}
}
} finally {
t();
}
})();
r.set(s, {
promise: o,
signal: c
});
try {
return await o;
} finally {
r.delete(s);
}
};
for (;;) {
if (!a) return { kind: "unavailable" };
c?.throwIfAborted();
const t = await prepare();
if (!a || t === void 0) return { kind: "unavailable" };
c?.throwIfAborted();
const n = await e.consume(t);
if (n !== false) return {
kind: "ok",
value: n
};
}
}
};
}
//#endregion
//#region src/gateway/control-ui-session-routes.ts
let publicSessionModule;
function isControlUiPublicSessionPath(e, t) {
return e === `${t}/share/session` || e === `${t}/share/session/card.png`;
}
/** One HTTP-server lifetime for public document work and protected app handoffs. */
function createControlUiSessionRoutes(e) {
const t = normalizeControlUiBasePath(e.controlUiBasePath);
let n;
let r;
const publicGate = () => n ??= createControlUiPublicSessionRequestGate();
return {
matches(e, n) {
if (isControlUiPublicSessionPath(e, t) || e === `${t}/share/session/media` || e === controlUiSessionEntryPath(t)) return true;
if (!e.startsWith(`${t}/chat/`) || e === `${t}/chat/`) return false;
const r = parseControlUiSessionPath(e, t);
const i = new URL(n ?? e, "http://localhost").searchParams;
return !(r?.kind === "main" && [
"catalog",
"host",
"thread"
].every((e) => i.getAll(e).length === 1 && i.get(e)?.trim()));
},
reject(e) {
respondNotFound(e);
return true;
},
dispose() {
n?.dispose();
r?.then((e) => e.dispose());
},
async serve(n) {
const { req: i, res: a, config: o } = n;
const s = new URL(i.url ?? "/", "http://localhost").pathname;
const c = e.getGatewayRequestContext?.();
const l = getSessionRowProjection(c);
const serveApp = async (r, s) => {
const c = i.url;
i.url = r;
try {
return await (await getControlUiModule()).handleControlUiHttpRequest(i, a, {
...n,
basePath: t,
root: e.controlUiRoot,
terminalEnabled: e.isTerminalEnabled?.() ?? isTerminalConfigEnabled(o),
agentId: resolveAssistantAgentId(o),
sessionEntryPath: r,
isSessionEntryCurrent: s
});
} finally {
i.url = c;
}
};
if (s === `${t}/share/session/media`) return (await import("./control-ui-public-session-media-gs7-lWCH.mjs")).serveControlUiPublicSessionMedia({
...n,
basePath: t,
projection: l,
gate: publicGate()
});
if (isControlUiPublicSessionPath(s, t)) {
const s = publicGate();
const { PUBLIC_SESSION_CONTENT_SECURITY_POLICY: c, servePublicSessionRepresentation: u } = await (publicSessionModule ??= import("./control-ui-public-session.runtime.js"));
const d = {
pullRequests: e.getGatewayRequestContext?.()?.controlUiSessionPullRequests,
render: async (e) => {
r ??= import("./control-ui-public-session-card-DXRufkzk.mjs").then((e) => e.createPublicSessionCardRenderer());
return (await r).render(e);
},
fallback: async () => {
a.setHeader("Cache-Control", "no-store");
const { readControlUiRootAsset: t } = await import("./server-control-ui-root-BHJFGMyZ.mjs");
const n = e.controlUiRoot;
const r = (n && (n.kind === "bundled" || n.kind === "resolved") ? await t(n, "social-card.png", true) : void 0)?.file.body;
if (!r) {
respondNotFound(a);
return;
}
a.statusCode = 200;
a.setHeader("Content-Type", "image/png");
a.setHeader("Content-Length", r.byteLength);
a.end(i.method === "HEAD" ? void 0 : r);
}
};
const f = {
...n,
basePath: t,
projection: l,
gate: s,
card: d
};
const p = i.url ? new URL(i.url, "http://localhost") : void 0;
if (!p) {
respondNotFound(a);
return true;
}
const m = resolveGatewayPublicOrigin(o);
const h = p.pathname === `${t}/share/session/card.png`;
const g = isSecurePublicSessionIngress(i, n.ingress, m);
a.setHeader("Cache-Control", "no-store");
a.setHeader("X-Robots-Tag", "noindex, nofollow");
a.setHeader("Content-Security-Policy", c);
const unavailable = (e, t = 1) => {
if (h) return d.fallback().then(() => true);
const n = e === 404 ? "This public session is unavailable." : e === 429 ? "Too many public session requests. Please retry later." : "This public session is temporarily unavailable. Please retry.";
a.statusCode = e;
a.setHeader("Content-Type", "text/plain; charset=utf-8");
a.setHeader("Content-Length", Buffer.byteLength(n));
if (e === 429 || e === 503) a.setHeader("Retry-After", String(t));
a.end(i.method === "HEAD" ? void 0 : n);
return true;
};
const _ = h ? parseControlUiPublicSessionCardUrl(p, t) : parseControlUiPublicSessionShareUrl(p, t);
const v = resolveControlUiShareOrigin(i, m);
const y = p.searchParams.get("offset") ?? "0";
const b = Number(y);
if (i.method !== "GET" && i.method !== "HEAD" || !_ || !v || !o || p.searchParams.getAll("offset").length > 1 || !/^(?:0|[1-9][0-9]{0,9})$/u.test(y)) return unavailable(404);
if (!g) return unavailable(404);
if (i.method === "HEAD") {
if (h) return unavailable(404);
a.statusCode = 405;
a.setHeader("Allow", "GET");
a.setHeader("Content-Length", "0");
a.end();
return true;
}
const x = s.admitClient(n.ingress.rateLimit.subject.key);
if (x.kind === "rate-limited") return unavailable(429, x.retryAfterSeconds);
try {
const { resolvePublicSessionShareToken: e } = await import("./control-ui-public-session-token-Ba44mALQ.mjs");
const n = await e(_.token);
if (!n) return unavailable(404);
if (!l) return unavailable(503);
if (h) {
const { servePublicSessionCardRepresentation: e } = await import("./control-ui-public-session-card-response-FnYnjIv4.mjs");
return await e({
...f,
locator: n,
projection: l,
host: new URL(v).host,
token: _.token
});
}
const r = buildControlUiPublicSessionSharePath({
basePath: t,
token: _.token
});
const a = m || i.socket instanceof TLSSocket ? `${v}${r}` : void 0;
return await u({
...f,
locator: n,
projection: l,
offset: b,
requestKey: JSON.stringify([
createHash("sha256").update(_.token).digest("base64url"),
b,
v
]),
document: {
latestUrl: r,
mediaBaseUrl: buildPublicSessionMediaBaseUrl(t, _.token),
canonicalUrl: a,
assetBasePath: t,
cardUrl: `${v}${buildControlUiPublicSessionCardPath({
basePath: t,
token: _.token
})}`
},
olderUrl: (e) => `${r}&offset=${e}`,
unavailable
});
} catch {
return unavailable(503);
}
}
if (s !== controlUiSessionEntryPath(t)) return (await (publicSessionModule ??= import("./control-ui-public-session.runtime.js"))).serveControlUiPublicChat({
...n,
basePath: t,
projection: l,
gate: publicGate(),
serveApp
});
return (await import("./control-ui-session-entry-B-IpOTzy.mjs")).serveControlUiSessionEntry({
...n,
basePath: t,
projection: l,
agentDatabaseStartup: c?.agentDatabaseStartup,
serveApp
});
}
};
}
//#endregion
//#region src/gateway/server-http-probes.ts
function startupProbeBody(e, t) {
if (!t) return JSON.stringify({
ok: e.ok,
status: e.status
});
return JSON.stringify({
ok: e.ok,
status: e.status,
version: resolveRuntimeServiceVersion(process.env),
buildId: resolveRuntimeServiceBuildId(),
uptimeMs: e.uptimeMs,
...e.status === "starting" ? { pendingReason: e.pendingReason } : {}
});
}
/** Handles live/ready/startup probe endpoints before normal gateway routing. */
async function handleGatewayProbeRequest(e, t, n, r, i, a, o, s, c) {
const l = classifyGatewayProbePath(n);
if (l === "namespace" || l === "outside") return false;
const u = (e.method ?? "GET").toUpperCase();
if (u !== "GET" && u !== "HEAD") {
t.statusCode = 405;
t.setHeader("Allow", "GET, HEAD");
t.setHeader("Content-Type", "text/plain; charset=utf-8");
t.end("Method Not Allowed");
return true;
}
t.setHeader("Content-Type", "application/json; charset=utf-8");
t.setHeader("Cache-Control", "no-store");
let d;
let f;
if (l === "ready" && s || l === "startup") {
async function shouldIncludeGatewayProbeDetails() {
if (readPreparedGatewayIngressAttribution(e)?.kind === "direct-local" || !readPreparedGatewayIngressAttribution(e) && isLocalDirectRequest(e)) return true;
if (r.mode === "none") return false;
const { getBearerToken: t, resolveHttpBrowserOriginPolicy: n } = await getHttpAuthUtilsModule();
const s = t(e);
return (await authorizeHttpGatewayConnect({
auth: r,
connectAuth: s ? {
token: s,
password: s
} : null,
req: e,
trustedProxies: i,
allowRealIpFallback: a,
rateLimiter: o,
browserOriginPolicy: n(e)
})).ok;
}
const t = l === "ready" ? s : void 0;
const n = await shouldIncludeGatewayProbeDetails();
try {
if (t) {
const e = t();
d = e.ready ? 200 : 503;
const r = n ? getGatewayRecentCrashes() : [];
f = JSON.stringify(n ? {
...e,
...r.length ? { recentCrashes: r } : {}
} : { ready: e.ready });
} else {
const e = c?.() ?? {
ok: true,
status: "started",
uptimeMs: 0
};
d = e.ok ? 200 : 503;
f = startupProbeBody(e, n);
}
} catch {
d = 503;
f = t ? JSON.stringify(n ? {
ready: false,
coreReady: false,
failing: ["internal"],
uptimeMs: 0
} : { ready: false }) : startupProbeBody({
ok: false,
status: "starting",
uptimeMs: 0,
pendingReason: "internal"
}, n);
}
} else {
d = 200;
f = JSON.stringify({
ok: true,
status: l
});
}
t.statusCode = d;
t.setHeader("Content-Length", String(Buffer.byteLength(f)));
t.end(u === "HEAD" ? void 0 : f);
return true;
}
//#endregion
//#region src/gateway/server-http-request.ts
/** Listener and service transports enter the same admission and route owner. */
function createGatewayHttpRequestHandler(e) {
const { clients: t, controlUiBasePath: n, controlUiRoot: r, handleHooksRequest: i, handlePluginRequest: a, shouldEnforcePluginGatewayAuth: o, resolvePluginNodeCapabilityRoute: s, resolvedAuth: c, rateLimiter: l, joinRateLimiter: u, getReadiness: d, getStartup: f } = e;
const p = e.getResolvedAuth ?? (() => c);
const m = e.getRuntimeConfig ?? readRuntimeConfig;
const h = n && n !== "/" ? n.replace(/\/$/, "") : "";
const g = controlUiPluginAssetRoot(h);
const _ = createControlUiSessionRoutes(e);
const handleServerRequest = (t, n, r) => {
if (!getRemoteControlUiIngressContext(t)) markGatewayIngressTransport(t, e.ingressTransport ?? { kind: "ordinary" });
return runGatewayHttpRequest(t, n, e.httpRequestLifetime, () => runWithDiagnosticTraceContext(createDiagnosticTraceContext(), () => runWithMainThreadTask("gateway:http", () => handleRequest(t, n, r)))).catch((e) => {
console.error("[gateway-http] failed to finalize request:", e);
n.destroy(e instanceof Error ? e : void 0);
});
};
async function handleRequest(v, y, b) {
const x = getRemoteControlUiIngressContext(v);
assertRemoteControlUiIngressCurrent(x);
if (getWebhookLegacyListener(v)) {
try {
if (!await a?.(v, y) && !y.writableEnded && !y.destroyed) {
y.writeHead(404);
y.end();
}
} catch (e) {
if (finishGatewayHttpAuthorityError(y, e) || finishGatewayHttpDatabaseAdmissionError(y, e)) return;
console.error("[gateway-http] legacy plugin request failed:", e);
y.destroy(e instanceof Error ? e : void 0);
return "failed";
}
return;
}
setDefaultSecurityHeaders(y, getRuntimeConfigSnapshot()?.gateway?.http?.securityHeaders);
if (b === "reject") {
y.writeHead(417);
y.end();
return;
}
if (b === "continue") y.writeContinue();
if (isWebSocketUpgradeRequest(v)) return;
if (v.headers.upgrade !== void 0) {
y.statusCode = 400;
y.setHeader("Connection", "close");
y.setHeader("Content-Type", "text/plain; charset=utf-8");
y.end("Bad Request");
return;
}
try {
const b = URL.parse(v.url ?? "/", "http://localhost")?.pathname;
if (b === void 0) {
sendGatewayAuthFailure(y, {
ok: false,
reason: "unauthorized"
});
return;
}
if (isControlUiSharePath(b, h)) y.setHeader("X-Robots-Tag", "noindex, nofollow");
const S = x ? resolveRemoteControlUiHttpRoute(v, h, x.resolvePrincipal().scopes) : void 0;
if (x && !S) {
respondNotFound(y);
return;
}
const C = classifyGatewayProbePath(b);
if (C === "live") {
await handleGatewayProbeRequest(v, y, b, c, [], false, l, d, f);
return;
}
if (C === "outside" || C === "namespace") await e.waitForRequestRuntime?.();
const w = m();
const T = e.controlUiEnabled ?? w.gateway?.controlUi?.enabled ?? true;
const E = w.gateway?.http?.endpoints?.chatCompletions;
const D = w.gateway?.http?.endpoints?.responses;
const O = e.openAiChatCompletionsEnabled ?? E?.enabled ?? false;
const k = e.openResponsesEnabled ?? D?.enabled ?? false;
const A = O || k;
const j = w.gateway?.trustedProxies ?? [];
const M = w.gateway?.allowRealIpFallback === true;
const N = prepareGatewayIngressAttribution({
req: v,
trustedProxies: j,
allowRealIpFallback: M,
tailscaleWhois: (e) => readTailscaleWhoisIdentity(e, void 0, {
cacheTtlMs: 0,
errorTtlMs: 0
})
});
const P = normalizePluginNodeCapabilityScopedUrl(v.url ?? "/");
if (P.malformedScopedPath) {
sendGatewayAuthFailure(y, {
ok: false,
reason: "unauthorized"
});
return;
}
if (P.rewrittenUrl) v.url = P.rewrittenUrl;
const F = P.pathname;
const I = resolvePluginRoutePathContext(F);
const L = s?.(I);
const R = p();
if (!x && (N.kind !== "unattributable-proxy" || isTrustedProxyAddress(N.remoteAddress, j)) && await handleGatewayProbeRequest(v, y, F, R, j, M, l, d, f)) return;
if (N.kind === "unattributable-proxy") {
e.reportUnattributableProxy?.(N);
if (!L && a && e.isPluginAuthenticatedRoute?.(I) && await a(v, y, I, { gatewayRequestClientIp: N.remoteAddress })) return;
sendGatewayAuthFailure(y, {
ok: false,
reason: N.reason
});
return;
}
const z = N.clientIp;
const B = {
auth: R,
cfg: w,
getRuntimeConfig: m,
getResolvedAuth: p,
trustedProxies: j,
allowRealIpFallback: M,
rateLimiter: l
};
const operatorAuth = () => ({
...B,
resolveGatewayContext: e.getGatewayRequestContext?.()?.resolveGatewayContext
});
const V = {
basePath: n,
config: w,
...B
};
const loadControlUi = () => {
const e = v.url ? new URL(v.url, "http://localhost") : void 0;
return e && (e.pathname === resolveAssistantMediaRoutePath(n) || classifyControlUiRequest({
basePath: normalizeControlUiBasePath(n),
pathname: e.pathname,
search: e.search,
method: v.method,
accept: v.headers.accept
}).kind !== "not-control-ui") ? getControlUiModule() : void 0;
};
const handleControlUiRequest = async () => (await loadControlUi())?.handleControlUiHttpRequest(v, y, {
...V,
terminalEnabled: e.isTerminalEnabled?.() ?? isTerminalConfigEnabled(w),
agentId: resolveAssistantAgentId(w),
root: r
}) ?? false;
const handleStandaloneControlUiRequest = async () => {
if (!T || !await handleControlUiRequest()) respondNotFound(y);
return true;
};
const H = [];
const addRequestStage = (e, t, n = false, r) => {
if (e && (!x || r === S)) H.push(n ? () => runWithGatewayHttpWorkAdmission(y, t) : t);
};
const addAdmittedStage = (e, t, n) => addRequestStage(e, t, true, n);
addRequestStage(classifyWorkerGatewayPath(F) !== "outside", () => {
respondNotFound(y);
return true;
});
const U = {
req: v,
res: y,
clientIp: N.rateLimit.subject.key,
rateLimiter: u
};
addAdmittedStage(F.startsWith("/__openclaw__/native-hook"), async () => (await getNativeHookRelayModule()).handleNativeHookRelayHttpRequest(U));
addAdmittedStage(classifyWorkerBootstrapArtifactTransferPath(F) !== "outside", () => handleArtifactTransferHttpRequest({
classifyPath: classifyWorkerBootstrapArtifactTransferPath,
routePrefix: `${WORKER_BOOTSTRAP_ARTIFACT_TRANSFER_PATH}/artifacts/`,
...U,
callback: e.handleWorkerBootstrapArtifactTransferRequest
}));
addAdmittedStage(classifyNodeWorkerBundleTransferPath(F) !== "outside", () => handleArtifactTransferHttpRequest({
classifyPath: classifyNodeWorkerBundleTransferPath,
routePrefix: `${NODE_WORKER_BUNDLE_TRANSFER_PATH}/bundles/`,
...U,
callback: e.handleNodeWorkerBundleTransferRequest
}));
addAdmittedStage(classifyNodeWorkspaceTransferPath(F) !== "outside", () => handleNodeWorkspaceTransferHttpRequest({
...U,
callback: e.handleNodeWorkspaceTransferRequest
}));
const W = parseDevicePairingJoinRequestPath(F);
if (W !== null) addAdmittedStage(true, async () => (await getDevicePairingJoinHttpModule()).handleDevicePairingJoinHttpRequest({
...U,
shortcode: W
}));
addAdmittedStage(F === PROVIDER_OAUTH_CALLBACK_PATH, () => handleProviderOAuthCallback(v, y));
addAdmittedStage(F.startsWith("/api/artifacts/download/") || h.length > 0 && F.startsWith(`${h}${"/api/artifacts/download/"}`), async () => (await getArtifactDownloadsModule()).handleArtifactDownloadHttpRequest(v, y, {
clients: t,
basePath: h
}), "artifact");
addAdmittedStage(v.method === "GET" && F === "/oauth/mcp/callback" && Boolean(e.handleMcpOAuthCallbackRequest), () => e.handleMcpOAuthCallbackRequest?.(v, y) ?? false);
addRequestStage(true, () => i(v, y));
addAdmittedStage(Boolean(e.handleWatchNodeRequest) && F.startsWith("/api/nodes/watch/"), () => e.handleWatchNodeRequest?.(v, y) ?? false);
addAdmittedStage(A && (F === "/v1/models" || F.startsWith("/v1/models/")), async () => (await getModelsHttpModule()).handleOpenAiModelsHttpRequest(v, y, B));
addAdmittedStage(A && F === "/v1/embeddings", async () => (await getEmbeddingsHttpModule()).handleOpenAiEmbeddingsHttpRequest(v, y, B));
addAdmittedStage(F === "/tools/invoke", async () => (await getToolsInvokeHttpModule()).handleToolsInvokeHttpRequest(v, y, operatorAuth()));
addAdmittedStage(/^\/sessions\/[^/]+\/kill$/.test(F), async () => (await getSessionKillHttpModule()).handleSessionKillHttpRequest(v, y, B));
addAdmittedStage(/^\/sessions\/[^/]+\/history$/.test(F), async () => (await getSessionHistoryHttpModule()).handleSessionHistoryHttpRequest(v, y, {
...B,
getCommittedRuntimeConfig: () => e.getGatewayRequestContext?.()?.getCommittedRuntimeConfig?.() ?? m()
}));
addAdmittedStage(F.startsWith("/__openclaw__/board/"), async () => (await getBoardHttpModule()).handleBoardHttpRequest(v, y, { resolveGatewayContext: e.getGatewayRequestContext?.()?.resolveGatewayContext }), "board");
addAdmittedStage(F.startsWith(g), async () => {
if (!T) {
respondNotFound(y);
return true;
}
return await (await getControlUiPluginAssetsModule()).handleControlUiPluginAssetRequest(v, y, V);
}, "native-assets");
for (const [e, t] of CONTROL_UI_USER_IMAGE_HTTP_ROUTES) addAdmittedStage(e(F, h).matched, async () => (await t())(v, y, F, {
...B,
basePath: h
}), "resource");
addAdmittedStage(k && F === "/v1/responses", async () => (await getOpenResponsesHttpModule()).handleOpenResponsesHttpRequest(v, y, {
...operatorAuth(),
config: D
}));
addAdmittedStage(O && F === "/v1/chat/completions", async () => (await getOpenAiHttpModule()).handleOpenAiHttpRequest(v, y, {
...operatorAuth(),
config: E
}));
const G = isControlUiApprovalDocumentPath({
basePath: n,
pathname: F
});
const K = isControlUiFocusPath(F, n);
const q = _.matches(F, v.url);
addRequestStage(!T && q, () => _.reject(y));
addAdmittedStage(T && q, () => _.serve({
...B,
req: v,
res: y,
config: w,
ingress: N
}));
addRequestStage(G || isControlUiSharePath(F, h) && !q, handleStandaloneControlUiRequest);
addRequestStage(Boolean(L), async () => {
const { authorizePluginNodeCapabilityRequest: e } = await getPluginNodeCapabilityAuthModule();
const n = await e({
req: v,
auth: R,
trustedProxies: j,
allowRealIpFallback: M,
clients: t,
nodeCapability: L,
capability: P.capability,
rateLimiter: l
});
if (!n.ok) {
sendGatewayAuthFailure(y, n);
return true;
}
return false;
});
addRequestStage(Boolean(L) && isCoreCanvasHostEnabled(w) && isCanvasDocumentHttpPath(F), async () => (await getCanvasServeModule()).handleCanvasDocumentHttpRequest(v, y));
addRequestStage(T && isControlUiPluginManagerRequest({
basePath: n,
pathname: F,
method: v.method
}), handleControlUiRequest, false, "document");
const J = classifyMcpAppStandalonePath(F);
addAdmittedStage(w.mcp?.apps?.enabled === true && (J === "shell" || J === "view"), async () => {
return await (await getMcpAppStandaloneModule()).handleMcpAppStandaloneHttpRequest(v, y, {
sandboxPort: w.mcp?.apps?.sandboxPort,
sandboxOrigin: w.mcp?.apps?.sandboxOrigin
});
});
if (a && (!x || S === "plugin-panel")) {
let e = null;
H.push(async () => {
if (!x && (!(o ?? shouldEnforceDefaultPluginGatewayAuth)(I) || (await getCachedPluginGatewayAuthBypassPaths(w)).has(F))) return false;
const { authorizePluginGatewayHttpRequestOrReply: t } = await getHttpAuthUtilsModule();
const { resolvePluginRouteRuntimeOperatorScopes: n } = await getPluginRouteRuntimeScopesModule();
e = await t({
req: v,
res: y,
...B,
requestPath: F,
resolveOperatorScopes: n
});
return !e;
}, () => {
if (e?.requestAuth.hasCurrentClientAuthority?.() === false) {
sendGatewayAuthFailure(y, {
ok: false,
reason: "unauthorized"
});
return true;
}
return a(v, y, I, {
gatewayAuthSatisfied: e !== null,
gatewayRequestAuth: e?.requestAuth,
gatewayRequestOperatorScopes: e?.operatorScopes,
gatewayRequestClientIp: z
});
});
}
addRequestStage(K, handleStandaloneControlUiRequest, false, "document");
addRequestStage(F.startsWith("/api/chat/media/outgoing/") || h.length > 0 && F.startsWith(`${h}/api/chat/media/outgoing/`), async () => (await getManagedMediaAttachmentsModule()).handleManagedOutgoingMediaHttpRequest(v, y, {
...B,
basePath: h,
clients: t
}), false, "outgoing-media");
for (const [t, n] of CONTROL_UI_IMAGE_HTTP_ROUTES) addRequestStage(T && t.some((e) => parseControlUiResourcePath(e, F, h).matched), async () => (await n())(v, y, {
...V,
sessionRowProjectionOwner: e.getGatewayRequestContext?.()?.sessionRowProjectionOwner
}), false, "resource");
addRequestStage(F === resolveAssistantMediaRoutePath(n), async () => (await loadControlUi())?.handleControlUiAssistantMediaRequest(v, y, {
...V,
agentId: resolveAssistantAgentId(w)
}) ?? false, false, "assistant-media");
addRequestStage(T, async () => (await loadControlUi())?.handleControlUiAvatarRequest(v, y, V) ?? false, false, "resource");
addRequestStage(T, handleControlUiRequest, false, "document");
for (const e of H) {
assertRemoteControlUiIngressCurrent(x);
if (await e() || y.destroyed || y.writableEnded) return;
}
assertRemoteControlUiIngressCurrent(x);
if (e.isStartupPluginRuntimeReady?.() === false) {
y.setHeader("Cache-Control", "no-store");
y.setHeader("Retry-After", "1");
respondPlainText(y, 503, "Plugin runtime is starting");
return;
}
respondNotFound(y);
return;
} catch (e) {
if (finishGatewayHttpAuthorityError(y, e) || finishGatewayHttpDatabaseAdmissionError(y, e)) return;
console.error("[gateway-http] unhandled error in request handler:", e);
finishFailedGatewayHttpResponse(y);
return "failed";
}
}
return Object.assign(handleServerRequest, { dispose: () => _.dispose() });
}
//#endregion
//#region src/gateway/server-http.ts
const requestHandlers = /* @__PURE__ */ new WeakMap();
function getGatewayHttpRequestHandler(e) {
const t = requestHandlers.get(e);
if (!t) throw new Error("Gateway HTTP owner is unavailable");
return t;
}
function createGatewayHttpServer(e) {
const t = createGatewayHttpRequestHandler(e);
const n = e.testListener ?? (e.tlsOptions ? createServer$2(e.tlsOptions) : createServer$1());
requestHandlers.set(n, t);
n.on("request", (e, n) => void t(e, n));
n.once("close", () => t.dispose());
n.on("checkContinue", (e, n) => void t(e, n, "continue"));
n.on("checkExpectation", (e, n) => void t(e, n, "reject"));
n.on("connect", (e, t) => {
runHttpConnectionRequest(e, async () => {
t.destroy();
}, "upgrade");
});
return n;
}
//#endregion
//#region src/gateway/server/plugin-legacy-listeners.ts
const endpointKey = ({ host: e, port: t }) => `${e ?? "<unspecified>"}:${t}`;
/** Compatibility ports share Gateway dispatch and the route owner's existing handoff leases. */
function startPluginLegacyListeners(e) {
const t = /* @__PURE__ */ new Map();
const n = /* @__PURE__ */ new Set();
const r = AsyncLocalStorage.snapshot();
let i = false;
let a = false;
const close = ({ server: e, controller: t }, n = false) => {
t.abort();
e.close();
if (n) e.closeAllConnections();
};
const reconcile = () => {
a = false;
if (i) return;
const r = /* @__PURE__ */ new Map();
for (const t of e.getRegistry().httpRoutes) for (const e of t.legacyListeners ?? []) {
const n = endpointKey(e);
if (!r.has(n) || !t.legacyListenerHandoffs?.includes(e)) r.set(n, e);
}
for (const [e, n] of t) if (!r.has(e)) {
t.delete(e);
close(n);
}
for (const [i, a] of r) {
const r = t.get(i);
if (r) {
r.endpoint = a;
const e = a.timeouts ?? r.defaultTimeouts;
r.server.headersTimeout = e.headers;
r.server.requestTimeout = e.request;
r.server.setTimeout(e.socket);
continue;
}
const o = createServer$1();
const s = new AbortController();
const c = {
server: o,
controller: s,
endpoint: a,
defaultTimeouts: {
headers: o.headersTimeout,
request: o.requestTimeout,
socket: o.timeout
}
};
n.add(c);
o.once("close", () => {
n.delete(c);
if (t.get(i) === c) t.delete(i);
const r = e.httpServers.indexOf(o);
if (r !== -1) e.httpServers.splice(r, 1);
});
if (a.timeouts) {
o.headersTimeout = a.timeouts.headers;
o.requestTimeout = a.timeouts.request;
o.setTimeout(a.timeouts.socket);
}
o.on("request", (t, n) => {
const r = c.endpoint;
if (r.health && t.url === r.health.path) {
runHttpConnectionRequest(t, async () => {
if (r.health?.contentType) n.setHeader("Content-Type", r.health.contentType);
n.writeHead(200);
n.end("ok");
}, n).catch((e) => n.destroy(e instanceof Error ? e : void 0));
return;
}
markPluginHttpLegacyListener(t, r);
e.gatewayServer.emit("request", t, n);
});
o.on("error", (n) => {
if (t.get(i) === c) t.delete(i);
close(c, true);
e.warn(`Legacy webhook listener ${i} failed: ${String(n)}. The Gateway webhook route remains available; update the external callback or reverse proxy to the Gateway port.`);
});
if (a.port === 0) o.once("listening", () => {
const t = o.address();
if (t && typeof t !== "string") e.warn(`Legacy webhook port 0 selected ${t.address}:${t.port}; this port changes on restart. Update the external callback or reverse proxy to the Gateway port.`);
});
t.set(i, c);
e.httpServers.push(o);
try {
o.listen({
port: a.port,
host: a.host,
signal: s.signal
});
} catch (e) {
o.emit("error", e);
}
}
};
pluginHttpRouteChanges.onChange = () => {
if (!a && !i) {
a = true;
queueMicrotask(() => r(reconcile));
}
};
const stop = () => {
if (i) return;
i = true;
pluginHttpRouteChanges.onChange = void 0;
e.gatewayServer.off("close", stop);
for (const e of n) close(e, true);
t.clear();
};
e.gatewayServer.once("close", stop);
reconcile();
return stop;
}
//#endregion
//#region src/gateway/server/preauth-connection-budget.ts
const DEFAULT_MAX_PREAUTH_CONNECTIONS_PER_IP = 128;
const UNKNOWN_CLIENT_IP_BUDGET_KEY = "__openclaw_unknown_client_ip__";
function createPreauthConnectionBudget() {
const e = process.env.OPENCLAW_MAX_PREAUTH_CONNECTIONS_PER_IP || (isVitestRuntimeEnv() ? process.env.OPENCLAW_TEST_MAX_PREAUTH_CONNECTIONS_PER_IP : void 0);
const t = parseStrictPositiveInteger(e) ?? DEFAULT_MAX_PREAUTH_CONNECTIONS_PER_IP;
const n = /* @__PURE__ */ new Map();
const normalizeBudgetKey = (e) => {
return e?.trim() || UNKNOWN_CLIENT_IP_BUDGET_KEY;
};
return {
acquire(e) {
const r = normalizeBudgetKey(e);
const i = (n.get(r) ?? 0) + 1;
if (i > t) return false;
n.set(r, i);
return true;
},
release(e) {
const t = normalizeBudgetKey(e);
const r = n.get(t);
if (r === void 0) return;
if (r <= 1) {
n.delete(t);
return;
}
n.set(t, r - 1);
}
};
}
//#endregion
//#region src/gateway/server-runtime-state.ts
const loadGatewayPluginsHttpModule = async () => await import("./plugins-http-DmRAZBs5.mjs");
function hasMatchingGatewayPluginRoute(e, t, n) {
if (!t) return (e.httpRoutes ?? []).length > 0;
const r = findMatchingPluginHttpRoutes(e, t);
return n ? r.some((e) => typeof e.handleUpgrade === "function") : r.length > 0;
}
/** Creates the HTTP/WebSocket transport for one gateway start. */
async function createGatewayHttpTransport(e) {
const t = getSpawnBroker();
const n = captureSqliteReadOnlyWorkerScope();
if (e.testListener) {
const t = e.testListener.address();
if (e.gatewayTls?.enabled || e.bindHost !== "127.0.0.1" || !t || typeof t === "string" || t.address !== e.bindHost || t.port !== e.port) throw new Error("Test Gateway listener must own the configured HTTP loopback endpoint");
}
const r = e.getRuntimeConfig ?? (() => e.cfg);
const resolvePluginRouteRegistry = () => e.getPluginRouteRegistry?.() ?? e.pluginRegistry;
let i = null;
let a;
const getHookDispatcher = async () => {
const { createGatewayHookDispatcher: r } = await import("./hooks-CvuUaJwI.mjs");
return a ??= runWithSpawnBroker(t, () => n(() => r({
deps: e.deps,
logHooks: e.logHooks,
deferHookWake: e.deferHookWake,
...e.getGatewayRequestContext ? { resolveGatewayContext: e.getGatewayRequestContext } : {}
})));
};
const handleHooksRequest = async (t, n) => {
const r = e.hooksConfig();
if (!r) return false;
const a = new URL(t.url ?? "/", "http://localhost");
const o = r.basePath;
if (a.pathname !== o && !a.pathname.startsWith(`${o}/`)) return false;
return await runWithGatewayHttpWorkAdmission(n, async () => {
if (!i) {
const { createGatewayHooksRequestHandler: t } = await import("./hooks-CvuUaJwI.mjs");
i = t({
scheduler: e.scheduler,
deps: e.deps,
dispatcher: await getHookDispatcher(),
getHooksConfig: e.hooksConfig,
getClientIpConfig: e.getHookClientIpConfig,
bindHost: e.bindHost,
port: e.port,
logHooks: e.logHooks,
...e.getGatewayRequestContext ? { resolveGatewayContext: e.getGatewayRequestContext } : {}
});
}
return await i(t, n);
});
};
const handleMcpOAuthCallbackRequest = async (t, n) => {
const { handleMcpOAuthCallback: i } = await import("./mcp-oauth-callback--sGulBEr.mjs");
return await i(t, n, {
config: r(),
log: e.log
});
};
let o = null;
let s = null;
const handlePluginRequest = async (t, n, r, i) => {
if (o) return await o(t, n, r, i);
if (!hasMatchingGatewayPluginRoute(resolvePluginRouteRegistry(), r, false)) return false;
const { createGatewayPluginRequestHandler: a } = await loadGatewayPluginsHttpModule();
o = a({
registry: e.pluginRegistry,
getRouteRegistry: resolvePluginRouteRegistry,
log: e.logPlugins,
getGatewayRequestContext: e.getGatewayRequestContext
});
return await o(t, n, r, i);
};
const handlePluginUpgrade = async (t, n, r, i, a) => {
if (s) return await s(t, n, r, i, a);
if (!hasMatchingGatewayPluginRoute(resolvePluginRouteRegistry(), i, true)) return false;
const { createGatewayPluginUpgradeHandler: o } = await loadGatewayPluginsHttpModule();
s = o({
registry: e.pluginRegistry,
getRouteRegistry: resolvePluginRouteRegistry,
log: e.logPlugins,
getGatewayRequestContext: e.getGatewayRequestContext
});
return await s(t, n, r, i, a);
};
const shouldEnforcePluginGatewayAuth = (e) => {
return shouldEnforceGatewayAuthForPluginPath(resolvePluginRouteRegistry(), e);
};
const isPluginAuthenticatedRoute = (e) => {
return isPluginAuthenticatedRoutePath(resolvePluginRouteRegistry(), e);
};
const resolvePluginNodeCapabilityRoute = (e) => {
const t = isCoreCanvasHostEnabled(r()) ? resolveCanvasNodeCapability(e.candidates) : void 0;
if (t) return t;
return findMatchingPluginNodeCapabilityRoute(resolvePluginRouteRegistry(), e)?.nodeCapability;
};
const c = e.tailscaleMode && e.tailscaleMode !== "off" ? e.tailscaleMode : void 0;
const l = await resolveGatewayListenHosts(e.bindHost);
if (!isLoopbackHost(e.bindHost)) e.log.warn("⚠️ Gateway is binding to a non-loopback address. Configure authentication before exposing to public networks.");
if (e.cfg.gateway?.controlUi?.dangerouslyAllowHostHeaderOriginFallback === true) e.log.warn("⚠️ gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback=true is enabled. Host-header origin fallback weakens origin checks and should only be used as break-glass.");
const u = new WebSocketServer({
noServer: true,
maxPayload: MAX_PREAUTH_PAYLOAD_BYTES,
allowSynchronousEvents: false,
perMessageDeflate: GATEWAY_PER_MESSAGE_DEFLATE
});
const d = createPreauthConnectionBudget();
const f = [];
const p = [];
const m = [];
const h = createGatewayPortalService({
httpBindHosts: m,
httpServers: f,
ingress: e.cfg.gateway?.portals?.ingress,
managedTailscale: Boolean(c),
gatewayOrigins: [e.cfg.gateway?.publicOrigin, ...e.cfg.gateway?.controlUi?.allowedOrigins ?? []].filter((e) => Boolean(e)),
...e.gatewayTls?.enabled ? { tlsOptions: e.gatewayTls.tlsOptions } : {}
});
const g = createGatewayUnattributableProxyReporter(e.log);
let _;
const createGatewayListener = (t, n, i) => {
const a = createGatewayHttpServer({
testListener: i,
clients: e.clients,
controlUiEnabled: e.controlUiEnabled,
controlUiBasePath: e.controlUiBasePath,
controlUiRoot: e.controlUiRoot,
openAiChatCompletionsEnabled: e.openAiChatCompletionsEnabled,
openResponsesEnabled: e.openResponsesEnabled,
handleWatchNodeRequest: e.handleWatchNodeRequest,
handleHooksRequest,
handleMcpOAuthCallbackRequest,
handlePluginRequest,
shouldEnforcePluginGatewayAuth,
isPluginAuthenticatedRoute,
resolvePluginNodeCapabilityRoute,
resolvedAuth: e.resolvedAuth,
getResolvedAuth: e.getResolvedAuth,
rateLimiter: e.rateLimiter,
joinRateLimiter: e.joinRateLimiter,
handleNodeWorkerBundleTransferRequest: e.handleNodeWorkerBundleTransferRequest,
handleWorkerBootstrapArtifactTransferRequest: e.handleWorkerBootstrapArtifactTransferRequest,
handleNodeWorkspaceTransferRequest: e.handleNodeWorkspaceTransferRequest,
getReadiness: e.getReadiness,
getStartup: e.getStartup,
getRuntimeConfig: r,
getGatewayRequestContext: e.getGatewayRequestContext,
waitForRequestRuntime: e.waitForRequestRuntime,
isStartupPluginRuntimeReady: e.isStartupPluginRuntimeReady,
httpRequestLifetime: e.httpRequestLifetime,
isTerminalEnabled: e.isTerminalEnabled,
tlsOptions: n,
ingressTransport: t,
reportUnattributableProxy: g
});
const o = attachGatewayUpgradeHandler({
httpServer: a,
controlUiBasePath: e.controlUiBasePath,
wss: u,
handlePluginUpgrade,
shouldEnforcePluginGatewayAuth,
isPluginAuthenticatedRoute,
resolvePluginNodeCapabilityRoute,
clients: e.clients,
preauthConnectionBudget: d,
resolvedAuth: e.resolvedAuth,
getResolvedAuth: e.getResolvedAuth,
rateLimiter: e.rateLimiter,
publicRateLimiter: e.joinRateLimiter,
workerIngressEnabled: e.workerIngressEnabled,
log: e.log,
desktopSessionRegistry: e.desktopSessionRegistry,
nodeDesktopStreamBroker: e.nodeDesktopStreamBroker,
getGatewayRequestContext: e.getGatewayRequestContext,
waitForRequestRuntime: e.waitForRequestRuntime,
isStartupPending: e.isStartupPending,
ingressTransport: t,
reportUnattributableProxy: g
});
if (t.kind === "ordinary") _ ??= o;
return a;
};
for (const t of l) {
const n = createGatewayListener({ kind: "ordinary" }, e.gatewayTls?.enabled ? e.gatewayTls.tlsOptions : void 0, t === e.bindHost ? e.testListener : void 0);
p.push(n);
f.push(n);
}
const v = c ? createGatewayListener({
kind: "managed-tailscale",
mode: c
}, void 0) : void 0;
if (v) f.push(v);
let y;
const b = p[0];
if (!b) throw new Error("Gateway HTTP server failed to start");
if (e.getGatewayRequestContext && _) {
const t = getGatewayContextLifetime(e.getGatewayRequestContext).signal;
const n = e.httpRequestLifetime?.requestEntryLifetime;
bindGatewayControlUiIngressHost(e.getGatewayRequestContext, {
resolveGatewayContext: e.getGatewayRequestContext,
controlUiBasePath: e.controlUiBasePath,
getResolvedAuth: e.getResolvedAuth,
getRuntimeConfig: r,
handleRequest: getGatewayHttpRequestHandler(b),
handleUpgrade: _,
handleSandboxRequest: createSandboxHostHttpRequestHandler(),
admissionSignal: n?.signal ?? t,
signal: n ? AbortSignal.any([t, n.retainedSignal]) : t
});
}
let x;
let S = null;
let C = null;
let w = false;
const startSandboxHost = async () => {
if (e.updateCanary) throw new Error("Sandbox host is disabled during update validation");
if (S) return await S;
S = (async () => {
if (m.length === 0) throw new Error("Gateway listener must start before the sandbox host");
const t = resolveSandboxHostPort(e.port, e.cfg.mcp?.apps?.sandboxPort);
const n = l.map(() => createSandboxHostHttpServer(e.gatewayTls?.enabled ? e.gatewayTls.tlsOptions : void 0));
f.push(...n);
try {
for (const r of m) {
const i = n[l.indexOf(r)];
if (!i) throw new Error(`Missing sandbox host HTTP server for bind host ${r}`);
await listenGatewayHttpServer({
httpServer: i,
bindHost: r,
port: t,
retryEaddrinuse: false,
serviceName: "MCP App sandbox",
endpointScheme: e.gatewayTls?.enabled ? "https" : "http"
});
}
} catch (e) {
await closeHttpServers(n);
for (const e of n) {
const t = f.indexOf(e);
if (t >= 0) f.splice(t, 1);
}
throw e;
}
x = t;
return t;
})();
const t = S;
t.catch(() => {
if (S === t) S = null;
});
return await t;
};
const ensureSandboxHostPort = async () => {
if (!w) {
if (!C) throw new Error("Gateway listener must start before the sandbox host");
await C;
}
return await startSandboxHost();
};
const startListening = async () => {
if (C) {
await C;
return;
}
C = (async () => {
if (v) {
await listenGatewayHttpServer({
httpServer: v,
bindHost: "127.0.0.1",
port: 0,
retryEaddrinuse: false,
serviceName: "Tailscale gateway ingress"
});
const t = v.address();
if (!t || typeof t === "string") throw new Error("Tailscale gateway ingress failed to resolve its loopback port");
y = {
host: "127.0.0.1",
port: t.port
};
await e.prepareManagedTailscaleIngress?.(y);
}
const t = e.bindHost !== "127.0.0.1" && l.includes("127.0.0.1") ? "127.0.0.1" : void 0;
const n = t ? [t, ...l.filter((e) => e !== t)] : l;
const r = /* @__PURE__ */ new Set();
for (const i of n) {
const n = l.indexOf(i);
const a = p[n];
if (!a) throw new Error(`Missing gateway HTTP server for bind host ${i}`);
const o = i === t;
try {
if (a !== e.testListener) await listenGatewayHttpServer({
httpServer: a,
bindHost: i,
port: e.port,
retryEaddrinuse: !o
});
r.add(i);
} catch (t) {
if (i === l[0] || o) throw t;
e.log.warn(`gateway: failed to bind loopback alias ${i}:${e.port} (${String(t)})`);
}
}
m.push(...l.filter((e) => r.has(e)));
if (m.length === 0) throw new Error("Gateway HTTP server failed to start");
e.onListening?.();
if (!e.updateCanary) await h.startIngress();
if (!e.updateCanary && e.cfg.mcp?.apps?.enabled === true) await startSandboxHost();
if (!e.updateCanary) startPluginLegacyListeners({
gatewayServer: b,
httpServers: f,
getRegistry: resolvePluginRouteRegistry,
warn: (t) => e.logPlugins.warn(t)
});
w = true;
})();
await C;
};
return {
httpServer: b,
httpServers: f,
httpBindHosts: m,
startListening,
wss: u,
preauthConnectionBudget: d,
portalService: h,
getTailscaleIngressEndpoint: () => y,
getMcpAppSandboxPort: () => x,
ensureSandboxHostPort,
dispatchHookAgentTurn: async (e, t) => await (await getHookDispatcher()).dispatchHookAgentTurn(t, e)
};
}
//#endregion
//#region src/gateway/server-agent-database-startup.ts
function assertAgentDatabaseConfiguration(e, t, n, r) {
const i = resolveConfiguredAgentDatabaseTargets(e, {
env: r,
agentId: t
});
if (n.some((e) => !isConfiguredAgentDatabaseTarget(i, t, e))) throw new Error(`Agent ${t} database configuration changed during startup inspection`);
}
/** Finish only the deferred agent's preparation before its admission owner recovers it. */
function activateGatewayAgentDatabaseStartup(e) {
const t = getSpawnBroker();
const createPreparationGuard = (t, n, r, i, a) => {
let o;
return () => {
i.throwIfAborted();
a();
if (!e.isCurrent()) throw new Error(`Agent ${t} startup preparation was superseded`);
const s = e.getConfig();
if (s !== o) {
assertAgentDatabaseConfiguration(s, t, n, r);
o = s;
}
};
};
e.admission?.activate({
isCurrent: e.isCurrent,
preparationReady: e.preparationReady,
captureReadAdmission: ({ agentId: e, paths: t, env: n, signal: r, assertCurrent: i }) => createPreparationGuard(e, t, n, r, i),
openAgent: ({ agentId: e, paths: n, env: r, signal: i, assertCurrent: a }) => runWithSpawnBroker(t, async () => {
try {
var t = _usingCtx();
const { captureOpenClawAgentDatabaseExecution: o, prepareOpenClawAgentDatabaseExecution: s } = await import("./openclaw-agent-execution-D8fPsYYC.mjs");
const c = t.a(new AsyncDisposableStack());
const l = createPreparationGuard(e, n, r, i, a);
l();
for (const t of n) {
const n = o({
agentId: e,
path: t,
env: r
});
c.defer(() => n.release());
await s({
agentId: e,
path: t,
env: r
}, l, i);
}
return c.move();
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}),
migrateAgent: ({ agentId: n, paths: r, env: i, signal: a, assertCurrent: o }) => runWithSpawnBroker(t, async () => {
const { prepareGatewayStartupSessions: s } = await import("./server-startup-session-migration-BZABLvmL.mjs");
const c = createPreparationGuard(n, r, i, a, o);
const l = await s({
cfg: e.getConfig(),
env: i,
agentIds: /* @__PURE__ */ new Set([n]),
assertCurrent: c,
log: e.log
});
c();
return { maintain: () => runWithSpawnBroker(t, async () => {
await e.waitForPostReadyWork();
const { runGatewaySessionStartupMaintenance: t } = await import("./server-startup-session-migration-BZABLvmL.mjs");
await t({
databases: l,
signal: a,
assertCurrent: createPreparationGuard(n, r, i, a, () => a.throwIfAborted()),
log: e.log
});
}) };
}),
publishAgent: ({ agentId: n, paths: r, env: i, signal: a, assertCurrent: o, phase: s }) => runWithSpawnBroker(t, async () => {
s("secrets");
const [{ refreshPreparedModelRuntimeSnapshots: t, getPreparedModelRuntimeSnapshot: c, getPendingPreparedModelRuntimeReplacement: l, retirePreparedModelRuntimeAgent: u }, { listConfiguredOwnerInputs: d }, { getActiveSecretsRuntimeSnapshot: f, getActiveSecretsRuntimeSnapshotRevision: p, refreshActiveSecretsRuntimeSnapshotForConfig: m }, { clearRuntimeAuthProfileStoreSnapshotAtDatabasePath: h }] = await Promise.all([
import("./prepared-model-runtime-D6x7ghYr.mjs"),
import("./prepared-model-runtime.configured-CZFMsAl-.mjs"),
import("./runtime-9a9hqNhJ.mjs"),
import("./runtime-snapshots-CCqTMPcH.mjs")
]);
o();
const g = e.getConfig();
assertAgentDatabaseConfiguration(g, n, r, i);
if (!listAgentIds(g).includes(n)) return;
const _ = p();
const v = f();
if (!v || !await m({
sourceConfig: v.sourceConfig,
runtimeSourceConfig: getRuntimeConfigSourceSnapshot() ?? void 0,
includeAuthStoreRefs: true,
assertCurrent: () => {
a.throwIfAborted();
o();
if (!e.isCurrent() || e.getConfig() !== g || p() !== _) throw new AgentDatabaseStartupSupersededError(n, "secrets");
}
})) throw new Error(`Agent ${n} secrets preparation could not publish`);
const y = e.getConfig();
const b = p();
const x = f();
const S = resolveAgentDir(y, n, i);
const C = resolveAuthProfileDatabasePath(S);
if (b !== _ + 1 || !x?.authStores.some((e) => isSameOpenClawAgentDatabasePath(e.databasePath, C))) throw new Error(`Agent ${n} secrets preparation has not published its auth store`);
const assertPreparationCurrent = () => {
a.throwIfAborted();
o();
if (!e.isCurrent() || e.getConfig() !== y || p() !== b) throw new AgentDatabaseStartupSupersededError(n, "startup");
};
assertPreparationCurrent();
s("models");
const w = e.getPluginMetadataSnapshot();
await withPluginRuntimeRegistryScope(e.getPluginRegistry(), () => t(y, {
agentIds: /* @__PURE__ */ new Set([n]),
catalogMode: "static",
allowGatewaySubagentBinding: true,
...w ? { pluginMetadataSnapshot: w } : {},
isPublicationCurrent: () => assertionSucceeds(assertPreparationCurrent)
})).catch(async (e) => {
if (!isPreparedModelRuntimePluginLifecycleFailure(e)) throw e;
await l();
throw new AgentDatabaseStartupSupersededError(n, "startup");
});
assertPreparationCurrent();
const T = d(y, void 0, true).find((e) => e.agentId === n);
if (!T) throw new Error(`Agent ${n} model preparation is no longer configured`);
if (!c(T)) {
const e = l();
if (e) {
await e;
throw new AgentDatabaseStartupSupersededError(n, "startup");
}
throw new Error(`Agent ${n} model preparation has not published`);
}
return () => {
if (!e.isCurrent()) return;
u({
agentId: n,
agentDirs: [S]
}).catch((t) => e.log.warn(`Agent ${n} model runtime retirement failed: ${String(t)}`));
h(C, S);
};
})
});
}
//#endregion
//#region src/gateway/server-tls-renewal.ts
/** Renew only the running listener's accepted paths; TLS topology remains startup-owned. */
function startGatewayTlsRenewal(e) {
const { runtime: t } = e;
const n = e.scheduler.scope();
const r = t.tlsOptions;
if (!t.enabled || !r || n.signal.aborted) return;
const i = [
t.certPath,
t.keyPath,
t.caPath
].filter((e) => Boolean(e));
let a = e.enabled;
let o = 0;
let s;
let c = Promise.resolve();
const isCurrent = (e) => a && !n.signal.aborted && o === e;
const requestRefresh = () => {
const i = ++o;
s?.cancel();
if (!isCurrent(i)) {
if (!a && !n.signal.aborted) e.log.info("gateway TLS renewal deferred (gateway.reload.mode=off)");
return;
}
s = n.schedule({
id: "gateway:tls-renewal",
delayMs: 300,
run: () => c = c.then(async () => {
if (!isCurrent(i)) return;
const n = await loadGatewayTlsServerRuntime({
enabled: true,
autoGenerate: false,
certPath: t.certPath,
keyPath: t.keyPath,
caPath: t.caPath
});
if (!isCurrent(i)) return;
if (!n.enabled || !n.tlsOptions) throw new Error(n.error ?? "TLS renewal did not produce listener material");
if (isDeepStrictEqual(r, n.tlsOptions)) return;
for (const t of e.servers) if (t instanceof Server) t.setSecureContext(n.tlsOptions);
Object.assign(r, n.tlsOptions);
t.fingerprintSha256 = n.fingerprintSha256;
await e.onRenewed().catch((t) => {
e.log.warn(`gateway TLS renewed but discovery refresh failed: ${String(t)}`);
});
e.log.info("gateway TLS certificate renewed without restarting listeners");
}).catch((t) => {
if (isCurrent(i)) e.log.warn(`gateway TLS renewal failed; keeping accepted material: ${String(t)}`);
})
});
};
for (const e of i) watchFile(e, {
interval: 1e3,
persistent: false
}, requestRefresh);
requestRefresh();
return {
name: "tls-renewal",
setEnabled: (e) => {
if (a !== e) {
a = e;
requestRefresh();
}
},
async stop() {
n.beginClose();
for (const e of i) unwatchFile(e, requestRefresh);
await n.stop();
}
};
}
//#endregion
//#region src/gateway/server/client-human-presence.ts
function hasAuthenticatedControlUiIdentity(e) {
return [...e].some((e) => !e.invalidated && e.socket.readyState === 1 && e.internal?.authenticatedControlUi === true && Boolean(e.authenticatedUserId || e.authenticatedUserProfile) && authorizeOperatorScopesForMethod("sessions.create", e.connect.scopes ?? []).allowed && isBrowserOperatorUiClient(e.connect.client));
}
/** Bind live Control UI demand and cleanup before requests and reconciliation start. */
async function startWorkerHumanPresence(e) {
const { clients: t, service: n, log: r } = e;
let i = hasAuthenticatedControlUiIdentity(t);
const a = /* @__PURE__ */ new Map();
const refresh = () => {
const e = hasAuthenticatedControlUiIdentity(t);
if (e !== i) {
i = e;
n.setHumanPresence(e).catch((e) => r.warn(`prepared-pool human presence update failed: ${String(e)}`));
}
};
const observeClients = () => {
for (const [e, n] of a) if (!t.has(e)) {
n();
a.delete(e);
}
for (const e of t) if (!a.has(e)) a.set(e, onGatewayPolicyClientInvalidated(e, refresh));
refresh();
};
t.onChange = observeClients;
observeClients();
e.registerSidecar({ stop: () => {
t.onChange = void 0;
for (const e of a.values()) e();
a.clear();
} });
await n.setHumanPresence(i);
}
//#endregion
//#region src/gateway/server-startup-finish.ts
const [POST_READY_MAINTENANCE_DELAY_MS, RETAINED_PLUGIN_CLEANUP_DELAY_MS] = [250, 3e4];
async function finishGatewayStartup(e) {
const { kernelRuntime: t, port: n, opts: r, log: i, logHealth: a, logWsControl: o, logHooks: s, logChannels: c, logCron: l, logReload: u } = e;
const { minimalTestGateway: d, deps: f, runtimeState: p, kernel: m, startupTrace: h, broadcast: g, broadcastToConnIds: _, clients: v, sharedGatewaySessionGenerationState: y, workerEnvironmentService: b, workerPlacementRuntime: x, terminalLaunchPolicy: S, terminalSessions: C, startChannel: w, stopChannel: T, lifecycle: E, startupState: D, pluginRuntime: O, resolvePluginGatewayContext: k, gatewayTls: A, bindHost: j, getResolvedAuth: M, authRateLimiter: N, browserAuthRateLimiter: P, nodeReapprovalCoordinator: F, gatewayPluginConfigAtStart: I, startupActivationSourceConfig: L, defaultWorkspaceDir: R, pluginManifestRecords: z, pluginMetadataSnapshot: B, ambientEnvTriggers: V, startChannels: H, broadcastPluginEvent: U, controlUiRootLifecycle: W, sidecarStartup: G, cfgAtStart: K, releaseStartupAccountStarts: q, cronReconciliation: J, cronStartState: Y, prepareReloadCandidate: ee, configSnapshot: X, channelManager: te, activateRuntimeSecrets: ne, applyFixedGatewayOverlays: re, resolveSharedGatewaySessionGenerationForConfig: ie, stopRegisteredPostReadySidecars: ae, registerPostReadySidecars: oe, registerGatewayLifetimeSidecars: Z, registerConnectionDependentSidecars: Q, unregisterConnectionDependentSidecar: se, chatMetadataLifecycle: ce, gatewayRequestContext: le, getPluginMetadataSnapshot: $, getPluginNodeCapabilities: ue } = t;
const de = getAgentDatabaseStartupAdmission();
const fe = createDeferredCore();
const pe = t.createHttpTransportOptions().getReadiness;
const { attachGatewayWsConnectionHandler: me } = await h.measure("gateway.ws-imports", () => import("./ws-connection-hvra8GXF.mjs"));
if (b) await startWorkerHumanPresence({
clients: v,
service: b,
log: i,
registerSidecar: Z
});
await h.measure("gateway.ws-attach", () => me({
wss: t.wss,
clients: v,
connectionWork: t.connectionWork,
bootId: e.bootId,
preauthConnectionBudget: t.preauthConnectionBudget,
port: n,
gatewayHost: j ?? void 0,
pluginSurfaceScheme: A.enabled ? "https" : "http",
getPluginNodeCapabilities: ue,
getResolvedAuth: M,
getRequiredSharedGatewaySessionGeneration: y.reader,
rateLimiter: N,
browserRateLimiter: P,
nodeReapprovalCoordinator: F,
isConnectPending: () => !D.dispatchReady,
startupMethodsReady: m.startupMethodsReady,
isStartupPending: t.isGatewayStartupPending,
isPendingWorkerNodeSetup: b?.hasPendingNodeEnrollmentSetup,
admitsNodeSetupCompletion: b?.admitsNodeSetupCompletion,
gatewayMethods: p.gatewayMethods,
events: GATEWAY_EVENTS,
logGateway: i,
logHealth: a,
logWsControl: o,
extraHandlers: t.attachedGatewayExtraHandlers,
getMethodRegistry: () => t.getAttachedGatewayMethodRegistry(),
...b ? { workerConnectionService: b } : {},
broadcast: g,
refreshHealthSnapshot: le.refreshHealthSnapshot,
buildRequestContext: () => le
}));
await h.measure("http.listen", () => t.startListening());
h.mark("http.bound");
const he = t.ensureRequestRuntimeReady().then(() => {
flushDiagnosticsTimeline();
m.setDispatchReady(true);
if (de && !r.updateCanary && !E.closePreludeStarted) activateGatewayAgentDatabaseStartup({
admission: de,
preparationReady: fe.promise,
waitForPostReadyWork: e.waitForPostReadyWork,
getConfig: readRuntimeConfig,
getPluginRegistry: () => O.registry,
getPluginMetadataSnapshot: $,
isCurrent: () => !E.closePreludeStarted,
log: i
});
});
const ge = t.startEarlyRuntime();
await Promise.allSettled([he, ge]);
await he;
const _e = await ge;
const ve = Date.now();
let ye = false;
let be = false;
const activateScheduledServicesWhenReady = () => {
if (r.updateCanary || E.closePreludeStarted || !ye || !D.sidecarsReady || be) return;
be = true;
import("./server-runtime-services-CxjHyClJ.mjs").then((e) => {
if (E.closePreludeStarted) return;
const n = e.activateGatewayScheduledServices({
scheduler: t.scheduler,
minimalTestGateway: d,
cfgAtStart: K,
deps: f,
sessionDeliveryRecoveryMaxEnqueuedAt: ve,
log: i,
resolveGatewayContext: k
});
m.setScheduledServiceHandles(n);
});
};
const { startGatewayActiveWork: xe } = await h.measure("gateway.active-work-import", () => import("./server-work-metrics-GDMti_QP.mjs"));
const Se = xe(t, i);
const trackStartupWork = (e) => {
const n = Promise.resolve().then(() => e(t.connectionWork.signal));
return t.connectionWork.track(() => n);
};
const Ce = await trackStartupWork(() => h.measure("runtime.post-attach", () => import("./server-startup-post-attach-CVeTLlkq.mjs").then(({ startGatewayPostAttachRuntime: a }) => a({
scheduler: t.scheduler,
minimalTestGateway: d,
updateCanary: r.updateCanary,
cfgAtStart: K,
getConfig: readRuntimeConfig,
port: n,
log: i,
isNixMode,
startupStartedAt: r.startupStartedAt,
broadcastToConnIds: _,
broadcast: g,
getClientConnIds: le.getClientConnIds,
broadcastPluginEvent: U,
controlUiRootLifecycle: W,
gatewayPluginConfigAtStart: I,
activationSourceConfig: L,
pluginManifestRecords: z,
...B ? { pluginMetadataSnapshot: B } : {},
getCurrentPluginRegistry: () => O.registry,
shouldStartPluginServices: () => m.pluginRuntimeGeneration.currentServices() === null && m.pluginRuntimeGeneration.getReloadStatus() === void 0,
ambientEnvTriggers: V,
pluginRegistry: O.registry,
defaultWorkspaceDir: R,
deps: f,
startChannels: H,
resolveGatewayContext: le.resolveGatewayContext,
logHooks: s,
logChannels: c,
unlockStartupMethods: m.unlockStartupMethods,
refreshChatMetadata: ce.refresh,
loadStartupPlugins: async () => {
const { loadGatewayStartupPluginRuntime: e } = await import("./server-startup-plugins-CpDU2lcS.mjs");
return e({
cfg: I,
signal: t.connectionWork.signal,
activationSourceConfig: L,
workspaceDir: t.pluginWorkspaceDir,
log: i,
baseMethods: t.baseMethods,
coreGatewayMethodNames: t.coreGatewayMethodNames,
hostServices: t.pluginHostServices,
startupPluginIds: t.startupPluginIds,
pluginLookUpTable: t.pluginLookUpTable,
startupTrace: h,
ambientEnvTriggers: V,
resolveGatewayContext: k
});
},
onStartupPluginsLoading: () => {
D.pendingReason = "startup-sidecars";
},
onStartupPluginsLoaded: async (e) => {
const n = [];
const r = await t.prepareAttachedPluginRuntime(e, (e) => n.push(e));
try {
if (E.closePreludeStarted) return false;
r.publish();
D.pendingReason = "startup-sidecars";
r.afterCommit();
const n = indexPluginNodeCapabilitySurfaces(ue());
for (const e of v) reconcileClientPluginNodeCapabilities(e, n);
await t.refreshAttachedGatewayDiscovery(e.pluginRegistry);
return true;
} finally {
await Promise.allSettled(n);
}
},
getCronService: m.getCronService,
onChannelsStarted: q,
onPluginServices: (e) => m.pluginRuntimeGeneration.setServices(e),
onPostReadySidecars: oe,
onGatewayLifetimeSidecars: Z,
trackStartupWork,
unregisterConnectionDependentSidecar: se,
startWorkerEnvironmentRuntime: async () => {
if (E.closePreludeStarted) return null;
fe.resolve();
return x ? await x.startRuntime({
startupTrace: h,
isClosePreludeStarted: () => E.closePreludeStarted,
registerSidecar: Q,
unregisterSidecar: se
}) : null;
},
onSidecarsReady: () => {
m.markSidecarsReady();
activateScheduledServicesWhenReady();
},
getReadiness: pe,
isClosing: () => E.closePreludeStarted,
startupTrace: h,
sidecarStartup: G,
waitForPostReadyWork: e.waitForPostReadyWork,
activeWorkInspectors: Se
}))));
m.setPostAttachHandles(Ce);
if (d) fe.resolve();
h.detail("memory.ready", [...collectGatewayProcessMemoryUsageMb(), ...d ? [] : await h.measure("runtime.worker-pool-metrics", collectGatewayWorkerPoolMetrics)]);
const we = await pe.prepare();
if (!E.closePreludeStarted && we.publish().ready) {
h.mark("ready");
if (G === "defer") i.info("gateway ready");
}
finishGatewayRestartTrace("restart.ready", collectGatewayProcessMemoryUsageMb());
if (r.updateCanary) return { startupSettled: Ce.startupSettled };
ye = true;
activateScheduledServicesWhenReady();
const { startManagedGatewayConfigReloader: Te } = await import("./server-reload-managed-BeuafUwk.mjs");
const assertRuntimeSecurityConfig = (e, i) => {
assertGatewayRuntimeSecurityConfig({
cfg: e,
port: n,
bindHost: j,
controlUiEnabled: r.controlUiEnabled ?? e.gateway?.controlUi?.enabled ?? true,
tailscaleMode: t.tailscaleMode,
resolvedAuth: resolveGatewayAuth({
authConfig: e.gateway?.auth,
tailscaleMode: t.tailscaleMode,
env: i
})
});
};
const Ee = startGatewayTlsRenewal({
scheduler: t.scheduler,
runtime: A,
servers: t.httpServers,
enabled: K.gateway?.reload?.mode !== "off",
onRenewed: async () => p.discovery?.update({ gatewayTlsFingerprintSha256: A.fingerprintSha256 }),
log: i.child("tls")
});
if (Ee) Z(Ee);
let De = isCustomPluginUiEnabled(I);
const Oe = {
scheduler: t.scheduler,
onReloadEnabledChange: Ee?.setEnabled,
configRevisionProjector: le.configRevisionProjector,
resolveGatewayContext: k,
minimalTestGateway: d,
initialConfig: readRuntimeConfig(),
initialPluginInstallRecords: B?.index.installRecords,
initialCompareConfig: X.sourceConfig,
initialSnapshotRawHash: X.exists ? hashConfigRaw(X.raw) : null,
initialAuthoredConfig: X.parsed,
initialIncludedPaths: X.includedPaths ?? [],
initialSnapshotValid: X.valid,
initialSnapshotIssues: X.issues,
watchPath: X.path,
readSnapshot: readConfigFileSnapshotForRuntimeTransaction,
promoteSnapshot: promoteConfigSnapshotToLastKnownGood,
subscribeToWrites: (e) => registerConfigWriteListener(e, {
ownsRuntimeActivationFor: X.path,
preCommitRuntimePreflight: async (e, t) => {
const n = await ee({
runtimeConfig: e,
sourceConfig: e
});
const r = await ne(n.runtimeConfig, {
reason: "reload",
activate: false,
env: n.runtimeEnv.env,
includeAuthStoreRefs: t?.includeAuthStoreRefs
});
const i = readRuntimeConfig();
const a = buildGatewayReloadPlan(diffGatewayReloadPaths(getRuntimeConfigSourceSnapshot() ?? X.sourceConfig, e, listConfigReloadRefinementPrefixes()), {
previousConfig: i,
candidateConfig: r.config
});
if (t?.requireImmediateApplication) {
if (r.config.gateway?.reload?.mode === "off") throw new Error("The saved sign-in is inactive because Gateway reload is disabled. Enable config reload and restart the Gateway before retrying it.");
if (a.restartGateway || a.reloadPlugins) throw new Error(a.reloadPlugins ? "Update or enable the selected provider plugin in Plugins, then retry this saved sign-in. Your current connection is unchanged." : "Apply the required Gateway settings update separately, then retry this saved sign-in. Your current connection is unchanged.");
}
if (!a.restartGateway) assertRuntimeSecurityConfig(r.config, n.runtimeEnv.env);
return n;
}
}),
deps: f,
broadcast: g,
getState: m.getReloadState,
setState: (e) => {
m.setReloadHookState(e);
if (m.swapCronState(e.cronState) !== e.cronState) Y.handled = true;
},
getPluginMetadataSnapshot: $,
getPluginRegistry: () => t.pluginRuntime.registry,
startChannel: w,
stopChannel: T,
getChannelAutostartSuppression: te.getAutostartSuppression,
stopPostReadySidecars: ae,
reloadPlugins: m.reloadPlugins,
reloadPluginServices: async (e, t) => {
const n = p.pluginServices;
if (!n) throw new Error("Plugin services are not attached");
await n.reload(e, t);
},
logHooks: s,
logChannels: c,
logCron: l,
logReload: u,
cronReconciliation: J,
onCronRestart: () => {
Y.handled = true;
},
prepareTerminalConfig: (e, t) => {
S.prepareConfig(t, { restartPending: e.restartGateway });
},
reconcileRuntimePolicy: async (e, n) => {
C.closeDisallowedAgents((e) => S.resolve(e).ok);
if (n !== "committed") return;
C.updateDetachGraceMs((e.gateway?.terminal?.detachedSessionTimeoutSeconds ?? 300) * 1e3);
disconnectDisallowedGatewayPolicyClients(v.authorityClients, e);
for (const n of t.nodeRegistry.refreshRuntimePolicy(e)) refreshConnectedNodeSurfaceCaches({
context: le,
nodeSession: n
});
const r = (await Promise.allSettled([
t.hostDesktopService.reconcileRuntimePolicy(),
t.gatewayComputerService.reconcileRuntimePolicy(),
b?.reconcileDesktopPolicy(),
t.nodeDesktopService.reconcileRuntimePolicy(),
p.discovery?.update({ mdnsMode: e.discovery?.mdns?.mode }),
(async () => {
const t = isCustomPluginUiEnabled(e);
if (t !== De) {
const { listControlUiPluginCatalog: e } = await import("./control-ui-plugin-assets-ZUxE2s-C.mjs");
const n = await e();
g("plugins.controlUi.changed", { revision: n.revision });
De = t;
}
})()
])).find((e) => e.status === "rejected");
if (r) throw r.reason;
},
commitRuntimePolicy: (e) => {
W.setEnabled(r.controlUiEnabled ?? e.gateway?.controlUi?.enabled ?? true);
t.configureDiagnostics(e);
p.reconcileAuditPolicy?.(e);
const n = e.gateway?.auth?.rateLimit;
N.updateConfig(n);
P.updateConfig({
...n,
exemptLoopback: false
});
F.updateConfig(n);
S.commitConfig();
b?.schedulePreparedRefill();
},
acceptTerminalConfig: S.acceptConfig,
channelManager: te,
activateRuntimeSecrets: ne,
assertRuntimeSecurityConfig,
prepareConfigCandidate: ee,
applyRuntimeConfigOverrides: re,
resolveSharedGatewaySessionGenerationForConfig: ie,
sharedGatewaySessionGenerationState: y,
clients: v,
...r.hotReloadRecovery ? { requestRecoveryRestart: r.hotReloadRecovery } : {},
restartRecoveryAvailable: r.hotReloadRecovery !== void 0
};
if (E.closePreludeStarted) return { startupSettled: Ce.startupSettled };
const ke = Te(Oe);
m.setConfigReloaderHandle(ke);
await ke.ready;
if (E.closePreludeStarted) return { startupSettled: Ce.startupSettled };
await promoteConfigSnapshotToLastKnownGood(X).catch((e) => {
i.warn(`gateway: failed to promote config last-known-good backup: ${String(e)}`);
});
if (!d) {
const n = await import("./server-runtime-services-CxjHyClJ.mjs");
n.scheduleGatewayPostReadyMaintenance({
scheduler: t.scheduler,
signal: t.connectionWork.signal,
delayMs: POST_READY_MAINTENANCE_DELAY_MS,
isClosing: () => E.closePreludeStarted,
waitForPostReadyWork: e.waitForPostReadyWork,
startupMaintenance: t,
startMaintenance: () => _e.startMaintenance(Se, k),
applyMaintenance: async (e) => {
if (E.closePreludeStarted) {
await clearGatewayMaintenanceHandles(e);
return;
}
m.setMaintenanceHandles(e);
e.startMediaCleanup();
},
shouldStartCron: () => !E.closePreludeStarted && !Y.handled,
markCronStartHandled: () => {
Y.handled = true;
},
cronState: p.cronState,
cronReconciliation: J,
cronConfig: K,
logCron: l,
log: i,
recordPostReadyMemory: () => {
h.detail("memory.post-ready", collectGatewayProcessMemoryUsageMb());
}
});
const r = [...Object.values(B?.index.installRecords ?? {}).flatMap((e) => e.installPath ? [e.installPath] : []), ...B?.plugins.flatMap((e) => e.setupSource ? [
e.rootDir,
e.source,
e.setupSource
] : [e.rootDir, e.source]) ?? []];
Z(n.scheduleGatewayIdleTask({
id: "maintenance:retained-plugin-generations",
scheduler: t.scheduler,
delayMs: RETAINED_PLUGIN_CLEANUP_DELAY_MS,
retryDelayMs: RETAINED_PLUGIN_CLEANUP_DELAY_MS,
repeatDelayMs: 36e5,
isClosing: () => E.closePreludeStarted,
isBusy: () => getActiveGatewayRootWorkCount({ excludeCurrent: true }) > 0,
run: async () => {
await e.waitForPostReadyWork();
const { cleanupGatewayRetiredPluginArtifacts: n } = await import("./server-retained-plugin-cleanup-B6CrEQDW.mjs");
await n({
log: i,
startupInstallPaths: r,
startupConfig: K,
signal: t.connectionWork.signal,
assertCurrent: () => {
if (E.closePreludeStarted) throw t.connectionWork.signal.reason ?? /* @__PURE__ */ new Error("Gateway is closing");
}
});
},
log: i,
errorMessage: "retained npm generation cleanup failed"
}));
Z(n.scheduleGatewayIdleTask({
id: "maintenance:sqlite-snapshots",
scheduler: t.scheduler,
delayMs: RETAINED_PLUGIN_CLEANUP_DELAY_MS,
retryDelayMs: RETAINED_PLUGIN_CLEANUP_DELAY_MS,
isClosing: () => E.closePreludeStarted,
isBusy: () => getActiveGatewayRootWorkCount({ excludeCurrent: true }) > 0,
repeatDelayMs: 9e5,
run: async () => {
const { reclaimAbandonedSqliteSnapshotsAsync: e } = await import("./sqlite-snapshot-reclamation-Cv7-gXpg.mjs");
await e();
},
log: i,
errorMessage: "SQLite snapshot staging cleanup failed"
}));
} else h.detail("memory.post-ready", collectGatewayProcessMemoryUsageMb());
return { startupSettled: Ce.startupSettled };
}
//#endregion
//#region src/gateway/server-start.ts
const { log, logTailscale, logChannels, logHealth, logCron, logReload, logHooks, logWsControl } = gatewayKernelLogs;
const POST_READY_WORK_START_DELAY_MS = 500;
async function startGatewayServerCore(e = 18789, t = {}) {
await installGatewayDatabaseEngine(t.startupConfigSnapshotRead?.snapshot, t.startupConfigSnapshotRead?.databaseEngineSelection);
const n = new LegacyPluginSdkResourceHost();
const start = (r) => runOutsideAsyncWorkScope(() => startGatewayServerWithSdkHost(e, t, n, r));
return await n.run(() => t.startupOperation ? t.startupOperation(start) : start());
}
async function startGatewayServerWithSdkHost(e, t, n, r) {
const { promise: i, resolve: a } = createDeferredCore();
const o = await createGatewayKernel(e, t, {
deferEarlyRuntime: true,
deferRequestRuntime: true,
sdkResourceHost: n
});
bumpSkillsSnapshotVersion({ reason: "manual" });
if (!o.minimalTestGateway) beginMacOSSystemCaWarmupOnce({ log });
let s;
let c;
let stopStartingTailscale;
const { closeOnStartupFailure: l, prepareClose: u, terminalSessions: d, shutdownRuntime: f } = o;
try {
const n = await createGatewayHttpTransport({
...o.createHttpTransportOptions(),
httpRequestLifetime: o.gatewayRequestContext,
waitForRequestRuntime: o.ensureRequestRuntimeReady,
updateCanary: t.updateCanary,
onListening: t.gatewayStateOwner?.markListening,
deferHookWake: async (e) => {
const t = o.kernel.getReloadState().cronState;
const n = t.deferHookWake;
if (!n) throw new Error("Scheduled Hook wake admission is unavailable; restart the Gateway");
const commitGuard = () => {
e.commitGuard();
if (o.lifecycle.closePreludeStarted || o.kernel.getReloadState().cronState !== t) throw new Error("Scheduled Hook wake owner changed; retry the request");
};
commitGuard();
return await n({
...e,
commitGuard
});
},
...!o.minimalTestGateway && o.tailscaleMode !== "off" ? { prepareManagedTailscaleIngress: async (t) => {
const { startGatewayTailscaleExposure: n } = await import("./server-tailscale-B0Ej1YLD.mjs");
const i = await n({
tailscaleMode: o.tailscaleMode,
preserveFunnel: o.tailscaleConfig.preserveFunnel ?? false,
port: e,
backend: t,
controlUiBasePath: o.controlUiBasePath,
logTailscale,
signal: r
});
o.kernel.setTailscaleCleanup(i);
stopStartingTailscale = () => {
c ??= i?.();
c?.catch(() => {});
};
r?.addEventListener("abort", stopStartingTailscale, { once: true });
if (r?.aborted) {
stopStartingTailscale();
r.throwIfAborted();
}
} } : {}
});
o.transportBridge.attach(n);
s = (await finishGatewayStartup({
kernelRuntime: {
...o,
...n
},
port: e,
opts: t,
bootId: o.bootId,
log,
logHealth,
logWsControl,
logHooks,
logChannels,
logCron,
logReload,
waitForPostReadyWork: () => i
})).startupSettled;
r?.throwIfAborted();
} catch (e) {
a();
return await rethrowGatewayStartupError(e, () => l(e));
} finally {
if (stopStartingTailscale) r?.removeEventListener("abort", stopStartingTailscale);
await c;
}
s.then(() => {
if (o.lifecycle.closePreludeStarted) return;
o.scheduler.schedule({
id: "startup:post-ready-work",
delayMs: POST_READY_WORK_START_DELAY_MS,
run: a
});
}, () => {});
let p;
return {
startupSettled: s,
getTailscaleIngressEndpoint: o.transportBridge.getTailscaleIngressEndpoint,
close: (t) => {
if (!p) p = o.runClose(async () => {
const n = u(t);
a();
await runGatewayCloseSteps({
owner: o,
exitAfterClose: t?.exitAfterClose,
close: await n,
disposeTerminalSessions: () => d.disposeAll(),
runStopHooks: async () => {
await f.runGlobalGatewayStopSafely({
registry: o.pluginRuntime.registry,
event: { reason: t?.reason ?? "gateway stopping" },
ctx: { port: e },
onError: (e) => log.warn(`gateway_stop hook failed: ${formatErrorMessage$1(e)}`)
});
},
onError: (e) => log.error(e)
});
}).catch((e) => {
if (hasRetainedPluginRuntimeCloseError(e)) p = void 0;
throw e;
});
return p;
}
};
}
//#endregion
export { startGatewayServerCore };