akanjs 3.2.0-rc.2 → 3.2.0-rc.21

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.
Files changed (667) hide show
  1. package/ARCHITECTURE.md +42 -41
  2. package/CHANGELOG.md +593 -3
  3. package/CONTRIBUTING.md +26 -0
  4. package/base/base.ts +2 -1
  5. package/client/clientRuntime.ts +1 -0
  6. package/client/cn.ts +2 -2
  7. package/client/csrTypes.ts +15 -1
  8. package/client/frameConfig.ts +5 -2
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +33 -82
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/RouteDefinition.ts +24 -7
  14. package/client/route/RouteGuards.ts +2 -1
  15. package/client/route/RouteHead.ts +11 -2
  16. package/client/route/routeArgs.ts +7 -0
  17. package/client/router.ts +25 -6
  18. package/client/rscNavigation.ts +3 -3
  19. package/client/rscRoutePatch.ts +42 -0
  20. package/client/viewportMeta.ts +34 -4
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/PipelinePlanSchema.ts +2 -2
  23. package/common/akanGraph.ts +1 -1
  24. package/common/err.ts +122 -0
  25. package/common/facetBarrel.ts +38 -0
  26. package/common/failureCode.ts +18 -0
  27. package/common/index.ts +9 -0
  28. package/common/isGuardRefusal.ts +14 -0
  29. package/common/mcpExposure.ts +17 -4
  30. package/common/mcpFailure.ts +9 -0
  31. package/common/pipelinePlan.ts +1 -1
  32. package/common/restartSchedule.ts +55 -0
  33. package/common/routeConvention.ts +3 -1
  34. package/common/types.ts +18 -1
  35. package/constant/constantRegistry.ts +4 -8
  36. package/constant/crystalize.ts +1 -2
  37. package/constant/getDefault.ts +1 -1
  38. package/constant/immerify.ts +1 -1
  39. package/constant/index.ts +78 -21
  40. package/constant/purify.ts +4 -9
  41. package/constant/serialize.ts +4 -2
  42. package/constant/types.ts +1 -0
  43. package/constant/via.ts +1 -2
  44. package/dictionary/agent.dictionary.ts +4 -0
  45. package/dictionary/base.dictionary.ts +1 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/databaseRegistry.ts +2 -1
  49. package/document/documentSchema.ts +1 -0
  50. package/document/filterMeta.ts +4 -1
  51. package/document/into.ts +2 -1
  52. package/document/loaderInfo.ts +2 -1
  53. package/document/noDocumentError.ts +4 -1
  54. package/document/queryEvaluator.ts +1 -1
  55. package/document/types.ts +1 -1
  56. package/fetch/client/fetchClient.ts +87 -270
  57. package/fetch/client/fetchClientTypes.ts +49 -0
  58. package/fetch/client/fetchHandle.ts +11 -1
  59. package/fetch/client/httpClient.ts +14 -2
  60. package/fetch/client/inflightQueries.ts +17 -0
  61. package/fetch/client/remoteError.ts +4 -20
  62. package/fetch/client/requestScope.ts +32 -0
  63. package/fetch/client/signalCatalog.ts +131 -0
  64. package/fetch/client/wsClient.ts +11 -0
  65. package/fetch/index.ts +1 -0
  66. package/fetch/staleReads.ts +27 -0
  67. package/fetch/streamedRead.ts +23 -0
  68. package/package.json +1 -1
  69. package/server/agentHooks.ts +16 -0
  70. package/server/akanApp.ts +107 -1272
  71. package/server/akanOption.ts +17 -4
  72. package/server/akanServer.ts +167 -675
  73. package/server/artifact/builderRpc.ts +33 -10
  74. package/server/artifact/ipcTypes.ts +9 -3
  75. package/server/artifact/routeSeedIndexStore.ts +4 -2
  76. package/server/assetHeaders.ts +6 -0
  77. package/server/console.ts +6 -4
  78. package/server/decorators.ts +2 -2
  79. package/server/devtools/README.md +4 -3
  80. package/server/devtools/devtoolsRouter.ts +9 -5
  81. package/server/devtools/studio/studioRoute.ts +18 -11
  82. package/server/di/diLifecycle.ts +24 -35
  83. package/server/di/predefinedAdaptor.ts +24 -1
  84. package/server/di/resolveHierarchy.ts +19 -6
  85. package/server/di/utils.ts +7 -3
  86. package/server/ed25519Key.ts +31 -15
  87. package/server/flightRowReader.ts +95 -18
  88. package/server/gateway/childSupervisor.ts +326 -0
  89. package/server/gateway/devHostChannel.ts +47 -0
  90. package/server/gateway/gatewayChildren.ts +135 -0
  91. package/server/gateway/gatewayConfig.ts +182 -0
  92. package/server/gateway/gatewayHttpProxy.ts +231 -0
  93. package/server/gateway/gatewayLogging.ts +111 -0
  94. package/server/gateway/gatewayRooms.ts +141 -0
  95. package/server/gateway/gatewayStatus.ts +116 -0
  96. package/server/gateway/gatewayStatusPage.ts +54 -0
  97. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  98. package/server/head.tsx +4 -19
  99. package/server/hmr/devHmrController.ts +10 -1
  100. package/server/htmlResultCache.ts +234 -0
  101. package/server/imageOptimizer.ts +4 -1
  102. package/server/index.ts +257 -17
  103. package/server/lifecycle/parentChannel.ts +78 -0
  104. package/server/lifecycle/shutdownManager.ts +6 -3
  105. package/server/lifecycle/startGuard.ts +90 -0
  106. package/server/logging/logControlSocket.ts +42 -3
  107. package/server/logging/serverLogging.ts +74 -0
  108. package/server/machine/machineToken.ts +10 -3
  109. package/server/mcp/AgentTools.ts +149 -0
  110. package/server/mcp/AgentToolsAccount.ts +26 -0
  111. package/server/mcp/McpDispatcher.ts +48 -19
  112. package/server/mcp/McpPages.ts +21 -6
  113. package/server/mcp/McpRateLimiter.ts +14 -0
  114. package/server/mcp/McpRouter.ts +52 -23
  115. package/server/mcp/McpUiSession.ts +2 -1
  116. package/server/mcp/index.ts +1 -0
  117. package/server/nativeFile.ts +30 -11
  118. package/server/nativeSecret.ts +12 -3
  119. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  120. package/server/ops/opsRoute.ts +5 -1
  121. package/server/ops/opsToken.ts +3 -1
  122. package/server/resolver/CascadeRunner.ts +10 -4
  123. package/server/resolver/database.resolver.ts +10 -417
  124. package/server/resolver/databaseModelInstance.ts +200 -0
  125. package/server/resolver/invalidSignal.ts +7 -0
  126. package/server/resolver/livePause.ts +34 -0
  127. package/server/resolver/modelFacade.ts +136 -0
  128. package/server/resolver/modelLoaders.ts +52 -0
  129. package/server/resolver/modelSchema.ts +52 -0
  130. package/server/resolver/signal.resolver.ts +92 -116
  131. package/server/resolver/timedQuery.ts +16 -0
  132. package/server/resolver/websocketOf.ts +23 -0
  133. package/server/routeElementComposer.tsx +131 -9
  134. package/server/routeState.ts +5 -1
  135. package/server/routeTreeBuilder.ts +22 -9
  136. package/server/routing/apiRouter.ts +44 -25
  137. package/server/routing/builtinRoutes.ts +194 -0
  138. package/server/routing/localRooms.ts +34 -0
  139. package/server/routing/roomReplay.ts +2 -2
  140. package/server/routing/serverLimits.ts +4 -1
  141. package/server/routing/serverListener.ts +194 -0
  142. package/server/rscClient.tsx +210 -227
  143. package/server/rscClientCache.ts +165 -0
  144. package/server/rscClientChunks.ts +209 -0
  145. package/server/rscClientFetch.ts +15 -3
  146. package/server/rscClientPatch.ts +78 -15
  147. package/server/rscDocumentHead.tsx +170 -0
  148. package/server/rscFlightRenderer.ts +83 -0
  149. package/server/rscFlightStream.ts +257 -0
  150. package/server/rscHeadPatch.ts +17 -56
  151. package/server/rscHostReloads.ts +238 -0
  152. package/server/rscHostRenderStream.ts +297 -0
  153. package/server/rscHostRequests.ts +158 -0
  154. package/server/rscHttp.ts +18 -6
  155. package/server/rscInlineStream.ts +34 -0
  156. package/server/rscNavigationState.ts +21 -1
  157. package/server/rscPagePrompts.ts +11 -5
  158. package/server/rscParkedRedirect.ts +23 -0
  159. package/server/rscPatchPlanner.ts +220 -0
  160. package/server/rscPrefetchCache.ts +68 -32
  161. package/server/rscRenderControl.ts +33 -0
  162. package/server/rscRenderFallbacks.ts +297 -0
  163. package/server/rscRenderHandler.ts +439 -0
  164. package/server/rscRenderStats.ts +49 -0
  165. package/server/rscResponse.ts +78 -0
  166. package/server/rscResultCaches.ts +74 -0
  167. package/server/rscRouteDocument.tsx +299 -0
  168. package/server/rscSegmentOutlet.tsx +24 -5
  169. package/server/rscSegmentOutletReference.ts +14 -12
  170. package/server/rscWorker.tsx +86 -1392
  171. package/server/rscWorkerCache.ts +56 -0
  172. package/server/rscWorkerHost.ts +145 -811
  173. package/server/rscWorkerProcess.ts +155 -0
  174. package/server/rscWorkerRecycler.ts +128 -0
  175. package/server/serverConfig.ts +128 -0
  176. package/server/serverMetrics.ts +52 -0
  177. package/server/sitemap.ts +1 -0
  178. package/server/ssrFromRscRenderer.tsx +20 -20
  179. package/server/ssrTypes.ts +9 -0
  180. package/server/webArtifact.ts +86 -0
  181. package/server/webAssetRoutes.ts +84 -0
  182. package/server/webCsrSurface.ts +172 -0
  183. package/server/webDocumentRoute.ts +180 -0
  184. package/server/webRouteContext.ts +232 -0
  185. package/server/webRouter.ts +126 -1242
  186. package/server/webRscRoute.ts +155 -0
  187. package/server/webSiteFiles.ts +139 -0
  188. package/server/wellKnownRoutes.ts +73 -0
  189. package/service/agent.service.ts +59 -5
  190. package/service/agentAccounts.ts +19 -0
  191. package/service/agentLoop/agentLoop.ts +387 -0
  192. package/service/agentLoop/agentLoopTypes.ts +112 -0
  193. package/service/agentLoop/deltaStream.ts +40 -0
  194. package/service/agentLoop/loopCompaction.ts +135 -0
  195. package/service/agentLoop/loopRequest.ts +62 -0
  196. package/service/agentLoop/loopToolOutput.ts +54 -0
  197. package/service/agentLoop/loopToolkits.ts +107 -0
  198. package/service/agentLoop/loopTranscript.ts +102 -0
  199. package/{signal → service}/agentMeter.ts +83 -15
  200. package/{signal → service}/agentRelayPolicy.ts +30 -7
  201. package/service/documentStoreError.ts +16 -0
  202. package/service/index.ts +7 -0
  203. package/service/injectError.ts +5 -0
  204. package/service/injectInfo.ts +30 -18
  205. package/service/insightQueryError.ts +19 -0
  206. package/service/ipcTypes.ts +3 -1
  207. package/service/liveSyncHub.ts +5 -2
  208. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  209. package/service/predefinedAdaptor/anthropicLlm.ts +52 -21
  210. package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
  211. package/service/predefinedAdaptor/compress.adaptor.ts +7 -3
  212. package/service/predefinedAdaptor/database.adaptor.ts +3 -1
  213. package/service/predefinedAdaptor/documentTransfer.ts +2 -1
  214. package/service/predefinedAdaptor/index.ts +2 -0
  215. package/service/predefinedAdaptor/insightQuery.ts +35 -11
  216. package/service/predefinedAdaptor/llm.adaptor.ts +22 -2
  217. package/service/predefinedAdaptor/llmSpend.ts +80 -0
  218. package/service/predefinedAdaptor/openaiDialect.ts +52 -17
  219. package/service/predefinedAdaptor/openaiLlm.ts +17 -9
  220. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  221. package/service/predefinedAdaptor/searchIndex.ts +5 -1
  222. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  223. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  224. package/service/predefinedAdaptor/solidSqlite.ts +3 -2
  225. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  226. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  227. package/service/predefinedAdaptor/sql/DocumentWriter.ts +292 -0
  228. package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
  229. package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
  230. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  231. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  232. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
  233. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +83 -1124
  234. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +319 -0
  235. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
  238. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
  239. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  240. package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
  241. package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
  242. package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
  243. package/service/predefinedAdaptor/sql/values.ts +8 -4
  244. package/service/predefinedAdaptor/sseData.ts +14 -0
  245. package/service/predefinedAdaptor/storage.adaptor.ts +9 -4
  246. package/service/predefinedAdaptor/websocket.adaptor.ts +199 -43
  247. package/service/serve.ts +3 -2
  248. package/service/serviceModule.ts +2 -2
  249. package/service/serviceRegistry.ts +1 -0
  250. package/signal/SignalFailure.ts +30 -1
  251. package/signal/agent.signal.ts +30 -9
  252. package/signal/agentTurnStream.ts +12 -8
  253. package/signal/byIdRead.ts +18 -0
  254. package/signal/carriedClientIps.ts +1 -0
  255. package/signal/endpointErrorContract.ts +20 -2
  256. package/signal/endpointInfo.ts +6 -5
  257. package/signal/exception.ts +1 -0
  258. package/signal/index.ts +314 -30
  259. package/signal/internalInfo.ts +6 -4
  260. package/signal/mcp/McpDocument.ts +8 -1
  261. package/signal/mcp/Msg.ts +23 -10
  262. package/signal/mcp/index.ts +1 -0
  263. package/signal/mcp/promptError.ts +9 -0
  264. package/signal/middleware.ts +12 -3
  265. package/signal/openapi/openapi.ts +10 -1
  266. package/signal/resolveFieldContext.ts +34 -0
  267. package/signal/serializer/fetch.serializer.ts +23 -15
  268. package/signal/signalContext.ts +24 -57
  269. package/signal/signalContractError.ts +10 -0
  270. package/signal/signalDeclarationError.ts +13 -0
  271. package/signal/signalRegistry.ts +3 -1
  272. package/signal/slice.ts +24 -20
  273. package/signal/sliceInfo.ts +12 -9
  274. package/signal/trace.ts +3 -0
  275. package/signal/types.ts +35 -6
  276. package/store/action.ts +44 -1086
  277. package/store/actionErrorKey.ts +9 -0
  278. package/store/actionOption.ts +22 -0
  279. package/store/baseSt.ts +1 -0
  280. package/store/draftFlush.ts +5 -0
  281. package/store/draftStore.ts +2 -0
  282. package/store/formDrafts.ts +115 -0
  283. package/store/formFieldSetters.ts +229 -0
  284. package/store/index.ts +125 -17
  285. package/store/modelActionContext.ts +65 -0
  286. package/store/modelListPatch.ts +53 -0
  287. package/store/modelOpenActions.ts +158 -0
  288. package/store/modelWriteActions.ts +240 -0
  289. package/store/modelWriteGuard.ts +82 -0
  290. package/store/openSeq.ts +34 -0
  291. package/store/rootStore.ts +2 -0
  292. package/store/sliceListActions.ts +370 -0
  293. package/store/sliceLiveActions.ts +130 -0
  294. package/store/stateBuilder.ts +2 -0
  295. package/store/storeInstance.ts +9 -10
  296. package/store/uploadPoll.ts +52 -0
  297. package/store/withSelector.ts +6 -4
  298. package/types/base/base.d.ts +2 -1
  299. package/types/client/clientRuntime.d.ts +1 -0
  300. package/types/client/cn.d.ts +2 -2
  301. package/types/client/csrTypes.d.ts +15 -1
  302. package/types/client/frameConfig.d.ts +1 -0
  303. package/types/client/index.d.ts +25 -26
  304. package/types/client/locale.d.ts +1 -0
  305. package/types/client/makePageProto.d.ts +28 -26091
  306. package/types/client/nativeThemeColor.d.ts +6 -0
  307. package/types/client/route/RouteDefinition.d.ts +2 -2
  308. package/types/client/route/RouteHead.d.ts +5 -1
  309. package/types/client/route/routeArgs.d.ts +6 -0
  310. package/types/client/router.d.ts +6 -3
  311. package/types/client/rscNavigation.d.ts +3 -2
  312. package/types/client/rscRoutePatch.d.ts +22 -0
  313. package/types/client/viewportMeta.d.ts +3 -1
  314. package/types/common/CodeTranscript.d.ts +1 -1
  315. package/types/common/akanGraph.d.ts +1 -1
  316. package/types/common/err.d.ts +48 -0
  317. package/types/common/facetBarrel.d.ts +4 -0
  318. package/types/common/failureCode.d.ts +6 -0
  319. package/types/common/index.d.ts +8 -2
  320. package/types/common/isGuardRefusal.d.ts +3 -0
  321. package/types/common/mcpExposure.d.ts +9 -2
  322. package/types/common/mcpFailure.d.ts +6 -0
  323. package/types/common/restartSchedule.d.ts +16 -0
  324. package/types/common/routeConvention.d.ts +2 -0
  325. package/types/common/types.d.ts +18 -1
  326. package/types/constant/constantRegistry.d.ts +3 -1
  327. package/types/constant/crystalize.d.ts +1 -1
  328. package/types/constant/getDefault.d.ts +1 -1
  329. package/types/constant/immerify.d.ts +1 -1
  330. package/types/constant/index.d.ts +21 -21
  331. package/types/constant/purify.d.ts +2 -1
  332. package/types/constant/serialize.d.ts +1 -1
  333. package/types/constant/types.d.ts +1 -0
  334. package/types/dictionary/agent.dictionary.d.ts +1 -1
  335. package/types/dictionary/base.dictionary.d.ts +1 -1
  336. package/types/dictionary/dictionary.d.ts +9 -9
  337. package/types/dictionary/locale.d.ts +1 -1
  338. package/types/dictionary/trans.d.ts +3 -26
  339. package/types/document/databaseRegistry.d.ts +2 -1
  340. package/types/document/documentSchema.d.ts +1 -0
  341. package/types/document/filterMeta.d.ts +4 -1
  342. package/types/document/into.d.ts +1 -1
  343. package/types/document/loaderInfo.d.ts +2 -1
  344. package/types/document/noDocumentError.d.ts +8 -1
  345. package/types/document/queryEvaluator.d.ts +1 -1
  346. package/types/document/types.d.ts +1 -1
  347. package/types/fetch/client/fetchClient.d.ts +6 -36
  348. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  349. package/types/fetch/client/fetchHandle.d.ts +1 -0
  350. package/types/fetch/client/httpClient.d.ts +2 -0
  351. package/types/fetch/client/inflightQueries.d.ts +2 -0
  352. package/types/fetch/client/remoteError.d.ts +0 -4
  353. package/types/fetch/client/requestScope.d.ts +6 -0
  354. package/types/fetch/client/signalCatalog.d.ts +25 -0
  355. package/types/fetch/client/wsClient.d.ts +1 -0
  356. package/types/fetch/index.d.ts +1 -0
  357. package/types/fetch/staleReads.d.ts +8 -0
  358. package/types/fetch/streamedRead.d.ts +8 -0
  359. package/types/server/agentHooks.d.ts +4 -0
  360. package/types/server/akanApp.d.ts +2 -20
  361. package/types/server/akanOption.d.ts +9 -3
  362. package/types/server/akanServer.d.ts +1 -1
  363. package/types/server/artifact/builderRpc.d.ts +8 -0
  364. package/types/server/artifact/ipcTypes.d.ts +8 -0
  365. package/types/server/assetHeaders.d.ts +1 -0
  366. package/types/server/console.d.ts +4 -3
  367. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  368. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  369. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  370. package/types/server/ed25519Key.d.ts +1 -0
  371. package/types/server/flightRowReader.d.ts +3 -1
  372. package/types/server/gateway/childSupervisor.d.ts +33 -0
  373. package/types/server/gateway/devHostChannel.d.ts +14 -0
  374. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  375. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  376. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  377. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  378. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  379. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  380. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  381. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  382. package/types/server/head.d.ts +2 -2
  383. package/types/server/htmlResultCache.d.ts +51 -0
  384. package/types/server/index.d.ts +17 -17
  385. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  386. package/types/server/lifecycle/startGuard.d.ts +10 -0
  387. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  388. package/types/server/logging/serverLogging.d.ts +12 -0
  389. package/types/server/mcp/AgentTools.d.ts +31 -0
  390. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  391. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  392. package/types/server/mcp/McpPages.d.ts +2 -1
  393. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  394. package/types/server/mcp/index.d.ts +1 -0
  395. package/types/server/resolver/database.resolver.d.ts +2 -2
  396. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  397. package/types/server/resolver/invalidSignal.d.ts +2 -0
  398. package/types/server/resolver/livePause.d.ts +5 -0
  399. package/types/server/resolver/modelFacade.d.ts +5 -0
  400. package/types/server/resolver/modelLoaders.d.ts +9 -0
  401. package/types/server/resolver/modelSchema.d.ts +6 -0
  402. package/types/server/resolver/signal.resolver.d.ts +2 -2
  403. package/types/server/resolver/timedQuery.d.ts +8 -0
  404. package/types/server/resolver/websocketOf.d.ts +2 -0
  405. package/types/server/routeElementComposer.d.ts +45 -6
  406. package/types/server/routeState.d.ts +2 -0
  407. package/types/server/routing/builtinRoutes.d.ts +24 -0
  408. package/types/server/routing/localRooms.d.ts +14 -0
  409. package/types/server/routing/roomReplay.d.ts +2 -2
  410. package/types/server/routing/serverListener.d.ts +31 -0
  411. package/types/server/rscClient.d.ts +1 -5
  412. package/types/server/rscClientCache.d.ts +34 -0
  413. package/types/server/rscClientChunks.d.ts +18 -0
  414. package/types/server/rscClientFetch.d.ts +1 -1
  415. package/types/server/rscClientPatch.d.ts +12 -1
  416. package/types/server/rscDocumentHead.d.ts +32 -0
  417. package/types/server/rscFlightRenderer.d.ts +14 -0
  418. package/types/server/rscFlightStream.d.ts +52 -0
  419. package/types/server/rscHeadPatch.d.ts +5 -4
  420. package/types/server/rscHostReloads.d.ts +54 -0
  421. package/types/server/rscHostRenderStream.d.ts +53 -0
  422. package/types/server/rscHostRequests.d.ts +29 -0
  423. package/types/server/rscHttp.d.ts +4 -2
  424. package/types/server/rscInlineStream.d.ts +9 -0
  425. package/types/server/rscNavigationState.d.ts +8 -3
  426. package/types/server/rscParkedRedirect.d.ts +12 -0
  427. package/types/server/rscPatchPlanner.d.ts +49 -0
  428. package/types/server/rscPrefetchCache.d.ts +8 -7
  429. package/types/server/rscRenderControl.d.ts +12 -0
  430. package/types/server/rscRenderFallbacks.d.ts +41 -0
  431. package/types/server/rscRenderHandler.d.ts +29 -0
  432. package/types/server/rscRenderStats.d.ts +32 -0
  433. package/types/server/rscResponse.d.ts +9 -0
  434. package/types/server/rscResultCaches.d.ts +18 -0
  435. package/types/server/rscRouteDocument.d.ts +52 -0
  436. package/types/server/rscSegmentOutlet.d.ts +5 -0
  437. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  438. package/types/server/rscWorker.d.ts +1 -3
  439. package/types/server/rscWorkerCache.d.ts +33 -1
  440. package/types/server/rscWorkerHost.d.ts +9 -76
  441. package/types/server/rscWorkerProcess.d.ts +31 -0
  442. package/types/server/rscWorkerRecycler.d.ts +22 -0
  443. package/types/server/serverConfig.d.ts +30 -0
  444. package/types/server/serverMetrics.d.ts +11 -0
  445. package/types/server/sitemap.d.ts +1 -0
  446. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  447. package/types/server/ssrTypes.d.ts +8 -0
  448. package/types/server/webArtifact.d.ts +7 -0
  449. package/types/server/webAssetRoutes.d.ts +11 -0
  450. package/types/server/webCsrSurface.d.ts +18 -0
  451. package/types/server/webDocumentRoute.d.ts +19 -0
  452. package/types/server/webRouteContext.d.ts +45 -0
  453. package/types/server/webRouter.d.ts +4 -35
  454. package/types/server/webRscRoute.d.ts +24 -0
  455. package/types/server/webSiteFiles.d.ts +12 -0
  456. package/types/server/wellKnownRoutes.d.ts +5 -0
  457. package/types/service/agent.service.d.ts +13 -4
  458. package/types/service/agentAccounts.d.ts +8 -0
  459. package/types/service/agentLoop/agentLoop.d.ts +31 -0
  460. package/types/service/agentLoop/agentLoopTypes.d.ts +126 -0
  461. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  462. package/types/service/agentLoop/loopCompaction.d.ts +11 -0
  463. package/types/service/agentLoop/loopRequest.d.ts +6 -0
  464. package/types/service/agentLoop/loopToolOutput.d.ts +7 -0
  465. package/types/service/agentLoop/loopToolkits.d.ts +14 -0
  466. package/types/service/agentLoop/loopTranscript.d.ts +12 -0
  467. package/types/service/agentMeter.d.ts +50 -0
  468. package/types/service/agentRelayPolicy.d.ts +45 -0
  469. package/types/service/documentStoreError.d.ts +7 -0
  470. package/types/service/index.d.ts +7 -0
  471. package/types/service/injectError.d.ts +4 -0
  472. package/types/service/injectInfo.d.ts +2 -1
  473. package/types/service/insightQueryError.d.ts +9 -0
  474. package/types/service/ipcTypes.d.ts +6 -0
  475. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  476. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  477. package/types/service/predefinedAdaptor/index.d.ts +2 -0
  478. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +18 -2
  479. package/types/service/predefinedAdaptor/llmSpend.d.ts +22 -0
  480. package/types/service/predefinedAdaptor/openaiDialect.d.ts +2 -1
  481. package/types/service/predefinedAdaptor/openaiLlm.d.ts +1 -1
  482. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  483. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  484. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  485. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  486. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  487. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +24 -0
  488. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  489. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  490. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -32
  491. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +20 -0
  492. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  493. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
  494. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  495. package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
  496. package/types/service/predefinedAdaptor/sseData.d.ts +5 -0
  497. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +14 -5
  498. package/types/service/serviceModule.d.ts +1 -1
  499. package/types/service/serviceRegistry.d.ts +1 -0
  500. package/types/signal/SignalFailure.d.ts +2 -0
  501. package/types/signal/agentTurnStream.d.ts +2 -1
  502. package/types/signal/byIdRead.d.ts +7 -0
  503. package/types/signal/carriedClientIps.d.ts +4 -0
  504. package/types/signal/endpointErrorContract.d.ts +3 -0
  505. package/types/signal/exception.d.ts +1 -0
  506. package/types/signal/index.d.ts +32 -30
  507. package/types/signal/mcp/McpDocument.d.ts +2 -0
  508. package/types/signal/mcp/index.d.ts +1 -0
  509. package/types/signal/mcp/promptError.d.ts +5 -0
  510. package/types/signal/resolveFieldContext.d.ts +15 -0
  511. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  512. package/types/signal/signalContext.d.ts +1 -13
  513. package/types/signal/signalContractError.d.ts +4 -0
  514. package/types/signal/signalDeclarationError.d.ts +4 -0
  515. package/types/signal/slice.d.ts +15 -13
  516. package/types/signal/trace.d.ts +3 -0
  517. package/types/signal/types.d.ts +33 -6
  518. package/types/store/action.d.ts +8 -27
  519. package/types/store/actionErrorKey.d.ts +1 -0
  520. package/types/store/actionOption.d.ts +24 -0
  521. package/types/store/baseSt.d.ts +2 -295
  522. package/types/store/draftFlush.d.ts +4 -0
  523. package/types/store/formDrafts.d.ts +21 -0
  524. package/types/store/formFieldSetters.d.ts +80 -0
  525. package/types/store/index.d.ts +17 -16
  526. package/types/store/modelActionContext.d.ts +189 -0
  527. package/types/store/modelListPatch.d.ts +34 -0
  528. package/types/store/modelOpenActions.d.ts +12 -0
  529. package/types/store/modelWriteActions.d.ts +16 -0
  530. package/types/store/modelWriteGuard.d.ts +42 -0
  531. package/types/store/openSeq.d.ts +17 -0
  532. package/types/store/rootStore.d.ts +6 -0
  533. package/types/store/sliceListActions.d.ts +295 -0
  534. package/types/store/sliceLiveActions.d.ts +6 -0
  535. package/types/store/stateBuilder.d.ts +2 -0
  536. package/types/store/uploadPoll.d.ts +16 -0
  537. package/types/store/withSelector.d.ts +1 -1
  538. package/types/ui/Agent/Chat.d.ts +5 -2
  539. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  540. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  541. package/types/ui/Field/Choice.d.ts +2 -1
  542. package/types/ui/Field/index.d.ts +1 -1
  543. package/types/ui/Link/inputModality.d.ts +5 -0
  544. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  545. package/types/ui/Load/Edit_Client.d.ts +2 -0
  546. package/types/ui/Load/Pagination.d.ts +4 -1
  547. package/types/ui/Load/Stream.d.ts +7 -1
  548. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  549. package/types/ui/Load/Units.d.ts +2 -0
  550. package/types/ui/Load/View.d.ts +2 -0
  551. package/types/ui/Reference/origin.d.ts +1 -0
  552. package/types/ui/index.d.ts +1 -1
  553. package/types/ui/overlayLayer.d.ts +6 -1
  554. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  555. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  556. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  557. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  558. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  559. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  560. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +18 -11
  561. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  562. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  563. package/types/vendor/use-agentic/index.d.ts +1 -0
  564. package/types/vendor/use-agentic/types.d.ts +11 -0
  565. package/types/webkit/CsrGuards.d.ts +2 -0
  566. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  567. package/types/webkit/nativeCore.d.ts +1 -0
  568. package/types/webkit/nativePurchase.d.ts +2 -1
  569. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  570. package/types/webkit/useCsrLocationState.d.ts +21 -0
  571. package/types/webkit/useCsrNavigation.d.ts +25 -0
  572. package/types/webkit/useCsrRefs.d.ts +33 -0
  573. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  574. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  575. package/types/webkit/useCsrTransitions.d.ts +2 -0
  576. package/types/webkit/useFrameRuntime.d.ts +1 -0
  577. package/types/webkit/useGeoLocation.d.ts +1 -1
  578. package/types/webkit/useHistory.d.ts +2 -3
  579. package/types/webkit/usePurchase.d.ts +1 -1
  580. package/types/webkit/useResolvedFrame.d.ts +38 -0
  581. package/types/webkit/useSyncNavigation.d.ts +22 -0
  582. package/types/webkit/useTransitionStore.d.ts +1 -0
  583. package/ui/Agent/Chat.tsx +392 -235
  584. package/ui/Agent/ChatHeader.tsx +59 -0
  585. package/ui/Agent/ChatPendingCards.tsx +49 -0
  586. package/ui/Agent/fetchRunner.ts +8 -1
  587. package/ui/BottomSheet.tsx +1 -1
  588. package/ui/Button.tsx +1 -0
  589. package/ui/Data/Item.tsx +2 -2
  590. package/ui/Data/ListContainer.tsx +348 -181
  591. package/ui/Data/useViewModal.ts +10 -4
  592. package/ui/Dialog/LegacyModal.tsx +1 -1
  593. package/ui/Dialog/Modal.tsx +1 -1
  594. package/ui/Field/Choice.tsx +3 -1
  595. package/ui/Link/inputModality.ts +21 -0
  596. package/ui/Link/prefetchIntent.ts +7 -25
  597. package/ui/Link/viewportPrefetch.ts +30 -0
  598. package/ui/Load/Edit_Client.tsx +7 -1
  599. package/ui/Load/Pagination.tsx +10 -2
  600. package/ui/Load/Stream.tsx +24 -4
  601. package/ui/Load/StreamBoundary.tsx +65 -0
  602. package/ui/Load/Units.tsx +3 -0
  603. package/ui/Load/View.tsx +5 -1
  604. package/ui/Model/EditModal.tsx +2 -1
  605. package/ui/Popconfirm.tsx +1 -1
  606. package/ui/Reference/origin.ts +1 -0
  607. package/ui/Select.tsx +43 -51
  608. package/ui/Signal/RestApi.tsx +3 -2
  609. package/ui/System/Client.tsx +32 -8
  610. package/ui/index.ts +4 -0
  611. package/ui/overlayLayer.ts +22 -1
  612. package/vendor/@akanjs/native/CHANGELOG.md +7 -1
  613. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +27 -12
  614. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  615. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  616. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  617. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +509 -0
  618. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  619. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  620. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  621. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  622. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  623. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  624. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  625. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  626. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  627. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  628. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  629. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  630. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  631. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  632. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +18 -11
  633. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  634. package/vendor/use-agentic/AgentSession.ts +11 -11
  635. package/vendor/use-agentic/CHANGELOG.md +46 -1
  636. package/vendor/use-agentic/Compaction.ts +2 -1
  637. package/vendor/use-agentic/ToolRunner.ts +6 -3
  638. package/vendor/use-agentic/Transcript.ts +6 -3
  639. package/vendor/use-agentic/WIRE.md +29 -7
  640. package/vendor/use-agentic/failureCode.ts +44 -0
  641. package/vendor/use-agentic/httpRunner.ts +15 -4
  642. package/vendor/use-agentic/index.ts +1 -0
  643. package/vendor/use-agentic/types.ts +11 -0
  644. package/webkit/CsrGuards.ts +7 -2
  645. package/webkit/McpAppAgent.ts +8 -3
  646. package/webkit/McpAppFetchBridge.ts +11 -5
  647. package/webkit/RouteLevelBoundary.tsx +37 -0
  648. package/webkit/nativeCore.ts +1 -0
  649. package/webkit/nativePurchase.ts +6 -3
  650. package/webkit/useCamera.tsx +22 -21
  651. package/webkit/useCsrKeyboard.ts +155 -0
  652. package/webkit/useCsrLocationState.ts +58 -0
  653. package/webkit/useCsrNavigation.ts +302 -0
  654. package/webkit/useCsrRefs.ts +52 -0
  655. package/webkit/useCsrRenderTrace.ts +68 -0
  656. package/webkit/useCsrStackLifecycle.ts +120 -0
  657. package/webkit/useCsrTransitions.ts +552 -0
  658. package/webkit/useCsrValues.ts +69 -1234
  659. package/webkit/useGeoLocation.tsx +4 -1
  660. package/webkit/useHistory.ts +2 -2
  661. package/webkit/useLocation.ts +3 -2
  662. package/webkit/usePurchase.tsx +4 -2
  663. package/webkit/useResolvedFrame.ts +116 -0
  664. package/webkit/useSyncNavigation.ts +109 -0
  665. package/webkit/useTransitionStore.ts +13 -0
  666. package/types/signal/agentMeter.d.ts +0 -27
  667. package/types/signal/agentRelayPolicy.d.ts +0 -25
@@ -1,64 +1,27 @@
1
1
  import type { AkanWebConfig, AkanWebOption } from "akanjs";
2
- import { type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix, normalizeRoutePrefix } from "akanjs/base";
3
- import { Logger, parseBasePaths, websocketBinaryFrameContract } from "akanjs/common";
4
- import { DictionaryLookup, DictionaryRegistry } from "akanjs/dictionary";
5
- import type {
6
- Adaptor,
7
- AdaptorCls,
8
- AkanIpcMessage,
9
- AkanMetricsReport,
10
- DatabaseConfig,
11
- Service,
12
- ServiceCls,
13
- SolidConfig,
14
- } from "akanjs/service";
15
- import type { ServerSignal, ServerSignalCls, WebsocketPublishData } from "akanjs/signal";
16
- import { AgentMeter } from "../signal/agentMeter";
17
- import { AgentRelayPolicy } from "../signal/agentRelayPolicy";
2
+ import { AkanError, type BackendEnv, type BaseEnv, getApiPrefix, getEnv, getWsPrefix } from "akanjs/base";
3
+ import { Logger } from "akanjs/common";
4
+ import type { Adaptor, AdaptorCls, DatabaseConfig, Service, ServiceCls, SolidConfig } from "akanjs/service";
5
+ import type { ServerSignal, ServerSignalCls } from "akanjs/signal";
18
6
  import { CrossSiteGuard } from "../signal/CrossSiteGuard";
19
7
  import { EndpointRateLimit } from "../signal/endpointRateLimit";
20
- import { AgentRelayAccess } from "../signal/guards";
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";
8
+ import { AgentHooks } from "./agentHooks";
25
9
  import type { AkanLib, AkanLibProps } from "./akanLib";
26
- import { BinaryPubsub } from "./binaryPubsub";
27
- import { DevtoolsRouter } from "./devtools";
28
10
  import { DiLifecycle } from "./di/diLifecycle";
29
- import type { HmrWsData, HmrWsHub } from "./hmr/wsHub";
30
- import { OrphanGroup } from "./lifecycle/orphanGroup";
31
- import { isPortInUseError } from "./lifecycle/portInUse";
32
- import { resolveRuntimeDir } from "./lifecycle/runtimeDir";
11
+ import { ParentChannel } from "./lifecycle/parentChannel";
33
12
  import { ShutdownManager } from "./lifecycle/shutdownManager";
34
- import { HubFileSink } from "./logging/hubFileSink";
35
- import { LogControlSocket } from "./logging/logControlSocket";
36
- import { LogForwarder } from "./logging/logForwarder";
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";
13
+ import { StartGuard } from "./lifecycle/startGuard";
14
+ import { ServerLogging } from "./logging/serverLogging";
15
+ import { AgentTools, type McpAuthOption, type McpRateLimitOption, type McpRouter } from "./mcp";
45
16
  import { WebProxyRunner } from "./proxy";
46
17
  import { SignalResolver } from "./resolver";
47
- import { type ApiRouteInputs, ApiRouter } from "./routing/apiRouter";
48
- import type { AppWsData } from "./routing/appWsData";
49
- import { HostAllowlist } from "./routing/hostAllowlist";
50
- import { RoomReplay } from "./routing/roomReplay";
18
+ import { BuiltinRoutes } from "./routing/builtinRoutes";
51
19
  import { RouteHosts } from "./routing/routeHosts";
52
- import { ServerLimits } from "./routing/serverLimits";
53
- import { createSoloAppRoutes } from "./routing/soloAppRoutes";
20
+ import { type AkanAppPrepared, ServerListener } from "./routing/serverListener";
21
+ import { ServerConfig } from "./serverConfig";
22
+ import { ServerMetrics } from "./serverMetrics";
54
23
  import { SessionRefresh } from "./sessionRefresh";
55
- import {
56
- getWebConfigFromEnv,
57
- type HttpRoutes,
58
- type LocalPublish,
59
- type SignalRoutes,
60
- type WebsocketRoutes,
61
- } from "./types";
24
+ import { getWebConfigFromEnv } from "./types";
62
25
  import type { WebRouter } from "./webRouter";
63
26
 
64
27
  export interface AkanServerProps extends AkanLibProps {
@@ -134,17 +97,6 @@ export interface McpServerOption {
134
97
  modern?: boolean;
135
98
  }
136
99
 
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
100
  export interface AkanServerConsoleInfo {
149
101
  name: string;
150
102
  status: AkanServer["status"];
@@ -160,50 +112,37 @@ export interface AkanServerConsoleInfo {
160
112
 
161
113
  export class AkanServer {
162
114
  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
115
  #prepared: AkanAppPrepared | null = null;
116
+ #webRouter: WebRouter | null = null;
166
117
  readonly logger: Logger;
167
118
  readonly name: string;
168
119
  readonly libs: AkanLib[];
169
120
  readonly env: BackendEnv;
170
121
  prefix = getApiPrefix();
171
122
  websocketPrefix = getWsPrefix();
172
- openapi = AkanServer.#isEnvEnabled("AKAN_OPENAPI", "AKAN_PUBLIC_OPENAPI");
123
+ openapi = ServerConfig.isEnvEnabled("AKAN_OPENAPI", "AKAN_PUBLIC_OPENAPI");
173
124
 
174
- mcp = !AkanServer.#isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
175
- mcpReadOnly = AkanServer.#isEnvEnabled("AKAN_MCP_READONLY", "AKAN_PUBLIC_MCP_READONLY");
176
- mcpAuth: McpAuthOption = AkanServer.#mcpAuthFromEnv();
177
- mcpOption: Omit<McpServerOption, "enabled" | "readOnly" | "auth"> = AkanServer.#mcpOptionFromEnv();
125
+ mcp = !ServerConfig.isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
126
+ mcpReadOnly = ServerConfig.isEnvEnabled("AKAN_MCP_READONLY", "AKAN_PUBLIC_MCP_READONLY");
127
+ mcpAuth: McpAuthOption = ServerConfig.mcpAuthFromEnv();
128
+ mcpOption: Omit<McpServerOption, "enabled" | "readOnly" | "auth"> = ServerConfig.mcpOptionFromEnv();
178
129
  serverMode: "federation" | "batch" | "all";
179
130
  /** Resolved at `init`: what this process actually serves, after env and artifact availability. */
180
131
  web: AkanWebConfig = getWebConfigFromEnv();
181
132
  modules: string[];
182
133
  disableModules: string[];
183
134
  disableLibs: string[];
184
- shutdownTimeoutMs = AkanServer.#defaultShutdownTimeoutMs();
135
+ shutdownTimeoutMs = ServerConfig.defaultShutdownTimeoutMs();
185
136
 
186
137
  #di: DiLifecycle;
187
- #openApiDocument: ReturnType<typeof createOpenApiDocument> | null = null;
188
- #mcpRouter: McpRouter | null = null;
189
138
  readonly #initTimings = new Map<string, number>();
190
- #localPublish: LocalPublish | null = null;
191
- readonly #binaryPubsub = new BinaryPubsub();
192
- #metricsTimer: Timer | null = null;
193
-
194
- readonly #solo = !process.env.AKAN_CHILD_SOCKET;
195
- #logWriter: RotatingLogWriter | null = null;
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;
139
+ readonly #logging: ServerLogging;
140
+ readonly #listener: ServerListener;
141
+ readonly #metrics: ServerMetrics;
142
+ readonly #parent: ParentChannel;
143
+ readonly #builtinRoutes: BuiltinRoutes;
144
+ readonly #start: StartGuard;
205
145
  #schedules = true;
206
- #orphanExiting = false;
207
146
  constructor(
208
147
  name = "AkanServer",
209
148
  env: BackendEnv = {},
@@ -214,13 +153,17 @@ export class AkanServer {
214
153
  | undefined) ?? "all",
215
154
  ...libsOrOptions: (AkanLib | AkanServerOptions)[]
216
155
  ) {
217
- const { libs, options } = AkanServer.#splitLibsAndOptions(libsOrOptions);
156
+ const { libs, options } = ServerConfig.splitLibsAndOptions(libsOrOptions);
157
+
158
+ const solo = !process.env.AKAN_CHILD_SOCKET;
218
159
  this.name = name;
219
160
  this.logger = new Logger(name);
161
+ this.#logging = new ServerLogging(solo, this.logger);
162
+ this.#start = new StartGuard(this.logger, () => this.#teardown());
220
163
  this.libs = libs;
221
164
  this.env = libs.reduce((current, lib) => lib.option.resolveEnv(current), { ...env });
222
165
 
223
- if (AkanServer.#isEdge(this.env) && !AkanServer.#isEnvEnabled("AKAN_MCP", "AKAN_PUBLIC_MCP")) this.mcp = false;
166
+ if (ServerConfig.isEdge(this.env) && !ServerConfig.isEnvEnabled("AKAN_MCP", "AKAN_PUBLIC_MCP")) this.mcp = false;
224
167
  this.openapi = options?.openapi ?? this.openapi;
225
168
 
226
169
  EndpointRateLimit.reset();
@@ -228,12 +171,7 @@ export class AkanServer {
228
171
  libs.forEach((lib) => {
229
172
  const mcp = lib.option.getMcp(this.env);
230
173
  if (mcp !== undefined) this.setMcp(mcp);
231
- const agentAccess = lib.option.getAgentAccess();
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 });
174
+ AgentHooks.apply(lib.option);
237
175
  const crossSite = lib.option.getCrossSite();
238
176
  if (crossSite !== undefined) CrossSiteGuard.configure(crossSite);
239
177
  const rateLimit = lib.option.getRateLimit(this.env);
@@ -245,49 +183,66 @@ export class AkanServer {
245
183
  this.setMcp(options?.mcp ?? this.mcp);
246
184
  this.serverMode = serverMode;
247
185
 
248
- this.modules = options?.modules ?? AkanServer.#envList("AKAN_MODULES") ?? [];
249
- this.disableModules = options?.disableModules ?? AkanServer.#envList("AKAN_DISABLE_MODULES") ?? [];
250
- this.disableLibs = options?.disableLibs ?? AkanServer.#envList("AKAN_DISABLE_LIBS") ?? [];
186
+ this.modules = options?.modules ?? ServerConfig.envList("AKAN_MODULES") ?? [];
187
+ this.disableModules = options?.disableModules ?? ServerConfig.envList("AKAN_DISABLE_MODULES") ?? [];
188
+ this.disableLibs = options?.disableLibs ?? ServerConfig.envList("AKAN_DISABLE_LIBS") ?? [];
251
189
  this.#di = new DiLifecycle(
252
190
  { env: this.env, modules: this.modules, disableModules: this.disableModules, disableLibs: this.disableLibs },
253
191
  ...libs,
254
192
  );
193
+ const webRouter = () => this.#webRouter;
194
+ this.#listener = new ServerListener(this, this.#di, solo);
195
+ this.#metrics = new ServerMetrics(this, this.#listener, webRouter);
196
+ this.#parent = new ParentChannel(this, this.#logging, webRouter);
197
+ this.#builtinRoutes = new BuiltinRoutes({
198
+ owner: this,
199
+ di: this.#di,
200
+ solo,
201
+ listener: this.#listener,
202
+ metrics: this.#metrics,
203
+ logging: this.#logging,
204
+ });
255
205
  }
256
206
  setPrefix(prefix: string) {
257
- if (this.status !== "stopped") throw new Error("Route prefix must be set before app initialization.");
258
- this.prefix = AkanServer.#requireRoutePrefix(prefix, "prefix");
207
+ if (this.status !== "stopped")
208
+ throw new AkanError("alreadyInitialized", "Route prefix must be set before app initialization.");
209
+ this.prefix = ServerConfig.requireRoutePrefix(prefix, "prefix");
259
210
  return this;
260
211
  }
261
212
  setWebsocketPrefix(websocketPrefix: string) {
262
- if (this.status !== "stopped") throw new Error("Websocket prefix must be set before app initialization.");
263
- this.websocketPrefix = AkanServer.#requireRoutePrefix(websocketPrefix, "websocketPrefix");
213
+ if (this.status !== "stopped")
214
+ throw new AkanError("alreadyInitialized", "Websocket prefix must be set before app initialization.");
215
+ this.websocketPrefix = ServerConfig.requireRoutePrefix(websocketPrefix, "websocketPrefix");
264
216
  return this;
265
217
  }
266
218
  setOpenApi(openapi = true) {
267
- if (this.status !== "stopped") throw new Error("OpenAPI config must be set before app initialization.");
219
+ if (this.status !== "stopped")
220
+ throw new AkanError("alreadyInitialized", "OpenAPI config must be set before app initialization.");
268
221
  this.openapi = openapi;
269
222
  return this;
270
223
  }
271
224
  /** Narrows the web surface; never widens it past what the build produced. */
272
225
  setWeb(web: AkanWebOption = true) {
273
- if (this.status !== "stopped") throw new Error("Web config must be set before app initialization.");
274
- this.web = AkanServer.#narrowWeb(this.web, web);
226
+ if (this.status !== "stopped")
227
+ throw new AkanError("alreadyInitialized", "Web config must be set before app initialization.");
228
+ this.web = ServerConfig.narrowWeb(this.web, web);
275
229
  return this;
276
230
  }
277
231
  setMcp(mcp: boolean | McpServerOption = true) {
278
- if (this.status !== "stopped") throw new Error("MCP config must be set before app initialization.");
232
+ if (this.status !== "stopped")
233
+ throw new AkanError("alreadyInitialized", "MCP config must be set before app initialization.");
279
234
 
280
235
  const requested = typeof mcp === "boolean" ? mcp : (mcp.enabled ?? this.mcp);
281
- this.mcp = requested && !AkanServer.#isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
236
+ this.mcp = requested && !ServerConfig.isEnvOff("AKAN_MCP", "AKAN_PUBLIC_MCP");
282
237
  if (typeof mcp === "boolean") return this;
283
238
  const { enabled: _enabled, readOnly, auth, excludeSignals, excludeEndpoints, ...rest } = mcp;
284
239
  if (readOnly !== undefined) this.mcpReadOnly = readOnly;
285
- if (auth) this.mcpAuth = { ...this.mcpAuth, ...AkanServer.#defined(auth) };
240
+ if (auth) this.mcpAuth = { ...this.mcpAuth, ...ServerConfig.defined(auth) };
286
241
  const added = (current: string[] | undefined, names: string[] | undefined) =>
287
242
  names ? [...new Set([...(current ?? []), ...names])] : current;
288
- this.mcpOption = AkanServer.#defined({
243
+ this.mcpOption = ServerConfig.defined({
289
244
  ...this.mcpOption,
290
- ...AkanServer.#defined(rest),
245
+ ...ServerConfig.defined(rest),
291
246
  excludeSignals: added(this.mcpOption.excludeSignals, excludeSignals),
292
247
  excludeEndpoints: added(this.mcpOption.excludeEndpoints, excludeEndpoints),
293
248
  });
@@ -295,15 +250,17 @@ export class AkanServer {
295
250
  }
296
251
  /** The router `/mcp` is served by once routes are built; `null` before, or when MCP is off. */
297
252
  get mcpRouter(): McpRouter | null {
298
- return this.#mcpRouter;
253
+ return this.#builtinRoutes.mcpRouter;
299
254
  }
300
255
  setDatabaseConfig(database: DatabaseConfig) {
301
- if (this.status !== "stopped") throw new Error("Database config must be set before app initialization.");
256
+ if (this.status !== "stopped")
257
+ throw new AkanError("alreadyInitialized", "Database config must be set before app initialization.");
302
258
  this.env.database = database;
303
259
  return this;
304
260
  }
305
261
  setSolidConfig(solid: SolidConfig) {
306
- if (this.status !== "stopped") throw new Error("Solid config must be set before app initialization.");
262
+ if (this.status !== "stopped")
263
+ throw new AkanError("alreadyInitialized", "Solid config must be set before app initialization.");
307
264
  this.env.solid = solid;
308
265
  return this;
309
266
  }
@@ -316,27 +273,27 @@ export class AkanServer {
316
273
  get<Sig extends ServerSignalCls>(cls: Sig): InstanceType<Sig>;
317
274
  get<Adp extends AdaptorCls>(cls: Adp): InstanceType<Adp>;
318
275
  get(cls: ServiceCls | ServerSignalCls | AdaptorCls): Service | ServerSignal | Adaptor {
319
- this.#assertCanGet();
276
+ assertCanGet(this.status);
320
277
  return this.#di.getByClass(cls);
321
278
  }
322
279
 
323
280
  getService<T = Service>(refName: string): T {
324
- this.#assertCanGet("Service", refName);
281
+ assertCanGet(this.status, "Service", refName);
325
282
  return this.#di.getService<T>(refName);
326
283
  }
327
284
 
328
285
  getSignal<T = ServerSignal>(refName: string): T {
329
- this.#assertCanGet("Server signal", refName);
286
+ assertCanGet(this.status, "Server signal", refName);
330
287
  return this.#di.getSignal<T>(refName);
331
288
  }
332
289
 
333
290
  getAdaptor<T = Adaptor>(refName: string): T {
334
- this.#assertCanGet("Adaptor", refName);
291
+ assertCanGet(this.status, "Adaptor", refName);
335
292
  return this.#di.getAdaptor<T>(refName);
336
293
  }
337
294
 
338
295
  inspectConsole(): AkanServerConsoleInfo {
339
- this.#assertCanGet();
296
+ assertCanGet(this.status);
340
297
  const env = getEnv();
341
298
  return {
342
299
  name: this.name,
@@ -360,35 +317,41 @@ export class AkanServer {
360
317
  }
361
318
 
362
319
  async init(option: { routes?: boolean; web?: AkanWebOption } = {}) {
320
+ if (this.status !== "stopped")
321
+ throw new AkanError("alreadyInitialized", "AkanServer is not able to init. It is already running.");
322
+ ServerConfig.assertPrefixClearsBasePaths(this.prefix);
363
323
  const start = performance.now();
364
324
  this.#initTimings.clear();
365
- await this.#init(option);
325
+ if (await this.#start.unwound(() => this.#start.stoppedDuring(() => this.#init(option)))) return this;
366
326
  const stages = [...this.#di.initTimings, ...this.#initTimings].map(([stage, ms]) => `${stage} ${ms.toFixed(1)}`);
367
327
  this.logger.debug(`Initialized in ${(performance.now() - start).toFixed(1)}ms (${stages.join(" · ")})`);
368
328
  return this;
369
329
  }
370
330
 
371
331
  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
332
  this.status = "initializing";
374
- this.#assertPrefixClearsBasePaths();
375
- const { routes, wsRoutes, routeOptions } = await this.#di.initializeAll();
333
+ AgentTools.provide(this.#di, this);
334
+ const { routes, wsRoutes, routeOptions } = await this.#di.initializeAll().catch((error: unknown) => {
335
+
336
+ this.status = "stopped";
337
+ throw error;
338
+ });
339
+ if (this.#start.stopHeld) return this;
376
340
  if (!initRoutes) {
377
341
  this.#prepared = null;
378
342
  this.status = "initialized";
379
343
  return this;
380
344
  }
381
345
  RouteHosts.declare();
382
- const requestedWeb = AkanServer.#narrowWeb(this.web, web);
346
+ const requestedWeb = ServerConfig.narrowWeb(this.web, web);
383
347
  const noWeb = () => {
384
348
  this.#prepared = {
385
349
  routes,
386
350
  routeOptions,
387
351
  wsRoutes,
388
- builtinRoutes: this.#timedBuiltinRoutes(null),
352
+ builtinRoutes: this.#builtinRoutes.timed(null, this.#initTimings),
389
353
  renderEnvRoutes: {},
390
354
  hmrHub: null,
391
- webRouter: null,
392
355
  webProxyRunner: null,
393
356
  };
394
357
  this.status = "initialized";
@@ -401,12 +364,10 @@ export class AkanServer {
401
364
  }
402
365
  const webStart = performance.now();
403
366
  const { WebRouter } = await import("./webRouter");
367
+ if (this.#start.stopHeld) return this;
404
368
  const webRouter = await WebRouter.create({
405
369
  web: requestedWeb,
406
-
407
- upgradeHmrWs: (req, data) =>
408
- (this.#wsServer?.requestIP(req as Bun.BunRequest) ? this.#wsServer : this.#server)?.upgrade(req, { data }) ??
409
- false,
370
+ upgradeHmrWs: (req, data) => this.#listener.upgradeHmrWs(req, data),
410
371
  });
411
372
 
412
373
  if (!webRouter) {
@@ -414,6 +375,7 @@ export class AkanServer {
414
375
  this.logger.warn("web off: no build artifact under .akan/artifact; serving api only");
415
376
  return noWeb();
416
377
  }
378
+ this.#webRouter = webRouter;
417
379
  this.web = webRouter.web;
418
380
  this.logger.verbose(`web on: ssr=${this.web.ssr} csr=${this.web.csr}`);
419
381
  const { renderEnvRoutes, hmrHub } = await webRouter.initializeRoute();
@@ -423,10 +385,9 @@ export class AkanServer {
423
385
  routes,
424
386
  routeOptions,
425
387
  wsRoutes,
426
- builtinRoutes: this.#timedBuiltinRoutes(webRouter),
388
+ builtinRoutes: this.#builtinRoutes.timed(webRouter, this.#initTimings),
427
389
  renderEnvRoutes,
428
390
  hmrHub,
429
- webRouter,
430
391
  webProxyRunner,
431
392
  };
432
393
  this.status = "initialized";
@@ -434,130 +395,24 @@ export class AkanServer {
434
395
  }
435
396
 
436
397
  async listen() {
437
- if (this.status !== "initialized" || !this.#prepared) {
438
- throw new Error("AkanServer is not able to listen. Call `init` first.");
439
- }
398
+ const prepared = this.#prepared;
399
+ if (this.status !== "initialized" || !prepared)
400
+ throw new AkanError("notInitialized", "AkanServer is not able to listen. Call `init` first.");
440
401
  this.status = "starting";
441
402
  Logger.role = this.serverMode;
442
- await this.#startLogTransport();
443
- this.#startFileLogging();
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;
403
+ return await this.#start.unwound(() => this.#listen(prepared));
404
+ }
554
405
 
406
+ async #listen(prepared: AkanAppPrepared) {
407
+ if (await this.#start.stoppedDuring(() => this.#logging.startTransport(this.#webRouter))) return this;
408
+ this.#logging.startFileLogging(this.serverMode);
409
+ const { unix, port } = this.#listener.listen(prepared, this.#webRouter);
555
410
  this.status = "running";
556
- this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#reportMetrics());
411
+ this.#metrics.start();
557
412
  if (this.#schedules) this.#di.registerSchedule(this.serverMode);
558
413
  this.logger.verbose(`🚀 ${this.name} is running on ${unix ? `unix://${unix}` : `port ${port}`}`);
559
- const wsPort = this.#wsServer?.port;
560
- this.#sendReady({
414
+ const wsPort = this.#listener.wsPort;
415
+ this.#parent.sendReady({
561
416
  type: "ready",
562
417
  pid: process.pid,
563
418
  replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
@@ -567,7 +422,7 @@ export class AkanServer {
567
422
  healthPath: "/_akan/app/child-health",
568
423
  crossSite: CrossSiteGuard.option(),
569
424
  });
570
- if (this.#schedules) await this.#di.runSchedulerInit();
425
+ if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
571
426
  ShutdownManager.register(this.logger, () => this.stop());
572
427
  return this;
573
428
  }
@@ -581,453 +436,90 @@ export class AkanServer {
581
436
  const isNoListenCommand = process.env.AKAN_COMMAND_TYPE === "script" || process.env.AKAN_COMMAND_TYPE === "console";
582
437
  const shouldListen = (listen ?? !isNoListenCommand) && this.serverMode !== "batch";
583
438
 
584
- if (shouldListen || !isNoListenCommand) this.#registerParentIpc();
439
+ if (shouldListen || !isNoListenCommand) this.#parent.register();
585
440
  await this.init({ routes: shouldListen, web });
586
- if (this.#parentGone) return this;
587
- if (!shouldListen) {
441
+ if (this.#parent.gone || this.status !== "initialized") return this;
442
+ if (shouldListen) return this.listen();
443
+ return await this.#start.unwound(async () => {
588
444
  const websocket = this.#di.getWebsocketAdaptor();
589
445
  if (websocket)
590
- SignalResolver.setLocalPublish((roomId, data) => this.#localPublish?.(roomId, data), websocket, this.#di.live);
446
+ SignalResolver.setLocalPublish(
447
+ (roomId, data) => this.#listener.publishLocal(roomId, data),
448
+ websocket,
449
+ this.#di.live,
450
+ );
591
451
  this.status = "running";
592
- if (!isNoListenCommand) {
593
- Logger.role = this.serverMode;
594
- this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#reportMetrics());
595
- if (this.#schedules) this.#di.registerSchedule(this.serverMode);
596
- await this.#startLogTransport();
597
- this.#sendReady({
598
- type: "ready",
599
- pid: process.pid,
600
- replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
601
- role: this.serverMode,
602
- });
603
- if (this.#schedules) await this.#di.runSchedulerInit();
604
- ShutdownManager.register(this.logger, () => this.stop());
605
- }
452
+ if (isNoListenCommand) return this;
453
+ Logger.role = this.serverMode;
454
+ this.#metrics.start();
455
+ if (this.#schedules) this.#di.registerSchedule(this.serverMode);
456
+ if (await this.#start.stoppedDuring(() => this.#logging.startTransport())) return this;
457
+ this.#parent.sendReady({
458
+ type: "ready",
459
+ pid: process.pid,
460
+ replicaIdx: Number(process.env.AKAN_REPLICA_IDX ?? 0),
461
+ role: this.serverMode,
462
+ });
463
+ if (this.#schedules && this.status === "running") await this.#di.runSchedulerInit();
464
+ ShutdownManager.register(this.logger, () => this.stop());
606
465
  return this;
607
- }
608
- return this.listen();
466
+ });
609
467
  }
610
468
  stop(): Promise<void> {
611
- this.#stopping ??= this.#stop().finally(() => {
612
- this.#stopping = null;
613
- });
614
- return this.#stopping;
469
+ return this.#start.stop(() => this.status === "running" || this.status === "initialized");
615
470
  }
616
471
 
617
- async #stop() {
618
- if (this.status !== "running" && this.status !== "initialized") {
619
- this.logger.warn("AkanServer is not running. Cannot stop.");
620
- return;
621
- }
622
-
472
+ async #teardown() {
473
+ if (this.status === "stopped") return;
623
474
  try {
624
475
  const now = Date.now();
625
476
  this.logger.info("Shutting down gracefully...");
626
477
  this.status = "stopping";
627
- if (this.#metricsTimer) clearInterval(this.#metricsTimer);
628
- this.#metricsTimer = null;
478
+ this.#metrics.stop();
629
479
  this.#di.getWebsocketAdaptor()?.clearEventHandler();
630
- this.#server?.stop(true);
631
- this.#wsServer?.stop(true);
632
- this.#server = null;
633
- this.#wsServer = null;
634
- SignalContext.setHttpPeerResolver(null);
480
+ this.#listener.close();
635
481
 
636
- this.#prepared?.webRouter?.dispose();
637
- await this.#withShutdownTimeout(this.#di.destroyAll());
482
+ this.#webRouter?.dispose();
483
+ this.#webRouter = null;
484
+ await withShutdownTimeout(this.#di.destroyAll(), this.shutdownTimeoutMs);
638
485
  this.#prepared = null;
639
486
  this.status = "stopped";
640
487
  this.logger.info(`Shutdown completed successfully in ${Date.now() - now}ms`);
641
-
642
- await this.#stopLogTransport();
643
- await this.#stopFileLogging();
644
488
  } catch (error) {
489
+
645
490
  this.logger.error(`Error during shutdown: ${error instanceof Error ? error.message : String(error)}`);
646
491
  this.status = "stopped";
647
492
  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
- ...(webRouter ? DevtoolsRouter.buildsFrom(() => webRouter.builderRpc) : {}),
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
493
  } finally {
1030
- if (timeout) clearTimeout(timeout);
494
+
495
+ await this.#logging.stop();
1031
496
  }
1032
497
  }
1033
498
  }
499
+
500
+ const assertCanGet = (status: AkanServer["status"], type = "Dependency", refName?: string) => {
501
+ if (status === "initialized" || status === "running") return;
502
+ const target = refName ? `${type} "${refName}"` : type;
503
+ throw new AkanError(
504
+ "notInitialized",
505
+ `${target} is not initialized while AkanServer status is "${status}". ` +
506
+ "Call server.start() or server.init() first.",
507
+ );
508
+ };
509
+
510
+ const withShutdownTimeout = async <T>(promise: Promise<T>, timeoutMs: number) => {
511
+ let timeout: Timer | null = null;
512
+ try {
513
+ return await Promise.race([
514
+ promise,
515
+ new Promise<T>((_, reject) => {
516
+ timeout = setTimeout(
517
+ () => reject(new AkanError("shutdownTimeout", `Shutdown timed out after ${timeoutMs}ms`)),
518
+ timeoutMs,
519
+ );
520
+ }),
521
+ ]);
522
+ } finally {
523
+ if (timeout) clearTimeout(timeout);
524
+ }
525
+ };