akanjs 3.2.0-rc.8 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +41 -38
- package/CHANGELOG.md +0 -679
- package/CONTRIBUTING.md +3 -0
- package/base/base.ts +2 -1
- package/client/clientRuntime.ts +1 -0
- package/client/cn.ts +2 -2
- package/client/csrTypes.ts +2 -0
- package/client/frameConfig.ts +1 -0
- package/client/index.ts +249 -26
- package/client/locale.ts +1 -0
- package/client/makePageProto.tsx +12 -85
- package/client/nativeThemeColor.ts +51 -0
- package/client/route/PageDefinition.ts +11 -3
- package/client/route/RouteDefinition.ts +24 -7
- package/client/route/RouteGuards.ts +2 -1
- package/client/route/RouteHead.ts +4 -1
- package/client/route/routeArgs.ts +8 -0
- package/client/router.ts +17 -2
- package/client/rscNavigation.ts +1 -0
- package/client/viewportMeta.ts +86 -6
- package/common/CodeTranscript.ts +1 -1
- package/common/Logger.ts +4 -2
- package/common/PipelinePlanSchema.ts +2 -2
- package/common/clientAddress.ts +14 -0
- package/common/err.ts +122 -0
- package/common/eventStream.ts +71 -19
- package/common/facetBarrel.ts +38 -0
- package/common/index.ts +7 -0
- package/common/isGuardRefusal.ts +14 -0
- package/common/loggedFailure.ts +11 -0
- package/common/mcpExposure.ts +17 -4
- package/common/pipelinePlan.ts +1 -1
- package/common/routeConvention.ts +3 -1
- package/common/types.ts +18 -1
- package/constant/constantRegistry.ts +4 -8
- package/constant/crystalize.ts +1 -2
- package/constant/getDefault.ts +1 -1
- package/constant/immerify.ts +1 -1
- package/constant/index.ts +78 -21
- package/constant/purify.ts +4 -9
- package/constant/serialize.ts +4 -2
- package/constant/types.ts +1 -0
- package/constant/via.ts +1 -2
- package/dictionary/agent.dictionary.ts +12 -0
- package/dictionary/base.dictionary.ts +11 -0
- package/dictionary/locale.ts +1 -1
- package/dictionary/trans.ts +14 -97
- package/document/dataLoader.ts +39 -19
- package/document/databaseRegistry.ts +2 -1
- package/document/documentSchema.ts +1 -0
- package/document/filterMeta.ts +4 -1
- package/document/into.ts +2 -1
- package/document/loaderInfo.ts +2 -1
- package/document/noDocumentError.ts +4 -1
- package/document/queryEvaluator.ts +1 -1
- package/document/types.ts +1 -1
- package/fetch/client/fetchClient.ts +83 -269
- package/fetch/client/fetchClientTypes.ts +49 -0
- package/fetch/client/httpClient.ts +3 -2
- package/fetch/client/remoteError.ts +4 -20
- package/fetch/client/requestScope.ts +41 -0
- package/fetch/client/signalCatalog.ts +131 -0
- package/fetch/client/wsClient.ts +82 -6
- package/fetch/requestStorage.ts +1 -0
- package/package.json +1 -1
- package/server/agentHooks.ts +16 -0
- package/server/akanApp.ts +110 -1272
- package/server/akanOption.ts +30 -3
- package/server/akanServer.ts +179 -674
- package/server/artifact/builderRpc.ts +14 -6
- package/server/artifact/routeSeedIndexStore.ts +4 -2
- package/server/assetHeaders.ts +6 -0
- package/server/console.ts +6 -4
- package/server/decorators.ts +2 -2
- package/server/di/diLifecycle.ts +24 -35
- package/server/di/predefinedAdaptor.ts +24 -1
- package/server/di/resolveHierarchy.ts +19 -6
- package/server/di/stageFailedError.ts +10 -0
- package/server/di/utils.ts +8 -3
- package/server/ed25519Key.ts +31 -15
- package/server/flightRowReader.ts +106 -20
- package/server/gateway/childSupervisor.ts +328 -0
- package/server/gateway/devHostChannel.ts +47 -0
- package/server/gateway/gatewayChildren.ts +161 -0
- package/server/gateway/gatewayConfig.ts +182 -0
- package/server/gateway/gatewayHttpProxy.ts +231 -0
- package/server/gateway/gatewayLogging.ts +111 -0
- package/server/gateway/gatewayRooms.ts +141 -0
- package/server/gateway/gatewayStatus.ts +122 -0
- package/server/gateway/gatewayStatusPage.ts +54 -0
- package/server/gateway/gatewayWebSocketRelay.ts +149 -0
- package/server/gateway/listeningPort.ts +13 -0
- package/server/hmr/devHmrController.ts +10 -1
- package/server/htmlResultCache.ts +234 -0
- package/server/imageOptimizer.ts +4 -1
- package/server/index.ts +281 -17
- package/server/lifecycle/parentChannel.ts +79 -0
- package/server/lifecycle/shutdownManager.ts +6 -3
- package/server/lifecycle/startGuard.ts +90 -0
- package/server/logging/hubFileSink.ts +1 -0
- package/server/logging/logControlSocket.ts +42 -3
- package/server/logging/logHub.ts +0 -0
- package/server/logging/logStdoutWriter.ts +3 -1
- package/server/logging/logStreamRoute.ts +28 -11
- package/server/logging/serverLogging.ts +74 -0
- package/server/machine/machineToken.ts +10 -3
- package/server/mcp/AgentTools.ts +149 -0
- package/server/mcp/AgentToolsAccount.ts +26 -0
- package/server/mcp/McpApps.ts +32 -2
- package/server/mcp/McpDispatcher.ts +44 -30
- package/server/mcp/McpPages.ts +34 -12
- package/server/mcp/McpRateLimiter.ts +14 -0
- package/server/mcp/McpRouter.ts +4 -2
- package/server/mcp/McpUiSession.ts +2 -1
- package/server/mcp/index.ts +1 -0
- package/server/migration/migrationCommand.ts +31 -2
- package/server/migration/migrationRunner.ts +36 -1
- package/server/nativeFile.ts +39 -12
- package/server/nativeSecret.ts +12 -3
- package/server/oauth/OAuthClientIdMetadata.ts +2 -2
- package/server/ops/migrateJobs.ts +2 -2
- package/server/ops/opsCommand.ts +1 -1
- package/server/ops/opsRoute.ts +5 -1
- package/server/ops/opsToken.ts +3 -1
- package/server/remote/RemoteFetch.ts +161 -0
- package/server/remote/RemoteMcp.ts +242 -0
- package/server/remote/RemoteOAuth.ts +270 -0
- package/server/remote/RemoteSource.ts +214 -0
- package/server/remote/index.ts +17 -0
- package/server/remote/remoteError.ts +19 -0
- package/server/resolver/CascadeRunner.ts +20 -8
- package/server/resolver/database.resolver.ts +10 -417
- package/server/resolver/databaseModelInstance.ts +209 -0
- package/server/resolver/invalidSignal.ts +7 -0
- package/server/resolver/livePause.ts +34 -0
- package/server/resolver/modelFacade.ts +136 -0
- package/server/resolver/modelLoaders.ts +84 -0
- package/server/resolver/modelSchema.ts +52 -0
- package/server/resolver/roomAdmission.ts +68 -0
- package/server/resolver/signal.resolver.ts +45 -111
- package/server/resolver/sliceCrud.ts +63 -0
- package/server/resolver/timedQuery.ts +16 -0
- package/server/resolver/websocketOf.ts +2 -1
- package/server/routeElementComposer.tsx +45 -6
- package/server/routeTreeBuilder.ts +23 -9
- package/server/routing/apiRouter.ts +53 -28
- package/server/routing/builtinRoutes.ts +194 -0
- package/server/routing/localRooms.ts +34 -0
- package/server/routing/roomReplay.ts +2 -2
- package/server/routing/serverLimits.ts +4 -1
- package/server/routing/serverListener.ts +194 -0
- package/server/rscClient.tsx +122 -195
- package/server/rscClientCache.ts +165 -0
- package/server/rscClientChunks.ts +126 -8
- package/server/rscClientFetch.ts +9 -2
- package/server/rscClientPatch.ts +78 -15
- package/server/rscDocumentHead.tsx +177 -0
- package/server/rscFlightRenderer.ts +83 -0
- package/server/rscFlightStream.ts +259 -0
- package/server/rscHostReloads.ts +238 -0
- package/server/rscHostRenderStream.ts +297 -0
- package/server/rscHostRequests.ts +158 -0
- package/server/rscHttp.ts +18 -6
- package/server/rscNavigationState.ts +24 -1
- package/server/rscPagePrompts.ts +65 -14
- package/server/rscPrefetchCache.ts +31 -17
- package/server/rscRenderControl.ts +33 -0
- package/server/rscRenderFallbacks.ts +299 -0
- package/server/rscRenderHandler.ts +439 -0
- package/server/rscRenderStats.ts +49 -0
- package/server/rscResultCaches.ts +74 -0
- package/server/rscRouteDocument.tsx +316 -0
- package/server/rscSegmentOutletReference.ts +5 -1
- package/server/rscStaticApp.tsx +73 -0
- package/server/rscWorker.tsx +112 -1341
- package/server/rscWorkerHost.ts +175 -803
- package/server/rscWorkerProcess.ts +155 -0
- package/server/rscWorkerRecycler.ts +128 -0
- package/server/serverConfig.ts +128 -0
- package/server/serverMetrics.ts +52 -0
- package/server/sitemap.ts +1 -0
- package/server/ssrFromRscRenderer.tsx +20 -20
- package/server/ssrStaticApp.tsx +243 -0
- package/server/webArtifact.ts +86 -0
- package/server/webAssetRoutes.ts +84 -0
- package/server/webCsrSurface.ts +172 -0
- package/server/webDocumentRoute.ts +180 -0
- package/server/webRouteContext.ts +232 -0
- package/server/webRouter.ts +129 -1165
- package/server/webRscRoute.ts +155 -0
- package/server/webSiteFiles.ts +139 -0
- package/server/webStaticApp.ts +62 -0
- package/server/wellKnownRoutes.ts +73 -0
- package/service/agent.service.ts +14 -2
- package/service/agentAccounts.ts +19 -0
- package/service/agentLoop/agentLoop.ts +550 -0
- package/service/agentLoop/agentLoopTypes.ts +220 -0
- package/service/agentLoop/deltaStream.ts +40 -0
- package/service/agentLoop/loopAnswer.ts +67 -0
- package/service/agentLoop/loopAsk.ts +44 -0
- package/service/agentLoop/loopCompaction.ts +146 -0
- package/service/agentLoop/loopRemotes.ts +181 -0
- package/service/agentLoop/loopRequest.ts +120 -0
- package/service/agentLoop/loopStored.ts +24 -0
- package/service/agentLoop/loopToolOutput.ts +54 -0
- package/service/agentLoop/loopToolkits.ts +155 -0
- package/service/agentLoop/loopTranscript.ts +138 -0
- package/{signal → service}/agentMeter.ts +2 -1
- package/{signal → service}/agentRelayPolicy.ts +43 -8
- package/service/endpointCacheKeys.ts +14 -2
- package/service/index.ts +6 -0
- package/service/injectInfo.ts +2 -1
- package/service/ipcTypes.ts +8 -2
- package/service/liveRoomLimit.ts +68 -0
- package/service/liveRoomLimitError.ts +16 -0
- package/service/liveSyncHub.ts +24 -2
- package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
- package/service/predefinedAdaptor/anthropicLlm.ts +33 -14
- package/service/predefinedAdaptor/compress.adaptor.ts +2 -2
- package/service/predefinedAdaptor/database.adaptor.ts +62 -19
- package/service/predefinedAdaptor/index.ts +1 -0
- package/service/predefinedAdaptor/llm.adaptor.ts +24 -1
- package/service/predefinedAdaptor/openaiDialect.ts +72 -23
- package/service/predefinedAdaptor/openaiLlm.ts +1 -1
- package/service/predefinedAdaptor/role.adaptor.ts +2 -0
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
- package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
- package/service/predefinedAdaptor/solidSqlite.ts +6 -3
- package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
- package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
- package/service/predefinedAdaptor/sql/DocumentWriter.ts +298 -0
- package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
- package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
- package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +127 -1069
- package/service/predefinedAdaptor/sql/SqlTableSchema.ts +357 -0
- package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
- package/service/predefinedAdaptor/sql/TransactionScope.ts +14 -7
- package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
- package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
- package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +20 -9
- package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
- package/service/predefinedAdaptor/sql/types.ts +28 -4
- package/service/predefinedAdaptor/sseData.ts +88 -0
- package/service/predefinedAdaptor/storage.adaptor.ts +2 -1
- package/service/predefinedAdaptor/websocket.adaptor.ts +74 -44
- package/service/serviceRegistry.ts +1 -0
- package/signal/SignalFailure.ts +35 -0
- package/signal/agent.signal.ts +15 -9
- package/signal/agentTurnStream.ts +23 -9
- package/signal/byIdRead.ts +18 -0
- package/signal/carriedClientIps.ts +1 -0
- package/signal/endpointCache.ts +61 -6
- package/signal/endpointErrorContract.ts +1 -1
- package/signal/endpointRateLimit.ts +84 -3
- package/signal/index.ts +322 -32
- package/signal/mcp/McpDocument.ts +8 -1
- package/signal/mcp/mcpProtocol.ts +6 -1
- package/signal/mcp/pagePrompt.ts +15 -0
- package/signal/middleware.ts +10 -3
- package/signal/openapi/openapi.ts +10 -1
- package/signal/resolveFieldContext.ts +34 -0
- package/signal/serializer/fetch.serializer.ts +22 -15
- package/signal/signalContext.ts +15 -42
- package/signal/slice.ts +22 -19
- package/signal/trace.ts +44 -5
- package/signal/types.ts +46 -8
- package/store/action.ts +32 -1057
- package/store/actionErrorMessage.ts +20 -0
- package/store/actionOption.ts +22 -0
- package/store/baseSt.ts +1 -0
- package/store/formFieldSetters.ts +229 -0
- package/store/index.ts +125 -17
- package/store/modelActionContext.ts +65 -0
- package/store/modelOpenActions.ts +158 -0
- package/store/modelWriteActions.ts +240 -0
- package/store/modelWriteGuard.ts +3 -12
- package/store/openSeq.ts +34 -0
- package/store/sliceListActions.ts +370 -0
- package/store/sliceLiveActions.ts +140 -0
- package/store/stateBuilder.ts +2 -0
- package/store/storeInstance.ts +4 -18
- package/store/storeRegistry.ts +1 -1
- package/test/conformance.ts +25 -5
- package/types/base/base.d.ts +2 -1
- package/types/client/clientRuntime.d.ts +1 -0
- package/types/client/cn.d.ts +2 -2
- package/types/client/csrTypes.d.ts +2 -0
- package/types/client/frameConfig.d.ts +1 -0
- package/types/client/index.d.ts +25 -26
- package/types/client/locale.d.ts +1 -0
- package/types/client/makePageProto.d.ts +5 -13
- package/types/client/nativeThemeColor.d.ts +6 -0
- package/types/client/route/PageDefinition.d.ts +5 -2
- package/types/client/route/RouteDefinition.d.ts +2 -2
- package/types/client/route/routeArgs.d.ts +7 -0
- package/types/client/router.d.ts +3 -1
- package/types/client/rscNavigation.d.ts +1 -0
- package/types/client/viewportMeta.d.ts +5 -2
- package/types/common/CodeTranscript.d.ts +1 -1
- package/types/common/clientAddress.d.ts +5 -0
- package/types/common/err.d.ts +48 -0
- package/types/common/eventStream.d.ts +5 -1
- package/types/common/facetBarrel.d.ts +4 -0
- package/types/common/index.d.ts +6 -3
- package/types/common/isGuardRefusal.d.ts +3 -0
- package/types/common/loggedFailure.d.ts +2 -0
- package/types/common/mcpExposure.d.ts +9 -2
- package/types/common/routeConvention.d.ts +2 -0
- package/types/common/types.d.ts +18 -1
- package/types/constant/constantRegistry.d.ts +3 -1
- package/types/constant/crystalize.d.ts +1 -1
- package/types/constant/getDefault.d.ts +1 -1
- package/types/constant/immerify.d.ts +1 -1
- package/types/constant/index.d.ts +21 -21
- package/types/constant/purify.d.ts +2 -1
- package/types/constant/serialize.d.ts +1 -1
- package/types/constant/types.d.ts +1 -0
- package/types/dictionary/agent.dictionary.d.ts +1 -1
- package/types/dictionary/base.dictionary.d.ts +1 -1
- package/types/dictionary/dictionary.d.ts +9 -9
- package/types/dictionary/locale.d.ts +1 -1
- package/types/dictionary/trans.d.ts +3 -26
- package/types/document/dataLoader.d.ts +5 -0
- package/types/document/databaseRegistry.d.ts +2 -1
- package/types/document/documentSchema.d.ts +1 -0
- package/types/document/filterMeta.d.ts +4 -1
- package/types/document/into.d.ts +1 -1
- package/types/document/loaderInfo.d.ts +2 -1
- package/types/document/noDocumentError.d.ts +8 -1
- package/types/document/queryEvaluator.d.ts +1 -1
- package/types/document/types.d.ts +1 -1
- package/types/fetch/client/fetchClient.d.ts +6 -36
- package/types/fetch/client/fetchClientTypes.d.ts +40 -0
- package/types/fetch/client/httpClient.d.ts +2 -0
- package/types/fetch/client/remoteError.d.ts +0 -4
- package/types/fetch/client/requestScope.d.ts +11 -0
- package/types/fetch/client/signalCatalog.d.ts +25 -0
- package/types/fetch/client/wsClient.d.ts +2 -0
- package/types/fetch/requestStorage.d.ts +1 -0
- package/types/server/agentHooks.d.ts +4 -0
- package/types/server/akanApp.d.ts +2 -20
- package/types/server/akanOption.d.ts +16 -2
- package/types/server/akanServer.d.ts +2 -2
- package/types/server/assetHeaders.d.ts +1 -0
- package/types/server/console.d.ts +4 -3
- package/types/server/di/predefinedAdaptor.d.ts +1 -0
- package/types/server/di/stageFailedError.d.ts +5 -0
- package/types/server/ed25519Key.d.ts +1 -0
- package/types/server/flightRowReader.d.ts +8 -2
- package/types/server/gateway/childSupervisor.d.ts +35 -0
- package/types/server/gateway/devHostChannel.d.ts +14 -0
- package/types/server/gateway/gatewayChildren.d.ts +50 -0
- package/types/server/gateway/gatewayConfig.d.ts +82 -0
- package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
- package/types/server/gateway/gatewayLogging.d.ts +16 -0
- package/types/server/gateway/gatewayRooms.d.ts +25 -0
- package/types/server/gateway/gatewayStatus.d.ts +63 -0
- package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
- package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
- package/types/server/gateway/listeningPort.d.ts +5 -0
- package/types/server/htmlResultCache.d.ts +51 -0
- package/types/server/index.d.ts +19 -17
- package/types/server/lifecycle/parentChannel.d.ts +13 -0
- package/types/server/lifecycle/startGuard.d.ts +10 -0
- package/types/server/logging/logHub.d.ts +5 -1
- package/types/server/logging/logStreamRoute.d.ts +2 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/logging/serverLogging.d.ts +12 -0
- package/types/server/mcp/AgentTools.d.ts +31 -0
- package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
- package/types/server/mcp/McpApps.d.ts +6 -2
- package/types/server/mcp/McpDispatcher.d.ts +10 -1
- package/types/server/mcp/McpPages.d.ts +2 -1
- package/types/server/mcp/McpRateLimiter.d.ts +3 -0
- package/types/server/mcp/index.d.ts +1 -0
- package/types/server/migration/migrationCommand.d.ts +1 -1
- package/types/server/migration/migrationRunner.d.ts +9 -1
- package/types/server/remote/RemoteFetch.d.ts +42 -0
- package/types/server/remote/RemoteMcp.d.ts +52 -0
- package/types/server/remote/RemoteOAuth.d.ts +58 -0
- package/types/server/remote/RemoteSource.d.ts +51 -0
- package/types/server/remote/index.d.ts +5 -0
- package/types/server/remote/remoteError.d.ts +12 -0
- package/types/server/remote.d.ts +1 -0
- package/types/server/resolver/CascadeRunner.d.ts +2 -2
- package/types/server/resolver/database.resolver.d.ts +2 -2
- package/types/server/resolver/databaseModelInstance.d.ts +4 -0
- package/types/server/resolver/invalidSignal.d.ts +2 -0
- package/types/server/resolver/livePause.d.ts +5 -0
- package/types/server/resolver/modelFacade.d.ts +5 -0
- package/types/server/resolver/modelLoaders.d.ts +15 -0
- package/types/server/resolver/modelSchema.d.ts +6 -0
- package/types/server/resolver/roomAdmission.d.ts +7 -0
- package/types/server/resolver/signal.resolver.d.ts +1 -1
- package/types/server/resolver/sliceCrud.d.ts +8 -0
- package/types/server/resolver/timedQuery.d.ts +8 -0
- package/types/server/routeElementComposer.d.ts +21 -5
- package/types/server/routing/builtinRoutes.d.ts +24 -0
- package/types/server/routing/localRooms.d.ts +14 -0
- package/types/server/routing/roomReplay.d.ts +2 -2
- package/types/server/routing/serverListener.d.ts +31 -0
- package/types/server/rscClientCache.d.ts +34 -0
- package/types/server/rscClientChunks.d.ts +3 -1
- package/types/server/rscClientFetch.d.ts +1 -1
- package/types/server/rscClientPatch.d.ts +12 -1
- package/types/server/rscDocumentHead.d.ts +33 -0
- package/types/server/rscFlightRenderer.d.ts +14 -0
- package/types/server/rscFlightStream.d.ts +53 -0
- package/types/server/rscHostReloads.d.ts +54 -0
- package/types/server/rscHostRenderStream.d.ts +53 -0
- package/types/server/rscHostRequests.d.ts +29 -0
- package/types/server/rscHttp.d.ts +4 -2
- package/types/server/rscNavigationState.d.ts +5 -1
- package/types/server/rscPagePrompts.d.ts +13 -0
- package/types/server/rscPrefetchCache.d.ts +7 -6
- package/types/server/rscRenderControl.d.ts +12 -0
- package/types/server/rscRenderFallbacks.d.ts +41 -0
- package/types/server/rscRenderHandler.d.ts +29 -0
- package/types/server/rscRenderStats.d.ts +32 -0
- package/types/server/rscResultCaches.d.ts +18 -0
- package/types/server/rscRouteDocument.d.ts +52 -0
- package/types/server/rscStaticApp.d.ts +28 -0
- package/types/server/rscWorker.d.ts +1 -3
- package/types/server/rscWorkerHost.d.ts +10 -70
- package/types/server/rscWorkerProcess.d.ts +31 -0
- package/types/server/rscWorkerRecycler.d.ts +22 -0
- package/types/server/serverConfig.d.ts +30 -0
- package/types/server/serverMetrics.d.ts +11 -0
- package/types/server/sitemap.d.ts +1 -0
- package/types/server/ssrFromRscRenderer.d.ts +2 -2
- package/types/server/ssrStaticApp.d.ts +20 -0
- package/types/server/webArtifact.d.ts +7 -0
- package/types/server/webAssetRoutes.d.ts +11 -0
- package/types/server/webCsrSurface.d.ts +18 -0
- package/types/server/webDocumentRoute.d.ts +19 -0
- package/types/server/webRouteContext.d.ts +45 -0
- package/types/server/webRouter.d.ts +3 -28
- package/types/server/webRscRoute.d.ts +24 -0
- package/types/server/webSiteFiles.d.ts +12 -0
- package/types/server/webStaticApp.d.ts +8 -0
- package/types/server/wellKnownRoutes.d.ts +5 -0
- package/types/service/agent.service.d.ts +3 -0
- package/types/service/agentAccounts.d.ts +8 -0
- package/types/service/agentLoop/agentLoop.d.ts +33 -0
- package/types/service/agentLoop/agentLoopTypes.d.ts +235 -0
- package/types/service/agentLoop/deltaStream.d.ts +3 -0
- package/types/service/agentLoop/loopAnswer.d.ts +13 -0
- package/types/service/agentLoop/loopAsk.d.ts +12 -0
- package/types/service/agentLoop/loopCompaction.d.ts +12 -0
- package/types/service/agentLoop/loopRemotes.d.ts +40 -0
- package/types/service/agentLoop/loopRequest.d.ts +9 -0
- package/types/service/agentLoop/loopStored.d.ts +6 -0
- package/types/service/agentLoop/loopToolOutput.d.ts +8 -0
- package/types/service/agentLoop/loopToolkits.d.ts +17 -0
- package/types/service/agentLoop/loopTranscript.d.ts +13 -0
- package/types/{signal → service}/agentMeter.d.ts +1 -1
- package/types/{signal → service}/agentRelayPolicy.d.ts +18 -3
- package/types/service/index.d.ts +6 -0
- package/types/service/injectInfo.d.ts +2 -1
- package/types/service/ipcTypes.d.ts +10 -0
- package/types/service/liveRoomLimit.d.ts +26 -0
- package/types/service/liveRoomLimitError.d.ts +9 -0
- package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
- package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
- package/types/service/predefinedAdaptor/database.adaptor.d.ts +9 -7
- package/types/service/predefinedAdaptor/index.d.ts +1 -0
- package/types/service/predefinedAdaptor/llm.adaptor.d.ts +12 -0
- package/types/service/predefinedAdaptor/openaiDialect.d.ts +3 -2
- package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
- package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
- package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
- package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
- package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
- package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +25 -0
- package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
- package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
- package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +5 -28
- package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +22 -0
- package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
- package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +3 -1
- package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -15
- package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
- package/types/service/predefinedAdaptor/sql/types.d.ts +27 -4
- package/types/service/predefinedAdaptor/sseData.d.ts +13 -0
- package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -3
- package/types/service/serviceRegistry.d.ts +1 -0
- package/types/signal/SignalFailure.d.ts +4 -0
- package/types/signal/agentTurnStream.d.ts +3 -0
- package/types/signal/byIdRead.d.ts +7 -0
- package/types/signal/carriedClientIps.d.ts +4 -0
- package/types/signal/endpointRateLimit.d.ts +12 -0
- package/types/signal/index.d.ts +32 -32
- package/types/signal/mcp/McpDocument.d.ts +2 -0
- package/types/signal/mcp/mcpProtocol.d.ts +5 -0
- package/types/signal/mcp/pagePrompt.d.ts +13 -0
- package/types/signal/resolveFieldContext.d.ts +15 -0
- package/types/signal/serializer/fetch.serializer.d.ts +3 -1
- package/types/signal/signalContext.d.ts +2 -14
- package/types/signal/slice.d.ts +15 -13
- package/types/signal/trace.d.ts +12 -1
- package/types/signal/types.d.ts +38 -7
- package/types/store/action.d.ts +4 -27
- package/types/store/actionErrorMessage.d.ts +1 -0
- package/types/store/actionOption.d.ts +24 -0
- package/types/store/baseSt.d.ts +1 -0
- package/types/store/formFieldSetters.d.ts +80 -0
- package/types/store/index.d.ts +17 -16
- package/types/store/modelActionContext.d.ts +189 -0
- package/types/store/modelOpenActions.d.ts +12 -0
- package/types/store/modelWriteActions.d.ts +16 -0
- package/types/store/modelWriteGuard.d.ts +2 -5
- package/types/store/openSeq.d.ts +17 -0
- package/types/store/sliceListActions.d.ts +295 -0
- package/types/store/sliceLiveActions.d.ts +6 -0
- package/types/store/stateBuilder.d.ts +2 -0
- package/types/test/conformance.d.ts +3 -1
- package/types/ui/Agent/Chat.d.ts +5 -2
- package/types/ui/Agent/ChatHeader.d.ts +13 -0
- package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
- package/types/ui/Agent/ToolRow.d.ts +13 -0
- package/types/ui/Field/Choice.d.ts +2 -1
- package/types/ui/Field/index.d.ts +1 -1
- package/types/ui/Reference/origin.d.ts +1 -0
- package/types/ui/UiOverride/UiOverride.d.ts +2 -0
- package/types/ui/index.d.ts +2 -1
- package/types/ui/overlayLayer.d.ts +8 -2
- package/types/ui/recipe/badgeRecipe.d.ts +3 -3
- package/types/ui/recipe/buttonRecipe.d.ts +3 -3
- package/types/ui/recipe/inputRecipe.d.ts +1 -1
- package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
- package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
- package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +22 -13
- package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
- package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
- package/types/vendor/use-agentic/Compaction.d.ts +3 -1
- package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
- package/types/vendor/use-agentic/Transcript.d.ts +1 -1
- package/types/vendor/use-agentic/failureCode.d.ts +4 -0
- package/types/vendor/use-agentic/index.d.ts +1 -0
- package/types/vendor/use-agentic/types.d.ts +12 -3
- package/types/webkit/CsrGuards.d.ts +3 -0
- package/types/webkit/McpAppHost.d.ts +24 -0
- package/types/webkit/RouteLevelBoundary.d.ts +17 -0
- package/types/webkit/csrRefresh.d.ts +13 -0
- package/types/webkit/index.d.ts +3 -0
- package/types/webkit/needsBrowser.d.ts +5 -0
- package/types/webkit/useCamera.d.ts +1 -1
- package/types/webkit/useCsrKeyboard.d.ts +19 -0
- package/types/webkit/useCsrLocationState.d.ts +21 -0
- package/types/webkit/useCsrNavigation.d.ts +25 -0
- package/types/webkit/useCsrRefs.d.ts +33 -0
- package/types/webkit/useCsrRenderTrace.d.ts +13 -0
- package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
- package/types/webkit/useCsrTransitions.d.ts +2 -0
- package/types/webkit/useGeoLocation.d.ts +1 -1
- package/types/webkit/useHistory.d.ts +2 -3
- package/types/webkit/useResolvedFrame.d.ts +38 -0
- package/types/webkit/useSyncNavigation.d.ts +22 -0
- package/ui/Agent/Bubble.tsx +4 -118
- package/ui/Agent/Chat.tsx +402 -235
- package/ui/Agent/ChatHeader.tsx +59 -0
- package/ui/Agent/ChatPendingCards.tsx +49 -0
- package/ui/Agent/ToolRow.tsx +117 -0
- package/ui/Agent/fetchRunner.ts +8 -1
- package/ui/BottomSheet.tsx +1 -1
- package/ui/Data/Item.tsx +2 -2
- package/ui/Data/ListContainer.tsx +348 -181
- package/ui/Data/useViewModal.ts +10 -4
- package/ui/Dialog/LegacyModal.tsx +1 -1
- package/ui/Dialog/Modal.tsx +1 -1
- package/ui/Field/Choice.tsx +3 -1
- package/ui/Load/StreamBoundary.tsx +1 -6
- package/ui/Load/View.tsx +2 -1
- package/ui/Model/EditModal.tsx +2 -1
- package/ui/Popconfirm.tsx +1 -1
- package/ui/Reference/origin.ts +1 -0
- package/ui/Select.tsx +43 -51
- package/ui/Signal/RestApi.tsx +3 -2
- package/ui/System/Client.tsx +4 -1
- package/ui/UiOverride/UiOverride.tsx +2 -0
- package/ui/index.ts +5 -0
- package/ui/overlayLayer.ts +25 -2
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +31 -13
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
- package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
- package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
- package/vendor/@akanjs/native/native/desktop/src/external.rs +240 -114
- package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
- package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
- package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +696 -0
- package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
- package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
- package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
- package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
- package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
- package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
- package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
- package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
- package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
- package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
- package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
- package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
- package/vendor/@akanjs/native/plugins/external-view/src/index.ts +22 -13
- package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
- package/vendor/use-agentic/AgentClientTools.ts +33 -0
- package/vendor/use-agentic/AgentSession.ts +35 -73
- package/vendor/use-agentic/CHANGELOG.md +0 -43
- package/vendor/use-agentic/Compaction.ts +12 -2
- package/vendor/use-agentic/SessionQuestion.ts +99 -0
- package/vendor/use-agentic/ToolRunner.ts +3 -15
- package/vendor/use-agentic/Transcript.ts +8 -5
- package/vendor/use-agentic/WIRE.md +28 -9
- package/vendor/use-agentic/failureCode.ts +44 -0
- package/vendor/use-agentic/httpRunner.ts +22 -8
- package/vendor/use-agentic/index.ts +1 -0
- package/vendor/use-agentic/types.ts +13 -1
- package/webkit/CsrGuards.ts +11 -2
- package/webkit/McpAppFetchBridge.ts +3 -1
- package/webkit/McpAppHost.ts +122 -0
- package/webkit/RenderLayer.tsx +48 -14
- package/webkit/RouteLevelBoundary.tsx +37 -0
- package/webkit/csrRefresh.ts +33 -0
- package/webkit/index.ts +3 -0
- package/webkit/lazy.tsx +5 -1
- package/webkit/needsBrowser.ts +10 -0
- package/webkit/useCamera.tsx +18 -7
- package/webkit/useCsrKeyboard.ts +155 -0
- package/webkit/useCsrLocationState.ts +58 -0
- package/webkit/useCsrNavigation.ts +302 -0
- package/webkit/useCsrRefs.ts +52 -0
- package/webkit/useCsrRenderTrace.ts +68 -0
- package/webkit/useCsrStackLifecycle.ts +120 -0
- package/webkit/useCsrTransitions.ts +552 -0
- package/webkit/useCsrValues.ts +73 -1235
- package/webkit/useGeoLocation.tsx +1 -3
- package/webkit/useHistory.ts +2 -2
- package/webkit/useLocation.ts +3 -2
- package/webkit/useResolvedFrame.ts +116 -0
- package/webkit/useSyncNavigation.ts +109 -0
- package/vendor/@akanjs/native/CHANGELOG.md +0 -21
package/server/akanServer.ts
CHANGED
|
@@ -1,64 +1,35 @@
|
|
|
1
1
|
import type { AkanWebConfig, AkanWebOption } from "akanjs";
|
|
2
|
-
import { type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix
|
|
3
|
-
import { Logger
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
ServiceCls,
|
|
13
|
-
SolidConfig,
|
|
2
|
+
import { AkanError, type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix } from "akanjs/base";
|
|
3
|
+
import { Logger } from "akanjs/common";
|
|
4
|
+
import {
|
|
5
|
+
type Adaptor,
|
|
6
|
+
type AdaptorCls,
|
|
7
|
+
type DatabaseConfig,
|
|
8
|
+
LiveRoomLimit,
|
|
9
|
+
type Service,
|
|
10
|
+
type ServiceCls,
|
|
11
|
+
type SolidConfig,
|
|
14
12
|
} from "akanjs/service";
|
|
15
|
-
import type { ServerSignal, ServerSignalCls
|
|
16
|
-
import { AgentMeter } from "../signal/agentMeter";
|
|
17
|
-
import { AgentRelayPolicy } from "../signal/agentRelayPolicy";
|
|
13
|
+
import type { ServerSignal, ServerSignalCls } from "akanjs/signal";
|
|
18
14
|
import { CrossSiteGuard } from "../signal/CrossSiteGuard";
|
|
19
15
|
import { EndpointRateLimit } from "../signal/endpointRateLimit";
|
|
20
|
-
import {
|
|
21
|
-
import { createOpenApiDocument } from "../signal/openapi";
|
|
22
|
-
import { FetchSerializer } from "../signal/serializer";
|
|
23
|
-
import { SignalContext } from "../signal/signalContext";
|
|
24
|
-
import { AKAN_CHILD_HOST } from "./akanAppHeaders";
|
|
16
|
+
import { AgentHooks } from "./agentHooks";
|
|
25
17
|
import type { AkanLib, AkanLibProps } from "./akanLib";
|
|
26
|
-
import { BinaryPubsub } from "./binaryPubsub";
|
|
27
|
-
import { DevtoolsRouter } from "./devtools";
|
|
28
18
|
import { DiLifecycle } from "./di/diLifecycle";
|
|
29
|
-
import
|
|
30
|
-
import { OrphanGroup } from "./lifecycle/orphanGroup";
|
|
31
|
-
import { isPortInUseError } from "./lifecycle/portInUse";
|
|
32
|
-
import { resolveRuntimeDir } from "./lifecycle/runtimeDir";
|
|
19
|
+
import { ParentChannel } from "./lifecycle/parentChannel";
|
|
33
20
|
import { ShutdownManager } from "./lifecycle/shutdownManager";
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import { LogHub } from "./logging/logHub";
|
|
38
|
-
import { LogStreamRoute } from "./logging/logStreamRoute";
|
|
39
|
-
import { RotatingLogWriter } from "./logging/rotatingLogWriter";
|
|
40
|
-
import { type McpAuthOption, type McpRateLimitOption, McpRouter } from "./mcp";
|
|
41
|
-
import { AppInfo } from "./ops/appInfo";
|
|
42
|
-
import { OpsRoute } from "./ops/opsRoute";
|
|
43
|
-
import { SqliteFiles } from "./ops/sqliteFiles";
|
|
44
|
-
import { ProcessMetricsCollector } from "./processMetricsCollector";
|
|
21
|
+
import { StartGuard } from "./lifecycle/startGuard";
|
|
22
|
+
import { ServerLogging } from "./logging/serverLogging";
|
|
23
|
+
import { AgentTools, type McpAuthOption, type McpRateLimitOption, type McpRouter } from "./mcp";
|
|
45
24
|
import { WebProxyRunner } from "./proxy";
|
|
46
25
|
import { SignalResolver } from "./resolver";
|
|
47
|
-
import {
|
|
48
|
-
import type { AppWsData } from "./routing/appWsData";
|
|
49
|
-
import { HostAllowlist } from "./routing/hostAllowlist";
|
|
50
|
-
import { RoomReplay } from "./routing/roomReplay";
|
|
26
|
+
import { BuiltinRoutes } from "./routing/builtinRoutes";
|
|
51
27
|
import { RouteHosts } from "./routing/routeHosts";
|
|
52
|
-
import {
|
|
53
|
-
import {
|
|
28
|
+
import { type AkanAppPrepared, ServerListener } from "./routing/serverListener";
|
|
29
|
+
import { ServerConfig } from "./serverConfig";
|
|
30
|
+
import { ServerMetrics } from "./serverMetrics";
|
|
54
31
|
import { SessionRefresh } from "./sessionRefresh";
|
|
55
|
-
import {
|
|
56
|
-
getWebConfigFromEnv,
|
|
57
|
-
type HttpRoutes,
|
|
58
|
-
type LocalPublish,
|
|
59
|
-
type SignalRoutes,
|
|
60
|
-
type WebsocketRoutes,
|
|
61
|
-
} from "./types";
|
|
32
|
+
import { getWebConfigFromEnv } from "./types";
|
|
62
33
|
import type { WebRouter } from "./webRouter";
|
|
63
34
|
|
|
64
35
|
export interface AkanServerProps extends AkanLibProps {
|
|
@@ -134,17 +105,6 @@ export interface McpServerOption {
|
|
|
134
105
|
modern?: boolean;
|
|
135
106
|
}
|
|
136
107
|
|
|
137
|
-
interface AkanAppPrepared {
|
|
138
|
-
routes: SignalRoutes["routes"];
|
|
139
|
-
routeOptions: SignalRoutes["routeOptions"];
|
|
140
|
-
wsRoutes: WebsocketRoutes;
|
|
141
|
-
builtinRoutes: HttpRoutes;
|
|
142
|
-
renderEnvRoutes: HttpRoutes;
|
|
143
|
-
hmrHub: HmrWsHub | null;
|
|
144
|
-
webRouter: WebRouter | null;
|
|
145
|
-
webProxyRunner: WebProxyRunner | null;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
108
|
export interface AkanServerConsoleInfo {
|
|
149
109
|
name: string;
|
|
150
110
|
status: AkanServer["status"];
|
|
@@ -160,50 +120,37 @@ export interface AkanServerConsoleInfo {
|
|
|
160
120
|
|
|
161
121
|
export class AkanServer {
|
|
162
122
|
status: "stopped" | "initializing" | "initialized" | "starting" | "running" | "stopping" = "stopped";
|
|
163
|
-
#server: Bun.Server<AppWsData | HmrWsData> | null = null;
|
|
164
|
-
#wsServer: Bun.Server<AppWsData | HmrWsData> | null = null;
|
|
165
123
|
#prepared: AkanAppPrepared | null = null;
|
|
124
|
+
#webRouter: WebRouter | null = null;
|
|
166
125
|
readonly logger: Logger;
|
|
167
126
|
readonly name: string;
|
|
168
127
|
readonly libs: AkanLib[];
|
|
169
128
|
readonly env: BackendEnv;
|
|
170
129
|
prefix = getApiPrefix();
|
|
171
130
|
websocketPrefix = getWsPrefix();
|
|
172
|
-
openapi =
|
|
131
|
+
openapi = ServerConfig.isEnvEnabled("AKAN_OPENAPI", "AKAN_PUBLIC_OPENAPI");
|
|
173
132
|
|
|
174
|
-
mcp = !
|
|
175
|
-
mcpReadOnly =
|
|
176
|
-
mcpAuth: McpAuthOption =
|
|
177
|
-
mcpOption: Omit<McpServerOption, "enabled" | "readOnly" | "auth"> =
|
|
133
|
+
mcp = !ServerConfig.isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
|
|
134
|
+
mcpReadOnly = ServerConfig.isEnvEnabled("AKAN_MCP_READONLY", "AKAN_PUBLIC_MCP_READONLY");
|
|
135
|
+
mcpAuth: McpAuthOption = ServerConfig.mcpAuthFromEnv();
|
|
136
|
+
mcpOption: Omit<McpServerOption, "enabled" | "readOnly" | "auth"> = ServerConfig.mcpOptionFromEnv();
|
|
178
137
|
serverMode: "federation" | "batch" | "all";
|
|
179
138
|
/** Resolved at `init`: what this process actually serves, after env and artifact availability. */
|
|
180
139
|
web: AkanWebConfig = getWebConfigFromEnv();
|
|
181
140
|
modules: string[];
|
|
182
141
|
disableModules: string[];
|
|
183
142
|
disableLibs: string[];
|
|
184
|
-
shutdownTimeoutMs =
|
|
143
|
+
shutdownTimeoutMs = ServerConfig.defaultShutdownTimeoutMs();
|
|
185
144
|
|
|
186
145
|
#di: DiLifecycle;
|
|
187
|
-
#openApiDocument: ReturnType<typeof createOpenApiDocument> | null = null;
|
|
188
|
-
#mcpRouter: McpRouter | null = null;
|
|
189
146
|
readonly #initTimings = new Map<string, number>();
|
|
190
|
-
#
|
|
191
|
-
readonly #
|
|
192
|
-
#
|
|
193
|
-
|
|
194
|
-
readonly #
|
|
195
|
-
#
|
|
196
|
-
#detachFileLog: (() => void) | null = null;
|
|
197
|
-
#logHub: LogHub | null = null;
|
|
198
|
-
#logControl: LogControlSocket | null = null;
|
|
199
|
-
#logForwarder: LogForwarder | null = null;
|
|
200
|
-
#logStream: LogStreamRoute | null = null;
|
|
201
|
-
#ops: OpsRoute | null | undefined;
|
|
202
|
-
#lastMetrics: AkanMetricsReport = {};
|
|
203
|
-
#stopping: Promise<void> | null = null;
|
|
204
|
-
#parentGone: boolean = false;
|
|
147
|
+
readonly #logging: ServerLogging;
|
|
148
|
+
readonly #listener: ServerListener;
|
|
149
|
+
readonly #metrics: ServerMetrics;
|
|
150
|
+
readonly #parent: ParentChannel;
|
|
151
|
+
readonly #builtinRoutes: BuiltinRoutes;
|
|
152
|
+
readonly #start: StartGuard;
|
|
205
153
|
#schedules = true;
|
|
206
|
-
#orphanExiting = false;
|
|
207
154
|
constructor(
|
|
208
155
|
name = "AkanServer",
|
|
209
156
|
env: BackendEnv = {},
|
|
@@ -214,80 +161,100 @@ export class AkanServer {
|
|
|
214
161
|
| undefined) ?? "all",
|
|
215
162
|
...libsOrOptions: (AkanLib | AkanServerOptions)[]
|
|
216
163
|
) {
|
|
217
|
-
const { libs, options } =
|
|
164
|
+
const { libs, options } = ServerConfig.splitLibsAndOptions(libsOrOptions);
|
|
165
|
+
|
|
166
|
+
const solo = !process.env.AKAN_CHILD_SOCKET;
|
|
218
167
|
this.name = name;
|
|
219
168
|
this.logger = new Logger(name);
|
|
169
|
+
this.#logging = new ServerLogging(solo, this.logger);
|
|
170
|
+
this.#start = new StartGuard(this.logger, () => this.#teardown());
|
|
220
171
|
this.libs = libs;
|
|
221
172
|
this.env = libs.reduce((current, lib) => lib.option.resolveEnv(current), { ...env });
|
|
222
173
|
|
|
223
|
-
if (
|
|
174
|
+
if (ServerConfig.isEdge(this.env) && !ServerConfig.isEnvEnabled("AKAN_MCP", "AKAN_PUBLIC_MCP")) this.mcp = false;
|
|
224
175
|
this.openapi = options?.openapi ?? this.openapi;
|
|
225
176
|
|
|
226
177
|
EndpointRateLimit.reset();
|
|
178
|
+
LiveRoomLimit.reset();
|
|
227
179
|
SessionRefresh.use(null);
|
|
228
180
|
libs.forEach((lib) => {
|
|
229
181
|
const mcp = lib.option.getMcp(this.env);
|
|
230
182
|
if (mcp !== undefined) this.setMcp(mcp);
|
|
231
|
-
|
|
232
|
-
if (agentAccess !== undefined) AgentRelayAccess.use(agentAccess);
|
|
233
|
-
const agentRequestPolicy = lib.option.getAgentRequestPolicy();
|
|
234
|
-
if (agentRequestPolicy !== undefined) AgentRelayPolicy.use(agentRequestPolicy);
|
|
235
|
-
const [usage, quota] = [lib.option.getAgentUsage(), lib.option.getAgentQuota()];
|
|
236
|
-
if (usage !== undefined || quota !== undefined) AgentMeter.use({ usage, quota });
|
|
183
|
+
AgentHooks.apply(lib.option);
|
|
237
184
|
const crossSite = lib.option.getCrossSite();
|
|
238
185
|
if (crossSite !== undefined) CrossSiteGuard.configure(crossSite);
|
|
239
186
|
const rateLimit = lib.option.getRateLimit(this.env);
|
|
240
187
|
if (rateLimit !== undefined) EndpointRateLimit.configure(rateLimit);
|
|
188
|
+
const liveRoomLimit = lib.option.getLiveRoomLimit();
|
|
189
|
+
if (liveRoomLimit) LiveRoomLimit.configure(liveRoomLimit);
|
|
241
190
|
const sessionRefresh = lib.option.getSessionRefresh();
|
|
242
191
|
if (sessionRefresh !== undefined) SessionRefresh.use(sessionRefresh);
|
|
243
192
|
});
|
|
244
193
|
EndpointRateLimit.applyEnv(process.env.AKAN_RATE_LIMIT, getEnv().environment);
|
|
194
|
+
LiveRoomLimit.applyEnv();
|
|
245
195
|
this.setMcp(options?.mcp ?? this.mcp);
|
|
246
196
|
this.serverMode = serverMode;
|
|
247
197
|
|
|
248
|
-
this.modules = options?.modules ??
|
|
249
|
-
this.disableModules = options?.disableModules ??
|
|
250
|
-
this.disableLibs = options?.disableLibs ??
|
|
198
|
+
this.modules = options?.modules ?? ServerConfig.envList("AKAN_MODULES") ?? [];
|
|
199
|
+
this.disableModules = options?.disableModules ?? ServerConfig.envList("AKAN_DISABLE_MODULES") ?? [];
|
|
200
|
+
this.disableLibs = options?.disableLibs ?? ServerConfig.envList("AKAN_DISABLE_LIBS") ?? [];
|
|
251
201
|
this.#di = new DiLifecycle(
|
|
252
202
|
{ env: this.env, modules: this.modules, disableModules: this.disableModules, disableLibs: this.disableLibs },
|
|
253
203
|
...libs,
|
|
254
204
|
);
|
|
205
|
+
const webRouter = () => this.#webRouter;
|
|
206
|
+
this.#listener = new ServerListener(this, this.#di, solo);
|
|
207
|
+
this.#metrics = new ServerMetrics(this, this.#listener, webRouter);
|
|
208
|
+
this.#parent = new ParentChannel(this, this.#logging, webRouter);
|
|
209
|
+
this.#builtinRoutes = new BuiltinRoutes({
|
|
210
|
+
owner: this,
|
|
211
|
+
di: this.#di,
|
|
212
|
+
solo,
|
|
213
|
+
listener: this.#listener,
|
|
214
|
+
metrics: this.#metrics,
|
|
215
|
+
logging: this.#logging,
|
|
216
|
+
});
|
|
255
217
|
}
|
|
256
218
|
setPrefix(prefix: string) {
|
|
257
|
-
if (this.status !== "stopped")
|
|
258
|
-
|
|
219
|
+
if (this.status !== "stopped")
|
|
220
|
+
throw new AkanError("alreadyInitialized", "Route prefix must be set before app initialization.");
|
|
221
|
+
this.prefix = ServerConfig.requireRoutePrefix(prefix, "prefix");
|
|
259
222
|
return this;
|
|
260
223
|
}
|
|
261
224
|
setWebsocketPrefix(websocketPrefix: string) {
|
|
262
|
-
if (this.status !== "stopped")
|
|
263
|
-
|
|
225
|
+
if (this.status !== "stopped")
|
|
226
|
+
throw new AkanError("alreadyInitialized", "Websocket prefix must be set before app initialization.");
|
|
227
|
+
this.websocketPrefix = ServerConfig.requireRoutePrefix(websocketPrefix, "websocketPrefix");
|
|
264
228
|
return this;
|
|
265
229
|
}
|
|
266
230
|
setOpenApi(openapi = true) {
|
|
267
|
-
if (this.status !== "stopped")
|
|
231
|
+
if (this.status !== "stopped")
|
|
232
|
+
throw new AkanError("alreadyInitialized", "OpenAPI config must be set before app initialization.");
|
|
268
233
|
this.openapi = openapi;
|
|
269
234
|
return this;
|
|
270
235
|
}
|
|
271
236
|
/** Narrows the web surface; never widens it past what the build produced. */
|
|
272
237
|
setWeb(web: AkanWebOption = true) {
|
|
273
|
-
if (this.status !== "stopped")
|
|
274
|
-
|
|
238
|
+
if (this.status !== "stopped")
|
|
239
|
+
throw new AkanError("alreadyInitialized", "Web config must be set before app initialization.");
|
|
240
|
+
this.web = ServerConfig.narrowWeb(this.web, web);
|
|
275
241
|
return this;
|
|
276
242
|
}
|
|
277
243
|
setMcp(mcp: boolean | McpServerOption = true) {
|
|
278
|
-
if (this.status !== "stopped")
|
|
244
|
+
if (this.status !== "stopped")
|
|
245
|
+
throw new AkanError("alreadyInitialized", "MCP config must be set before app initialization.");
|
|
279
246
|
|
|
280
247
|
const requested = typeof mcp === "boolean" ? mcp : (mcp.enabled ?? this.mcp);
|
|
281
|
-
this.mcp = requested && !
|
|
248
|
+
this.mcp = requested && !ServerConfig.isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
|
|
282
249
|
if (typeof mcp === "boolean") return this;
|
|
283
250
|
const { enabled: _enabled, readOnly, auth, excludeSignals, excludeEndpoints, ...rest } = mcp;
|
|
284
251
|
if (readOnly !== undefined) this.mcpReadOnly = readOnly;
|
|
285
|
-
if (auth) this.mcpAuth = { ...this.mcpAuth, ...
|
|
252
|
+
if (auth) this.mcpAuth = { ...this.mcpAuth, ...ServerConfig.defined(auth) };
|
|
286
253
|
const added = (current: string[] | undefined, names: string[] | undefined) =>
|
|
287
254
|
names ? [...new Set([...(current ?? []), ...names])] : current;
|
|
288
|
-
this.mcpOption =
|
|
255
|
+
this.mcpOption = ServerConfig.defined({
|
|
289
256
|
...this.mcpOption,
|
|
290
|
-
...
|
|
257
|
+
...ServerConfig.defined(rest),
|
|
291
258
|
excludeSignals: added(this.mcpOption.excludeSignals, excludeSignals),
|
|
292
259
|
excludeEndpoints: added(this.mcpOption.excludeEndpoints, excludeEndpoints),
|
|
293
260
|
});
|
|
@@ -295,15 +262,17 @@ export class AkanServer {
|
|
|
295
262
|
}
|
|
296
263
|
/** The router `/mcp` is served by once routes are built; `null` before, or when MCP is off. */
|
|
297
264
|
get mcpRouter(): McpRouter | null {
|
|
298
|
-
return this.#mcpRouter;
|
|
265
|
+
return this.#builtinRoutes.mcpRouter;
|
|
299
266
|
}
|
|
300
267
|
setDatabaseConfig(database: DatabaseConfig) {
|
|
301
|
-
if (this.status !== "stopped")
|
|
268
|
+
if (this.status !== "stopped")
|
|
269
|
+
throw new AkanError("alreadyInitialized", "Database config must be set before app initialization.");
|
|
302
270
|
this.env.database = database;
|
|
303
271
|
return this;
|
|
304
272
|
}
|
|
305
273
|
setSolidConfig(solid: SolidConfig) {
|
|
306
|
-
if (this.status !== "stopped")
|
|
274
|
+
if (this.status !== "stopped")
|
|
275
|
+
throw new AkanError("alreadyInitialized", "Solid config must be set before app initialization.");
|
|
307
276
|
this.env.solid = solid;
|
|
308
277
|
return this;
|
|
309
278
|
}
|
|
@@ -316,27 +285,27 @@ export class AkanServer {
|
|
|
316
285
|
get<Sig extends ServerSignalCls>(cls: Sig): InstanceType<Sig>;
|
|
317
286
|
get<Adp extends AdaptorCls>(cls: Adp): InstanceType<Adp>;
|
|
318
287
|
get(cls: ServiceCls | ServerSignalCls | AdaptorCls): Service | ServerSignal | Adaptor {
|
|
319
|
-
|
|
288
|
+
assertCanGet(this.status);
|
|
320
289
|
return this.#di.getByClass(cls);
|
|
321
290
|
}
|
|
322
291
|
|
|
323
292
|
getService<T = Service>(refName: string): T {
|
|
324
|
-
|
|
293
|
+
assertCanGet(this.status, "Service", refName);
|
|
325
294
|
return this.#di.getService<T>(refName);
|
|
326
295
|
}
|
|
327
296
|
|
|
328
297
|
getSignal<T = ServerSignal>(refName: string): T {
|
|
329
|
-
|
|
298
|
+
assertCanGet(this.status, "Server signal", refName);
|
|
330
299
|
return this.#di.getSignal<T>(refName);
|
|
331
300
|
}
|
|
332
301
|
|
|
333
302
|
getAdaptor<T = Adaptor>(refName: string): T {
|
|
334
|
-
|
|
303
|
+
assertCanGet(this.status, "Adaptor", refName);
|
|
335
304
|
return this.#di.getAdaptor<T>(refName);
|
|
336
305
|
}
|
|
337
306
|
|
|
338
307
|
inspectConsole(): AkanServerConsoleInfo {
|
|
339
|
-
|
|
308
|
+
assertCanGet(this.status);
|
|
340
309
|
const env = getEnv();
|
|
341
310
|
return {
|
|
342
311
|
name: this.name,
|
|
@@ -360,35 +329,41 @@ export class AkanServer {
|
|
|
360
329
|
}
|
|
361
330
|
|
|
362
331
|
async init(option: { routes?: boolean; web?: AkanWebOption } = {}) {
|
|
332
|
+
if (this.status !== "stopped")
|
|
333
|
+
throw new AkanError("alreadyInitialized", "AkanServer is not able to init. It is already running.");
|
|
334
|
+
ServerConfig.assertPrefixClearsBasePaths(this.prefix);
|
|
363
335
|
const start = performance.now();
|
|
364
336
|
this.#initTimings.clear();
|
|
365
|
-
await this.#init(option);
|
|
337
|
+
if (await this.#start.unwound(() => this.#start.stoppedDuring(() => this.#init(option)))) return this;
|
|
366
338
|
const stages = [...this.#di.initTimings, ...this.#initTimings].map(([stage, ms]) => `${stage} ${ms.toFixed(1)}`);
|
|
367
339
|
this.logger.debug(`Initialized in ${(performance.now() - start).toFixed(1)}ms (${stages.join(" · ")})`);
|
|
368
340
|
return this;
|
|
369
341
|
}
|
|
370
342
|
|
|
371
343
|
async #init({ routes: initRoutes = true, web }: { routes?: boolean; web?: AkanWebOption }) {
|
|
372
|
-
if (this.status !== "stopped") throw new Error("AkanServer is not able to init. It is already running.");
|
|
373
344
|
this.status = "initializing";
|
|
374
|
-
this.#
|
|
375
|
-
const { routes, wsRoutes, routeOptions } = await this.#di.initializeAll()
|
|
345
|
+
AgentTools.provide(this.#di, this);
|
|
346
|
+
const { routes, wsRoutes, routeOptions } = await this.#di.initializeAll().catch((error: unknown) => {
|
|
347
|
+
|
|
348
|
+
this.status = "stopped";
|
|
349
|
+
throw error;
|
|
350
|
+
});
|
|
351
|
+
if (this.#start.stopHeld) return this;
|
|
376
352
|
if (!initRoutes) {
|
|
377
353
|
this.#prepared = null;
|
|
378
354
|
this.status = "initialized";
|
|
379
355
|
return this;
|
|
380
356
|
}
|
|
381
357
|
RouteHosts.declare();
|
|
382
|
-
const requestedWeb =
|
|
358
|
+
const requestedWeb = ServerConfig.narrowWeb(this.web, web);
|
|
383
359
|
const noWeb = () => {
|
|
384
360
|
this.#prepared = {
|
|
385
361
|
routes,
|
|
386
362
|
routeOptions,
|
|
387
363
|
wsRoutes,
|
|
388
|
-
builtinRoutes: this.#
|
|
364
|
+
builtinRoutes: this.#builtinRoutes.timed(null, this.#initTimings),
|
|
389
365
|
renderEnvRoutes: {},
|
|
390
366
|
hmrHub: null,
|
|
391
|
-
webRouter: null,
|
|
392
367
|
webProxyRunner: null,
|
|
393
368
|
};
|
|
394
369
|
this.status = "initialized";
|
|
@@ -401,12 +376,10 @@ export class AkanServer {
|
|
|
401
376
|
}
|
|
402
377
|
const webStart = performance.now();
|
|
403
378
|
const { WebRouter } = await import("./webRouter");
|
|
379
|
+
if (this.#start.stopHeld) return this;
|
|
404
380
|
const webRouter = await WebRouter.create({
|
|
405
381
|
web: requestedWeb,
|
|
406
|
-
|
|
407
|
-
upgradeHmrWs: (req, data) =>
|
|
408
|
-
(this.#wsServer?.requestIP(req as Bun.BunRequest) ? this.#wsServer : this.#server)?.upgrade(req, { data }) ??
|
|
409
|
-
false,
|
|
382
|
+
upgradeHmrWs: (req, data) => this.#listener.upgradeHmrWs(req, data),
|
|
410
383
|
});
|
|
411
384
|
|
|
412
385
|
if (!webRouter) {
|
|
@@ -414,6 +387,7 @@ export class AkanServer {
|
|
|
414
387
|
this.logger.warn("web off: no build artifact under .akan/artifact; serving api only");
|
|
415
388
|
return noWeb();
|
|
416
389
|
}
|
|
390
|
+
this.#webRouter = webRouter;
|
|
417
391
|
this.web = webRouter.web;
|
|
418
392
|
this.logger.verbose(`web on: ssr=${this.web.ssr} csr=${this.web.csr}`);
|
|
419
393
|
const { renderEnvRoutes, hmrHub } = await webRouter.initializeRoute();
|
|
@@ -423,10 +397,9 @@ export class AkanServer {
|
|
|
423
397
|
routes,
|
|
424
398
|
routeOptions,
|
|
425
399
|
wsRoutes,
|
|
426
|
-
builtinRoutes: this.#
|
|
400
|
+
builtinRoutes: this.#builtinRoutes.timed(webRouter, this.#initTimings),
|
|
427
401
|
renderEnvRoutes,
|
|
428
402
|
hmrHub,
|
|
429
|
-
webRouter,
|
|
430
403
|
webProxyRunner,
|
|
431
404
|
};
|
|
432
405
|
this.status = "initialized";
|
|
@@ -434,130 +407,24 @@ export class AkanServer {
|
|
|
434
407
|
}
|
|
435
408
|
|
|
436
409
|
async listen() {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
410
|
+
const prepared = this.#prepared;
|
|
411
|
+
if (this.status !== "initialized" || !prepared)
|
|
412
|
+
throw new AkanError("notInitialized", "AkanServer is not able to listen. Call `init` first.");
|
|
440
413
|
this.status = "starting";
|
|
441
414
|
Logger.role = this.serverMode;
|
|
442
|
-
await this.#
|
|
443
|
-
|
|
444
|
-
const port = process.env.AKAN_CHILD_SOCKET
|
|
445
|
-
? undefined
|
|
446
|
-
: Number(process.env.AKAN_CHILD_WS_PORT || process.env.PORT || 8282);
|
|
447
|
-
const unix = process.env.AKAN_CHILD_SOCKET || undefined;
|
|
448
|
-
this.logger.verbose(`${this.name} is serving on ${unix ? `unix://${unix}` : `port ${port}`}`);
|
|
449
|
-
const { routes, routeOptions, wsRoutes, builtinRoutes, renderEnvRoutes, hmrHub, webRouter, webProxyRunner } =
|
|
450
|
-
this.#prepared;
|
|
451
|
-
const limits = new ServerLimits();
|
|
452
|
-
const websocketHandlers = {
|
|
453
|
-
...ApiRouter.buildWebsocketHandlers({
|
|
454
|
-
wsRoutes,
|
|
455
|
-
registry: this.#di.registry,
|
|
456
|
-
live: this.#di.live,
|
|
457
|
-
hmrHub,
|
|
458
|
-
hmrState: webRouter
|
|
459
|
-
? {
|
|
460
|
-
state: webRouter.renderState,
|
|
461
|
-
refresh: () => webRouter.refreshHmrState(),
|
|
462
|
-
errors: () => webRouter.hmrBuildErrors(),
|
|
463
|
-
}
|
|
464
|
-
: null,
|
|
465
|
-
logger: this.logger,
|
|
466
|
-
onDrain: () => this.#binaryPubsub.flush(),
|
|
467
|
-
}),
|
|
468
|
-
idleTimeout: limits.wsIdleTimeout,
|
|
469
|
-
data: {},
|
|
470
|
-
} as Bun.WebSocketHandler<AppWsData | HmrWsData>;
|
|
471
|
-
|
|
472
|
-
const hostAllowlist = unix ? null : HostAllowlist.fromEnv();
|
|
473
|
-
const hostname = ServerLimits.listenHostname();
|
|
474
|
-
|
|
475
|
-
const idleTimeout = unix ? 0 : limits.idleTimeout;
|
|
476
|
-
const buildRoutes = (upgradeAppWs: ApiRouteInputs["upgradeAppWs"], allowlist: HostAllowlist | null) =>
|
|
477
|
-
ApiRouter.buildRoutes({
|
|
478
|
-
prefix: this.prefix,
|
|
479
|
-
websocketPrefix: this.websocketPrefix,
|
|
480
|
-
routes,
|
|
481
|
-
builtinRoutes,
|
|
482
|
-
routeOptions,
|
|
483
|
-
renderEnvRoutes,
|
|
484
|
-
upgradeAppWs,
|
|
485
|
-
webProxyRunner,
|
|
486
|
-
hostAllowlist: allowlist,
|
|
487
|
-
bodyLimits: limits,
|
|
488
|
-
countChunkedBodies: !unix,
|
|
489
|
-
idleTimeout,
|
|
490
|
-
});
|
|
491
|
-
const serve = () =>
|
|
492
|
-
Bun.serve({
|
|
493
|
-
idleTimeout,
|
|
494
|
-
maxRequestBodySize: limits.uploadBodyBytes,
|
|
495
|
-
...(unix ? { unix } : { port, hostname }),
|
|
496
|
-
routes: buildRoutes((req, data) => this.#server?.upgrade(req, { data }) ?? false, hostAllowlist),
|
|
497
|
-
websocket: websocketHandlers,
|
|
498
|
-
} as Parameters<typeof Bun.serve>[0]);
|
|
499
|
-
this.#server = unix ? ServerLimits.serveOwnerOnly(unix, serve) : serve();
|
|
500
|
-
if (unix && process.env.AKAN_CHILD_WS_PORT) {
|
|
501
|
-
const preferredWsPort = Number(process.env.AKAN_CHILD_WS_PORT);
|
|
502
|
-
|
|
503
|
-
const wsServeOptions = (port: number) => ({
|
|
504
|
-
idleTimeout: 0,
|
|
505
|
-
port,
|
|
506
|
-
hostname: "127.0.0.1",
|
|
507
|
-
routes: buildRoutes(
|
|
508
|
-
(req, data) => this.#wsServer?.upgrade(req, { data }) ?? false,
|
|
509
|
-
new HostAllowlist([AKAN_CHILD_HOST]),
|
|
510
|
-
),
|
|
511
|
-
websocket: websocketHandlers,
|
|
512
|
-
});
|
|
513
|
-
try {
|
|
514
|
-
this.#wsServer = Bun.serve(wsServeOptions(preferredWsPort));
|
|
515
|
-
} catch (error) {
|
|
516
|
-
if (!isPortInUseError(error)) throw error;
|
|
517
|
-
|
|
518
|
-
this.logger.warn(`ws port ${preferredWsPort} is in use; falling back to an ephemeral port`);
|
|
519
|
-
this.#wsServer = Bun.serve(wsServeOptions(0));
|
|
520
|
-
}
|
|
521
|
-
this.logger.verbose(`${this.name} websocket fallback is serving on port ${this.#wsServer.port}`);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
const server = this.#server;
|
|
525
|
-
const wsServer = this.#wsServer;
|
|
526
|
-
|
|
527
|
-
SignalContext.setHttpPeerResolver((req) => server?.requestIP(req as Bun.BunRequest) ?? (unix ? null : undefined));
|
|
528
|
-
hmrHub?.setPublisher((topic, payload) => {
|
|
529
|
-
server?.publish(topic, payload);
|
|
530
|
-
wsServer?.publish(topic, payload);
|
|
531
|
-
});
|
|
532
|
-
|
|
533
|
-
const websocket = this.#di.getWebsocketAdaptor();
|
|
534
|
-
if (!websocket) throw new Error("WebSocket Redis adaptor is not registered");
|
|
535
|
-
this.#binaryPubsub.setServers(server, wsServer);
|
|
536
|
-
const subscribed = (roomId: string) =>
|
|
537
|
-
(server?.subscriberCount(roomId) ?? 0) + (wsServer?.subscriberCount(roomId) ?? 0) > 0;
|
|
538
|
-
const roomReplay = new RoomReplay({ vouches: RoomReplay.vouchesFor(websocket, this.#solo), subscribed });
|
|
539
|
-
const localPublish: LocalPublish = (roomId, data) => {
|
|
540
|
-
if (data instanceof Uint8Array) {
|
|
541
|
-
roomReplay.unnumbered(roomId);
|
|
542
|
-
this.#binaryPubsub.publish(roomId, websocketBinaryFrameContract.encode({ roomId, payload: data }), {
|
|
543
|
-
coalesce: SignalResolver.coalescesRoom(roomId),
|
|
544
|
-
});
|
|
545
|
-
return;
|
|
546
|
-
}
|
|
547
|
-
const publishData: WebsocketPublishData = { type: "pub", roomId, data };
|
|
548
|
-
const frame = roomReplay.frameOf(publishData, subscribed(roomId));
|
|
549
|
-
server?.publish(roomId, frame);
|
|
550
|
-
wsServer?.publish(roomId, frame);
|
|
551
|
-
};
|
|
552
|
-
SignalResolver.setLocalPublish(localPublish, websocket, this.#di.live, roomReplay);
|
|
553
|
-
this.#localPublish = localPublish;
|
|
415
|
+
return await this.#start.unwound(() => this.#listen(prepared));
|
|
416
|
+
}
|
|
554
417
|
|
|
418
|
+
async #listen(prepared: AkanAppPrepared) {
|
|
419
|
+
if (await this.#start.stoppedDuring(() => this.#logging.startTransport(this.#webRouter))) return this;
|
|
420
|
+
this.#logging.startFileLogging(this.serverMode);
|
|
421
|
+
const { unix, port } = this.#listener.listen(prepared, this.#webRouter);
|
|
555
422
|
this.status = "running";
|
|
556
|
-
this.#
|
|
423
|
+
this.#metrics.start();
|
|
557
424
|
if (this.#schedules) this.#di.registerSchedule(this.serverMode);
|
|
558
425
|
this.logger.verbose(`🚀 ${this.name} is running on ${unix ? `unix://${unix}` : `port ${port}`}`);
|
|
559
|
-
const wsPort = this.#
|
|
560
|
-
this.#sendReady({
|
|
426
|
+
const wsPort = this.#listener.wsPort;
|
|
427
|
+
this.#parent.sendReady({
|
|
561
428
|
type: "ready",
|
|
562
429
|
pid: process.pid,
|
|
563
430
|
replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
|
|
@@ -566,8 +433,9 @@ export class AkanServer {
|
|
|
566
433
|
wsUpstream: typeof wsPort === "number" ? { type: "tcp", host: "127.0.0.1", port: wsPort } : undefined,
|
|
567
434
|
healthPath: "/_akan/app/child-health",
|
|
568
435
|
crossSite: CrossSiteGuard.option(),
|
|
436
|
+
rscWorker: this.#webRouter?.rscWorkerStatus ?? null,
|
|
569
437
|
});
|
|
570
|
-
if (this.#schedules) await this.#di.runSchedulerInit();
|
|
438
|
+
if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
|
|
571
439
|
ShutdownManager.register(this.logger, () => this.stop());
|
|
572
440
|
return this;
|
|
573
441
|
}
|
|
@@ -581,453 +449,90 @@ export class AkanServer {
|
|
|
581
449
|
const isNoListenCommand = process.env.AKAN_COMMAND_TYPE === "script" || process.env.AKAN_COMMAND_TYPE === "console";
|
|
582
450
|
const shouldListen = (listen ?? !isNoListenCommand) && this.serverMode !== "batch";
|
|
583
451
|
|
|
584
|
-
if (shouldListen || !isNoListenCommand) this.#
|
|
452
|
+
if (shouldListen || !isNoListenCommand) this.#parent.register();
|
|
585
453
|
await this.init({ routes: shouldListen, web });
|
|
586
|
-
if (this.#
|
|
587
|
-
if (
|
|
454
|
+
if (this.#parent.gone || this.status !== "initialized") return this;
|
|
455
|
+
if (shouldListen) return this.listen();
|
|
456
|
+
return await this.#start.unwound(async () => {
|
|
588
457
|
const websocket = this.#di.getWebsocketAdaptor();
|
|
589
458
|
if (websocket)
|
|
590
|
-
SignalResolver.setLocalPublish(
|
|
459
|
+
SignalResolver.setLocalPublish(
|
|
460
|
+
(roomId, data) => this.#listener.publishLocal(roomId, data),
|
|
461
|
+
websocket,
|
|
462
|
+
this.#di.live,
|
|
463
|
+
);
|
|
591
464
|
this.status = "running";
|
|
592
|
-
if (
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
}
|
|
465
|
+
if (isNoListenCommand) return this;
|
|
466
|
+
Logger.role = this.serverMode;
|
|
467
|
+
this.#metrics.start();
|
|
468
|
+
if (this.#schedules) this.#di.registerSchedule(this.serverMode);
|
|
469
|
+
if (await this.#start.stoppedDuring(() => this.#logging.startTransport())) return this;
|
|
470
|
+
this.#parent.sendReady({
|
|
471
|
+
type: "ready",
|
|
472
|
+
pid: process.pid,
|
|
473
|
+
replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
|
|
474
|
+
role: this.serverMode,
|
|
475
|
+
});
|
|
476
|
+
if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
|
|
477
|
+
ShutdownManager.register(this.logger, () => this.stop());
|
|
606
478
|
return this;
|
|
607
|
-
}
|
|
608
|
-
return this.listen();
|
|
479
|
+
});
|
|
609
480
|
}
|
|
610
481
|
stop(): Promise<void> {
|
|
611
|
-
|
|
612
|
-
this.#stopping = null;
|
|
613
|
-
});
|
|
614
|
-
return this.#stopping;
|
|
482
|
+
return this.#start.stop(() => this.status === "running" || this.status === "initialized");
|
|
615
483
|
}
|
|
616
484
|
|
|
617
|
-
async #
|
|
618
|
-
if (this.status
|
|
619
|
-
this.logger.warn("AkanServer is not running. Cannot stop.");
|
|
620
|
-
return;
|
|
621
|
-
}
|
|
622
|
-
|
|
485
|
+
async #teardown() {
|
|
486
|
+
if (this.status === "stopped") return;
|
|
623
487
|
try {
|
|
624
488
|
const now = Date.now();
|
|
625
489
|
this.logger.info("Shutting down gracefully...");
|
|
626
490
|
this.status = "stopping";
|
|
627
|
-
|
|
628
|
-
this.#metricsTimer = null;
|
|
491
|
+
this.#metrics.stop();
|
|
629
492
|
this.#di.getWebsocketAdaptor()?.clearEventHandler();
|
|
630
|
-
this.#
|
|
631
|
-
this.#wsServer?.stop(true);
|
|
632
|
-
this.#server = null;
|
|
633
|
-
this.#wsServer = null;
|
|
634
|
-
SignalContext.setHttpPeerResolver(null);
|
|
493
|
+
this.#listener.close();
|
|
635
494
|
|
|
636
|
-
this.#
|
|
637
|
-
|
|
495
|
+
this.#webRouter?.dispose();
|
|
496
|
+
this.#webRouter = null;
|
|
497
|
+
await withShutdownTimeout(this.#di.destroyAll(), this.shutdownTimeoutMs);
|
|
638
498
|
this.#prepared = null;
|
|
639
499
|
this.status = "stopped";
|
|
640
500
|
this.logger.info(`Shutdown completed successfully in ${Date.now() - now}ms`);
|
|
641
|
-
|
|
642
|
-
await this.#stopLogTransport();
|
|
643
|
-
await this.#stopFileLogging();
|
|
644
501
|
} catch (error) {
|
|
502
|
+
|
|
645
503
|
this.logger.error(`Error during shutdown: ${error instanceof Error ? error.message : String(error)}`);
|
|
646
504
|
this.status = "stopped";
|
|
647
505
|
throw error;
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
#registerParentIpc() {
|
|
652
|
-
process.on("message", (message) => this.#handleIpcMessage(message as AkanIpcMessage));
|
|
653
|
-
process.on("disconnect", () => this.#handleParentDisconnect());
|
|
654
|
-
|
|
655
|
-
if (process.send && !process.connected) this.#handleParentDisconnect();
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
#sendReady(message: AkanIpcMessage) {
|
|
659
|
-
if (process.send?.(message) === false) this.#handleParentDisconnect();
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
#handleParentDisconnect() {
|
|
663
|
-
if (this.#parentGone) return;
|
|
664
|
-
this.#parentGone = true;
|
|
665
|
-
this.logger.warn("Parent IPC channel closed; shutting down to avoid an orphaned replica");
|
|
666
|
-
setTimeout(() => this.#exitOrphaned(1), this.shutdownTimeoutMs + 1_000);
|
|
667
|
-
void this.stop()
|
|
668
|
-
.then(() => this.#exitOrphaned(0))
|
|
669
|
-
.catch(() => this.#exitOrphaned(1));
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
#exitOrphaned(code: number) {
|
|
673
|
-
if (this.#orphanExiting) return;
|
|
674
|
-
this.#orphanExiting = true;
|
|
675
|
-
OrphanGroup.exit(code);
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
#handleIpcMessage(message: AkanIpcMessage) {
|
|
679
|
-
if (!message || typeof message !== "object") return;
|
|
680
|
-
if (message.type === "health.ping")
|
|
681
|
-
process.send?.({
|
|
682
|
-
type: "health.pong",
|
|
683
|
-
nonce: message.nonce,
|
|
684
|
-
sentAt: message.sentAt,
|
|
685
|
-
pid: process.pid,
|
|
686
|
-
} satisfies AkanIpcMessage);
|
|
687
|
-
else if (message.type === "log.level") {
|
|
688
|
-
this.#logForwarder?.setMinSev(message.minSev);
|
|
689
|
-
this.#prepared?.webRouter?.setLogLevel(message.minSev);
|
|
690
|
-
} else if (message.type === "shutdown") {
|
|
691
|
-
void this.stop()
|
|
692
|
-
.then(() => process.exit(0))
|
|
693
|
-
.catch(() => process.exit(1));
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
async #reportMetrics() {
|
|
698
|
-
const metrics = await ProcessMetricsCollector.collect({
|
|
699
|
-
role: this.serverMode,
|
|
700
|
-
pubsubCoalesceCount: this.#binaryPubsub.coalescedCount,
|
|
701
|
-
...(this.#prepared?.webRouter?.getMetrics() ?? {}),
|
|
702
|
-
});
|
|
703
|
-
this.#lastMetrics = metrics;
|
|
704
|
-
process.send?.({ type: "metrics.report", pid: process.pid, metrics } satisfies AkanIpcMessage);
|
|
705
|
-
if (process.env.AKAN_MEMORY_LOG === "1") {
|
|
706
|
-
this.logger.info(`memory role=${this.serverMode} ${ProcessMetricsCollector.format(metrics)}`);
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
#assertCanGet(type = "Dependency", refName?: string) {
|
|
711
|
-
if (this.status === "initialized" || this.status === "running") return;
|
|
712
|
-
const target = refName ? `${type} "${refName}"` : type;
|
|
713
|
-
throw new Error(
|
|
714
|
-
`${target} is not initialized while AkanServer status is "${this.status}". ` +
|
|
715
|
-
"Call server.start() or server.init() first.",
|
|
716
|
-
);
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
#reportLocaleCoverage() {
|
|
720
|
-
for (const { locale, missing, total } of DictionaryRegistry.getLocaleGaps()) {
|
|
721
|
-
const listed = missing.slice(0, 10).join(", ");
|
|
722
|
-
const rest = missing.length > 10 ? `, and ${missing.length - 10} more` : "";
|
|
723
|
-
this.logger.warn(
|
|
724
|
-
`Locale "${locale}" is configured but ${missing.length}/${total} dictionaries do not declare it, so their keys fall back to the default locale: ${listed}${rest}`,
|
|
725
|
-
);
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
#timedBuiltinRoutes(webRouter: WebRouter | null): HttpRoutes {
|
|
730
|
-
const start = performance.now();
|
|
731
|
-
const builtinRoutes = this.#createBuiltinRoutes(webRouter);
|
|
732
|
-
this.#initTimings.set("builtinRoutes", performance.now() - start);
|
|
733
|
-
return builtinRoutes;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
#createBuiltinRoutes(webRouter: WebRouter | null): HttpRoutes {
|
|
737
|
-
const { appName } = getEnv();
|
|
738
|
-
const openapiRoutes: HttpRoutes = this.openapi
|
|
739
|
-
? {
|
|
740
|
-
"/openapi.json": { GET: () => Response.json(this.#getOpenApiDocument(appName)) },
|
|
741
|
-
}
|
|
742
|
-
: {};
|
|
743
|
-
|
|
744
|
-
const mcpRouter =
|
|
745
|
-
this.mcp && this.serverMode !== "batch"
|
|
746
|
-
? new McpRouter({
|
|
747
|
-
registry: this.#di.registry,
|
|
748
|
-
env: this.env,
|
|
749
|
-
live: this.#di.live,
|
|
750
|
-
middleware: new Map(this.#di.modules.middleware),
|
|
751
|
-
instructions: `Domain tools for the ${appName} app.`,
|
|
752
|
-
...this.mcpOption,
|
|
753
|
-
readOnly: this.mcpReadOnly,
|
|
754
|
-
auth: this.mcpAuth,
|
|
755
|
-
pagePrompts: webRouter?.pagePrompts(),
|
|
756
|
-
apps: this.mcpOption.apps !== false,
|
|
757
|
-
appShell: this.mcpOption.apps === false ? undefined : webRouter?.mcpAppShell(),
|
|
758
|
-
})
|
|
759
|
-
: null;
|
|
760
|
-
this.#mcpRouter = mcpRouter;
|
|
761
|
-
const mcpRoutes: HttpRoutes = mcpRouter?.createRoutes() ?? {};
|
|
762
|
-
this.#logStream ??= this.#solo ? LogStreamRoute.fromEnv(() => this.#logHub) : null;
|
|
763
|
-
const soloRoutes: HttpRoutes = this.#solo
|
|
764
|
-
? createSoloAppRoutes(
|
|
765
|
-
() => ({
|
|
766
|
-
role: this.serverMode,
|
|
767
|
-
running: this.status === "running",
|
|
768
|
-
status: this.status,
|
|
769
|
-
port: this.#server?.port ?? null,
|
|
770
|
-
rscWorker: webRouter?.rscWorkerStatus ?? null,
|
|
771
|
-
metrics: this.#lastMetrics,
|
|
772
|
-
}),
|
|
773
|
-
this.#logStream,
|
|
774
|
-
this.#opsRoute(),
|
|
775
|
-
)
|
|
776
|
-
: {};
|
|
777
|
-
|
|
778
|
-
mcpRouter?.report();
|
|
779
|
-
this.#reportLocaleCoverage();
|
|
780
|
-
|
|
781
|
-
const devtoolsRoutes = new DevtoolsRouter({
|
|
782
|
-
di: this.#di,
|
|
783
|
-
env: getEnv(),
|
|
784
|
-
name: this.name,
|
|
785
|
-
serverMode: this.serverMode,
|
|
786
|
-
prefix: this.prefix,
|
|
787
|
-
websocketPrefix: this.websocketPrefix,
|
|
788
|
-
openapi: this.openapi,
|
|
789
|
-
getStatus: () => this.status,
|
|
790
|
-
...DevtoolsRouter.buildsFrom(webRouter),
|
|
791
|
-
}).createRoutes();
|
|
792
|
-
return { ...openapiRoutes, ...mcpRoutes, ...devtoolsRoutes, ...soloRoutes };
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
#opsRoute() {
|
|
796
|
-
if (this.#ops !== undefined) return this.#ops;
|
|
797
|
-
this.#ops = OpsRoute.fromEnv({
|
|
798
|
-
detail: () => AppInfo.detail({ serverMode: this.serverMode, solo: true, replicaIdx: 0 }),
|
|
799
|
-
sources: () => this.#sqliteSources(),
|
|
800
|
-
});
|
|
801
|
-
return this.#ops;
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
#sqliteSources() {
|
|
805
|
-
const fromEnv = SqliteFiles.fromEnv();
|
|
806
|
-
const filePathOf = (refName: string) => {
|
|
807
|
-
try {
|
|
808
|
-
return (this.#di.getAdaptor(refName) as { config?: { filePath?: unknown } }).config?.filePath;
|
|
809
|
-
} catch {
|
|
810
|
-
return undefined;
|
|
811
|
-
}
|
|
812
|
-
};
|
|
813
|
-
const main = filePathOf("sqliteDatabase");
|
|
814
|
-
const solid = filePathOf("solidQueue") ?? filePathOf("solidCache");
|
|
815
|
-
return {
|
|
816
|
-
main: typeof main === "string" ? main : fromEnv.main,
|
|
817
|
-
solid: fromEnv.solid && typeof solid === "string" ? solid : fromEnv.solid,
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
#startFileLogging() {
|
|
822
|
-
if (!this.#solo || this.#logWriter) return;
|
|
823
|
-
this.#logWriter = RotatingLogWriter.fromRuntimeDir(resolveRuntimeDir());
|
|
824
|
-
if (this.#logWriter) this.#detachFileLog = HubFileSink.attach(this.#logWriter, this.#logHub, this.serverMode);
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
async #stopFileLogging() {
|
|
828
|
-
this.#detachFileLog?.();
|
|
829
|
-
this.#detachFileLog = null;
|
|
830
|
-
const writer = this.#logWriter;
|
|
831
|
-
this.#logWriter = null;
|
|
832
|
-
await writer?.close();
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
async #startLogTransport() {
|
|
836
|
-
if (this.#logHub || this.#logForwarder) return;
|
|
837
|
-
const webRouter = this.#prepared?.webRouter ?? null;
|
|
838
|
-
if (this.#solo) {
|
|
839
|
-
const hub = LogHub.attach();
|
|
840
|
-
this.#logHub = hub;
|
|
841
|
-
hub.onFloorChange((minSev) => webRouter?.setLogLevel(minSev));
|
|
842
|
-
webRouter?.onLogRecords((records, dropped) => {
|
|
843
|
-
hub.ingestMany(records);
|
|
844
|
-
if (dropped) this.logger.warn(`RSC worker dropped ${dropped} log records (ipc backpressure)`);
|
|
845
|
-
});
|
|
846
|
-
this.#logControl = await LogControlSocket.open(hub, resolveRuntimeDir(), this.logger);
|
|
847
|
-
return;
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
if (Logger.isNdjson) Logger.consoleOutput = false;
|
|
851
|
-
const forwarder = new LogForwarder((message, onSent) => process.send?.(message, undefined, undefined, onSent));
|
|
852
|
-
this.#logForwarder = forwarder;
|
|
853
|
-
webRouter?.onLogRecords((records) => forwarder.pushMany(records));
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
async #stopLogTransport() {
|
|
857
|
-
await this.#logControl?.stop();
|
|
858
|
-
this.#logControl = null;
|
|
859
|
-
this.#logHub?.close();
|
|
860
|
-
this.#logHub = null;
|
|
861
|
-
await this.#logForwarder?.close();
|
|
862
|
-
this.#logForwarder = null;
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
#getOpenApiDocument(appName: string) {
|
|
866
|
-
this.#openApiDocument ??= createOpenApiDocument(FetchSerializer.serializeRegistry(this.#di.live).signal, {
|
|
867
|
-
title: `${appName} API`,
|
|
868
|
-
version: "0.0.0",
|
|
869
|
-
servers: this.#getOpenApiServers(),
|
|
870
|
-
resolveDescription: AkanServer.#createDescriptionResolver(),
|
|
871
|
-
});
|
|
872
|
-
return this.#openApiDocument;
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
static #createDescriptionResolver() {
|
|
876
|
-
const lookup = new DictionaryLookup();
|
|
877
|
-
return (key: string) => lookup.text(key);
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
#getOpenApiServers() {
|
|
881
|
-
const serverHttpUri = (this.env as { serverHttpUri?: string }).serverHttpUri;
|
|
882
|
-
if (!serverHttpUri) return undefined;
|
|
883
|
-
const withoutPrefix = serverHttpUri.replace(/\/$/, "");
|
|
884
|
-
return [{ url: withoutPrefix.endsWith(this.prefix) ? withoutPrefix.slice(0, -this.prefix.length) : withoutPrefix }];
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
static #requireRoutePrefix(value: string, field: string) {
|
|
888
|
-
const normalized = normalizeRoutePrefix(value);
|
|
889
|
-
if (!normalized) throw new Error(`${field} must be a path segment such as "/api"; "${value}" is not one.`);
|
|
890
|
-
return normalized;
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
#assertPrefixClearsBasePaths() {
|
|
894
|
-
const basePaths = parseBasePaths(process.env.AKAN_PUBLIC_BASE_PATHS);
|
|
895
|
-
const first = this.prefix.split("/")[1];
|
|
896
|
-
const collision = basePaths.find((basePath) => basePath === first);
|
|
897
|
-
if (!collision) return;
|
|
898
|
-
throw new Error(`Route prefix "${this.prefix}" collides with the "${collision}" basePath; give the API its own.`);
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
static #splitLibsAndOptions(libsOrOptions: (AkanLib | AkanServerOptions)[]) {
|
|
902
|
-
const last = libsOrOptions.at(-1);
|
|
903
|
-
const options = AkanServer.#isServerOptions(last) ? last : undefined;
|
|
904
|
-
const libs = (options ? libsOrOptions.slice(0, -1) : libsOrOptions) as AkanLib[];
|
|
905
|
-
return { libs, options };
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
static #isServerOptions(value: AkanLib | AkanServerOptions | undefined): value is AkanServerOptions {
|
|
909
|
-
return Boolean(
|
|
910
|
-
value &&
|
|
911
|
-
!("database" in value) &&
|
|
912
|
-
!("service" in value) &&
|
|
913
|
-
!("scalar" in value) &&
|
|
914
|
-
("openapi" in value ||
|
|
915
|
-
"mcp" in value ||
|
|
916
|
-
"modules" in value ||
|
|
917
|
-
"disableModules" in value ||
|
|
918
|
-
"disableLibs" in value),
|
|
919
|
-
);
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
static #isEdge(env: BackendEnv) {
|
|
923
|
-
return ((env as { operationMode?: string }).operationMode ?? process.env.AKAN_PUBLIC_OPERATION_MODE) === "edge";
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
static #isEnvEnabled(...names: string[]) {
|
|
927
|
-
return names.some((name) => process.env[name] === "true" || process.env[name] === "1");
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
static #narrowWeb(current: AkanWebConfig, web: AkanWebOption | undefined): AkanWebConfig {
|
|
931
|
-
if (web === undefined || web === true) return current;
|
|
932
|
-
if (web === false) return { ssr: false, csr: false };
|
|
933
|
-
return { ssr: current.ssr, csr: web.csr && current.csr };
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
static #isEnvOff(...names: string[]) {
|
|
937
|
-
return names.some((name) => process.env[name] === "false" || process.env[name] === "0");
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
static #mcpAuthFromEnv(): McpAuthOption {
|
|
941
|
-
const authorizationServers = AkanServer.#envList("AKAN_MCP_AUTH_SERVERS");
|
|
942
|
-
const scopes = AkanServer.#envList("AKAN_MCP_SCOPES");
|
|
943
|
-
return {
|
|
944
|
-
...(authorizationServers?.length ? { authorizationServers } : {}),
|
|
945
|
-
...(scopes?.length ? { scopes } : {}),
|
|
946
|
-
...(process.env.AKAN_MCP_RESOURCE ? { resource: process.env.AKAN_MCP_RESOURCE } : {}),
|
|
947
|
-
};
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
static #defined<T extends object>(source: T): Partial<T> {
|
|
951
|
-
return Object.fromEntries(Object.entries(source).filter(([, value]) => value !== undefined)) as Partial<T>;
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
static #mcpOptionFromEnv(): Omit<McpServerOption, "enabled" | "readOnly" | "auth"> {
|
|
955
|
-
const allowedOrigins = AkanServer.#envList("AKAN_MCP_ALLOWED_ORIGINS");
|
|
956
|
-
const pageSize = Number(process.env.AKAN_MCP_PAGE_SIZE);
|
|
957
|
-
const promptBudget = Number(process.env.AKAN_MCP_PROMPT_BUDGET);
|
|
958
|
-
return {
|
|
959
|
-
...AkanServer.#mcpPathFromEnv(),
|
|
960
|
-
...(process.env.AKAN_MCP_VERSION ? { version: process.env.AKAN_MCP_VERSION } : {}),
|
|
961
|
-
...(process.env.AKAN_MCP_INSTRUCTIONS ? { instructions: process.env.AKAN_MCP_INSTRUCTIONS } : {}),
|
|
962
|
-
...(allowedOrigins?.length ? { allowedOrigins } : {}),
|
|
963
|
-
...(Number.isInteger(pageSize) && pageSize > 0 ? { pageSize } : {}),
|
|
964
|
-
...(Number.isInteger(promptBudget) && promptBudget > 0 ? { promptBudget } : {}),
|
|
965
|
-
...(process.env.AKAN_MCP_LANGUAGE ? { language: process.env.AKAN_MCP_LANGUAGE } : {}),
|
|
966
|
-
...(AkanServer.#isEnvOff("AKAN_MCP_LEGACY_TEXT") ? { legacyTextBlock: false } : {}),
|
|
967
|
-
...(AkanServer.#isEnvOff("AKAN_MCP_APPS") ? { apps: false } : {}),
|
|
968
|
-
...AkanServer.#mcpModernFromEnv(),
|
|
969
|
-
...AkanServer.#mcpOutputSchemaFromEnv(),
|
|
970
|
-
...AkanServer.#mcpRateLimitFromEnv(),
|
|
971
|
-
};
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
static #mcpModernFromEnv(): Pick<McpServerOption, "modern"> {
|
|
975
|
-
if (AkanServer.#isEnvEnabled("AKAN_MCP_MODERN")) return { modern: true };
|
|
976
|
-
return AkanServer.#isEnvOff("AKAN_MCP_MODERN") ? { modern: false } : {};
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
static #mcpRateLimitFromEnv(): Pick<McpServerOption, "rateLimit"> {
|
|
980
|
-
const raw = process.env.AKAN_MCP_RATE_LIMIT?.trim().toLowerCase();
|
|
981
|
-
if (raw === "off" || raw === "false" || raw === "0") return { rateLimit: false };
|
|
982
|
-
const option: McpRateLimitOption = {};
|
|
983
|
-
if (raw) {
|
|
984
|
-
const [calls, seconds] = raw.split("/").map((part) => Number(part));
|
|
985
|
-
if (Number.isInteger(calls) && calls > 0) option.calls = calls;
|
|
986
|
-
if (Number.isInteger(seconds) && seconds > 0) option.windowMs = seconds * 1000;
|
|
987
|
-
}
|
|
988
|
-
const concurrent = Number(process.env.AKAN_MCP_CONCURRENT);
|
|
989
|
-
if (Number.isInteger(concurrent) && concurrent >= 0) option.concurrent = concurrent;
|
|
990
|
-
return Object.keys(option).length ? { rateLimit: option } : {};
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
static #mcpOutputSchemaFromEnv(): Pick<McpServerOption, "outputSchema"> {
|
|
994
|
-
const value = process.env.AKAN_MCP_OUTPUT_SCHEMA;
|
|
995
|
-
return value === "full" || value === "shallow" || value === "none" ? { outputSchema: value } : {};
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
static #mcpPathFromEnv() {
|
|
999
|
-
const path = process.env.AKAN_MCP_PATH?.trim();
|
|
1000
|
-
if (!path) return {};
|
|
1001
|
-
return { path: path.startsWith("/") ? path : `/${path}` };
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
static #envList(name: string) {
|
|
1005
|
-
return process.env[name]
|
|
1006
|
-
?.split(",")
|
|
1007
|
-
.map((entry) => entry.trim())
|
|
1008
|
-
.filter(Boolean);
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
static #defaultShutdownTimeoutMs() {
|
|
1012
|
-
const configured = Number(process.env.AKAN_SHUTDOWN_TIMEOUT_MS);
|
|
1013
|
-
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
1014
|
-
return process.env.AKAN_COMMAND_TYPE === "start" ? 3_000 : 30_000;
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
async #withShutdownTimeout<T>(promise: Promise<T>) {
|
|
1018
|
-
let timeout: Timer | null = null;
|
|
1019
|
-
try {
|
|
1020
|
-
return await Promise.race([
|
|
1021
|
-
promise,
|
|
1022
|
-
new Promise<T>((_, reject) => {
|
|
1023
|
-
timeout = setTimeout(
|
|
1024
|
-
() => reject(new Error(`Shutdown timed out after ${this.shutdownTimeoutMs}ms`)),
|
|
1025
|
-
this.shutdownTimeoutMs,
|
|
1026
|
-
);
|
|
1027
|
-
}),
|
|
1028
|
-
]);
|
|
1029
506
|
} finally {
|
|
1030
|
-
|
|
507
|
+
|
|
508
|
+
await this.#logging.stop();
|
|
1031
509
|
}
|
|
1032
510
|
}
|
|
1033
511
|
}
|
|
512
|
+
|
|
513
|
+
const assertCanGet = (status: AkanServer["status"], type = "Dependency", refName?: string) => {
|
|
514
|
+
if (status === "initialized" || status === "running") return;
|
|
515
|
+
const target = refName ? `${type} "${refName}"` : type;
|
|
516
|
+
throw new AkanError(
|
|
517
|
+
"notInitialized",
|
|
518
|
+
`${target} is not initialized while AkanServer status is "${status}". ` +
|
|
519
|
+
"Call server.start() or server.init() first.",
|
|
520
|
+
);
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
const withShutdownTimeout = async <T>(promise: Promise<T>, timeoutMs: number) => {
|
|
524
|
+
let timeout: Timer | null = null;
|
|
525
|
+
try {
|
|
526
|
+
return await Promise.race([
|
|
527
|
+
promise,
|
|
528
|
+
new Promise<T>((_, reject) => {
|
|
529
|
+
timeout = setTimeout(
|
|
530
|
+
() => reject(new AkanError("shutdownTimeout", `Shutdown timed out after ${timeoutMs}ms`)),
|
|
531
|
+
timeoutMs,
|
|
532
|
+
);
|
|
533
|
+
}),
|
|
534
|
+
]);
|
|
535
|
+
} finally {
|
|
536
|
+
if (timeout) clearTimeout(timeout);
|
|
537
|
+
}
|
|
538
|
+
};
|