UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

171 lines • 321 kB
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{D as parseStrictPositiveInteger,y as isFutureDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import{n as isTruthyEnvValue,s as isVitestRuntimeEnv}from"./env-fLMEolk5.mjs";import{n as BROWSER_PAIR_ROUTE_PREFIX}from"./browser-pair-CVYTNOrU.mjs";import"./src-0ci69Prg.mjs";import{a as extractErrorCode,d as readErrorName,s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings,d as normalizeSortedUniqueTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{n as sliceUtf16Safe,r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{a as getTrackedWorkerCpuSources}from"./worker-cpu-Cmr50ooq.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{r as runWithMainThreadTask,t as createMainThreadStallMonitor}from"./main-thread-stall-CJLZRvCI.mjs";import{o as measureGatewayBootstrapStep}from"./startup-trace-CnJbL2Y9.mjs";import{c as isSecretRef}from"./ref-contract-CdpCUlb6.mjs";import"./types.secrets-UWdyCdE6.mjs";import{i as copyConfigResolutionFacts}from"./resolution-facts-DYKtoyes.mjs";import{n as materializeErrorStack}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{c as runOutsideAsyncWorkScope,o as getAsyncWorkSignal,t as AsyncWorkScope}from"./async-work-scope-DBcxYU4O.mjs";import{u as getPluginMetadataSnapshotCache}from"./plugin-cache-B6QVpzXr.mjs";import{a as pluginInstanceInvocation}from"./plugin-instance-invocation-na_CYyUz.mjs";import{r as resolveOpenClawPackageRootSync}from"./openclaw-root-DP80HYD2.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as resolveConfigDir}from"./config-dir-DaqnOvHp.mjs";import{n as ok,t as err}from"./result-CkiK_t2O.mjs";import{t as pruneMapToMaxSize}from"./map-size-DLQqorvK.mjs";import{S as resolveIsConfigReadOnly,c as isNamedProfile,l as isNixMode,m as resolveConfigPath,u as normalizeStateDirEnv}from"./paths-D_FOvGon.mjs";import{o as registerSecretValueForRedaction}from"./secret-redaction-registry-DospXE4m.mjs";import{t as formatErrorMessage$1}from"./errors-D37BJTfI.mjs";import{t as createLegacyPluginSdkReplyDispatch}from"./legacy-sdk-reply-dispatch-BBfp03px.mjs";import{r as createLazyPromiseLoader}from"./lazy-promise-CismJCQR.mjs";import{i as createLazyRuntimeNamedExport,n as createLazyRuntimeMethodBinder,r as createLazyRuntimeModule}from"./lazy-runtime-Ds6M7vp4.mjs";import{d as withPluginRuntimeRegistryScope,f as bindGatewayContextResolver,g as getGatewayContextLifetime}from"./gateway-request-scope-7deHmsb_.mjs";import{i as hasRetainedPluginRuntimeCloseError}from"./runtime-close-error-Ct99vNsO.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{t as isControlUiFocusPath}from"./focus-icmPO6hc.mjs";import{L as buildControlUiSessionPath,N as parseAgentSessionKey}from"./session-key-BPgKfU2m.mjs";import{t as resolveIncognitoSessionExpiresAt}from"./incognito-session-key-C3kQAqyd.mjs";import{n as bindLegacyPluginSdkResourceHost,t as LegacyPluginSdkResourceHost}from"./legacy-sdk-resource-host-9HMZFK01.mjs";import{n as notifyListeners,r as registerListener}from"./listeners-awzYn4LE.mjs";import{t as bumpSkillsSnapshotVersion}from"./refresh-state-DQEO5OFV.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{c as resolveIncognitoOpenClawAgentSqlitePath,o as isSameOpenClawAgentDatabasePath}from"./openclaw-agent-db.paths-SkzMsgQ0.mjs";import{a as resolveAgentDir}from"./agent-scope-config-CG9CFpGX.mjs";import{n as runtimeProcessEntrypoints}from"./runtime-process-entrypoints-Dnd1WskT.mjs";import{a as resolveRuntimeWorkerUrl,i as resolveRuntimeWorkerThreadExecArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{l as selectCurrentPluginMetadataCache,n as registerPluginMetadataProcessMemoLifecycleClear,o as getGatewayPluginMetadataSnapshot,r as retainGatewayPluginMetadata}from"./plugin-metadata-lifecycle-Bdt91XXL.mjs";import{I as hasInternalDiagnosticEventInterest,o as emitInternalDiagnosticEvent,p as isDiagnosticsEnabled,t as areDiagnosticsEnabledForProcess,y as setDiagnosticsEnabledForProcess,z as onInternalDiagnosticEventInterest}from"./diagnostic-events-BYBrlAdF.mjs";import{D as runWithDiagnosticTraceContext,_ as createDiagnosticTraceContext,i as flushDiagnosticsTimeline}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as applyLoggingConfig}from"./logger-bB_ZfEX5.mjs";import{n as runtimeForLogger,t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as deferSqlitePostCommitPublication}from"./sqlite-post-commit-CAVf6ZAG.mjs";import{o as resolveRuntimeServiceBuildId,u as resolveRuntimeServiceVersion}from"./version-DrZ9Nfde.mjs";import{t as isContainerEnvironment}from"./container-environment-C0Hd9WfF.mjs";import{r as resolveDatabasePath,s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{a as withArtifactPreservingStateReads,o as withLiveStateReads}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{n as captureSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-context-BjXXEC4m.mjs";import{_ as withSqliteReadOnlyWorkerScope}from"./sqlite-readonly-worker-C1mJaAX6.mjs";import{n as getSpawnBroker,r as runWithSpawnBroker}from"./context-state-CSLm35p3.mjs";import"./context-B64RxSW7.mjs";import{a as getRecordedChildRuntimeViability,c as prepareChildRuntimeViability}from"./child-runtime-viability-1cqYEa1U.mjs";import{d as ModelAccountConnectAuthorityError,f as ModelAccountConnectInputError}from"./openclaw-state-worker-error-Ca5E4dEV.mjs";import{r as createSqliteWorkerOperationAdmission}from"./sqlite-worker-operation-admission-BZvXBQev.mjs";import{S as registerOpenClawStateDatabaseLifecycleListener,h as openClawStateDatabaseCache,x as registerOpenClawStateDatabaseAsyncResource}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{n as runWithProcessCleanupBudget,t as getProcessCleanupBudget}from"./cleanup-budget-CjwqRUhX.mjs";import{c as initializePublishedConfigRuntimeEnv,i as collectConfigRuntimeEnvOwnership,l as prepareConfigRuntimeEnv}from"./config-env-vars-DCDGIBtT.mjs";import{n as withGatewayServiceInstallation,t as getGatewayServiceInstallation}from"./gateway-service-installation-context-GcjP_Bvh.mjs";import{t as GatewayScheduler}from"./gateway-scheduler-C24cnvAu.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{c as setGatewayPluginMetadataSnapshot}from"./current-plugin-metadata-snapshot-CYi8VAby.mjs";import{i as runOpenClawStateWorkerOperation}from"./openclaw-state-worker-store-7se2aIrr.mjs";import{i as hashConfigRaw}from"./io.read-helpers-B0XuPBY2.mjs";import{m as assertOpenClawStateWriteAllowedAtPath}from"./openclaw-state-db-BlgxYkYw.mjs";import{a as sessionChangeScopeAffectsStoredRows,o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{E as setAppliedRuntimeConfigSnapshot,a as getRuntimeConfigSnapshot,c as getRuntimeConfigSourceSnapshot,h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{a as hasGatewayClientCap,l as normalizeGatewayClientName,n as GATEWAY_CLIENT_IDS,t as GATEWAY_CLIENT_CAPS}from"./client-info-Dr3-kuD1.mjs";import{t as isUserModelAuthProfileId}from"./user-model-account-id-CU4k7NMV.mjs";import{c as onUserProfilesChanged,g as readUserProfileVersion,r as captureUserProfileModelAccountLinksAuthority}from"./user-profile-events-CkQlfQnE.mjs";import{p as resolvePluginMetadataSnapshot}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{n as captureConfigOverrideApplier}from"./runtime-overrides-C2xuSpIx.mjs";import{n as isOpenClawIdEnabled}from"./openclaw-id-policy-CE_0QXmB.mjs";import{n as openClawIdAccessWarning}from"./access-plugin-C41HMCfK.mjs";import{i as getPluginInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import{t as GatewayOperatorAccessUnavailableError}from"./operator-authority-error-B9EU9j0W.mjs";import{A as pluginHttpRouteChanges,a as createPluginRegistryOwner}from"./runtime-Cl6PvJHC.mjs";import{o as listLoadedChannelPluginsForRegistry}from"./registry-loaded-BEn6LBRM.mjs";import{a as QUESTIONS_SCOPE,c as SESSION_WRITE_SCOPE,d as WRITE_SCOPE,i as PAIRING_SCOPE,l as TALK_SCOPE,n as APPROVALS_SCOPE,o as READ_SCOPE,s as SESSION_READ_SCOPE,t as ADMIN_SCOPE}from"./operator-scopes-bEvB7E5X.mjs";import{o as prepareRemoteModelCatalogStartupSnapshot}from"./remote-overlay-BQPwRXZH.mjs";import{t as KeyedAsyncQueue}from"./keyed-async-queue-qBcorzrt.mjs";import{t as createConfigIO}from"./io.factory-y6nIrp_4.mjs";import{t as logConfigWarningsOnce}from"./io.warnings-Dshur5lA.mjs";import{n as assertGatewayConfigEnvSelectionUnchanged}from"./gateway-env-selection-DK2Gpi3i.mjs";import{c as readConfigFileSnapshotForRuntimeTransaction,i as promoteConfigSnapshotToLastKnownGood,u as readConfigFileSnapshotWithPluginMetadata,y as registerConfigWriteListener}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{t as installGatewayDatabaseEngine}from"./server-database-engine-yPBqNAGb.mjs";import{i as closePreparedModelRuntimeSnapshots}from"./prepared-model-runtime.lifecycle--BWG5_Dq.mjs";import{a as prepareGatewayAgentCliShim,t as clearGatewayAgentCliShim}from"./openclaw-cli-shim-Dy3eN8cI.mjs";import{t as ensureOpenClawCliOnPath}from"./path-env-CQquKbU7.mjs";import{I as getActiveGatewayRootWorkCount,d as isGatewayRestartDraining,i as beginGatewayShutdownCleanup,l as getGatewaySuspendAdmissionPhase,p as isGatewayWorkAdmissionClosed,w as runWithGatewayIndependentRootWorkAdmission}from"./gateway-work-admission-CnMW3_qr.mjs";import{i as canIsolateAgentDatabase,y as listAgentDatabaseAdmissionRefusals}from"./agent-database-admission-DiJx9iIl.mjs";import{i as onInternalSessionTranscriptUpdate}from"./transcript-events-DDI7aMLK.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{t as resolveSharedMainAuthAgentDir}from"./shared-main-dir-CnBJA5xX.mjs";import{a as getActiveSecretsRuntimeConfigSnapshot,i as clearSecretsRuntimeSnapshotState}from"./runtime-state-lO6JkIdi.mjs";import{t as assertionSucceeds}from"./assertion-BDJqrEL5.mjs";import{n as getAgentDatabaseStartupAdmission,t as AgentDatabaseStartupSupersededError}from"./agent-database-startup-B70N6vNa.mjs";import{t as isCoreCanvasHostEnabled}from"./config-Cz6TtEO6.mjs";import{i as withCoreCanvasNodeCapability,n as isCanvasDocumentHttpPath,r as resolveCanvasNodeCapability}from"./constants--GNaxU9G.mjs";import{t as adoptPluginHttpRouteHandoffs}from"./http-registry-DZEFGoNA.mjs";import{t as extractAssistantPhaseText}from"./chat-message-content-BwODI7B3.mjs";import{t as createAgentRuntimeApprovalAuthorityValidator}from"./agent-runtime-approval-authority-cp7kvQ_b.mjs";import{d as revokeAttachGrantsForSession,t as GatewayConnectionWork}from"./server-connection-work-90yhik6H.mjs";import{n as operatorScopeSatisfied}from"./operator-scope-compat-TmgAKmD2.mjs";import{n as authorizeOperatorScopesForMethod}from"./method-scopes-Dalbwzsv.mjs";import{c as listCoreGatewayMethodNames,n as createCoreGatewayMethodDescriptors,r as isCoreGatewayMethodClassified,t as STARTUP_UNAVAILABLE_GATEWAY_METHODS}from"./core-method-policy-DeU1xgVA.mjs";import{n as createGatewayMethodRegistry,t as createGatewayMethodDescriptorsFromHandlers}from"./registry-Bzz0JtUN.mjs";import{_ as resolveGatewayListenHosts,a as isLoopbackAddress,d as isTrustedProxyAddress,r as isLocalDirectRequest,s as isLoopbackHost,y as resolveHostName}from"./net-Bu4cO5Pq.mjs";import{n as isBrowserOperatorUiClient}from"./message-channel-514k57tV.mjs";import{l as withSystemEventOwner}from"./system-event-ownership-CSF0k-1v.mjs";import{i as publishSystemEventStoreConfig}from"./session-store-path-Co-EGagp.mjs";import{n as onGatewayWorkMetricsChanged,t as notifyGatewayWorkMetricsChanged}from"./gateway-work-metrics-events-CCdVcPvz.mjs";import{h as isIrohEndpointKey}from"./validate-Btv7lFe1.mjs";import{_ as setOpenClawIdNodeDescriptionLookup,b as setOpenClawIdTunnelPrincipalResolver,o as notifyOpenClawIdTunnelPrincipalsChanged,r as isOpenClawIdTunnelPrincipalAdmitted,v as setOpenClawIdTunnelActivityRecorder,y as setOpenClawIdTunnelPrincipalLookup}from"./tunnel-principal-CmwEB_uz.mjs";import{t as createCronExecutionId}from"./run-id-CYBVQnKU.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{g as resolveOperatorRolePolicyForProfile,m as resolveOperatorRolePolicy,r as authorizeGatewaySessionCreation,x as readGatewayAccessRevision}from"./operator-role-policy-g-dxw0h4.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import{l as enqueueSystemEvent}from"./system-events-BXet8b2T.mjs";import"./operator-access-policy-lm0chPjw.mjs";import{c as resolveSystemMainSessionTarget}from"./main-session-C6FGqx0x.mjs";import{n as readSessionEntriesFromStoreInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{o as runWithSessionActorStorage}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import{t as flattenMarkdownToPlainText}from"./markdown-plain-text-VmGCJXBJ.mjs";import{g as stripInternalRuntimeContext}from"./internal-runtime-context-DervRrPi.mjs";import{t as beginSessionEffect}from"./session-controller.lifecycle-M3NLAkoz.mjs";import{r as onSessionIdentityMutation}from"./session-lifecycle-events-DfZH8odb.mjs";import{s as resolveConfiguredAgentDatabaseTargets,t as isConfiguredAgentDatabaseTarget}from"./targets-DZpbOEi4.mjs";import{a as tryLoadActivatedBundledPluginPublicSurfaceModule}from"./facade-runtime-DOjwP1Dh.mjs";import{u as sanitizeAssistantVisibleTextWithProfile}from"./assistant-visible-text-CrogYVOU.mjs";import{p as isTranscriptOnlyOpenClawAssistantMessage}from"./transcript-only-openclaw-assistant-mgMsWI54.mjs";import{b as updateSessionProfileInvolvementAsync}from"./session-accessor-CY8UYP4m.mjs";import{t as memorySessionActorOwners}from"./session-actor-memory-owner-yGnpeolI.mjs";import{a as decodeSandboxHostCsp,n as buildSandboxHostDocument,s as resolveSandboxHostPort,t as SANDBOX_HOST_PATH}from"./sandbox-host-BjACc9t5.mjs";import{t as warnSessionPersistenceDeprecation}from"./session-persistence-deprecation--5O4MOIT.mjs";import{o as resolveSessionEventAgentScope,r as resolveRequestedSessionAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{a as resolveSessionStoreIdentity}from"./session-store-key-DZXBwthg.mjs";import"./sessions-DQD7zQ95.mjs";import{o as upsertPresence,r as listSystemPresence,t as commitPresence}from"./system-presence-BtA5jBNR.mjs";import{i as GATEWAY_EVENT_NODE_RUNNER_INVENTORY_CHANGED,n as GATEWAY_EVENT_DEVICE_PAIR_CHANGED,o as GATEWAY_EVENT_UPDATE_RUN_CHANGED,r as GATEWAY_EVENT_ID_PEOPLE_CHANGED,t as GATEWAY_EVENTS}from"./events-Cmrg6oec.mjs";import{L as MAX_HUMAN_MENTIONS,R as MAX_MENTIONABLE_USERS,z as MENTION_INBOX_MAX_ITEMS}from"./logs-chat-CUeTJ2fB.mjs";import{t as GATEWAY_RESTART_UNAVAILABLE_REASON}from"./restart-unavailable-BX-3Xstf.mjs";import{t as authenticatedProfileUnavailableError}from"./gateway-client-identity-H5JO7081.mjs";import{n as getSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{b as resolveSessionVisibility,h as isSessionVisibilityAllowed,y as resolveSessionSharingTargetAsync}from"./session-sharing-policy-CQ0Zqotl.mjs";import{i as prepareTalkConnectionClose}from"./session-registry-B7s8l649.mjs";import{n as createProfileSessionEntryFilter,o as prepareProjectedSessionSharing,s as prepareSessionSharing,t as canReceiveSessionEvent}from"./session-sharing-read-Cm-EAfc6.mjs";import"./session-sharing-BmRcWi9h.mjs";import{n as prepareSessionSharingRead,t as isSameSessionSharingTarget}from"./session-sharing-target-read-CpQVyqky.mjs";import{a as incrementPresenceVersion,c as createPresenceRecipientProjection,i as getPresenceVersion,o as refreshGatewayHealthSnapshot,r as getHealthVersion}from"./health-state-CMzpZHKj.mjs";import{t as MAX_PREAUTH_PAYLOAD_BYTES}from"./payload-limits-DoYTH2mg.mjs";import{i as MAX_BUFFERED_BYTES}from"./server-constants-BmIepgnr.mjs";import{i as onGatewayPolicyClientInvalidated,r as invalidateGatewayPolicyClient}from"./ws-policy-close-piWBcH1L.mjs";import{c as normalizePluginNodeCapabilityScopedUrl,d as reconcileClientPluginNodeCapabilities,o as indexPluginNodeCapabilitySurfaces}from"./plugin-node-capability-C3FKPhfC.mjs";import{n as resolvePluginRoutePathContext,t as isProtectedPluginRoutePathFromContext}from"./path-context-KfiICw5_.mjs";import{t as findMatchingPluginHttpRoutes}from"./route-match-D1KlyYyY.mjs";import{n as listPluginNodeCapabilities,t as findMatchingPluginNodeCapabilityRoute}from"./route-capability-wb2ZeurL.mjs";import{t as SerializedGatewayFrame}from"./serialized-json-DvvcynCi.mjs";import{n as invalidateSharedReadResponses}from"./shared-read-responses-BqJMP9cX.mjs";import{t as resolveGrantExpiryDaysConfig}from"./standing-grant-expiry-config-DLLQoEhB.mjs";import{i as retireQuestionChannelGateway}from"./question-channel-runtime-D0rgm92e.mjs";import{i as closeGatewayDeviceRevocation}from"./device-revocation-CZLiYG03.mjs";import{t as shouldUseGatewayOwnerProfile}from"./gateway-owner-profile-CqplJoy-.mjs";import{a as resolveDiscoverableProviderOwnerPluginIds}from"./providers-CcG8xzp1.mjs";import{a as isPreparedModelRuntimePluginLifecycleFailure}from"./prepared-model-runtime-admission-errors-DZto8oll.mjs";import{d as runHttpConnectionRequest}from"./http-body-CsPV_uT5.mjs";import{r as getPluginRuntimeLoadContext}from"./load-context-BgV8IMWg.mjs";import{m as closeAuthProfileUsage}from"./store-CX8ovUiF.mjs";import{a as listUserModelAccounts,d as readUserModelAccountSummary,h as setUserProfileAuthLink,o as listUserProfileAuthLinks,s as listUserProfileAuthLinksAsync,t as clearUserProfileAuthLink}from"./user-model-accounts-IUTOAdBk.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-Dot5G-J1.mjs";import{n as mergeGatewayAuthConfig,r as resolveGatewayAuth}from"./auth-resolve-UwT9_UjV.mjs";import{t as resolveGatewayPublicOrigin}from"./gateway-public-origin-BbL1ndHu.mjs";import{a as resolveControlUiAllowedOrigins,n as ensureControlUiAllowedOriginsForNonLoopbackBind}from"./gateway-control-ui-origins-wkTBwi2O.mjs";import{a as getRemoteControlUiIngressContext,c as markGatewayIngressTransport,d as readPreparedGatewayIngressAttribution,i as createGatewayUnattributableProxyReporter,l as prepareGatewayIngressAttribution,n as PROXY_ATTRIBUTION_REQUIRED_REASON,r as assertRemoteControlUiIngressCurrent,s as hasGatewayProxyIdentityHeaders,t as PROXY_ATTRIBUTION_GUIDANCE,u as readGatewayIngressTransport}from"./ingress-attribution-Ct_hJMPU.mjs";import{i as setOpenClawIdClawOriginResolver,t as clawOriginOfRecord}from"./claw-origin-C0aOQKGI.mjs";import{i as hasGatewayDelegationClaim,r as disposeGatewayDelegationCredentials}from"./trusted-proxy-delegation-Cn2wiXdt.mjs";import{r as isGatewayAuthPolicyCurrent}from"./auth-policy-DPmo4h9a.mjs";import{t as deriveSessionTitle}from"./session-utils-core-DZPF_XHj.mjs";import{n as createGatewayChatMetadataLifecycle,t as broadcastChatMetadataChanged}from"./server-chat-metadata-lifecycle-CD7poacH.mjs";import{s as subscribeSecretStoreChanges}from"./secret-store-hidden-github-Bm9aelD7.mjs";import{i as purgeExpiredSecretStoreEntries,n as getSecretStoreExpiryDeadline}from"./secret-store-DkBLQ_7g.mjs";import{n as installActiveGitHubOAuthLifecycle,t as createGitHubOAuthLifecycle}from"./github-oauth-lifecycle-B_rexKVW.mjs";import{o as prepareWorktreeRunEndClose}from"./run-end-lifecycle-mk2iX8J8.mjs";import{n as startGitHubPublicationDiscovery}from"./github-publication-discovery-B08DPIdM.mjs";import{c as ensureAuthProfileStoreWithoutExternalProfilesAsync,s as ensureAuthProfileStoreWithoutExternalProfiles}from"./store-runtime-GNz-2GjY.mjs";import{i as resolveManifestProviderAuthChoices}from"./provider-auth-choices-Ca4qv7bL.mjs";import{t as runProviderPluginAuthMethodUnpersisted}from"./provider-auth-method-cNzE--nG.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-BWM-M-WW.mjs";import{n as sanitizeWizardStepForClient,t as WizardSession}from"./session-CN7tnCR5.mjs";import{r as queuePluginSessionsChanged}from"./gateway-events-CQ9u4w8V.mjs";import{s as controlUiPluginPolicyKey,u as controlUiPluginAssetRoot}from"./control-ui-plugin-tabs-DLV3mIzR.mjs";import{n as resolveControlUiWebPushUrl,t as normalizeControlUiBasePath}from"./control-ui-shared-Ch8iHnEl.mjs";import{a as parseControlUiUserAvatarPath,i as parseControlUiResourcePath,o as resolveAssistantMediaRoutePath}from"./control-ui-resource-routes-DrYH_3y1.mjs";import"./control-ui-contract-BJ8xy8WN.mjs";import{n as expectSessionAutomationSource}from"./session-automation-index-DOpU3gjw.mjs";import{t as resolveCurrentUserProfileDisplay}from"./current-user-profile-display-DM7faKkD.mjs";import{t as closeHttpServers}from"./http-server-lifecycle-R4ORonA7.mjs";import"./prepared-model-runtime.errors-CJIB8kC0.mjs";import{f as setGatewayRestartPolicy,p as setPreRestartDeferralCheck}from"./restart-B5SqvVCi.mjs";import{o as resolveAssistantAgentId}from"./assistant-avatar-DRKaA0CT.mjs";import{n as ConnectionSessionRows,t as prepareSessionEventProjection}from"./session-event-projection-5BIJTrbu.mjs";import{n as createVisibleActiveSessionRunProjector}from"./session-active-runs-BW6_s1BH.mjs";import{t as attachSessionChangeEventLifetime}from"./session-change-event-M_-ScXDH.mjs";import{n as readPreparedServerMethodModelCatalogs}from"./optional-model-catalog-DpWWaFJW.mjs";import{r as prepareSandboxRegistryClose}from"./registry-lifecycle-9GtuntEQ.mjs";import{r as fenceSessionSuspensionWritesForGatewayShutdown}from"./session-suspension-BVmAQtTx.mjs";import"./command-queue-fBrp5ERY.mjs";import{t as createGatewayActiveWorkSnapshot}from"./gateway-active-work-CdK8AANw.mjs";import{i as isGatewaySuspendControlAvailable,o as markGatewaySuspendExiting}from"./gateway-suspend-coordinator-WF7hqVpm.mjs";import{d as startGatewayDiagnosticHeartbeat,f as stopGatewayDiagnosticHeartbeat}from"./diagnostic-B89xdArk.mjs";import{i as roundDiagnosticMetric}from"./diagnostic-phase-D91Teuec.mjs";import{o as resolveCronJobsStorePathFromConfigAsync}from"./paths-BFxu7LPC.mjs";import{o as readDevicePairingNodeSnapshot}from"./device-pairing-store-readonly-BF1lFuan.mjs";import{c as removeRemoteNodeInfoForConnection,i as recordRemoteNodeInfo,s as removeRemoteNodeInfo}from"./remote-C-n5L_-0.mjs";import{f as requestNodePairing,p as reusePendingNodePairingForReconnect,r as finalizeNodePairingCleanupClaim}from"./device-pairing-node-CfTyktHs.mjs";import{t as createControlUiSessionPrRead}from"./control-ui-session-pr-read-C3wzjjYH.mjs";import{t as createControlUiSessionPullRequestSubscriptions}from"./control-ui-session-pr-subscriptions-6iDx4vIq.mjs";import{i as retireDeviceTokenClients,r as startNodeConnectionNotifications,t as projectHealthSummary}from"./presentation-9i6YmvuY.mjs";import{f as publishHooksTokenEnvKey}from"./hooks-Cy4qHxsj.mjs";import{h as waitForNodeWorkerSupervisor}from"./node-registry-private-SxRDxipR.mjs";import{i as clearNodeWakeState}from"./node-wake-state-CFYzfbEQ.mjs";import{f as resumeGatewayRestartTraceFromEnv,i as finishGatewayRestartTrace,n as collectGatewayProcessMemoryUsageMb,p as resumeGatewayRestartTraceFromHandoff,s as measureGatewayCloseStep}from"./restart-trace-BwVCyDSp.mjs";import{i as reconcileOrphanedMemoryDreamingJobs,n as applyGatewayLaneConcurrency,r as resolveGatewayLaneConcurrency,t as resolveHookClientIpConfig}from"./hook-client-ip-config-DejL4Zlg.mjs";import{r as waitForMediaCleanupDrains,t as MEDIA_CLEANUP_STOP_TIMEOUT_MS}from"./server-media-cleanup-lifecycle-Dxrgypb0.mjs";import{t as GatewayClientRequestError}from"./request-error-DCrb--_5.mjs";import{c as rethrowGatewayStartupError,l as runGatewayCloseSteps,s as resolveGatewayShutdownNotice}from"./server-shutdown-C-2ZDUBu.mjs";import{n as createGatewayReadyAnnouncer,t as beginMacOSSystemCaWarmupOnce}from"./system-ca-warmup-4Gv8tshV.mjs";import{n as recordClientPresenceActivity,t as buildClientPresence}from"./client-presence-fPGj28WB.mjs";import{r as registerGatewayModelCatalogPrivateAccess}from"./server-model-catalog-auth-DgYxoyva.mjs";import{t as createDefaultDeps}from"./deps-DA-Pf4pS.mjs";import{i as loadOrCreateProcessDeviceIdentityAsync}from"./device-identity-async-BkJXqwph.mjs";import{n as loadGatewayTlsServerRuntime}from"./gateway-BrwWynye.mjs";import{f as AUTH_RATE_LIMIT_SCOPE_WORKER_ADMISSION,h as createGatewayAuthRateLimiter,l as AUTH_RATE_LIMIT_SCOPE_NODE_REAPPROVAL,m as buildRateLimitIdentityKey}from"./auth-rate-limit-CJ17nIGS.mjs";import{r as authorizeHttpGatewayConnect}from"./auth-BwgQGI6W.mjs";import{r as createDesktopSessionRegistry}from"./session-registry-B3Crj2bR.mjs";import{c as setDeviceTokenBindingOwner,l as setDeviceTokenBindingsLoading}from"./device-token-binding-DqxswR4K.mjs";import{Q as SNAPSHOT_REPUBLISH_SECONDS}from"./src-BTTzpNjb.mjs";import{r as setOpenClawIdOwnerAccountResolver}from"./owner-account-CACyPlKi.mjs";import{_ as webPushAgentAllowed,f as isWebPushQuietHours,m as normalizeWebPushDisplayLabel,v as webPushCategoryEnabled}from"./push-web-store.records-CpwMfn9M.mjs";import{r as prepareWebPushNotificationSender,s as hasBoundWebPushSubscriptions}from"./push-web-B8uF21HK.mjs";import{a as webPushTargetClient,i as webPushSessionAccess,n as prepareWebPushAgentIcon,o as withCurrentWebPushAuthority,r as listCurrentWebPushTargets,t as currentWebPushAgentIcon}from"./web-push-avatar-DdEFvFaZ.mjs";import{a as readUserProfileDirectory}from"./user-profile-reads-BDQYAfao.mjs";import{r as resolveOperatorSessionCreation}from"./session-creation-provenance-DQXj4E5E.mjs";import{n as MENTION_RETENTION_MS,r as getMentionStoreHeadAdmission,t as MAX_MENTION_SOURCES}from"./mention-inbox-store-_qae8Kp8.mjs";import{n as logRejectedLargePayload}from"./diagnostic-payload-CBTOiWhC.mjs";import{r as preparePresenceDelivery,t as acceptsPresenceDeltas}from"./presence-delivery-COc21Ga8.mjs";import{t as isLiveTextAppend}from"./live-text-continuity-DEVbO3JK.mjs";import{t as closeGatewayTransportWithGrace}from"./connection-transport-close-BBdkIVgk.mjs";import{i as summarizeAgentEventForWsLog,r as logWs}from"./ws-log-DRCSDKLv.mjs";import{a as createSessionEventSubscriberRegistry,i as createChatRunState,o as createSessionMessageSubscriberRegistry}from"./server-chat-state-CvHqVUAH.mjs";import{t as createGatewayControlUiRootLifecycle}from"./server-control-ui-root-Ci3bJ5r7.mjs";import{t as SharedGatewaySessionGenerationState}from"./server-shared-auth-generation-By6Fk_Kv.mjs";import{t as isChannelStartupSuppressedByEnvironment}from"./server-sidecar-startup-mode-BKZ-CI0k.mjs";import{r as createWizardSessionTracker}from"./server-wizard-sessions-B4yJ1UMS.mjs";import{s as hasProfilerConflict}from"./diagnostic-profile-C4EYsS8Z.mjs";import{n as MAX_SAMPLES,r as formatStallProfile,t as MAX_PROFILE_BYTES}from"./diagnostic-stall-profile-DjaCxOem.mjs";import{n as DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,r as evaluateChannelHealth,t as DEFAULT_CHANNEL_CONNECT_GRACE_MS}from"./channel-health-policy-DxqVk75f.mjs";import{t as resolveSharedGatewaySessionGeneration}from"./ws-shared-generation-BJ1DAER5.mjs";import{n as isRestartEnabled}from"./commands.flags-BdxOktqL.mjs";import{r as readGatewayRestartHandoff}from"./restart-handoff-DPRsBMaK.mjs";import{n as resolveGatewayReloadPluginActivationCandidate,t as mergeActivationSectionsIntoRuntimeConfig}from"./plugin-activation-runtime-config-CVaezyxf.mjs";import{t as resolveGatewayStartupSourceConfig}from"./server-startup-secret-surfaces-Dyx83VAI.mjs";import{t as createGatewayStartupTrace}from"./server-startup-trace-bM0EFune.mjs";import{n as WebSocketServer}from"./websocket-0CTD22Gw.mjs";import{i as respondPlainText,r as respondNotFound}from"./control-ui-http-utils-M5A3tWWK.mjs";import{t as ARTIFACT_DOWNLOAD_PATH}from"./artifact-download-BzJIT0j4.mjs";import{d as retainArtifactDownloadStream,n as assertArtifactDownloadGrantCurrent,t as SESSION_FILE_PREVIEW_RESOURCE_PATH,u as resolveArtifactDownloadGrant}from"./artifact-download-grants-D28hFNXi.mjs";import{s as readTailscaleWhoisIdentity}from"./tailscale-ct7B4Rf-.mjs";import{t as rejectWebSocketUpgrade}from"./websocket-upgrade-reject-BQiimBdj.mjs";import{i as listenGatewayHttpServer,t as createGatewayPortalService}from"./portal-service-D3_nbQl6.mjs";import{t as bindGatewayControlUiIngressHost}from"./remote-control-ui-ingress-host-DSC7hpeU.mjs";import{r as NODE_PORTAL_ATTACH_PATH,t as NODE_DESKTOP_ATTACH_PATH}from"./node-desktop-stream-ldsAKscA.mjs";import{a as runWithGatewayHttpWorkAdmission,i as rejectGatewayUpgradeServiceUnavailable,r as shouldEnforceGatewayAuthForPluginPath,t as isPluginAuthenticatedRoutePath}from"./route-auth-HxuygSmj.mjs";import{i as markPublicWorkerIngress,t as GATEWAY_WS_CONNECTION_KIND_PROPERTY}from"./ws-types-b2-hi7jZ.mjs";import{n as parseDevicePairingJoinRequestPath}from"./join-code-D4rNoELt.mjs";import{r as markPluginHttpLegacyListener,t as getWebhookLegacyListener}from"./http-legacy-listener-CRLxpD4b.mjs";import{n as NODE_WORKER_BUNDLE_TRANSFER_PATH}from"./node-bundle-install-protocol-DsQ70tqL.mjs";import{t as parseControlUiUserBackgroundPath}from"./control-ui-user-background-route-Dnaasxs0.mjs";import{i as isControlUiPluginManagerRequest,n as isControlUiApprovalDocumentPath,r as isControlUiHttpRequest}from"./control-ui-routing-Da5orVDO.mjs";import{t as parseControlUiSessionPath}from"./parse-1lY3Sn7m.mjs";import{a as parseControlUiPublicSessionShareUrl,i as parseControlUiPublicSessionCardUrl,n as buildControlUiPublicSessionCardPath,r as buildControlUiPublicSessionSharePath}from"./public-share-NCPGMJDr.mjs";import{t as buildPublicSessionMediaBaseUrl}from"./control-ui-public-session-attachments-DyRHqlMl.mjs";import{t as isSecurePublicSessionIngress}from"./control-ui-public-session-ingress-C3MTUS7t.mjs";import{n as controlUiSessionEntryPath}from"./control-ui-session-entry-path-DptIgdbW.mjs";import{n as resolveControlUiShareOrigin,t as isControlUiSharePath}from"./control-ui-share-Q-oeBHhx.mjs";import{t as isTerminalConfigEnabled}from"./enabled-DLum2eQG.mjs";import{g as setDefaultSecurityHeaders,i as isWebSocketUpgradeRequest,l as sendGatewayAuthFailure,n as finishFailedGatewayHttpResponse,r as finishGatewayHttpDatabaseAdmissionError}from"./http-common-kI7-c_LU.mjs";import{a as finishGatewayHttpAuthorityError,o as runGatewayHttpRequest}from"./http-request-authority-BEm1hbys.mjs";import{a as handleProviderOAuthCallback,t as PROVIDER_OAUTH_CALLBACK_PATH}from"./provider-browser-auth-r1C9K1AJ.mjs";import{t as resolveRemoteControlUiHttpRoute}from"./remote-control-ui-http-routing-F_2-b47O.mjs";import{r as getGatewayRecentCrashes}from"./gateway-crash-DCoZGkY8.mjs";import{n as handleArtifactTransferHttpRequest}from"./artifact-transfer-http-B1BB1GOb.mjs";import{n as handleNodeWorkspaceTransferHttpRequest}from"./node-workspace-transfer-http-Dt1WdNdZ.mjs";import{t as GATEWAY_PER_MESSAGE_DEFLATE}from"./ws-compression-DDnYcEuy.mjs";import{r as listConfigReloadRefinementPrefixes,s as diffGatewayReloadPaths,t as buildGatewayReloadPlan}from"./config-reload-plan-BiVybSc3.mjs";import{n as resolveOpenClawIdClientPeerKey,t as resolveOpenClawIdClientChannel}from"./channel-B7lLTQhw.mjs";import{t as clearGatewayMaintenanceHandles}from"./server-maintenance-lifecycle-TiaFUSvL.mjs";import{n as refreshConnectedNodeSurfaceCaches}from"./nodes.read-lRFEEmoD.mjs";import{t as assertGatewayRuntimeSecurityConfig}from"./server-runtime-config-AeX7r7eZ.mjs";import{t as collectGatewayWorkerPoolMetrics}from"./process-vitals-CF2jdSpc.mjs";import{t as disconnectDisallowedGatewayPolicyClients}from"./ws-origin-policy-yqyGKSDH.mjs";import{n as DEFAULT_TERMINAL_DETACH_SECONDS}from"./session-limits-4tgQ7oTV.mjs";import{unwatchFile,watchFile}from"node:fs";import{versions}from"node:process";import{createHash,randomUUID}from"node:crypto";import{open,readFile as readFile$1}from"node:fs/promises";import{cpus}from"node:os";import{MessageChannel,Worker,isMainThread,receiveMessageOnPort}from"node:worker_threads";import*as v8$1 from"node:v8";import{AsyncLocalStorage}from"node:async_hooks";import{monitorEventLoopDelay,performance as performance$1}from"node:perf_hooks";import{getCallSites,isDeepStrictEqual}from"node:util";import{isProxy}from"node:util/types";import{setTimeout as setTimeout$1}from"node:timers/promises";import{createServer}from"node:http";import{TLSSocket}from"node:tls";import{url}from"node:inspector";import{Server,createServer as createServer$2}from"node:https";
//!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,openclawIdService:G,listStartupChannelGatewayMethods:K,workerEnvironmentStartup:q,activateRuntimeSecrets:J}=t;t.registerGatewayLifetimeSidecars({name:`computer-and-desktop-sessions`,preparePluginReload:W.preparePluginReload,stop:async()=>{await W.close();await U.stopAll()}});t.registerGatewayLifetimeSidecars({name:`openclaw-id`,stop:()=>G.stop()});const Y=f.secrets?.egressProxy?.enabled===true?await import(`./runtime-CtxGtp0G.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(Y)t.registerGatewayLifetimeSidecars({name:`secret-egress-proxy`,...Y});const sendNodeSessionEvent=(e,t,n,r)=>{E(e,t,n,r)};let ee;const startEarlyRuntime=()=>ee??=k.measure(`runtime.early`,()=>import(`./server-startup-early-h5QrOMMo.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:X},{startGatewayChannelHealthMonitor:te}]=await k.measure(`runtime.post-early-imports`,()=>Promise.all([import(`./server-runtime-subscriptions-D2L6B0jP.mjs`),import(`./server-runtime-startup-services-ux5dlF-B.mjs`)]));const{sessionCompanion:ne,sessionObserver:re,sessionActivitySummaries:ie,channelAdmissionAudit:ae,...oe}=await k.measure(`runtime.subscriptions`,()=>X({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,oe);await k.measure(`runtime.services`,()=>O.setChannelHealthMonitor(te({channelManager:A,scheduler:t.scheduler})));const{createOperatorApprovalSessionEventRuntime:se}=await import(`./operator-approval-session-events-B2AOv-kU.mjs`);const Z=/* @__PURE__ */ new Map;const ce=se({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 le=createAgentRuntimeApprovalAuthorityValidator(q?.placementStore);const{beginCloseApprovalObservers:Q,stopOperatorInteractions:ue,extraHandlers:de,coreGatewayHandlers:fe,...pe}=await k.measure(`gateway.handlers`,async()=>{const[{createGatewayAuxHandlers:e},{coreGatewayHandlers:n}]=await Promise.all([import(`./server-aux-handlers-BJnpCggj.mjs`),import(`./server-methods-DZVMDOjo.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:J,sharedGatewaySessionGenerationState:P,resolveSharedGatewaySessionGenerationForConfig:F,clients:N,channelManager:A,getChannelAutostartSuppression:A.getAutostartSuppression,logChannels:o,registerWorkerTurnClaimClosedHandler:q?.placementStore?e=>q.placementStore.registerTurnClaimClosedHandler(e):void 0,validateAgentRuntimeDelegatedAuthority:e=>le({kind:`agentRuntime`,agentId:`approval-manager`,sessionKey:`approval-manager`,operationalRunInstance:e.operationalRunInstance,delegatedAuthority:e}),onApprovalLifecycle:ce.publish,onAgentRunAuthorityClosed:e=>{W.revokeRunAuthority(e)}}),coreGatewayHandlers:n}});const{execApprovalManager:me,pluginApprovalManager:he,systemAgentApprovalManager:ge}=pe;const _e=t.connectionWork.signal;_e.addEventListener(`abort`,Q,{once:true});if(_e.aborted)Q();t.registerGatewayLifetimeSidecars({name:`operator-interactions`,stop:async()=>{_e.removeEventListener(`abort`,Q);await ue()}});await pe.ready;Z.set(`exec`,me);Z.set(`plugin`,he);Z.set(`system-agent`,ge);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[me,he])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 ve={..._.registry.gatewayHandlers,...de};let ye=new Set(Object.keys(_.registry.gatewayHandlers));const buildAttachedGatewayMethodRegistry=e=>{const t={...fe};const n={};for(const[e,r]of Object.entries(de))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 be=buildAttachedGatewayMethodRegistry(_.registry);const listAttachedGatewayMethods=()=>{const e=be.listAdvertisedMethods();e.push(...K());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-62cyde8J.mjs`);const i=buildAttachedGatewayMethodRegistry(e.pluginRegistry);const a=uniqueStrings([...i.listAdvertisedMethods(),...K(e.pluginRegistry)]);const o=new Set(Object.keys(e.pluginRegistry.gatewayHandlers));return{publish:s=>{adoptPluginHttpRouteHandoffs(_.registry,e.pluginRegistry);r(e.pluginRegistry,null,`gateway-bindable`,t.pluginWorkspaceDir,_.registry,n);_.publish(e.pluginRegistry,s);_.baseGatewayMethods=e.gatewayMethods;for(const e of ye)delete ve[e];Object.assign(ve,e.pluginRegistry.gatewayHandlers);ye=o;be=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-D4pi6bzJ.mjs`);return i({runtime:t,port:n,log:r,loadGatewayPluginBootstrapModule:()=>import(`./server-plugin-bootstrap-DCbSyGQu.mjs`),prepareAttachedPluginRuntime},e)};return{...t,kernel:{...O,reloadPlugins:reloadAttachedGatewayPlugins},startEarlyRuntime,sessionCompanion:ne,sessionObserver:re,sessionActivitySummaries:ie,channelAdmissionAudit:ae,approvalSessionEvents:ce,...pe,validateAgentRuntimeApprovalAuthority:le,attachedGatewayExtraHandlers:ve,getAttachedGatewayMethodRegistry:()=>be,getPluginNodeCapabilities,prepareAttachedPluginRuntime,refreshAttachedGatewayDiscovery,loadGatewayModelCatalog:s,loadGatewayModelCatalogSnapshot:c,readPreparedGatewayModelCatalog:l,readPreparedGatewayModelCatalogBatch:u,getPluginMetadataSnapshot:()=>t.pluginMetadataSnapshot}}
//!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`})}
//!src/plugins/personal-account-auth.ts
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-MIvUZNGN.mjs`);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)}
//!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}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{listLinks(e){warnModelAccountConnectDeprecation(`listLinks`);assertRunning(e);return{links:listUserProfileAuthLinks(e.owner)}},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)},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}},list(e,t){warnModelAccountConnectDeprecation(`list`);assertRunning(e);return{profileId:e.owner,...listUserModelAccounts({profileId:e.owner,cursor:t}),links:listUserProfileAuthLinks(e.owner)}},select(e,t){warnModelAccountConnectDeprecation(`select`);assertRunning(e);return setLinkNative(e,requireOwnedAccountProvider(readUserModelAccountSummary({profileId:e.owner,authProfileId:t})),t)},status(e,t){warnModelAccountConnectDeprecation(`status`);const n=findOperation(e,t);return n?projectResult(e,n):{status:`expired`}},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()}}}
//!src/gateway/session-incognito-lifetime.ts
const CLEANUP_RETRY_MS=6e4;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()}}}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-DtNInFRm.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)}}}
//!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-BGfS0RCy.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)}}))}
//!src/gateway/server-kernel-request-runtime.ts
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-DP4501_b.mjs`);return e({env:process.env})})]);const _=await s.measure(`gateway.request-context`,async()=>{const{createGatewayRequestContext:e}=await import(`./server-request-context-CA2TPjDd.mjs`);return e({runtime:t,configRevisionProjector:g,chatMetadataLifecycle:h,log:n,logHealth:r})});_.restartResumeWindows=t.opts.restartResumeWindows;const v=t.opts.updateCanary?void 0:s.measure(`sessions.projection`,async()=>{const{createSessionRowProjection:e}=await import(`./session-row-projection-CFOfCltS.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:isNamedOperatorRoleEnforcementEnabled(readRuntimeConfig())}))try{await s.measure(`gateway.owner-profile`,async()=>{const[{ensureCanonicalGatewayOwnerProfile:e},{resolveHostAccountName:t}]=await Promise.all([import(`./user-profile-writes-CfMSOyHi.mjs`),import(`./host-account-name-C6PbcNcO.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-BQaiAuDF.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-By7aiHqy.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}}
//!src/gateway/server-cron-lazy.ts
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-R2qmBhzc.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())}}}
//!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}}
//!src/gateway/server-diagnostics.ts
const QA_DIAGNOSTIC_ABORT_MS_ENV=`QA_DIAGNOSTIC_STUCK_SESSION_ABORT_MS`;const MIN_QA_DIAGNOSTIC_ABORT_MS=3e4;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}}})}}
//!src/gateway/server-lifecycle-close.ts
function createGatewayCloseEntrypoints(e,t,n){const run=t=>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))}}
//!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()}}}}
//!src/gateway/server-runtime-handles.ts
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}}
//!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}}
//!src/gateway/server-plugin-runtime-generation.ts
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)}}}
//!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)}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()}retire(e){this.retained.abort(e)}async waitForPendingEntries(){await Promise.all(this.active)}async sealAndJoin(){this.sealed=true;this.retire();await this.waitForPendingEntries()}};
//!src/gateway/session-viewer-presence.ts
function createSessionViewerPresenceDeclarations(e){let t=false;const replace=(n,r)=>{if(t)return[];const i=n.trim();const a=e.clients.getByConnectionId(i);if(!a||a.invalidated||a.socket.readyState!==1)return[];const o=[...new Set(r.map(e=>e.trim()).filter(Boolean))].toSorted();const s=a.watchedSessions??[];if(s.length===o.length&&s.every((e,t)=>e===o[t]))return o;a.watchedSessions=o.length>0?o:void 0;if(a.presenceKey){upsertPresence(a.presenceKey,buildClientPresence(a));if(o.length>0)recordClientPresenceActivity(e.clients,a);e.publishPresence()}return o};const unsubscribe=t=>{const n=e.clients.getByConnectionId(t.trim());if(n)n.watchedSessions=void 0};const isViewedOnDevice=(n,r)=>{if(t)return false;for(const t of e.clients){if(!t.watchedSessions?.includes(r))continue;if(!t.invalidated&&!t.connectionSignal?.aborted&&t.socket.readyState===1&&normalizeOptionalString(t.connect.device?.id)===n)return true}return false};const stop=()=>{t=true;for(const t of e.clients)t.watchedSessions=void 0};return{replace,unsubscribe,isViewedOnDevice,stop}}
//!src/gateway/terminal/open-admission.ts
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()}}
//!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-DuP8Y28l.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-Bvwcl_eF.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-BJ36IXdI.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-BcX1-FpV.mjs`);const{TERMINAL_EVENT_DATA:oe}=await import(`./session-types-B-kTT8pM.mjs`);const se=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 Z=T.current;const ce=createGatewayPluginRuntimeGeneration({getServices:()=>Z.pluginServices,setServices:e=>{Z.pluginServices=e}});const le=createDeferredCore();if(O.size===0)le.resolve();const Q=createGatewayReadyAnnouncer({getReadiness:t.getReadiness,isClosing:()=>U.closePreludeStarted,isChatSendAvailable:()=>!O.has(`chat.send`),areSidecarsReady:()=>D.sidecarsReady,startupTrace:t.startupTrace,log:r});const ue={startupMethodsReady:le.promise,pluginRuntimeGeneration:ce,pluginMetadata:e.pluginMetadata,setDispatchReady:e=>{D.dispatchReady=e},markSidecarsReady:()=>{D.sidecarsReady=true},unlockStartupMethods:()=>{for(const e of STARTUP_UNAVAILABLE_GATEWAY_METHODS)O.delete(e);le.resolve();return Q()},publishMethodSurface:e=>{Z.gatewayMethods.splice(0,Z.gatewayMethods.length,...e)},setEarlyRuntimeHandles:e=>{Z.skillsChangeUnsub=e.skillsChangeUnsub},swapDiscovery:e=>{const t=Z.discovery;Z.discovery=e;return t},setScheduledServiceHandles:e=>{Z.stopScheduledServices=e.stopScheduledServices;Z.stopDeliveryRecovery=e.stopDeliveryRecovery},setPostAttachHandles:e=>{Z.stopGatewayUpdateCheck=e.stopGatewayUpdateCheck},setTailscaleCleanup:e=>{Z.tailscaleCleanup=e},setConfigReloaderHandle:e=>{Z.configReloader=e},getReloadState:()=>({hooksConfig:Z.hooksConfig,hookClientIpConfig:Z.hookClientIpConfig,cronState:Z.cronState}),setReloadHookState:e=>{Z.hooksConfig=e.hooksConfig;publishHooksTokenEnvKey(e.hooksConfig);Z.hookClientIpConfig=e.hookClientIpConfig},getCronService:()=>Z.cronState.cron,swapCronState:e=>{const t=Z.cronState;Z.cronState=e;S.cron=e.cron;return t},setChannelHealthMonitor:e=>{Z.channelHealthMonitor=e},applyPluginLifecycleChange:e=>Z.configReloader.applyPluginLifecycleChange(e),getConfigReloaderHotReloadStatus:()=>Z.configReloader.hotReloadStatus?.(),setMaintenanceHandles:e=>{Z.maintenance=e;Z.stopMediaCleanup=e.stopMediaCleanup}};Z.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}});Z.sessionViewerPresence=createSessionViewerPresenceDeclarations({clients:p,publishPresence:t.publishPresence});t.attachSessionViewerPresence(Z.sessionViewerPresence);S.cron=Z.cronState.cron;const de=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-388WnVU-.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 fe=null;const stopMediaCleanupForClose=()=>fe??=Z.stopMediaCleanup();let pe;const stopModelAccountsForClose=()=>pe??=t.resolvePluginGatewayContext()?.modelAccountConnectService?.stop();const me=new AsyncWorkScope;let he=false;const markClosePreludeStarted=n=>{if(he)return e.pluginMetadata.beginClose();he=true;beginGatewayShutdownCleanup();const r=e.pluginMetadata.beginClose();const i=resolveGatewayShutdownNotice(n);markGatewaySuspendExiting();y.dispose();disposeGatewayDelegationCredentials();A.dispose();l.beginClose();Z.maintenance?.stopPeriodicTasks();me.beginClose();h(`shutdown`,i);Ce.beginClose();Z.stopDeliveryRecovery();stopMediaCleanupForClose();Z.stopGatewayUpdateCheck().catch(()=>{});stopConfigReloaderForClose().catch(()=>{});Z.controlUiSessionPullRequests?.stop();Z.sessionViewerPresence?.stop();t.stopPresencePublications();return r};let ge=null;const stopConfigReloaderForClose=()=>ge??=Z.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`,Z.stopDeliveryRecovery),step(`media-cleanup`,stopMediaCleanupForClose),step(`update-check`,()=>Z.stopGatewayUpdateCheck()),step(`config-reloader`,()=>stopConfigReloaderForClose().catch(()=>{})),step(`periodic-maintenance`,()=>Z.maintenance?.stopPeriodicTasks().catch(()=>{})),step(`session-pull-requests`,()=>Z.controlUiSessionPullRequests?.stop()),step(`health-work`,()=>me.drain())])};let _e=false;const runClosePrelude=async()=>{await beginClosePrelude();try{await step(`talk-persistence`,()=>l.drain())}finally{X();await re.close();await a.runGatewayClosePrelude({stopDiagnostics:stopGatewayDiagnosticHeartbeat,skillsChangeUnsub:()=>Z.skillsChangeUnsub({exitAfterClose:_e}),disposeNodeReapproval:()=>b.dispose(),stopChannelHealthMonitor:async()=>{const e=Z?.channelHealthMonitor;e?.shutdown();await e?.waitForIdle()},stopReadinessEventLoopHealth:k.stop,closeMcpServer:a.closeMcpLoopbackServer})}};const{getRuntimeSnapshot:ve,startChannels:ye,startChannel:be,stopChannel:xe,markChannelLoggedOut:Se}=x;const refreshGatewayHealthSnapshotWithRuntime=e=>{if(me.isClosing)return Promise.reject(/* @__PURE__ */ new Error(`Gateway health refresh owner is closed`));return me.track(()=>refreshGatewayHealthSnapshot({...e,getRuntimeSnapshot:ve,getEventLoopHealth:k.snapshot,getConfigReloaderHotReloadStatus:ue.getConfigReloaderHotReloadStatus,getSessionRowProjection:t.getSessionRowProjection,getCronState:()=>Z.cronState}))};const Ce=createGatewaySidecarStopOwner();const we=Ce.stopAndJoin;const Te=Z.postReadySidecars;const Ee=Z.gatewayLifetimeSidecars;const sealAndJoinRegisteredSidecarStops=async()=>{const e=(await Promise.allSettled([Te.sealAndJoin(),Ee.sealAndJoin()])).find(e=>e.status===`rejected`);if(e)throw e.reason};const prepareClose=async n=>{_e=n?.exitAfterClose===true;fenceSessionSuspensionWritesForGatewayShutdown();U.closePreludeStarted=true;s.beginClose();c.beginClose();m.dispose();stopModelAccountsForClose();closeAuthProfileUsage(e.sdkResourceHost);o.beginClose();t.scheduler.fence();t.resolvePluginGatewayContext()?.scopeUpgradeCoordinator?.beginClose();de.invalidate();const r=await a.prepareGatewayClose({resolveGatewayContext:t.resolvePluginGatewayContext,preparePluginRegistryClose:()=>v.prepareClose(),persistRunningSessionsForRestart:async(e,t)=>{const r=Z.configReloader.getCommittedRuntimeConfig?.();if(!r)return;await a.sessionRestartResume.persistRunningSessionsForRestart({cfg:r,signal:e,...n?.restartExpectedMs!=null?{collectNotice:t}:{}})},terminateRunningSubagentsForShutdown:async()=>{Promise.resolve(markClosePreludeStarted(n)).catch(()=>{});await a.subagentRegistry.terminateLiveSubagentsForShutdown(t.resolvePluginGatewayContext)},cancelReceivedWork:e=>{o.retire(e);t.scheduler.beginClose();t.connectionWork.beginClose(e)},disposeAllCodeModeRuns:a.disposeAllCodeModeRuns,updateCheckStop:Z.stopGatewayUpdateCheck,configReloader:{stop:stopConfigReloaderForClose}},n);await beginClosePrelude(n);return async()=>{ue.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:ue.swapDiscovery(null)?.stop??null,tailscaleCleanup:Z.tailscaleCleanup,clearSecretsRuntimeSnapshot:clearSecretsRuntimeSnapshotState,channelIds:i,stopChannel:xe,pluginServices:Z.pluginServices,cron:Z.cronState.cron,stopCronMaintenance:a.stopCronMaintenance,stopScheduledServices:Z.stopScheduledServices,maintenance:Z.maintenance,stopMediaCleanup:stopMediaCleanupForClose,agentUnsub:Z.agentUnsub,transcriptUnsub:Z.transcriptUnsub,lifecycleUnsub:Z.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 $={connectionWork:t.connectionWork,stopConnectionDependentSidecars:we,stopRegisteredGatewayLifetimeSidecars:Ee.stop,stopRegisteredPostReadySidecars:Te.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:$,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,...$,sdkResourceHost:e.sdkResourceHost,configureDiagnostics:Oe,requestEntryLifetime:o,subscribeSessionMessageEvents:d.subscribe,unsubscribeSessionMessageEvents:d.unsubscribe,...J,nodeDesktopService:te,watchNodeHttpRuntime:re,terminalSessions:se,runtimeState:Z,unavailableGatewayMethods:O,kernel:ue,pluginHostServices:{get cron(){return ue.getCronService()}},shutdownRuntime:a,lifecycle:U,cronReconciliation:de,getRuntimeSnapshot:ve,startChannels:ye,startChannel:be,stopChannel:xe,markChannelLoggedOut:Se,refreshGatewayHealthSnapshotWithRuntime,registerConnectionDependentSidecars:Ce.publish,unregisterConnectionDependentSidecar:Ce.remove,registerPostReadySidecars:Te.publish,registerGatewayLifetimeSidecars:Ee.publish,...createGatewayCloseEntrypoints(e.sdkResourceHost,prepareClose,closeOnStartupFailure)}}
//!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)})}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()}}}
//!src/gateway/openclaw-id/connection-identity.ts
function createOpenClawIdConnectionAccess(e){const prepareOwnerClientCheck=async(t,n)=>{if(!e.enabled())return()=>false;const r=t===`local_operator`?()=>true:t===`tunnel`&&n?await(await e.getAuthority()).prepareOwnerPeerCheck(n):()=>false;return()=>e.enabled()&&r()};return{async prepareMemberProfileCheck(t){if(!e.enabled())return()=>false;const{prepareUserProfileRoleAuthority:n}=await import(`./user-channel-identity-operations-H3Fg2KQ_.mjs`);const r=await n(t);const i=await e.getAuthority();const a=await i.memberProfiles(Object.keys(i.current()?.authority?.members??{}));return()=>{if(r&&!r.isCurrent())throw new Error(`Target profile changed; retry the role assignment.`);return e.enabled()&&Object.entries(a).some(([e,t])=>t.id===r?.profileId&&Object.hasOwn(i.current()?.authority?.members??{},e))}},prepareOwnerClientCheck,async ownerDeviceCount(){const t=await e.getAuthority();const{isOwnerDeviceActive:n}=await import(`./src-B9KLw6AZ.mjs`);const r=t.current()?.authority;return r?Object.values(r.owner_devices).filter(e=>n(e,Math.floor(Date.now()/1e3))).length:0},async isOwnerClient(e,t){return(await prepareOwnerClientCheck(e,t))()},async connectionIdentity(t,n){if(!e.enabled())return t===`local_operator`?{kind:`local`,accountEmail:null,accountName:null}:{kind:`none`};const r=await e.getAuthority();const i=t===`tunnel`&&n?await r.resolvePeer(n):void 0;const a=r.current();const o=a?.owner_profile?.sub===a?.discovery.owner_account_id||t===`local_operator`&&!a?.discovery.owner_account_id?a?.owner_profile:void 0;const s={accountEmail:o?.email??null,accountName:o?.name??null};if(t===`local_operator`)return{kind:`local`,...s};if(i?.kind===`owner`)return{kind:`owner`,deviceLabel:Object.values(a?.authority?.owner_devices??{}).find(e=>e.cert.body.peer_keys.includes(n))?.cert.body.label??null,ownerAccountId:a?.discovery.owner_account_id??null,...s};if(i?.kind===`member`){const t=(await r.memberProfiles([i.accountId]))[i.accountId];const a=n?await r.resolvePeer(n):void 0;if(!e.enabled()||a?.kind!==`member`||a.accountId!==i.accountId||a.role!==i.role)return{kind:`none`};return{kind:`member`,role:i.role,accountId:i.accountId,email:t?.email??null,displayName:t?.displayName??null,invitedBy:o&&(o.name||o.email)?{name:o.name??null,email:o.email??null}:null}}return{kind:`none`}}}}
//!src/gateway/openclaw-id/member-role-presets.ts
const MEMBER_ROLE_PRESETS={operator:{sessions:{others:`write`},agents:`*`,scopes:[READ_SCOPE,WRITE_SCOPE,APPROVALS_SCOPE,QUESTIONS_SCOPE,TALK_SCOPE]},guest:{sessions:{others:`view`},agents:`*`,scopes:[SESSION_WRITE_SCOPE],sandbox:`required`},viewer:{sessions:{others:`view`},agents:`*`,scopes:[SESSION_READ_SCOPE]}};function createMemberRolePresetActivation(e){let t=false;let n;let r=false;return{observeConfigApplication(e,t){const n=getRuntimeConfigSnapshot();const i=n?.gateway?.roles?.definitions;r=!t&&isOpenClawIdEnabled(e.gateway?.openclawId)&&(!isOpenClawIdEnabled(n?.gateway?.openclawId)||Object.keys(MEMBER_ROLE_PRESETS).some(t=>Object.hasOwn(e.gateway?.roles?.definitions??{},t)&&!Object.hasOwn(i??{},t)))},status(e){if(r)return{state:`failed`,reason:`Restart the Gateway to finish turning on OpenClaw ID member roles; the saved config has not been applied.`};return n&&e.state!==`off`?{state:`failed`,reason:n}:e},async reconcile(r,i=getRuntimeConfigSnapshot()){const a=r&&i?openClawIdAccessWarning(i):void 0;if(a){logConfigWarningsOnce({configPath:resolveConfigPath(),warnings:[{path:`gateway.openclawId.enabled`,message:a}],logger:e});return false}if(t===r)return false;t=r;n=void 0;if(!r)return false;try{const{replaceConfigFile:e,withConfigMutationExclusive:t}=await import(`./mutate-DK9uDX4F.mjs`);return await t(async t=>{if(!isOpenClawIdEnabled(t.gateway?.openclawId))return false;const n=t.gateway?.roles;const r=Object.entries(MEMBER_ROLE_PRESETS).filter(([e])=>!Object.hasOwn(n?.definitions??{},e));if(!r.length)return false;await e({sourceConfig:{...t,gateway:{...t.gateway,roles:{...n,definitions:{...n?.definitions,...structuredClone(Object.fromEntries(r))}}}},afterWrite:{mode:`auto`}});return true})}catch(t){n=`Could not save OpenClaw ID member role presets: ${String(t)}. Fix the config write failure, then restart the Gateway or turn OpenClaw ID off and on.`;e.warn(`openclaw-id: ${n}`);return false}}}}
//!src/gateway/openclaw-id/owner-expiry.ts
const MAX_TIMER_MS=2147483647;function createOwnerExpiryTimer(e){let t;const stop=()=>{if(t){clearTimeout(t);t=void 0}};return{arm(n){stop();if(n===void 0)return;const r=Math.min(MAX_TIMER_MS,Math.max(0,n*1e3-Date.now()));t=setTimeout(()=>{t=void 0;e.onExpired()},r);t.unref?.()},stop}}
//!src/gateway/openclaw-id/owner-lifecycle.ts
const DAY_SECONDS=86400;function inactivityWindows(e){const t=e?.ownerDeviceInactivityDays;const n=e?.memberDeviceInactivityDays;return{...t?{ownerDeviceSeconds:t*DAY_SECONDS}:{},...n?{memberPeerKeySeconds:n*DAY_SECONDS}:{}}}async function ownerLifecycleEvents(e,t,n){const r=await e.dropInactive(inactivityWindows(t));const i=await e.expiredOwnerPeers();if(r.length===0&&i.length===0)return;if(r.length>0)n.info(`openclaw-id: dropped ${r.length} device key(s) unused too long`);if(i.length>0)n.info(`openclaw-id: closing sessions of ${i.length} expired owner device key(s)`);const a=[.../* @__PURE__ */ new Set([...r,...i])];return[{type:`disconnect`,peer_keys:a},...r.length>0?[{type:`invalidate_tokens`,peer_keys:r}]:[],{type:`remove_node_pairings`,peer_keys:a},{type:`publish_snapshot`}]}async function armLocalExpiry(e,t,n,r){const i=t();const a=await e.nextOwnerExpiry(inactivityWindows(n()));if(i&&i===t()&&isOpenClawIdEnabled(n()))r.arm(a)}function createPeopleExpiry(e){const t=createOwnerExpiryTimer({onExpired:async()=>{e.changed();arm()}});const arm=()=>{if(e.enabled())t.arm(e.next())};return{arm,stop:()=>t.stop()}}
//!src/gateway/openclaw-id/publication-retry.ts
const PUBLICATION_RETRY_INITIAL_MS=2e3;const PUBLICATION_RETRY_MAX_MS=3e5;const PUBLICATION_REFRESH_MS=SNAPSHOT_REPUBLISH_SECONDS*1e3-3e5;function publicationPending(e){if(!e?.authority||!e.discovery.owner_account_id)return false;return e.discovery.publish_pending===true||e.discovery.published_snapshot_seq<e.authority.seq||e.discovery.published_binding_seq<(e.binding?.body.binding_seq??0)}function createPublicationRetry(e){const t=e.initialDelayMs??2e3;const n=e.maxDelayMs??3e5;const r=e.random??Math.random;const i=e.refreshMs??PUBLICATION_REFRESH_MS;let a=false;let o;let s;let c=false;let l=false;let u=0;let d;let f;const cancelTimer=()=>{if(d)clearTimeout(d);d=void 0;f=void 0};const cancelRefresh=()=>{if(o)clearTimeout(o);o=void 0;s=void 0};const armRefresh=()=>{cancelRefresh();if(!a)return;const e=Math.round(i*(.9+.1*r()));s=Date.now()+e;o=setTimeout(()=>{o=void 0;s=void 0;run()},e);o.unref?.()};const delayFor=e=>{const i=Math.min(n,t*2**(e-1));return Math.round(i*(.8+.2*r()))};const schedule=()=>{if(!a||d)return;u+=1;const t=delayFor(u);f=Date.now()+t;e.log.info(`openclaw-id: Discovery publication pending; retry ${u} in ${Math.round(t/1e3)}s`);d=setTimeout(()=>{d=void 0;f=void 0;run()},t);d.unref?.()};const publishWithRefresh=async e=>{const t=await e();if(t?.state===`published`||t?.state===`failed`&&t.code===`stale_snapshot`)armRefresh();return t};const attemptOnce=async()=>{l=false;const t=await publishWithRefresh(e.publish).catch(e=>({state:`failed`,code:`internal`,message:e instanceof Error?e.message:String(e),retryable:true}));if(t?.state===`published`){u=0;if(l)return`again`;await e.setPending(false);if(l){await e.setPending(true);return`again`}return`done`}if(t?.state===`failed`&&t.retryable){l=false;schedule();return`done`}if(t?.state===`failed`)e.log.warn(`openclaw-id: Discovery publication refused (${t.code}); kept pending`);return`done`};const run=async()=>{if(c){l=true;return}c=true;try{while(await attemptOnce()===`again`);}finally{c=false}};const adopt=async t=>{if(t?.state===`failed`){await e.setPending(true);if(t.retryable&&!c)schedule()}return t};return{publishDirect:publishWithRefresh,publishAdopted:async e=>await adopt(await publishWithRefresh(e)),adopt,async request(){await e.setPending(true);await run()},async resume(){if(c||!publicationPending(e.current()))return;cancelTimer();u=0;await run()},async start(){a=true;if(c||!e.current()?.authority)return;cancelTimer();u=0;await run()},stop(){a=false;cancelTimer();cancelRefresh();u=0},nextRetryAt(){return f},nextRefreshAt(){return s}}}
//!src/gateway/openclaw-id/rebind-publication.ts
function createRebindPublication(){let e;let t=0;return{hold:t=>{e=t},code(t){e=t??e;return e},published(n,r){e=void 0;if(n<=Math.max(1,r,t))return false;t=n;return true}}}
//!src/gateway/openclaw-id/remote-signout.ts
async function signOutTunnelPeer(e,t,n,r){if(!n)throw new Error(`Gateway sign-out is unavailable`);if(!await t.resolvePeer(e))return false;const{revokeDeviceToken:i}=await import(`./device-pairing-tokens-BWTp7I2S.mjs`);const a=n.captureConnections([e]);n.closeConnections(a);const o=t.current()?.token_bindings?.filter(t=>t.peer_key===e)??[];for(const e of o){const t=await i({deviceId:e.device_id,role:e.role,baseDir:r});if(!t.ok&&t.reason!==`unknown-device-or-role`)throw new Error(`Could not revoke this browser's Gateway token`)}return true}
//!src/gateway/openclaw-id/service-gateway-key.ts
function createServiceGatewayKey(e){const load=async()=>{const[{loadGatewaySigner:t},n]=await Promise.all([import(`./gateway-key-RmOlybDx.mjs`),e.getAuthority()]);return await t(e.getStateDir(),n.current()?.binding?.body.k_gw)};const tryLoad=async()=>{const{GatewayKeyRefusedError:e}=await import(`./gateway-key-RmOlybDx.mjs`);try{return{ok:true,...await load()}}catch(t){if(t instanceof e)return{ok:false,refused:t};throw t}};return{load,tryLoad,async refusal(){if(!(await e.getAuthority()).current()?.binding)return;const t=await tryLoad();return t.ok?void 0:t.refused.reason}}}
//!src/gateway/openclaw-id/service-rebind-owner.ts
function createServiceRebindOwner(e){let t=new AbortController;let n;return{stop(){t.abort()},run:async(r,i,a={})=>{if(t.signal.aborted&&e.enabled())t=new AbortController;const o=t.signal;const isCurrent=()=>!o.aborted&&e.enabled();const{createServiceRebind:s}=await import(`./service-rebind-BilH3VIs.mjs`);n??=s(e);return await n.run(r,i,a,isCurrent)}}}
//!src/gateway/openclaw-id/service-settings.ts
function resolveSettings(e,t){if(!e.relayUrl)return{missing:[`relayUrl`]};return{stateDir:t,relayUrl:e.relayUrl,forwardedProto:e.loaderDomain?`https`:`http`}}function sameSettings(e,t){return e.stateDir===t.stateDir&&e.relayUrl===t.relayUrl&&e.forwardedProto===t.forwardedProto}function appliedConfigKey(e){return JSON.stringify([e.discoveryUrl??null,e.loaderDomain??null,e.ownerDeviceInactivityDays??null,e.memberDeviceInactivityDays??null])}
//!src/gateway/openclaw-id/service-status.ts
function openClawIdTunnelStatus(e){return e.state===`key_refused`?{state:`keys_refused`,key:`endpoint`,reason:e.reason}:{state:`on`,tunnel:e}}
//!src/gateway/openclaw-id/service-token-bindings.ts
function createTokenBindingPublisher(e){const publish=t=>{if(e.closed())return;setDeviceTokenBindingOwner({lookup:(e,n)=>t.tokenBinding(e,n),record:(e,n,r)=>t.bindToken(e,n,r),forget:e=>t.unbindTokens(e),reportMismatch:t=>e.log.warn(`openclaw-id: security: refused device token for ${t.deviceId} (${t.role}) presented from ${t.presentedFrom??`a non-tunnel connection`}; bound to ${t.boundTo??`no tunnel key`}`)})};const load=async()=>{try{const t=await e.authority();if((await t.load())?.token_bindings?.length)publish(t)}catch(t){if(e.closed())return;setDeviceTokenBindingOwner(`unreadable`);e.log.warn(`openclaw-id: security: could not read device-token bindings; refusing device tokens until the Gateway restarts or OpenClaw ID turns on: ${String(t)}`)}};return{publish,loadAtStart(){const e=load();setDeviceTokenBindingsLoading(e);return e}}}
//!src/gateway/openclaw-id/service-tunnel-principals.ts
function createTunnelPrincipalPublisher(e){return{publish(){if(!e.enabled())return;setOpenClawIdTunnelPrincipalResolver(async t=>{const n=await e.authority();if(!e.enabled())return;const r=await n.resolvePeer(t);if(r)n.recordSeen(t).catch(t=>e.warn(`openclaw-id: could not record device activity: ${String(t)}`));return r});setOpenClawIdTunnelPrincipalLookup(t=>e.enabled()?e.current()?.currentPeer(t):void 0,async()=>{if(e.enabled())await e.authority()});setOpenClawIdNodeDescriptionLookup(t=>e.enabled()&&isIrohEndpointKey(t)?e.current()?.current()?.authority?.nodes[t]?.description:void 0);setOpenClawIdTunnelActivityRecorder(t=>{if(e.enabled())e.current()?.recordSeen(t).catch(t=>e.warn(`openclaw-id: could not record device activity: ${String(t)}`))});setOpenClawIdClawOriginResolver(()=>e.enabled()?clawOriginOfRecord(e.current()?.current()):void 0);setOpenClawIdOwnerAccountResolver(()=>e.enabled()?e.current()?.current()?.discovery.owner_account_id??void 0:void 0)},stop(){setOpenClawIdNodeDescriptionLookup(void 0);setOpenClawIdTunnelActivityRecorder(void 0);setOpenClawIdTunnelPrincipalResolver(void 0);setOpenClawIdTunnelPrincipalLookup(void 0);setOpenClawIdClawOriginResolver(void 0);setOpenClawIdOwnerAccountResolver(void 0)}}}
//!src/gateway/openclaw-id/service.ts
const refusal=(e,t)=>({ok:false,code:e,detail:t});function createOpenClawIdService(e){let t={state:`off`};const n=e.memberRolePresets??createMemberRolePresetActivation(e.log);let r;let i;let a;let o;let s;let c;const l=createRebindPublication();let u;let d;let f;let p=new AbortController;let m=false;let h;const g=/* @__PURE__ */ new Set;const peopleChanged=()=>{notifyOpenClawIdTunnelPrincipalsChanged();notifyListeners(g,void 0)};const _=createPeopleExpiry({next:()=>a?.nextPeopleExpiry(),enabled:()=>!m&&isOpenClawIdEnabled(e.getConfig()),changed:peopleChanged});const v=_.arm;let y=Promise.resolve();const b=createOwnerExpiryTimer({onExpired:()=>expireOwners().catch(t=>e.log.warn(`openclaw-id: owner expiry failed: ${String(t)}`))});const x=createPublicationRetry({publish:()=>publish(),current:()=>a?.current(),setPending:async e=>await(await getAuthority()).recordDiscovery({publish_pending:e}),log:e.log});const getEffects=()=>d??=u?.();const createdAuthority=async()=>{if(!a){o??=e.createAuthority?e.createAuthority():import(`./authority-VILCcQeh.mjs`).then(({createOpenClawIdAuthority:e})=>e());a=await o}return a};const getAuthority=async()=>{const e=await createdAuthority();if(m)return e;const t=!h;if(t)h=e.onPeopleChanged(()=>{peopleChanged();v()});const n=h;await e.load();if(t&&n===h){v();await armOwnerExpiry(e)}return e};const S=createServiceGatewayKey({getStateDir:e.getStateDir,getAuthority});const armOwnerExpiry=t=>armLocalExpiry(t,()=>h,e.getConfig,b);const stopRuntime=async()=>{r=void 0;p.abort();p=new AbortController;const e=i;i=void 0;x.stop();f?.stop();f=void 0;await e?.stop()};const pushMembership=async()=>{const e=await getAuthority();if(i){const{seq:t,admitted:n}=await e.admittedPeerKeys();i?.pushMembership(t,n)}await armOwnerExpiry(e)};const expireOwners=async()=>{const t=await ownerLifecycleEvents(await getAuthority(),e.getConfig(),e.log);await(t?applyEvents(t):pushMembership())};const applyResult=async e=>{if(!e.ok)return e;const t=await applyEvents(e.events);return t?{...e,removal:t}:e};const reconcile=async()=>{const o=e.getConfig();await n.reconcile(!m&&isOpenClawIdEnabled(o));if(m||!o||!isOpenClawIdEnabled(o)){stopLocalAuthority();await stopRuntime();t={state:`off`};return}w.publish();if(a)await armOwnerExpiry(await getAuthority());const s=resolveSettings(o,e.getStateDir());if(`missing`in s){await stopRuntime();t={state:`unconfigured`,missing:s.missing};return}if(i&&sameSettings(i.settings,s)&&r===appliedConfigKey(o))return;await stopRuntime();try{await armOwnerExpiry(await getAuthority());const n=await S.refusal();if(n){t={state:`keys_refused`,key:`gateway`,reason:n};e.log.warn(`openclaw-id: Gateway key refused (${n}); remote access is off, the Gateway keeps running. Restore the original key file, then restart the Gateway`);return}await getEffects();await publishTokenBindings();const{startTunnelRuntime:l}=await import(`./tunnel-runtime-BMv-VT5O.mjs`);i=await l({settings:s,gatewayServer:e.getGatewayServer,membership:await(await getAuthority()).admittedPeerKeys(),boundEndpointKey:()=>c=a?.current()?.binding?.body.k_srv??c,log:e.log,onStatus:e=>{t=openClawIdTunnelStatus(e)},handleApi:handleTunnelApi});t=openClawIdTunnelStatus(i.supervisor.status());r=appliedConfigKey(o);await startMailbox();await revokeBoundTokens(await(await getAuthority()).orphanedTokens());await reconcileNodePairings();x.start().catch(t=>e.log.warn(`openclaw-id: publication failed: ${String(t)}`))}catch(n){t={state:`failed`,reason:n instanceof Error?n.message:String(n)};e.log.warn(`openclaw-id: could not start remote access: ${t.reason}`)}};const publish=async t=>{const n=p.signal;const r=e.getConfig();if(!isOpenClawIdEnabled(r))return;const i=await getAuthority();let a=i.current();if(!r?.discoveryUrl||!r.relayUrl||!a?.authority)return;const[{publishClaw:o},{createDiscoveryClient:c}]=await Promise.all([import(`./publisher-C9wuNhfR.mjs`),import(`./discovery-client-Br8-soGl.mjs`)]);const u=await S.tryLoad();if(!u.ok){const{reason:e,message:t}=u.refused;s={state:`failed`,code:e,message:t,retryable:false};peopleChanged();return s}const{signer:d}=u;const f=l.code(t);if(n.aborted||!isOpenClawIdEnabled(e.getConfig()))return;const m=c({baseUrl:r.discoveryUrl,signer:d,signal:n});const{reconcileRegistration:h}=await import(`./registration-recovery-BZszOhtH.mjs`);const g=await h(i,m);a=i.current();const _=g??await o({record:a,relayUrl:r.relayUrl,client:m,signer:d,enrollmentCode:f});s=_;peopleChanged();if(_.state===`published`){const t=a.binding?.body.binding_seq??0;if(l.published(t,a.discovery.published_binding_seq)){const n={type:`notify_owners`,event:`rebind`,ref:`${t}`};notifyOwners([n]).catch(t=>e.log.warn(String(t)))}await i.recordDiscovery({owner_account_id:_.ownerAccountId,published_binding_seq:a.binding?.body.binding_seq??0,published_snapshot_seq:_.snapshotSeq,published_snapshot_at:_.snapshotIssuedAt});await startMailbox()}else if(_.state===`failed`){e.log.warn(`openclaw-id: Discovery publication failed (${_.code})`);if(_.ownerAccountId){await(await getAuthority()).recordDiscovery({owner_account_id:_.ownerAccountId,published_binding_seq:a.binding?.body.binding_seq??0});await startMailbox()}}return _};const revokeBoundTokens=async e=>{const t=await getEffects();if(!t||e.length===0)return;await(await getAuthority()).unbindTokens(await t.revokeDeviceTokens(e))};const reconcileNodePairings=async()=>{const e=await getAuthority();if(m)return;const t=await getEffects();if(m)return;await t?.reconcileNodePairings?.(t=>e.isCurrentNodeListing(t))};const applyEvents=async t=>{const n=await getEffects();const r=[...new Set(t.flatMap(e=>e.type===`disconnect`||e.type===`invalidate_tokens`?e.peer_keys:[]))];const i=r.length>0?n?.captureConnections(r)??[]:[];await pushMembership();let a;if(r.length>0){const e=t.some(e=>e.type===`cancel_runs`)?await n?.cancelRuns?.(i)??0:0;n?.closeConnections(i);await revokeBoundTokens((await getAuthority()).tokensBoundTo(r));a={devices:r.length,connectionsClosed:i.length,runsCancelled:e}}const o=[...new Set(t.flatMap(e=>e.type===`remove_node_pairings`?e.peer_keys:[]))];if(o.length>0)await n?.removeNodePairings?.(o);notifyOwners(t).catch(t=>e.log.warn(`openclaw-id: owner notices failed: ${String(t)}`));if(t.some(e=>e.type===`publish_snapshot`))x.request().catch(t=>e.log.warn(`openclaw-id: publication failed: ${String(t)}`));return a};const notifyOwners=async t=>{const n=p.signal;const{sendOwnerNotices:r}=await import(`./owner-notices-CxC2T1Jz.mjs`);if(n.aborted)return;await r({events:t,log:e.log,target:async()=>{const t=e.getConfig();const r=(await getAuthority()).current();if(!t?.discoveryUrl||!r?.discovery.owner_account_id)return;const{createDiscoveryClient:i}=await import(`./discovery-client-Br8-soGl.mjs`);const a=await S.tryLoad();if(n.aborted||!a.ok)return;const{signer:o}=a;return{clawId:r.claw_id,client:i({baseUrl:t.discoveryUrl,signer:o,signal:n})}}})};const C=createTokenBindingPublisher({authority:createdAuthority,log:e.log,closed:()=>m});const w=createTunnelPrincipalPublisher({authority:getAuthority,current:()=>a,enabled:()=>!m&&isOpenClawIdEnabled(e.getConfig()),warn:t=>e.log.warn(t)});const stopLocalAuthority=()=>{E.stop();b.stop();_.stop();h?.();h=void 0;w.stop()};const publishTokenBindings=async()=>{const e=await getAuthority();C.publish(e);w.publish()};const startMailbox=async()=>{const t=p.signal;const n=e.getConfig();const r=await(await getAuthority()).load();if(f||!i||!n?.discoveryUrl||!r?.authority||!r.discovery.owner_account_id)return;const[{startMailboxReader:a},{createDiscoveryClient:o}]=await Promise.all([import(`./mailbox-reader-wHffTjYh.mjs`),import(`./discovery-client-Br8-soGl.mjs`)]);const s=await getAuthority();const{signer:c}=await S.load();if(t.aborted||f)return;const l=o({baseUrl:n.discoveryUrl,signer:c,signal:t});f=a({clawId:r.claw_id,client:l,cursor:r.discovery.mailbox_cursor,sink:{submit:e=>s.submit(e,`mailbox`),redeem:(e,t)=>s.redeem(e,t),redeemNode:e=>s.redeemNode(e),saveCursor:e=>s.recordDiscovery({mailbox_cursor:e})},onEffects:async e=>{await applyEvents(e)},onRefused:async(t,n)=>{const{handleStaleSeqRefusal:i,isStaleSeqRefusal:a}=await import(`./stale-seq-B0qkW_5q.mjs`);if(a(t,n))await i({message:t,currentSeq:s.current()?.authority?.seq??0,republish:()=>x.request(),target:async()=>({clawId:r.claw_id,client:l}),log:e.log})},onConnected:()=>void x.resume().catch(t=>e.log.warn(`openclaw-id: publication failed: ${String(t)}`)),log:e.log})};const handleTunnelApi=async(t,n,r)=>{const{handleTunnelApiRequest:i}=await import(`./tunnel-api-BYDL7KD4.mjs`);const a=await getAuthority();await i(t,n,r,{isAdmitted:async e=>isOpenClawIdTunnelPrincipalAdmitted(await a.resolvePeer(e)),membership:async e=>await a.memberView(e)??await a.ownerView(e),prepareOwnerCheck:e=>a.prepareOwnerPeerCheck(e),submit:async e=>applyResult(await a.submit(e,`tunnel`)),registerInvite:async e=>{const t=await a.registerInvite(e,`tunnel`);if(t.ok)await applyEvents(t.events);return t},seq:async()=>(await a.load())?.authority?.seq??0,registerNodeInvite:async(e,t)=>{const n=await a.registerNodeInvite(e,`tunnel`,t);if(n.ok)await applyEvents(n.events);return n},signOut:async t=>signOutTunnelPeer(t,a,await getEffects(),e.getStateDir())})};const runningServerKey=()=>{if(t.state!==`on`||t.tunnel.state!==`running`)return;return t.tunnel.endpointKey};const checkClawName=async(t,n)=>{const r=p.signal;const i=e.getConfig();const{checkClawName:a}=await import(`./claw-name-check-DYVJL8iC.mjs`);return await a({channel:t,request:n,config:i,signal:r,gatewayKey:S})};const ownerLinkStatus=async t=>{const{readOwnerLinkStatus:n}=await import(`./owner-link-view-Dtnit6TQ.mjs`);return n({includeSandboxBackend:t?.includeSandboxBackend,enabled:isOpenClawIdEnabled(e.getConfig()),getAuthority,getEffects,lastPublish:s,publicationRetry:x})};const T=createOpenClawIdConnectionAccess({enabled:()=>isOpenClawIdEnabled(e.getConfig()),getAuthority});const restartForRebind=()=>stopRuntime().then(reconcile);const E=createServiceRebindOwner({...e,getAuthority,gatewayKey:S,enabled:()=>!m&&isOpenClawIdEnabled(e.getConfig()),holdCode:l.hold,restartRemoteAccess:()=>(y=y.then(restartForRebind,restartForRebind)).then(()=>t)});w.publish();return{onPeopleChanged(e){return registerListener(g,e)},...T,async recordVerifiedAccount(e){await(await getAuthority()).recordVerifiedAccount(e)},bindEffects(t){u=t;reconcileNodePairings().catch(t=>e.log.warn(`openclaw-id: could not reconcile node pairings: ${String(t)}`))},serveTunnelApi:handleTunnelApi,reconcileRuntimePolicy(){y=y.then(reconcile,reconcile);return y},observeConfigApplication:n.observeConfigApplication,status:()=>n.status(t),async linkSummary(){if(!isOpenClawIdEnabled(e.getConfig()))return{linked:false};const t=await(await getAuthority()).load();const n=t?.authority;if(!t||!n)return{linked:false};return{linked:true,clawId:t.claw_id,hostname:t.hostname??void 0,rootPub:n.anchor.root_pub}},linkStatus:ownerLinkStatus,async ownerBinding(){return(await getAuthority()).current()?.binding??null},async prepareLink(e,t){const n=await checkClawName(e,t);if(`ok`in n)return n;const r=runningServerKey();if(!r)return refusal(`tunnel_not_running`,`the tunnel is not running yet`);if(!n.available)return refusal(`name_taken`,`${n.hostname} is already taken`);const{pub:i}=await S.load();return await(await getAuthority()).prepareLink({kSrv:r,kGw:i,hostname:n.hostname,guard:t.guard})},checkClawName,async commitLink(t,n,r,i){const a=runningServerKey();if(!a)return refusal(`tunnel_not_running`,`the tunnel is not running yet`);const{pub:o}=await S.load();c=a;const s=await(await getAuthority()).commitLink(n,t,{kSrv:a,kGw:o,guard:i});if(!s.ok)return s;await pushMembership();const l=await x.publishDirect(()=>publish(r)).catch(t=>{e.log.warn(`openclaw-id: publication failed: ${String(t)}`)});await x.adopt(l);return{...s,...l?{publication:l}:{}}},rebind:E.run,async publish(e){return await x.publishAdopted(()=>publish(e))},async submitStatement(e,t){if(!e)return refusal(`not_direct`,`membership changes come from an owner device on this claw`);return await applyResult(await(await getAuthority()).submit(t,e))},async registerInvite(e,t){if(!e)return refusal(`not_direct`,`invites are registered from an owner device on this claw`);const n=await(await getAuthority()).registerInvite(t,e);if(n.ok)await applyEvents(n.events);return n},async registerNodeInvite(e,t){if(!e)return refusal(`not_direct`,`invites are registered from an owner device on this claw`);const n=await(await getAuthority()).registerNodeInvite(t,e);if(n.ok)await applyEvents(n.events);return n},loadTokenBindings(){return C.loadAtStart()},stop(){m=true;const stop=async()=>{stopLocalAuthority();await stopRuntime();setDeviceTokenBindingOwner(void 0);t={state:`off`}};y=y.then(stop,stop);return y}}}
//!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}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(isNamedOperatorRoleEnforcementEnabled(o)&&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)}}}
//!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.`})}
//!src/gateway/human-mention-policy.ts
const MAX_DIRECTORY_PROFILES=1e4;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={connect:{...e.connect},internal:{...e.internal,operatorRoleActor:{kind:`operator`,profileId:r.profileId}}};const a=resolveOperatorRolePolicy(i,t);if(a&&!operatorScopeSatisfied(`operator.sessions.read`,a.scopes))return err(errorShape(ErrorCodes.FORBIDDEN,`Your operator role cannot read mentions.`));const o=e.connect.scopes?.includes(`operator.admin`)&&(!a||a.scopes.includes(`operator.admin`));i.connect.scopes=o?[ADMIN_SCOPE]:[SESSION_READ_SCOPE];const{entryFilter:s}=prepareSessionSharing({cfg:t,client:i});return ok({profile:r,canRead:e=>s?.(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,n=false){if(!(`sessionKey`in t))return{readTarget:()=>null,release(){}};const r=e.getRuntimeConfig();const i=resolveRequestedSessionAgentId(r,t.sessionKey,t.agentId);if(!i.ok)return{readTarget:()=>null,release(){}};const a=await prepareSessionSharingRead({cfg:r,sessionKey:t.sessionKey,agentId:i.agentId});try{const t=a.readCurrent(e.getRuntimeConfig()).target;const r=n&&t&&!isIncognitoSessionKey(t.canonicalKey)?await readSessionEntriesFromStoreInWorker({agentId:t.agentId,storePath:t.storePath,sessionKeys:[t.storeKey],snapshotFields:[],includeParticipantRecords:true}):void 0;return{readTarget:()=>a.readCurrent(e.getRuntimeConfig()).target,readRanking:()=>{const n=a.readCurrent(e.getRuntimeConfig());if(!t||!isSameSessionSharingTarget(n.target,t))return;return{participants:r?.participantRecords?.[t.storeKey]??[],members:n.membership}},release:a.release}}catch(e){a.release();throw e}},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,s){const c=e.getRuntimeConfig();const l=resolveContext(t,r,c,o);if(!l.ok)return l;const{target:u,profile:d}=l.value;if(!i)throw new Error(`The mention directory has not been prepared.`);const f=JSON.stringify([n,u,c.gateway?.roles]);if(a?.key!==f)a={key:f,users:i.profiles.flatMap(({id:e,logins:t})=>{const n=recipientProfile(e,u,c);return n?[{profileId:n.profileId,displayName:humanMentionDisplayLabel(n.label??t[0],n.profileId),avatarUrl:n.avatarUrl,logins:t,online:false}]:[]}),truncated:i.truncated};const p=r.query?.trim().toLocaleLowerCase()??``;const m=a.users.filter(e=>(s?s.includes(e.profileId):e.profileId!==d.profileId)&&(!p||e.displayName.toLocaleLowerCase().includes(p)||e.logins.some(e=>e.toLocaleLowerCase().includes(p))));const h=/* @__PURE__ */ new Map;for(const e of m)h.set(e.displayName,(h.get(e.displayName)??0)+1);const g=/* @__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)g.add(t.profileId)}}const _=m.map(e=>({profileId:e.profileId,displayName:(h.get(e.displayName)??0)>1?`${truncateUtf16Safe(e.displayName,244)} (${e.profileId.slice(0,8)})`:e.displayName,avatarUrl:e.avatarUrl,online:g.has(e.profileId)}));const v=o?.readRanking?.();const y=/* @__PURE__ */ new Map;for(const e of v?.participants??[])if(e.identity.type===`profile`&&e.contributionCount>0&&e.lastPromptedAt!==null){const t=readProfile(e.identity.id)?.profileId;if(t)y.set(t,Math.max(y.get(t)??e.lastPromptedAt,e.lastPromptedAt))}_.sort((e,t)=>Number(y.has(t.profileId))-Number(y.has(e.profileId))||(y.get(t.profileId)??0)-(y.get(e.profileId)??0)||Number(v?.members.has(t.profileId)??false)-Number(v?.members.has(e.profileId)??false)||Number(t.online)-Number(e.online)||e.displayName.localeCompare(t.displayName)||e.profileId.localeCompare(t.profileId));return ok({users:_.slice(0,100),truncated:a.truncated||_.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])}}}
//!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}))}
//!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)}
//!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)}
//!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}}
//!src/gateway/mention-inbox-targets.ts
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}}
//!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}}
//!src/gateway/mention-inbox.ts
const log$6=createSubsystemLogger(`gateway/mentions`);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(){const n=i.processed.size===0&&m===0;if(d||t.signal.aborted||n)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,r){try{while(l.needsDirectoryPreparation())await l.prepareDirectory()}catch{n(mentionInboxUnavailable(log$6));return}let i;try{if(`sessionKey`in t)await o(t.sessionKey,t.agentId);i=await l.prepareContext(t,true)}catch{n(mentionInboxUnavailable(log$6));return}try{n(readOperation(()=>l.mentionable(e,t,i,r)))}finally{i.release()}},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}}
//!src/gateway/server-broadcast-live-text.ts
const log$5=createSubsystemLogger(`gateway/broadcast`);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.bind(void 0,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})}}}
//!src/gateway/server-broadcast-scopes.ts
const EVENT_SCOPE_GUARDS={agent:[SESSION_READ_SCOPE],[GATEWAY_EVENT_ID_PEOPLE_CHANGED]:[ADMIN_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],"worktrees.branches.changed":[WRITE_SCOPE],"projects.checkoutOptions.changed":[SESSION_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:[SESSION_READ_SCOPE],shutdown:[],"gateway.suspension":[],tick:[],"talk.event":[READ_SCOPE,SESSION_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],"templates.add.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`]);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 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}:{}}}function isTargetedTranscriptionEvent(e,t){return t&&isPlainEventPayload(e)&&typeof Object.getOwnPropertyDescriptor(e,`transcriptionSessionId`)?.value===`string`}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));if(e===`projects.checkoutOptions.changed`)return n&&Object.hasOwn(t,`projectId`)&&r.every(([e,t])=>`value`in t&&(e===`projectId`&&typeof t.value===`string`||e===`agentId`&&(t.value===void 0||typeof t.value===`string`)));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`||t===`presence`||operatorScopeSatisfied(`operator.read`,o)||i?.()===true))||r&&operatorScopeSatisfied(`operator.sessions.write`,o))}
//!src/gateway/server-broadcast-narration.ts
const NARRATION_INTERVAL_MS=2e3;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}}}
//!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`}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}
//!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&&o){const e=u.endsWith(`{}}`)?``:`,`;const t=`,${u.slice(1,-2)}${e}`;return s?[Buffer.from(t),s,o]:[Buffer.from(t),o]}const d=u.startsWith(`{"${e}":`)?`,${u.slice(1,-1)}`:``;return n?[Buffer.from(d)]:d}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;return new SerializedGatewayFrame([e.prefix,...o,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===`agent`||a===`session.tool`)&&isPlainEventPayload(o)&&o.stream===`tool`&&isPlainEventPayload(o.data)&&o.data.phase===`update`&&o.data.outputOnly===true;const b=a===`session.typing`||g;let x;let S=c;if(!u&&!S&&(b||_)){const t=new Set(b?void 0:e.clients.unscopedSessionEventConnIds);x=v?p.map(e=>v.get(e)):[];for(const e of x)for(const n of e)t.add(n);if(t.size===0)return;S=t}const C=Boolean(c);const w=a===`presence`?o:void 0;const T=a===`chat.metadata.changed`?modelMetadataInvalidationFragment(o):void 0;const E=a===`chat`&&isPlainEventPayload(o)&&o.state===`status`&&o.phase===`waiting_for_model`;const D=i.prepareToolPayload(a,o);let O;const hasSessionReadContext=()=>O??=(a!==`talk.event`||isTargetedTranscriptionEvent(o,C))&&(a===`users.prefs.changed`&&C||e.canReceiveSessionEvent!==void 0&&p.length>0&&p.every(e=>e.trim().length>0)||T!==void 0||isSessionReadInvalidation(a,o,C));let k;let A;let j;let M;let N=false;let P=false;let F=false;const I=/* @__PURE__ */ new Map;const L=u?.frames??{};let R;const getFrameFields=()=>L.fields??={prefix:Buffer.from(`{"type":"event","event":${JSON.stringify(a)}`),stateVersionFragment:s?.stateVersion===void 0?``:serializeFrameField(`stateVersion`,s.stateVersion)};const frameBaseFor=e=>({...getFrameFields(),payloadFragment:w?``:Buffer.from(e===o&&T!==void 0?T:serializeFrameField(`payload`,e))});const z=u?[u.client]:S?e.clients.getByConnectionIds(S):e.clients;for(const S of z){if(!e.clients.has(S)||S.invalidated===true||S.socket.readyState!==1||E&&!hasGatewayClientCap(S.connect.caps,GATEWAY_CLIENT_CAPS.MODEL_WAIT_STATUS)||s?.excludeClientCapability&&hasGatewayClientCap(S.connect.caps,s.excludeClientCapability))continue;const O=a===`question.requested`||a===`question.resolved`?s?.questionRecipient:void 0;const z=O!==void 0&&!operatorScopeSatisfied(`operator.questions`,S.connect.scopes??[]);if(!hasEventScope(S,a,l,z,hasSessionReadContext))continue;if(a===`chat.metadata.changed`&&!operatorScopeSatisfied(`operator.read`,S.connect.scopes??[])&&T===void 0)continue;if(O&&!isCurrent(()=>O(S)))continue;if((b||_&&!e.clients.unscopedSessionEventConnIds.has(S.connId))&&!(C&&g&&!u)){if(!p.length||!v)continue;x??=p.map(e=>v.get(e));if(!x.some(e=>e.has(S.connId)))continue}if(!O&&p.length>0&&e.canReceiveSessionEvent&&!e.canReceiveSessionEvent(S,p,m,a,o))continue;if(y&&!p.some(e=>v?.getLiveToolOutput(e).has(S.connId)))continue;if(u&&!isCurrent(d?.isCurrent)||d?.coalesce&&d.group.aborted)continue;if(i.consume(S,a,o,p,s))continue;if(!F){F=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 B=r.deliveryFor(S);if(d&&!d.coalesce)r.drain(B,d.group);if(B.retired)continue;const V=(t.get(S)??0)+1;const H=r.bufferedBytes(B);const U=H>MAX_BUFFERED_BYTES;if(!U)n.delete(S);else if(!n.has(S)){n.add(S);logRejectedLargePayload({surface:`gateway.ws.outbound_buffer`,bytes:H,limitBytes:MAX_BUFFERED_BYTES,reason:s?.dropIfSlow?`ws_send_buffer_drop`:`ws_send_buffer_close`})}if(U&&s?.dropIfSlow){t.set(S,V);deliveryLost(S);continue}if(U){deliveryLost(S);r.retireDelivery(B);closeGatewayTransportWithGrace(B.socket,1008,`slow consumer`);continue}if(!u&&d?.coalesce&&B.inFlight>0){let e=r.pending(B,d.group,d.coalesce.key);if(e&&!isCurrent(e.isCurrent)){r.takePending(B,e);e=void 0}try{const t=e?R?.get(e.payload):void 0;const n=t?t.payload:e?d.coalesce.merge(e.payload,o):o;const i=t?.frames??(n===o?L:{});if(e&&!t&&n!==o)(R??=/* @__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(B)-(e?.bytes??0)+u<=52428800){if(e)r.takePending(B,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:S,frames:i,publication:t})};r.enqueue(B,o);continue}}catch(e){deliveryLost(S);log$4.error(`broadcast serialization failed for event ${a}: ${formatErrorMessage$1(e)}`);return}r.drain(B,d.group);broadcastInternal(a,o,s,c,l,{client:S,frames:L,publication:f});continue}const W=r.canSendDelta(B,d,f);const G=d?.projection;const getDeliveryFrameBase=()=>D&&i.isNarration(S.connId,p)?L.toolNarration??=frameBaseFor(D()):a===`health`&&S.connect.caps?.includes(GATEWAY_CLIENT_CAPS.HEALTH_SUMMARY)?L.healthSummary??=frameBaseFor(projectHealthSummary(o)):W&&G?L.delta??=frameBaseFor(G.delta(o)):L.snapshot??=frameBaseFor(o);let K;let q;let J;try{if(!P){getFrameFields();const t=!u&&(a===`session.message`||a===`sessions.changed`)&&isPlainEventPayload(o);if(!t)getDeliveryFrameBase();M=e.prepareSessionEventProjection?.(a,o,{sessionKeys:p,agentId:m,...s?.prepareSessionProjection?{prepareSessionProjection:s.prepareSessionProjection}:{}});N=t&&M!==void 0;P=true}const t=N?getFrameFields():getDeliveryFrameBase();let n=N?``:getDeliveryFrameBase().payloadFragment;if(w){if(!e.preparePresenceProjection)throw new Error(`presence recipient projection unavailable`);k??=e.preparePresenceProjection(w.presence);const t={...w,presence:k(S)};if(acceptsPresenceDeltas(S)&&s?.stateVersion?.presence!==void 0){J=preparePresenceDelivery(S,w.presence,t.presence,s.stateVersion.presence);n=J.fragment}else{const e=Object.keys(t).length===1&&!(`toJSON`in t);n=(e?A?.get(t.presence):void 0)??serializeFrameField(`payload`,t);if(e&&typeof n===`string`){n=Buffer.from(n);(A??=/* @__PURE__ */ new Map).set(t.presence,n)}}}if(M){const e=M(S);if(e===void 0)continue;const t=e.serializeSession&&(j??=/* @__PURE__ */ new Map);n=t?.get(e.payload)||e.serializePayload?.()||serializeFrameField(`payload`,e.payload,e.serializeSession,e.serializeMessage);t?.set(e.payload,n);q=e.delivered}const r=(S.connect.role??`operator`)===`operator`?S.preparedRecipientProfileId:void 0;let i=I.get(n);if(!i)I.set(n,i=/* @__PURE__ */ new Map);let c=i.get(r);if(!c)i.set(r,c=/* @__PURE__ */ new Map);K=c.get(V);if(K===void 0){K=frameWithSequence(t,V,n,r);c.set(V,K)}if(h===null)h=prepareSessionEventMetrics(a,o,s?.sessionEventSubscriptionKeys??p,e.sessionMessageSubscribers)}catch(e){deliveryLost(S);log$4.error(`broadcast serialization failed for event ${a}: ${formatErrorMessage$1(e)}`);return}if(S.authPolicy?.delegation&&!isGatewayAuthPolicyCurrent(S.authPolicy)){invalidateGatewayPolicyClient(S,{reason:`gateway-policy-changed`,code:4001,message:`gateway policy changed`});continue}t.set(S,V);r.recordReceipt(B,p,d,f);B.inFlight+=1;let Y=false;const sent=e=>{if(Y)return;Y=true;B.inFlight-=1;if(B.retired)return;if(e){deliveryLost(S);r.retireDelivery(B);log$4.error(`broadcast send failed conn=${S.connId}: ${formatErrorMessage$1(e)}`,{event:a});B.socket.terminate()}else r.drain(B)};try{q?.(S);B.socket.batchWrites?.();const e=B.socket.send(K,{binary:false},sent);if(J&&!B.retired)S.presenceSnapshot=J.snapshot;B.socket.recordEventSent?.(a,K,h?.(S.connId),J?.mode??(w?`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}}
//!src/gateway/server/client-registry.ts
var GatewayClientRegistry=class extends Set{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Set;#r=0;#i;#a=/* @__PURE__ */ new Map;get unscopedSessionEventConnIds(){return this.#t}get authorityClients(){return{[Symbol.iterator]:()=>(/* @__PURE__ */ new Set([...this,...this.#a.keys()])).values()}}retainRequest(e){this.#a.set(e,(this.#a.get(e)??0)+1);let t=false;return()=>{if(t)return;t=true;const n=this.#a.get(e)-1;if(n===0)this.#a.delete(e);else this.#a.set(e,n)}}constructor(e,t){super();this.#i=t;for(const t of e??[])this.add(t)}add(e){if(!this.has(e)){this.#e.set(e.connId,{client:e,order:this.#r++});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?.();notifyListeners(this.#n,void 0)}return this}delete(e){if(!super.delete(e))return false;this.#i?.(e);if(this.#e.get(e.connId)?.client===e){this.#e.delete(e.connId);this.#t.delete(e.connId)}this.onChange?.();notifyListeners(this.#n,void 0);return true}clear(){if(this.size===0)return;for(const e of this)this.#i?.(e);super.clear();this.#e.clear();this.#t.clear();this.onChange?.();notifyListeners(this.#n,void 0)}subscribeChanges(e){return registerListener(this.#n,e)}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)}};
//!src/gateway/server-connection-state.ts
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}}
//!src/gateway/server-transport-bridge.ts
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()}}}
//!src/logging/diagnostic-stall-kernel.ts
function createStallKernelRecorder(e,t){if(!isMainThread)return;const n=new BigInt64Array(new SharedArrayBuffer(24));n[2]=3n;const r=hasProfilerConflict();const beat=()=>{Atomics.store(n,1,r||url()?1n:0n);Atomics.store(n,0,BigInt(Math.floor(performance$1.now())))};beat();const{port1:i,port2:a}=new MessageChannel;let o;let s;const stop=()=>{clearInterval(s);i.close();a.close();o?.terminate()};try{const r=resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.stallObserver);o=new Worker(r,{execArgv:resolveRuntimeWorkerThreadExecArgv(r),workerData:{heartbeat:n.buffer,port:a,packageRoot:t,timeOrigin:performance$1.timeOrigin},transferList:[a]});o.on(`error`,()=>{stop();e(`stall kernel recorder unavailable: worker-failed`)});o.unref();s=setInterval(beat,250);s.unref()}catch{stop();e(`stall kernel recorder unavailable: worker-start-failed`);return}return{take(e){const t=[];const r=[];let a;while(a=receiveMessageOnPort(i)){const i=a.message;if(`frames`in i){Atomics.add(n,2,1n);if(e&&i.at>=e.startedAt&&i.at<=e.endedAt&&r.length<3)r.push(i);continue}if(e&&i.at>=e.startedAt&&i.at<=e.endedAt&&t.length<3){i.at=Math.round(i.at-e.startedAt);t.push(i)}}if(!t.length)return{kernelSummary:``,stacks:r};let o=JSON.stringify(t);for(const e of[`psi`,`io`,`ctxt`,`rssKb`,`stack`,`sched`]){if(Buffer.byteLength(o)<=1400)break;for(const n of t)delete n[e];o=JSON.stringify(t)}return{kernelSummary:` kernel=${o}`,stacks:r}},stop}}
//!src/logging/diagnostic-stall-flight-recorder.ts
const WINDOW_MS=5e3;function createStallFlightRecorder(e){const t=isMainThread?resolveOpenClawPackageRootSync({moduleUrl:import.meta.url}):null;const n=createStallKernelRecorder(e,t);let r;let i;let a=0;const o=Number(versions.node.split(`.`)[0])>=26;let s=!isMainThread||Boolean(versions.bun);const c=Symbol.for(`openclaw.stallFlightRecorder.capture`);const stopProfile=()=>{if(Object.getOwnPropertyDescriptor(globalThis,c)?.value===capture)Reflect.deleteProperty(globalThis,c);s=true;i=void 0;const t=r;r=void 0;try{t?.[Symbol.dispose]()}catch{e(`stall flight recorder unavailable: profiler-cleanup-failed`)}};const start=()=>v8$1.startCpuProfile({sampleInterval:25,maxBufferSize:MAX_SAMPLES});const capture=()=>{if(s)return;const e=performance$1.now();if(!o){if(hasProfilerConflict()||process.getBuiltinModule(`inspector`)?.url()||process.getBuiltinModule(`trace_events`)?.getEnabledCategories())return;return{windows:[],stacks:[{at:e,frames:getCallSites(18,{sourceMap:false}).slice(2).map(e=>({functionName:e.functionName.length<=256?e.functionName:`[redacted]`,scriptId:e.scriptId,url:e.scriptName.length<=2048?e.scriptName:``,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber-1}))}],endedAt:e,captureMs:performance$1.now()-e}}if(!r)return;const t=r;r=start();a=performance$1.now();const n=performance$1.now();const c=t.stop();const l={json:c.length<=1048576?c:void 0,endedAt:n};const u=i?[i,l]:[l];i=l.json===void 0?void 0:l;return{windows:u,endedAt:n,captureMs:performance$1.now()-e}};try{if(!s)s=hasProfilerConflict()||Boolean(process.getBuiltinModule(`inspector`)?.url())||Boolean(process.getBuiltinModule(`trace_events`)?.getEnabledCategories());if(!s){if(o){r=start();a=performance$1.now()}Object.defineProperty(globalThis,c,{configurable:true,value:capture})}}catch{s=true;e(`stall flight recorder unavailable: profiler-start-failed`)}return{sample(i){const{kernelSummary:o=``,stacks:s=[]}=n?.take(i)??{};if(!i&&performance$1.now()-a<WINDOW_MS)return;try{const e=r?capture():void 0;if(i&&e)return formatStallProfile(e.windows,i,t,o)}catch{stopProfile();e(`stall flight recorder unavailable: profiler-capture-failed`)}return i&&(o||s.length)?formatStallProfile([],i,t,o,s):void 0},stop(){n?.stop();stopProfile()}}}
//!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 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_BYTES=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}async function readHostCpuTimes(e){try{if(process.platform===`linux`){const t=await open(`/proc/stat`,`r`);let n;try{({bytesRead:n}=await t.read(e,0,e.length,0))}finally{await t.close()}const r=e.indexOf(10);if(r<0||r>=n)return;const i=e.toString(`ascii`,0,r).split(/\s+/);if(i[0]!==`cpu`||i.length<7)return;const a={user:Number(i[1]),nice:Number(i[2]),sys:Number(i[3]),idle:Number(i[4]),irq:Number(i[6])};if(HOST_CPU_TIME_KEYS.some(e=>!Number.isFinite(a[e])||a[e]<0))return;let o=0;for(const e of(await readFile$1(`/sys/devices/system/cpu/online`,`utf8`)).trim().split(`,`)){const[t,n=t]=e.split(`-`).map(Number);o+=n-t+1}return o>0?{count:o,cpus:[{times:a}]}:void 0}const t=cpus();return t.length?{count:t.length,cpus:t}: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();const p=Buffer.alloc(HOST_CPU_STAT_BUFFER_BYTES);let m;let h=false;let cancelHostCpuSample;let g=i();let _;let v=null;let y;let cancelWorkerCpuSample;const captureHostCpu=(e,t)=>{cancelHostCpuSample?.();const r=m;m=void 0;if(h)return;let i=true;cancelHostCpuSample=()=>{i=false};h=true;readHostCpuTimes(p).then(a=>{h=false;if(!i||n()-e>CPU_SAMPLE_BUDGET_MS||!a)return;m={at:e,times:a};if(!t||!_||u!==e)return;const o=r&&e-r.at===t.intervalMs?hostCpuUtilization(a,r.times):void 0;_={..._,cpuBreakdown:{..._.cpuBreakdown,...o===void 0?{}:{hostUtilization:o},hostCpuCount:a.count}}})};const captureWorkerCpu=(e,t)=>{cancelWorkerCpuSample?.();const r=y;y=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;y={at:e,revision:a,usage:n};if(!t||!_||u!==e||!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;_={..._,cpuBreakdown:{..._.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>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 p=o.drain();if(p.stalls.length>0&&areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`gateway.main_thread.stall`)){const e=p.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:p.dropped}))}const m=Math.max(c?nanosecondsToMilliseconds(s.max):Math.max(0,t-l),p.delayMaxMs);if(!c&&m>EVENT_LOOP_DELAY_WARN_MS&&!p.stalls.length)p.stalls.push({elapsedMs:t-l,startedAt:l,endedAt:t,task:`unattributed`,taskMs:t-l});let h;const y=Math.round(performance$1.timeOrigin+n());for(const e of p.stalls){if(!h||e.elapsedMs>h.elapsedMs)h=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=${y}`)}const x=a.sample(h);if(x)log$3.warn(`main-thread stall profile: ${x}`);const S=Math.max(1,t-u);const C=p.dropped+p.unattributedDropped;if(C>0)log$3.warn(`main-thread stall: omitted=${C} pendingLimit=8`);if(m<EVENT_LOOP_DELAY_WARN_MS&&S<SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS){b=scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS-S);return}const w=c?nanosecondsToMilliseconds(s.percentile(99)):0;const T=r(d);const E=i();const D=roundDiagnosticMetric(i(E,g).utilization);const O=roundDiagnosticMetric((T.user+T.system)/1e3,1);const k=roundDiagnosticMetric(O/S);const A=readMainThreadCpuUsage();const j=cpuUsageDelta(A,f);f=A;const M=classifyGatewayEventLoopHealthReasons({intervalMs:S,delayP99Ms:w,delayMaxMs:m,utilization:D,cpuCoreRatio:k});const N=M.length>0;if(N)v??=t;else v=null;const P={degraded:N,degradedSinceMs:v===null?null:Math.max(0,Math.round(t-v)),reasons:M,intervalMs:S,delayP99Ms:w,delayMaxMs:m,utilization:D,cpuCoreRatio:k,cpuBreakdown:j===void 0?{}:{mainThreadCoreRatio:roundDiagnosticMetric(j/(S*1e3))}};s.reset();u=t;d=r();g=E;_=P;captureHostCpu(t,P);captureWorkerCpu(t,P);if(areDiagnosticsEnabledForProcess()&&hasInternalDiagnosticEventInterest(`gateway.event_loop.sample`))runWithDiagnosticTraceContext(void 0,()=>emitInternalDiagnosticEvent({type:`gateway.event_loop.sample`,intervalMs:S,delayMaxMs:m}));b=scheduleSample(!N&&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 b=s?scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS):void 0;if(s){captureHostCpu(u);captureWorkerCpu(u)}const x=onInternalDiagnosticEventInterest(`gateway.event_loop.sample`,()=>{const e=n();const t=Math.max(e,u+SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS);if(s&&t<l)b=scheduleSample(t-e)});const reset=()=>{o.reset();s?.reset();u=n();d=r();f=readMainThreadCpuUsage();cancelHostCpuSample?.();m=void 0;g=i();_=void 0;v=null;cancelWorkerCpuSample?.();y=void 0;if(s){captureHostCpu(u);captureWorkerCpu(u);b=scheduleSample(SUSTAINED_LOAD_SAMPLE_MIN_INTERVAL_MS)}};return{snapshot:()=>_,persistentDegradationSnapshot:()=>{const e=_;return e?.degradedSinceMs!=null&&e.degradedSinceMs>=PERSISTENT_DEGRADATION_WARN_AFTER_MS?e:void 0},reset,stop:()=>{x();a.stop();o.stop();b?.cancel();s?.disable();s=null;cancelHostCpuSample?.();m=void 0;cancelWorkerCpuSample?.();y=void 0;_=void 0;v=null}}}
//!src/gateway/server/presence-events.ts
const log$2=createSubsystemLogger(`gateway/presence`);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}}
//!src/gateway/server/readiness.ts
const DEFAULT_READINESS_CACHE_TTL_MS=1e3;function createStartupChecker(e,t){const{gatewayBootId:n}=e;return()=>{const r=Date.now()-e.startedAt;if(e.getGatewayDraining?.())return{ok:false,status:`draining`,uptimeMs:r};const i=e.getStartupPending?.()?e.getStartupPendingReason?.()??`startup-sidecars`:t?.().some(e=>e.code===`agent-database-inspection-pending`)?`agent-database-inspection`:void 0;if(i!==void 0)return{ok:false,status:`starting`,uptimeMs:r,pendingReason:i};return{ok:true,status:`started`,uptimeMs:r,...n===void 0?{}:{gatewayBootId: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&&d.phase!==`reloading`){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=[];const g=[];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.reason===`reconnect-grace`&&!h.includes(e))h.push(e);if(!n.healthy&&r&&n.reason===`not-running`){if(!g.includes(e))g.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?{degraded:h}:{},...g.length>0?{suppressed:g}:{}};return{...a,uptimeMs:c}};const read=(t,n)=>{const i=e.getAgentDatabaseAdmissionRefusals?.();const a=i?.filter(({code:e})=>e!==`agent-deletion`);const o=i?.filter(({code:e})=>e===`agent-deletion`);const s=readReadiness(a,t,n??r());const c=e.getEventLoopHealth;const l=c?.();return{...s,...a?.length?{agentDatabases:a}:{},...o?.length?{agentDeletions:o}:{},...l?{eventLoop:l}:{}}};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())}}})}
//!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-CZZnKgDa.mjs`))).createNodeDesktopStreamBroker();const T=(await m.measure(`host-desktop.runtime-import`,()=>import(`./host-source-BPDgoivu.mjs`))).createHostDesktopService({getConfig:()=>readRuntimeConfig().desktop?.host,registry:C});const E=(await m.measure(`computer.runtime-import`,()=>import(`./computer-service-DR37opWE.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-Dqb5PfID.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-Bk27z1IP.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,prepareRepositoryIntegration:async(e,t)=>{if(!H)throw new Error(`Repository publication worker is unavailable`);return await H.prepareRepositoryPublication(e,t)},...O?{environments:O}:{},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-BmIHqeqC.mjs`);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-UE2UBWE6.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-CTSAXBIz.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-JOyanZ9Z.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-CjlQ7R41.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 se=resolveHookClientIpConfig(h);const Z=h.gateway?.auth?.rateLimit;const ce=createGatewayAuthRateLimiter(Z,{scheduler:n,id:`auth/main`});const le=createGatewayAuthRateLimiter({...Z,exemptLoopback:false},{scheduler:n,id:`auth/browser`});const Q=createNodeReapprovalCoordinator(Z,{scheduler:n});const ue=await m.measure(`control-ui.root`,()=>createGatewayControlUiRootLifecycle({controlUiRootOverride:te,controlUiEnabled:ee,gatewayRuntime:u,log:o}));const{createTerminalLaunchPolicy:de}=await m.measure(`terminal.launch-import`,()=>import(`./launch-Bjgy_M6g.mjs`));const fe=de(h);const{runDefaultChannelSetupWizard:pe,runDefaultSetupWizard:me}=await m.measure(`gateway.wizard-imports`,()=>import(`./wizard-CG-yL6YS.mjs`));const he=a.wizardRunner??me;const ge=a.channelWizardRunner??pe;const{wizardSessions:_e,findRunningWizard:ve,purgeWizardSession:ye}=createWizardSessionTracker();const be=/* @__PURE__ */ new Map;const xe=createDefaultDeps();const Se={current:null};const Ce={handled:false};const we=await m.measure(`tls.runtime`,()=>loadGatewayTlsServerRuntime(h.gateway?.tls,o.child(`tls`)));const Te=Date.now();const Ee=createGatewayEventLoopHealthMonitor({scheduler:n,isIdle:()=>getActiveGatewayRootWorkCount({excludeCurrent:true})===0});const $={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-BSXbprdc.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=()=>(!$.dispatchReady||!$.sidecarsReady||De.size>0)&&!Oe.closePreludeStarted;const Pe={startedAt:Te,getStartupPending:isGatewayStartupPending,getStartupPendingReason:()=>$.pendingReason,getGatewayDraining:()=>Oe.closePreludeStarted||isGatewayWorkAdmissionClosed()};const Fe=createStartupChecker({...Pe,gatewayBootId:r},listAgentDatabaseAdmissionRefusals);const Ie=createReadinessChecker({channelManager:Me,...Pe,getEventLoopHealth:Ee.snapshot,getStateDatabaseFailure:()=>openClawStateDatabaseCache.getOpenClawStateDatabaseRecordedFailure(resolveDatabasePath()),getAgentDatabaseAdmissionRefusals:()=>{const e=readRuntimeConfig();return listAgentDatabaseAdmissionRefusals().filter(t=>t.code===`agent-deletion`||!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=createOpenClawIdService({memberRolePresets:t.memberRolePresets,getConfig:()=>readRuntimeConfig().gateway?.openclawId,getStateDir:()=>resolveStateDir(),getGatewayServer:()=>ze.current()?.httpServer,log:o.child(`openclaw-id`)});Be.loadTokenBindings();const Ve=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:ue.state,openAiChatCompletionsEnabled:a.openAiChatCompletionsEnabled,openResponsesEnabled:a.openResponsesEnabled,resolvedAuth:ne,rateLimiter:ce,joinRateLimiter:le,isTerminalEnabled:fe.isEnabled,gatewayTls:we,getResolvedAuth,hooksConfig:()=>Se.current===null?oe:Se.current.hooksConfig,getHookClientIpConfig:()=>Se.current?.hookClientIpConfig??se,pluginRegistry:S.registry,getPluginRouteRegistry:()=>S.registry,isRequestRuntimeReady:()=>$.dispatchReady,isStartupPluginRuntimeReady:()=>$.sidecarsReady,isChannelAutostartSuppressed:()=>Me.getAutostartSuppression()!==null&&Object.values(Me.getRuntimeSnapshot().channelAccounts).some(e=>Object.values(e??{}).some(e=>e.enabled!==false&&e.configured!==false&&e.lifecycle!==`ready`)),getGatewayRequestContext:x,deps:xe,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,openclawIdService:Be,gatewayComputerService:E,channelLogs:K,channelRuntimeEnvs:q,listStartupChannelGatewayMethods,listActiveGatewayMethods,bindHost:Y,controlUiRootLifecycle:ue,controlUiBasePath:X,resolvedAuth:ne,tailscaleConfig:re,tailscaleMode:ie,getResolvedAuth,resolveSharedGatewaySessionGenerationForConfig,resolveSharedGatewaySessionGenerationForRuntimeSnapshot,sharedGatewaySessionGenerationState:ae,initialHooksConfig:oe,initialHookClientIpConfig:se,authRateLimiter:ce,browserAuthRateLimiter:le,nodeReapprovalCoordinator:Q,terminalLaunchPolicy:fe,wizardRunner:he,channelWizardRunner:ge,wizardSessions:_e,findRunningWizard:ve,purgeWizardSession:ye,systemAgentSessions:be,deps:xe,runtimeStateRef:Se,cronStartState:Ce,gatewayTls:we,readinessEventLoopHealth:Ee,startupState:$,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:Ve.publish,stopPresencePublications:Ve.stop}}
//!src/gateway/startup-control-ui-origins.ts
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}}
//!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-qJc0YeSZ.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 withLiveStateReads(()=>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-BW_fgol_.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))},`runtime`);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-1Z19Xmtn.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-DfDqlvmM.mjs`));const{applyGatewayAuthOverridesForStartupPreflight:y,loadGatewayStartupConfigSnapshot:b}=await v;let x=await f.measure(`config.snapshot`,()=>b({minimalTestGateway:g,ambientEnvTriggers:_,log:i,measure:(e,t)=>f.measure(e,t),initialSnapshotRead:m}));const S=createMemberRolePresetActivation(i);if(await f.measure(`openclaw-id.member-roles`,()=>S.reconcile(isOpenClawIdEnabled(x.snapshot.config.gateway?.openclawId),x.snapshot.config)))x=await b({minimalTestGateway:g,ambientEnvTriggers:_,log:i,measure:(e,t)=>f.measure(e,t)});const C=x.snapshot;const w=r.auth?structuredClone(r.auth):void 0;const T=r.tailscale?structuredClone(r.tailscale):void 0;const E=g?{config:C.config,seededAllowedOrigins:false}:await f.measure(`control-ui.seed`,()=>maybeSeedControlUiAllowedOriginsAtStartup({config:C.config,log:i,runtimeBind:r.bind,runtimePort:n}));if(E.seededAllowedOrigins)copyConfigResolutionFacts(C.config,E.config);const D=E.seededAllowedOrigins?{...C,runtimeConfig:E.config,config:E.config}:C;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:O}=await v;const k=O({logSecrets:a,emitStateEvent:emitSecretsStateEvent,beforeSnapshotPublication:async e=>{const{publishCanonicalUserChannelPolicy:t}=await import(`./user-channel-identity-operations-H3Fg2KQ_.mjs`);await t(e?.gateway,e?.commands?.ownerAllowFrom)},...x.pluginMetadataSnapshot?{pluginMetadataSnapshot:x.pluginMetadataSnapshot}:{}});const A=C.sourceConfig;const j=captureConfigOverrideApplier()(D.config);f.setConfig(j);const{prepareGatewayStartupConfig:M}=await import(`./server-startup-config-helpers-DCAySTRj.mjs`);const N=await f.measure(`config.auth`,()=>M({configSnapshot:D,authOverride:w,tailscaleOverride:T,activateRuntimeSecrets:k,log:i,measure:(e,t,n)=>f.measure(e,t,n)}),{omitErrorMessage:true});const P=N.cfg;f.setConfig(P);if(!r.updateCanary)try{const e=await f.measure(`agents.github-profile-cleanup`,async()=>{const{cleanupRetiredManagedGitHubProfiles:e}=await import(`./github-tool-profile-cleanup-VDhNFYJ2.mjs`);return await e({config:P,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(N.generatedToken)i.warn(l());const F=P.gateway?.auth?.trustedProxy?.deviceAutoApprove;if(P.gateway?.auth?.mode===`trusted-proxy`&&F?.enabled===true&&F.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 I;let L;if(w){I={};L={};for(const e of[`mode`,`token`,`password`,`allowTailscale`,`rateLimit`,`trustedProxy`]){const t=w[e];if(t===void 0)continue;if((e===`token`||e===`password`)&&isSecretRef(t)){L[e]=structuredClone(t);continue}const n=P.gateway?.auth?.[e];if(n!==void 0)Object.assign(I,{[e]:structuredClone(n)})}}const R=N.generatedToken?mergeGatewayAuthConfig(I,{token:N.generatedToken}):I;setDiagnosticsEnabledForProcess(isDiagnosticsEnabled(P));setGatewayRestartPolicy({allowExternal:isRestartEnabled(P)});setPreRestartDeferralCheck(()=>createGatewayActiveWorkSnapshot().counts.totalActive);const z=E.seededAllowedOrigins?P.gateway?.controlUi?.allowedOrigins:void 0;const applyFixedGatewayOverlays=e=>{const t=y(e,{auth:N.generatedToken&&e.gateway?.auth?.mode===void 0?{mode:N.auth.mode,...R}:R,tailscale:T});if(!z||t.gateway?.controlUi?.allowedOrigins!==void 0||resolveControlUiAllowedOrigins(t).length>0)return t;const n={...t,gateway:{...t.gateway,controlUi:{...t.gateway?.controlUi,allowedOrigins:z}}};copyConfigResolutionFacts(t,n);return n};const applyReloadableGatewayAuthRefs=e=>L?.token||L?.password?y(e,{auth:L}):e;const prepareReloadCandidate=async e=>{const t=e.previousSourceConfig??getRuntimeConfigSourceSnapshot()??C.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(P,C.sourceConfig);applyLoggingConfig(P.logging);initializePublishedConfigRuntimeEnv(C.sourceConfig,{ownedEnv:collectConfigRuntimeEnvOwnership(C.sourceConfig,c,process.env),preserveExistingOwnership:true});if(!g&&!r.updateCanary){const{recoverConfiguredMcpDockerServers:e}=await import(`./mcp-docker-recovery-BmGWl2S4.mjs`);await e(P,x.pluginMetadataSnapshot?.manifestRegistry)}const B=[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-cgHyhAkt.mjs`);const t=await e(P);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-4nTzKdwr.mjs`);return e({cfg:P,env:process.env,log:i})})})(),f.measure(`plugins.bootstrap-imports`,()=>import(`./server-startup-plugins-BW2L989N.mjs`)),f.measure(`cron.store-path`,()=>resolveCronJobsStorePathFromConfigAsync(P))];await Promise.allSettled(B);const[V,H,{prepareGatewayPluginBootstrap:U},W]=await Promise.all(B);const G={current:void 0};const resolvePluginGatewayContext=()=>G.current;publishSystemEventStoreConfig(P);const K=await f.measure(`plugins.bootstrap`,async()=>{if(!r.updateCanary){const{initSubagentRegistry:e}=await import(`./subagent-registry-BP2GLmsn.mjs`);await e()}return U({cfgAtStart:P,activationSourceConfig:A,pluginMetadataSnapshot:x.pluginMetadataSnapshot,workerProviderIds:V?.durableProviderIds??[],minimalTestGateway:g,ambientEnvTriggers:_,log:i})});const{gatewayPluginConfigAtStart:q,defaultWorkspaceDir:J,pluginWorkspaceDir:Y,startupPluginIds:ee,pluginManifestRecords:X,pluginMetadataSnapshot:te,pluginLookUpTable:ne,baseMethods:re,ambientAutostartSuppressedChannelIds:ie}=K;copyConfigResolutionFacts(P,q);await setAppliedRuntimeConfigSnapshot(q,C.sourceConfig);const ae=listCoreGatewayMethodNames();const oe=getGatewayPluginMetadataSnapshot();const se=oe??te;if(oe)selectCurrentPluginMetadataCache(getPluginMetadataSnapshotCache(oe));else setGatewayPluginMetadataSnapshot(se,{config:A,compatibleConfigs:[j,P,q],env:process.env,workspaceDir:Y});if(ne){const e=ne.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:C,memberRolePresets:S,startupActivationSourceConfig:A,startupSessionDatabases:H,cronStorePath:W,cfgAtStart:P,generatedStartupAuthToken:N.generatedToken!==void 0,resolvedStartupAuthOverride:I,startupTailscaleOverride:T,applyFixedGatewayOverlays,prepareReloadCandidate,workerEnvironmentStartup:V,pluginGatewayContext:G,resolvePluginGatewayContext,pluginBootstrap:K,gatewayPluginConfigAtStart:q,defaultWorkspaceDir:J,pluginWorkspaceDir:Y,startupPluginIds:ee,pluginManifestRecords:X,pluginMetadataSnapshot:se,pluginLookUpTable:ne,baseMethods:re,ambientAutostartSuppressedChannelIds:ie,coreGatewayMethodNames:ae,activateRuntimeSecrets:k}}catch(e){t.e=e}finally{t.d()}}
//!src/gateway/server-kernel.ts
const loadGatewayModelCatalogModule=createLazyRuntimeModule(()=>import(`./server-model-catalog-BW8ifYXV.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-BY_U9tBy.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(` `)}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(createLegacyPluginSdkReplyDispatch());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-CkWDDB-R.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-Dqb5PfID.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-P77MN9KT.mjs`)).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]})}})}
//!src/gateway/session-file-preview-http.ts
async function handleSessionFilePreviewHttpRequest(e,t,n){const r=URL.parse(e.url??`/`,`http://localhost`);if(!r){respondPlainText(t,400,`Bad Request`);return true}if(!r.pathname.startsWith(`/__openclaw__/file-preview/`))return false;if(e.method!==`GET`&&e.method!==`HEAD`){t.setHeader(`Allow`,`GET, HEAD`);respondPlainText(t,405,`Method Not Allowed`);return true}const[i,a,...o]=r.pathname.slice(SESSION_FILE_PREVIEW_RESOURCE_PATH.length).split(`/`);const s=`${i}/${a}`;const c=resolveArtifactDownloadGrant(n,s);if(!c||c.grant.source.kind!==`preview`||o.length===0){respondNotFound(t);return true}const{client:l,grant:u,ticket:d}=c;const f=c.grant.source;const assertCurrent=()=>{const t=getRemoteControlUiIngressContext(e);assertRemoteControlUiIngressCurrent(t);if(t&&l.internal?.remoteIngressPrincipal?.assertCurrent!==t.resolvePrincipal().assertCurrent)throw new Error(`File preview belongs to another ingress grant`);assertArtifactDownloadGrantCurrent(n,l,d,u)};let p;try{assertCurrent();p=retainArtifactDownloadStream(n,l,d,u);const i=o.join(`/`)+r.search;if(i===f.documentPath){const n=getRemoteControlUiIngressContext(e);const r=buildSandboxHostDocument({blockDescendantFrames:true},n?[n.publicOrigin,...n.frameAncestors]:void 0);assertCurrent();for(const[e,n]of Object.entries(r.headers))t.setHeader(e,n);t.setHeader(`Cache-Control`,`private, no-store`);t.setHeader(`Content-Length`,Buffer.byteLength(r.html));t.end(e.method===`HEAD`?void 0:r.html);return true}const a=await f.read(i);assertCurrent();if(!a){respondNotFound(t);return true}t.setHeader(`Content-Type`,a.mimeType.startsWith(`text/`)?`${a.mimeType}; charset=utf-8`:a.mimeType);t.setHeader(`Content-Length`,a.body.byteLength);t.setHeader(`Cache-Control`,`private, no-store`);t.setHeader(`X-Content-Type-Options`,`nosniff`);t.setHeader(`Referrer-Policy`,`no-referrer`);t.setHeader(`Content-Security-Policy`,`default-src 'none'; sandbox`);t.end(e.method===`HEAD`?void 0:a.body)}catch{respondNotFound(t)}finally{p?.release()}return true}
//!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}function createSandboxHostHttpServer(e,t){const n=createSandboxHostHttpRequestHandler(t);const listener=(e,t)=>{n(e,t)};return e?createServer$2(e,listener):createServer(listener)}function createSandboxHostHttpRequestHandler(e){return async(t,n)=>{assertRemoteControlUiIngressCurrent(getRemoteControlUiIngressContext(t));if(e&&await handleSessionFilePreviewHttpRequest(t,n,e.clients))return;if(!handleMcpAppSandboxHttpRequest(t,n))respondPlainText(n,404,`Not Found`)}}
//!src/gateway/server-http-modules.ts
const getControlUiModule=createLazyRuntimeModule(()=>import(`./control-ui-DnqcM8jJ.mjs`));const loadControlUiAssistantMediaHandler=createLazyRuntimeNamedExport(()=>import(`./control-ui-assistant-media-http-Bm0I0BPd.mjs`),`handleControlUiAssistantMediaRequest`);function getControlUiAssistantMediaHandler(e,t){return(e?new URL(e,`http://localhost`):void 0)?.pathname===resolveAssistantMediaRoutePath(t)?loadControlUiAssistantMediaHandler():void 0}const getControlUiPluginAssetsModule=createLazyRuntimeModule(()=>import(`./control-ui-plugin-assets-Dj2RmlDn.mjs`));const getCanvasServeModule=createLazyRuntimeModule(()=>import(`./serve.runtime-BaY--SN5.mjs`));const getBoardHttpModule=createLazyRuntimeModule(()=>import(`./board-http-B1LiYY7i.mjs`));const getEmbeddingsHttpModule=createLazyRuntimeModule(()=>import(`./embeddings-http-ODqwC_Nv.mjs`));const getManagedMediaAttachmentsModule=createLazyRuntimeModule(()=>import(`./managed-image-attachments-BlvziMhk.mjs`));const getArtifactDownloadsModule=createLazyRuntimeModule(()=>import(`./artifact-downloads-CnxVkLfQ.mjs`));const getMcpAppStandaloneModule=createLazyRuntimeModule(()=>import(`./mcp-app-standalone-CwVxjD4m.mjs`));const getModelsHttpModule=createLazyRuntimeModule(()=>import(`./models-http-BqIc0-dW.mjs`));const getOpenAiHttpModule=createLazyRuntimeModule(()=>import(`./openai-http-CuxG1jSD.mjs`));const getOpenResponsesHttpModule=createLazyRuntimeModule(()=>import(`./openresponses-http-Ddn0854B.mjs`));const getSessionHistoryHttpModule=createLazyRuntimeModule(()=>import(`./sessions-history-http-DY-nh2y5.mjs`));const getSessionKillHttpModule=createLazyRuntimeModule(()=>import(`./session-kill-http-ZwEs4wD5.mjs`));const getToolsInvokeHttpModule=createLazyRuntimeModule(()=>import(`./tools-invoke-http-B-QWVj2U.mjs`));const getBrowserPairHttpModule=createLazyRuntimeModule(()=>import(`./browser-pair-http-DUpCNMHY.mjs`));const getDevicePairingJoinHttpModule=createLazyRuntimeModule(()=>import(`./device-pairing-join-http-BtOURmPT.mjs`));const getPluginNodeCapabilityAuthModule=createLazyRuntimeModule(()=>import(`./plugin-node-capability-auth-OcXdg_WB.mjs`));const getHttpAuthUtilsModule=createLazyRuntimeModule(()=>import(`./http-auth-utils-CiPjIg2A.mjs`));const getPluginRouteRuntimeScopesModule=createLazyRuntimeModule(()=>import(`./plugin-route-runtime-scopes-3qYo1Gpi.mjs`));const getNativeHookRelayModule=createLazyRuntimeModule(()=>import(`./native-hook-relay-http-BOQe9eDF.mjs`));
//!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 `;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}}async function resolveBundledChannelGatewayAuthBypassPaths(e){return((await loadChannelGatewayAuthApi(e.channelId))?.resolveGatewayAuthBypassPaths?.({cfg:e.cfg})??[]).flatMap(e=>typeof e===`string`&&e.trim()?[e.trim()]:[])}
//!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)}
//!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}}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(!readGatewayIngressTransport(s))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,trustedProxy:f().trustedProxy,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){rejectWebSocketUpgrade(p,{status:C.scopedPath?400:401});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-D-RievFt.mjs`);assertRemoteControlUiIngressCurrent(h);e(s,p,m);return}const{handleDesktopObserveUpgrade:t}=await import(`./observe-bridge-Cteupf99.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}
//!src/gateway/browser-pair-route.ts
function parseBrowserPairRequestPath(e,t){const n=`${t}${BROWSER_PAIR_ROUTE_PREFIX}/`;if(!e.startsWith(n))return null;const r=e.slice(n.length);return r===`start`||r===`collect`||r===`cancel`?r:null}
//!src/gateway/control-ui-image-http-routes.ts
const CONTROL_UI_IMAGE_HTTP_ROUTES=[[[`providerIcon`],createLazyRuntimeNamedExport(()=>import(`./provider-icon-http-ByAvNviE.mjs`),`handleProviderIconHttpRequest`)],[[`pluginIcon`,`pluginActivityIcon`,`catalogIcon`,`linkFavicon`],createLazyRuntimeNamedExport(()=>import(`./plugin-icon-http-C5bhyV2N.mjs`),`handlePluginIconHttpRequest`)],[[`pluginThemeArt`],createLazyRuntimeNamedExport(()=>import(`./plugin-theme-art-http-C5NVlTFb.mjs`),`handlePluginThemeArtHttpRequest`)],[[`workspaceIcon`],createLazyRuntimeNamedExport(()=>import(`./workspace-icon-http-B0kDiKfE.mjs`),`handleWorkspaceIconHttpRequest`)],[[`channelAvatar`],createLazyRuntimeNamedExport(()=>import(`./channel-avatar-http-yZmc2GO_.mjs`),`handleChannelAvatarHttpRequest`)]];const CONTROL_UI_USER_IMAGE_HTTP_ROUTES=[[parseControlUiUserBackgroundPath,createLazyRuntimeNamedExport(()=>import(`./user-background-http-D6K0voZI.mjs`),`handleUserBackgroundHttpRequest`)],[parseControlUiUserAvatarPath,createLazyRuntimeNamedExport(()=>import(`./user-profiles-http-DQoeG1iq.mjs`),`handleUserProfileAvatarHttpRequest`)]];
//!src/gateway/control-ui-public-session-cache.ts
const MAX_ENTRIES=128;const MAX_BYTES=16777216;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()}}}
//!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)}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}}}}}
//!src/gateway/control-ui-session-routes.ts
let publicSessionModule;function isControlUiPublicSessionPath(e,t){return e===`${t}/share/session`||e===`${t}/share/session/card.png`}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-Cdw16xQw.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-BRLvn0G9.mjs`));const d={pullRequests:e.getGatewayRequestContext?.()?.controlUiSessionPullRequests,render:async e=>{r??=import(`./control-ui-public-session-card-CfVBcAvg.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-B5514wlw.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-DXG0imec.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-Dhot0B-O.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-BRLvn0G9.mjs`))).serveControlUiPublicChat({...n,basePath:t,projection:l,gate:publicGate(),serveApp});return(await import(`./control-ui-session-entry-CqVFb5UH.mjs`)).serveControlUiSessionEntry({...n,basePath:t,projection:l,agentDatabaseStartup:c?.agentDatabaseStartup,serveApp})}}}
//!src/gateway/server-http-probes.ts
function startupProbeBody(e,t,n=false){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}:{},...n&&e.status===`started`?{gatewayBootId:e.gatewayBootId}:{}})}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`){const t=readPreparedGatewayIngressAttribution(e);async function shouldIncludeGatewayProbeDetails(){if(t?.kind===`direct-local`||!t&&isLocalDirectRequest(e))return true;if(r.mode===`none`)return false;const{getBearerToken:n,resolveHttpBrowserOriginPolicy:s}=await getHttpAuthUtilsModule();const c=n(e);return(await authorizeHttpGatewayConnect({auth:r,connectAuth:c?{token:c,password:c}:null,req:e,trustedProxies:i,allowRealIpFallback:a,rateLimiter:o,browserOriginPolicy:s(e)})).ok}const n=l===`ready`?s:void 0;const u=await shouldIncludeGatewayProbeDetails();try{if(n){const e=n();d=e.ready?200:503;const t=u?getGatewayRecentCrashes():[];f=JSON.stringify(u?{...e,...t.length?{recentCrashes:t}:{}}:{ready:e.ready})}else{const n=c?.()??{ok:true,status:`started`,uptimeMs:0};d=n.ok?200:503;f=startupProbeBody(n,u,e.url===`/startupz`&&e.headers[`x-openclaw-startup-boot-id`]===`1`&&t?.kind===`direct-local`&&isLoopbackAddress(e.socket.localAddress)&&isLoopbackHost(resolveHostName(e.headers.host))&&!isTrustedProxyAddress(t.clientIp,i)&&!hasGatewayProxyIdentityHeaders(e,r.trustedProxy)&&!hasGatewayDelegationClaim(e,r.trustedProxy?.userHeader)&&e.headers.origin===void 0&&e.headers.authorization===void 0&&e.headers[`proxy-authorization`]===void 0&&e.headers.cookie===void 0)}}catch{d=503;f=n?JSON.stringify(u?{ready:false,coreReady:false,failing:[`internal`],uptimeMs:0}:{ready:false}):startupProbeBody({ok:false,status:`starting`,uptimeMs:0,pendingReason:`internal`},u)}}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}
//!src/gateway/server-http-request.ts
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=normalizeControlUiBasePath(n);const g=controlUiPluginAssetRoot(h);const _=createControlUiSessionRoutes(e);const handleServerRequest=(t,n,r)=>{if(!readGatewayIngressTransport(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`);if(!b){sendGatewayAuthFailure(y,{ok:false,reason:`unauthorized`});return}const S=b.pathname;if(isControlUiSharePath(S,h))y.setHeader(`X-Robots-Tag`,`noindex, nofollow`);const C=x?resolveRemoteControlUiHttpRoute(v,h,x.resolvePrincipal().scopes):void 0;if(x&&!C){respondNotFound(y);return}const w=classifyGatewayProbePath(S);if(w===`live`){await handleGatewayProbeRequest(v,y,S,c,[],false,l,d,f);return}const T=w===`outside`?f?.():void 0;if(T&&T.status!==`started`&&(!x||C===`document`)){const{serveControlUiStartupRequest:t}=await import(`./control-ui-availability-y4LNF0pe.mjs`);if(await t(v,y,T,b,e))return}if(w===`outside`||w===`namespace`)await e.waitForRequestRuntime?.();const E=m();const D=e.controlUiEnabled??E.gateway?.controlUi?.enabled??true;const O=E.gateway?.http?.endpoints?.chatCompletions;const k=E.gateway?.http?.endpoints?.responses;const A=e.openAiChatCompletionsEnabled??O?.enabled??false;const j=e.openResponsesEnabled??k?.enabled??false;const M=A||j;const N=E.gateway?.trustedProxies??[];const P=E.gateway?.allowRealIpFallback===true;const F=prepareGatewayIngressAttribution({req:v,trustedProxies:N,trustedProxy:p().trustedProxy,allowRealIpFallback:P,tailscaleWhois:e=>readTailscaleWhoisIdentity(e,void 0,{cacheTtlMs:0,errorTtlMs:0})});const I=normalizePluginNodeCapabilityScopedUrl(v.url??`/`);if(I.malformedScopedPath){respondPlainText(y,400,`Bad Request`);return}if(I.rewrittenUrl)v.url=I.rewrittenUrl;const L=I.pathname;const R=resolvePluginRoutePathContext(L);const z=s?.(R);const B=p();if(!x&&(F.kind!==`unattributable-proxy`||isTrustedProxyAddress(F.remoteAddress,N))&&await handleGatewayProbeRequest(v,y,L,B,N,P,l,d,f))return;if(F.kind===`unattributable-proxy`){e.reportUnattributableProxy?.(F);if(!z&&a&&e.isPluginAuthenticatedRoute?.(R)&&await a(v,y,R,{gatewayRequestClientIp:F.remoteAddress}))return;sendGatewayAuthFailure(y,{ok:false,reason:F.reason});return}const V=F.clientIp;const H={auth:B,cfg:E,getRuntimeConfig:m,getResolvedAuth:p,trustedProxies:N,allowRealIpFallback:P,rateLimiter:l};const operatorAuth=()=>({...H,resolveGatewayContext:e.getGatewayRequestContext?.()?.resolveGatewayContext});const U={basePath:n,config:E,...H};const loadControlUi=()=>isControlUiHttpRequest(v,h)?getControlUiModule():void 0;const handleControlUiRequest=async()=>(await loadControlUi())?.handleControlUiHttpRequest(v,y,{...U,terminalEnabled:e.isTerminalEnabled?.()??isTerminalConfigEnabled(E),agentId:resolveAssistantAgentId(E),root:r})??false;const handleStandaloneControlUiRequest=async()=>{if(!D||!await handleControlUiRequest())respondNotFound(y);return true};const W=[];const addRequestStage=(e,t,n=false,r)=>{if(e&&(!x||r===C))W.push(n?()=>runWithGatewayHttpWorkAdmission(y,t):t)};const addAdmittedStage=(e,t,n)=>addRequestStage(e,t,true,n);addRequestStage(classifyWorkerGatewayPath(L)!==`outside`,()=>{respondNotFound(y);return true});const G={req:v,res:y,clientIp:F.rateLimit.subject.key,rateLimiter:u};addAdmittedStage(L.startsWith(`/__openclaw__/native-hook`),async()=>(await getNativeHookRelayModule()).handleNativeHookRelayHttpRequest(G));addAdmittedStage(classifyWorkerBootstrapArtifactTransferPath(L)!==`outside`,()=>handleArtifactTransferHttpRequest({classifyPath:classifyWorkerBootstrapArtifactTransferPath,routePrefix:`${WORKER_BOOTSTRAP_ARTIFACT_TRANSFER_PATH}/artifacts/`,...G,callback:e.handleWorkerBootstrapArtifactTransferRequest}));addAdmittedStage(classifyNodeWorkerBundleTransferPath(L)!==`outside`,()=>handleArtifactTransferHttpRequest({classifyPath:classifyNodeWorkerBundleTransferPath,routePrefix:`${NODE_WORKER_BUNDLE_TRANSFER_PATH}/bundles/`,...G,callback:e.handleNodeWorkerBundleTransferRequest}));addAdmittedStage(classifyNodeWorkspaceTransferPath(L)!==`outside`,()=>handleNodeWorkspaceTransferHttpRequest({...G,callback:e.handleNodeWorkspaceTransferRequest}));const K=parseDevicePairingJoinRequestPath(L);if(K!==null)addAdmittedStage(true,async()=>(await getDevicePairingJoinHttpModule()).handleDevicePairingJoinHttpRequest({...G,shortcode:K}));const q=D?parseBrowserPairRequestPath(L,h):null;if(q)addAdmittedStage(true,async()=>(await getBrowserPairHttpModule()).handleBrowserPairHttpRequest({...G,action:q,config:E}));addAdmittedStage(L===PROVIDER_OAUTH_CALLBACK_PATH,()=>handleProviderOAuthCallback(v,y));addAdmittedStage(L.startsWith(`/api/artifacts/download/`)||h.length>0&&L.startsWith(`${h}${`/api/artifacts/download/`}`),async()=>(await getArtifactDownloadsModule()).handleArtifactDownloadHttpRequest(v,y,{clients:t,basePath:h}),`artifact`);addAdmittedStage(v.method===`GET`&&L===`/oauth/mcp/callback`&&Boolean(e.handleMcpOAuthCallbackRequest),()=>e.handleMcpOAuthCallbackRequest?.(v,y)??false);addRequestStage(true,()=>i(v,y));addAdmittedStage(Boolean(e.handleWatchNodeRequest)&&L.startsWith(`/api/nodes/watch/`),()=>e.handleWatchNodeRequest?.(v,y)??false);addAdmittedStage(M&&(L===`/v1/models`||L.startsWith(`/v1/models/`)),async()=>(await getModelsHttpModule()).handleOpenAiModelsHttpRequest(v,y,H));addAdmittedStage(M&&L===`/v1/embeddings`,async()=>(await getEmbeddingsHttpModule()).handleOpenAiEmbeddingsHttpRequest(v,y,H));addAdmittedStage(L===`/tools/invoke`,async()=>(await getToolsInvokeHttpModule()).handleToolsInvokeHttpRequest(v,y,operatorAuth()));addAdmittedStage(/^\/sessions\/[^/]+\/kill$/.test(L),async()=>(await getSessionKillHttpModule()).handleSessionKillHttpRequest(v,y,H));addAdmittedStage(/^\/sessions\/[^/]+\/history$/.test(L),async()=>(await getSessionHistoryHttpModule()).handleSessionHistoryHttpRequest(v,y,{...H,getCommittedRuntimeConfig:()=>e.getGatewayRequestContext?.()?.getCommittedRuntimeConfig?.()??m()}));addAdmittedStage(L.startsWith(`/__openclaw__/board/`),async()=>(await getBoardHttpModule()).handleBoardHttpRequest(v,y,{resolveGatewayContext:e.getGatewayRequestContext?.()?.resolveGatewayContext}),`board`);addAdmittedStage(L.startsWith(g),async()=>{if(!D){respondNotFound(y);return true}return await(await getControlUiPluginAssetsModule()).handleControlUiPluginAssetRequest(v,y,U)},`native-assets`);for(const[e,t]of CONTROL_UI_USER_IMAGE_HTTP_ROUTES)addAdmittedStage(e(L,h).matched,async()=>(await t())(v,y,L,{...H,basePath:h}),`resource`);addAdmittedStage(j&&L===`/v1/responses`,async()=>(await getOpenResponsesHttpModule()).handleOpenResponsesHttpRequest(v,y,{...operatorAuth(),config:k}));addAdmittedStage(A&&L===`/v1/chat/completions`,async()=>(await getOpenAiHttpModule()).handleOpenAiHttpRequest(v,y,{...operatorAuth(),config:O}));const J=isControlUiApprovalDocumentPath({basePath:n,pathname:L});const Y=isControlUiFocusPath(L,n);const ee=_.matches(L,v.url);addRequestStage(!D&&ee,()=>_.reject(y));addAdmittedStage(D&&ee,()=>_.serve({...H,req:v,res:y,config:E,ingress:F}));addRequestStage(J||isControlUiSharePath(L,h)&&!ee,handleStandaloneControlUiRequest);addRequestStage(Boolean(z),async()=>{const{authorizePluginNodeCapabilityRequest:e}=await getPluginNodeCapabilityAuthModule();const n=await e({req:v,auth:B,trustedProxies:N,allowRealIpFallback:P,clients:t,nodeCapability:z,capability:I.capability,rateLimiter:l});if(!n.ok){sendGatewayAuthFailure(y,n);return true}return false});addRequestStage(Boolean(z)&&isCoreCanvasHostEnabled(E)&&isCanvasDocumentHttpPath(L),async()=>(await getCanvasServeModule()).handleCanvasDocumentHttpRequest(v,y));addRequestStage(D&&isControlUiPluginManagerRequest({basePath:n,pathname:L,method:v.method}),handleControlUiRequest,false,`document`);const X=classifyMcpAppStandalonePath(L);addAdmittedStage(E.mcp?.apps?.enabled===true&&(X===`shell`||X===`view`),async()=>{return await(await getMcpAppStandaloneModule()).handleMcpAppStandaloneHttpRequest(v,y,{sandboxPort:E.mcp?.apps?.sandboxPort,sandboxOrigin:E.mcp?.apps?.sandboxOrigin})});if(a&&(!x||C===`plugin-panel`)){let e=null;W.push(async()=>{if(!x&&(!(o??shouldEnforceDefaultPluginGatewayAuth)(R)||(await getCachedPluginGatewayAuthBypassPaths(E)).has(L)))return false;const{authorizePluginGatewayHttpRequestOrReply:t}=await getHttpAuthUtilsModule();const{resolvePluginRouteRuntimeOperatorScopes:n}=await getPluginRouteRuntimeScopesModule();e=await t({req:v,res:y,...H,requestPath:L,resolveOperatorScopes:n});return!e},()=>{if(e?.requestAuth.hasCurrentClientAuthority?.()===false){sendGatewayAuthFailure(y,{ok:false,reason:`unauthorized`});return true}return a(v,y,R,{gatewayAuthSatisfied:e!==null,gatewayRequestAuth:e?.requestAuth,gatewayRequestOperatorScopes:e?.operatorScopes,gatewayRequestClientIp:V})})}addRequestStage(Y,handleStandaloneControlUiRequest,false,`document`);addRequestStage(L.startsWith(`/api/chat/media/outgoing/`)||h.length>0&&L.startsWith(`${h}/api/chat/media/outgoing/`),async()=>(await getManagedMediaAttachmentsModule()).handleManagedOutgoingMediaHttpRequest(v,y,{...H,basePath:h,clients:t}),false,`outgoing-media`);for(const[t,n]of CONTROL_UI_IMAGE_HTTP_ROUTES)addRequestStage(D&&t.some(e=>parseControlUiResourcePath(e,L,h).matched),async()=>(await n())(v,y,{...U,sessionRowProjectionOwner:e.getGatewayRequestContext?.()?.sessionRowProjectionOwner}),false,`resource`);addRequestStage(L===resolveAssistantMediaRoutePath(n),async()=>(await getControlUiAssistantMediaHandler(v.url,n))?.(v,y,{...U,agentId:resolveAssistantAgentId(E)})??false,false,`assistant-media`);addRequestStage(D,async()=>(await loadControlUi())?.handleControlUiAvatarRequest(v,y,U)??false,false,`resource`);addRequestStage(D,handleControlUiRequest,false,`document`);for(const e of W){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}if(e.isChannelAutostartSuppressed?.()===true){y.setHeader(`Cache-Control`,`no-store`);y.setHeader(`Retry-After`,`1`);respondPlainText(y,503,`Channel autostart is suppressed by crash-loop safe mode`);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()})}
//!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());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}
//!src/gateway/server/plugin-legacy-listeners.ts
const endpointKey=({host:e,port:t})=>`${e??`<unspecified>`}:${t}`;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();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}
//!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)}}}
//!src/gateway/server-runtime-state.ts
const loadGatewayPluginsHttpModule=async()=>await import(`./plugins-http-DCCpHtb7.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}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-DvJ-CQBB.mjs`);return a??=runWithSpawnBroker(t,()=>n(()=>r({deps:e.deps,logHooks:e.logHooks,deferHookWake:e.deferHookWake,resolvePluginRegistry:resolvePluginRouteRegistry,...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-DvJ-CQBB.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-DLyyB9Kz.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.updateCanary&&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,isRequestRuntimeReady:e.isRequestRuntimeReady,isStartupPluginRuntimeReady:e.isStartupPluginRuntimeReady,isChannelAutostartSuppressed:e.isChannelAutostartSuppressed,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({clients:e.clients}),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,{clients:e.clients}));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)}}
//!src/gateway/openclaw-id/people-events.ts
function startOpenClawIdPeopleEvents(e){let t=false;const publish=async()=>{const n=await Promise.all([...e.clients].map(async t=>({client:t,currentOwner:await e.service.prepareOwnerClientCheck(resolveOpenClawIdClientChannel(t),resolveOpenClawIdClientPeerKey(t))})));if(t)return;const r=new Set(n.filter(({client:t,currentOwner:n})=>e.clients.has(t)&&!t.invalidated&&t.connectionKind!==`worker`&&!t.connectionSignal?.aborted&&(t.connect.role??`operator`)===`operator`&&authorizeOperatorScopesForMethod(`openclawId.people`,t.connect.scopes??[]).allowed&&n()).map(({client:e})=>e.connId));if(r.size>0)e.broadcastToConnIds(GATEWAY_EVENT_ID_PEOPLE_CHANGED,{},r)};const changed=()=>{publish().catch(t=>e.log.warn(`openclaw-id: People invalidation failed: ${String(t)}`))};const n=[e.service.onPeopleChanged(changed),e.clients.subscribeChanges(changed),onGatewayWorkMetricsChanged(changed)];return{stop:()=>{t=true;n.forEach(e=>e())}}}
//!src/gateway/openclaw-id/start-runtime-effects.ts
function startOpenClawIdRuntimeEffects({service:e,clients:t,context:n,log:r}){e.bindEffects(async()=>{const[{createOpenClawIdRemovalEffects:e},{createOpenClawIdMemberActivity:i}]=await Promise.all([import(`./removal-effects-D1JgFjs4.mjs`),import(`./member-activity-DUkuuljY.mjs`)]);return{...e({clients:()=>t.authorityClients,context:()=>n,log:r}),describeActivity:i({clients:()=>t}).describe}});e.reconcileRuntimePolicy().catch(e=>r.warn(`openclaw-id: start failed: ${String(e)}`))}
//!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`)}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,verifyIntegrity:e=>runWithSpawnBroker(t,async()=>{const{verifyAgentDatabaseStartupIntegrity:t}=await import(`./agent-database-startup-verification-C34GBYc1.mjs`);await t({...e,assertCurrent:e.configurationBound?createPreparationGuard(e.agentId,e.paths,e.env,e.signal,e.assertCurrent):e.assertCurrent})}),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-BaQEgQEk.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-4nTzKdwr.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();const{prepareAgentRestartRecovery:u}=await import(`./session-restart-resume-BxpIDUOk.mjs`);return{recoverInputs:await u({context:e.context,agentId:n,env:i,signal:a,assertCurrent:c,log:e.log}),maintain:()=>runWithSpawnBroker(t,async()=>{await e.waitForPostReadyWork();const{runGatewaySessionStartupMaintenance:t}=await import(`./server-startup-session-migration-4nTzKdwr.mjs`);await t({databases:l,signal:a,assertCurrent:createPreparationGuard(n,r,i,a,()=>a.throwIfAborted()),log:e.log});a.throwIfAborted();e.scheduleSessionFactsBackfill?.(l)})}}),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-CkWDDB-R.mjs`),import(`./prepared-model-runtime.configured-CWm1wUAt.mjs`),import(`./runtime-86Oj5trK.mjs`),import(`./runtime-snapshots-DFTHm7Wx.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)}})})}
//!src/gateway/server-tls-renewal.ts
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()}}}
//!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))}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)}
//!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:se,registerConnectionDependentSidecars:Z,unregisterConnectionDependentSidecar:ce,chatMetadataLifecycle:le,gatewayRequestContext:Q,getPluginMetadataSnapshot:ue,getPluginNodeCapabilities:de}=t;const fe=getAgentDatabaseStartupAdmission();const pe=createDeferredCore();const me=d||r.updateCanary?void 0:(await import(`./server-startup-session-migration-4nTzKdwr.mjs`)).createGatewaySessionFactsBackfillScheduler({scheduler:t.scheduler,signal:t.connectionWork.signal,waitForReady:()=>m.startupMethodsReady,log:i});const he=t.createHttpTransportOptions().getReadiness;const{attachGatewayWsConnectionHandler:ge}=await h.measure(`gateway.ws-imports`,()=>import(`./ws-connection-BvHUFsip.mjs`));await h.measure(`gateway.ws-attach`,()=>ge({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:de,getResolvedAuth:M,gatewayExposure:{bindHost:j,tailscaleMode:t.tailscaleMode},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:Q.refreshHealthSnapshot,buildRequestContext:()=>Q}));await h.measure(`http.listen`,()=>t.startListening());h.mark(`http.bound`);const _e=t.ensureRequestRuntimeReady().then(()=>{flushDiagnosticsTimeline();m.setDispatchReady(true);if(fe&&!r.updateCanary&&!E.closePreludeStarted)activateGatewayAgentDatabaseStartup({admission:fe,context:Q,preparationReady:pe.promise,waitForPostReadyWork:e.waitForPostReadyWork,scheduleSessionFactsBackfill:me,getConfig:readRuntimeConfig,getPluginRegistry:()=>O.registry,getPluginMetadataSnapshot:ue,isCurrent:()=>!E.closePreludeStarted,log:i})});const ve=t.startEarlyRuntime();await Promise.allSettled([_e,ve]);await _e;const ye=await ve;const be=Date.now();let xe=false;let Se=false;const activateScheduledServicesWhenReady=()=>{if(r.updateCanary||E.closePreludeStarted||!xe||!D.sidecarsReady||Se)return;Se=true;import(`./server-runtime-services-BO_Vqn5E.mjs`).then(e=>{if(E.closePreludeStarted)return;const n=e.activateGatewayScheduledServices({scheduler:t.scheduler,minimalTestGateway:d,cfgAtStart:K,deps:f,sessionDeliveryRecoveryMaxEnqueuedAt:be,log:i,resolveGatewayContext:k});m.setScheduledServiceHandles(n)})};const{startGatewayActiveWork:Ce}=await h.measure(`gateway.active-work-import`,()=>import(`./server-work-metrics-DDAaGE3u.mjs`));const we=Ce(t,i);const trackStartupWork=e=>{const n=Promise.resolve().then(()=>e(t.connectionWork.signal));return t.connectionWork.track(()=>n)};let Te=false;let Ee=false;const $=await trackStartupWork(()=>h.measure(`runtime.post-attach`,()=>import(`./server-startup-post-attach-Dmj4sf84.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:Q.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:Q.resolveGatewayContext,logHooks:s,logChannels:c,unlockStartupMethods:m.unlockStartupMethods,refreshChatMetadata:le.refresh,loadStartupPlugins:async()=>{const{loadGatewayStartupPluginRuntime:e}=await import(`./server-startup-plugins-BW2L989N.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(de());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:se,trackStartupWork,unregisterConnectionDependentSidecar:ce,startWorkerEnvironmentRuntime:async()=>{if(E.closePreludeStarted)return null;if(b)await startWorkerHumanPresence({clients:v,service:b,log:i,registerSidecar:se});pe.resolve();return x?await x.startRuntime({startupTrace:h,isClosePreludeStarted:()=>E.closePreludeStarted,registerSidecar:Z,unregisterSidecar:ce}):null},onSidecarsReady:()=>{Ee=true;if(G===`defer`||Te)m.markSidecarsReady();activateScheduledServicesWhenReady()},getReadiness:he,isClosing:()=>E.closePreludeStarted,startupTrace:h,sidecarStartup:G,waitForPostReadyWork:e.waitForPostReadyWork,activeWorkInspectors:we}))));flushDiagnosticsTimeline();Te=true;if(Ee&&G!==`defer`)m.markSidecarsReady();m.setPostAttachHandles($);if(d)pe.resolve();h.detail(`memory.ready`,[...collectGatewayProcessMemoryUsageMb(),...d?[]:await h.measure(`runtime.worker-pool-metrics`,collectGatewayWorkerPoolMetrics)]);const De=await he.prepare();if(!E.closePreludeStarted&&De.publish().ready){h.mark(`ready`);i.info(r.updateCanary?`candidate gateway ready; autonomous sidecars suppressed`:`gateway ready`)}finishGatewayRestartTrace(`restart.ready`,collectGatewayProcessMemoryUsageMb());if(r.updateCanary)return{startupSettled:$.startupSettled};xe=true;activateScheduledServicesWhenReady();se(startOpenClawIdPeopleEvents({clients:v,service:t.openclawIdService,broadcastToConnIds:_,log:i}));startOpenClawIdRuntimeEffects({service:t.openclawIdService,clients:v,context:Q,log:i});const{startManagedGatewayConfigReloader:Oe}=await import(`./server-reload-managed-qZzcSKYq.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 ke=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(ke)se(ke);let Ae=controlUiPluginPolicyKey(I);const je={scheduler:t.scheduler,onReloadEnabledChange:ke?.setEnabled,configRevisionProjector:Q.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:ue,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:Q,nodeSession:n});t.openclawIdService.reconcileRuntimePolicy().catch(e=>{u.warn(`OpenClaw ID policy reconciliation failed: ${String(e)}`)});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=controlUiPluginPolicyKey(e);if(t!==Ae){const{listControlUiPluginCatalog:e}=await import(`./control-ui-plugin-assets-Dj2RmlDn.mjs`);const n=await e();g(`plugins.controlUi.changed`,{revision:n.revision});Ae=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:$.startupSettled};const Me=Oe(je);m.setConfigReloaderHandle(Me);await Me.ready;if(E.closePreludeStarted)return{startupSettled:$.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-BO_Vqn5E.mjs`);n.scheduleGatewayPostReadyMaintenance({scheduler:t.scheduler,signal:t.connectionWork.signal,delayMs:POST_READY_MAINTENANCE_DELAY_MS,isClosing:()=>E.closePreludeStarted,waitForPostReadyWork:e.waitForPostReadyWork,startupMaintenance:t,scheduleSessionFactsBackfill:me,startMaintenance:()=>ye.startMaintenance(we,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])??[]];se(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-C-7iPZ_n.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`}))}else h.detail(`memory.post-ready`,collectGatewayProcessMemoryUsageMb());return{startupSettled:$.startupSettled}}
//!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(createLegacyPluginSdkReplyDispatch());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-BMKZwmC3.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}}}export{startGatewayServerCore};