akanjs 3.2.0-rc.9 → 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.
Files changed (641) hide show
  1. package/ARCHITECTURE.md +41 -38
  2. package/CHANGELOG.md +0 -680
  3. package/CONTRIBUTING.md +3 -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 +2 -0
  8. package/client/frameConfig.ts +1 -0
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +12 -85
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/PageDefinition.ts +11 -3
  14. package/client/route/RouteDefinition.ts +24 -7
  15. package/client/route/RouteGuards.ts +2 -1
  16. package/client/route/RouteHead.ts +4 -1
  17. package/client/route/routeArgs.ts +8 -0
  18. package/client/router.ts +17 -2
  19. package/client/rscNavigation.ts +1 -0
  20. package/client/viewportMeta.ts +86 -6
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/Logger.ts +4 -2
  23. package/common/PipelinePlanSchema.ts +2 -2
  24. package/common/clientAddress.ts +14 -0
  25. package/common/err.ts +122 -0
  26. package/common/eventStream.ts +71 -19
  27. package/common/facetBarrel.ts +38 -0
  28. package/common/index.ts +7 -0
  29. package/common/isGuardRefusal.ts +14 -0
  30. package/common/loggedFailure.ts +11 -0
  31. package/common/mcpExposure.ts +17 -4
  32. package/common/pipelinePlan.ts +1 -1
  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 +12 -0
  45. package/dictionary/base.dictionary.ts +11 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/dataLoader.ts +39 -19
  49. package/document/databaseRegistry.ts +2 -1
  50. package/document/documentSchema.ts +1 -0
  51. package/document/filterMeta.ts +4 -1
  52. package/document/into.ts +2 -1
  53. package/document/loaderInfo.ts +2 -1
  54. package/document/noDocumentError.ts +4 -1
  55. package/document/queryEvaluator.ts +1 -1
  56. package/document/types.ts +1 -1
  57. package/fetch/client/fetchClient.ts +83 -269
  58. package/fetch/client/fetchClientTypes.ts +49 -0
  59. package/fetch/client/httpClient.ts +3 -2
  60. package/fetch/client/remoteError.ts +4 -20
  61. package/fetch/client/requestScope.ts +41 -0
  62. package/fetch/client/signalCatalog.ts +131 -0
  63. package/fetch/client/wsClient.ts +82 -6
  64. package/fetch/requestStorage.ts +1 -0
  65. package/package.json +1 -1
  66. package/server/agentHooks.ts +16 -0
  67. package/server/akanApp.ts +110 -1272
  68. package/server/akanOption.ts +30 -3
  69. package/server/akanServer.ts +179 -674
  70. package/server/artifact/builderRpc.ts +14 -6
  71. package/server/artifact/routeSeedIndexStore.ts +4 -2
  72. package/server/assetHeaders.ts +6 -0
  73. package/server/console.ts +6 -4
  74. package/server/decorators.ts +2 -2
  75. package/server/di/diLifecycle.ts +24 -35
  76. package/server/di/predefinedAdaptor.ts +24 -1
  77. package/server/di/resolveHierarchy.ts +19 -6
  78. package/server/di/stageFailedError.ts +10 -0
  79. package/server/di/utils.ts +8 -3
  80. package/server/ed25519Key.ts +31 -15
  81. package/server/flightRowReader.ts +106 -20
  82. package/server/gateway/childSupervisor.ts +328 -0
  83. package/server/gateway/devHostChannel.ts +47 -0
  84. package/server/gateway/gatewayChildren.ts +161 -0
  85. package/server/gateway/gatewayConfig.ts +182 -0
  86. package/server/gateway/gatewayHttpProxy.ts +231 -0
  87. package/server/gateway/gatewayLogging.ts +111 -0
  88. package/server/gateway/gatewayRooms.ts +141 -0
  89. package/server/gateway/gatewayStatus.ts +122 -0
  90. package/server/gateway/gatewayStatusPage.ts +54 -0
  91. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  92. package/server/gateway/listeningPort.ts +13 -0
  93. package/server/hmr/devHmrController.ts +10 -1
  94. package/server/htmlResultCache.ts +234 -0
  95. package/server/imageOptimizer.ts +4 -1
  96. package/server/index.ts +281 -17
  97. package/server/lifecycle/parentChannel.ts +79 -0
  98. package/server/lifecycle/shutdownManager.ts +6 -3
  99. package/server/lifecycle/startGuard.ts +90 -0
  100. package/server/logging/hubFileSink.ts +1 -0
  101. package/server/logging/logControlSocket.ts +42 -3
  102. package/server/logging/logHub.ts +0 -0
  103. package/server/logging/logStdoutWriter.ts +3 -1
  104. package/server/logging/logStreamRoute.ts +28 -11
  105. package/server/logging/serverLogging.ts +74 -0
  106. package/server/machine/machineToken.ts +10 -3
  107. package/server/mcp/AgentTools.ts +149 -0
  108. package/server/mcp/AgentToolsAccount.ts +26 -0
  109. package/server/mcp/McpApps.ts +32 -2
  110. package/server/mcp/McpDispatcher.ts +44 -30
  111. package/server/mcp/McpPages.ts +34 -12
  112. package/server/mcp/McpRateLimiter.ts +14 -0
  113. package/server/mcp/McpRouter.ts +4 -2
  114. package/server/mcp/McpUiSession.ts +2 -1
  115. package/server/mcp/index.ts +1 -0
  116. package/server/migration/migrationCommand.ts +31 -2
  117. package/server/migration/migrationRunner.ts +36 -1
  118. package/server/nativeFile.ts +39 -12
  119. package/server/nativeSecret.ts +12 -3
  120. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  121. package/server/ops/migrateJobs.ts +2 -2
  122. package/server/ops/opsCommand.ts +1 -1
  123. package/server/ops/opsRoute.ts +5 -1
  124. package/server/ops/opsToken.ts +3 -1
  125. package/server/remote/RemoteFetch.ts +161 -0
  126. package/server/remote/RemoteMcp.ts +242 -0
  127. package/server/remote/RemoteOAuth.ts +270 -0
  128. package/server/remote/RemoteSource.ts +214 -0
  129. package/server/remote/index.ts +17 -0
  130. package/server/remote/remoteError.ts +19 -0
  131. package/server/resolver/CascadeRunner.ts +20 -8
  132. package/server/resolver/database.resolver.ts +10 -417
  133. package/server/resolver/databaseModelInstance.ts +209 -0
  134. package/server/resolver/invalidSignal.ts +7 -0
  135. package/server/resolver/livePause.ts +34 -0
  136. package/server/resolver/modelFacade.ts +136 -0
  137. package/server/resolver/modelLoaders.ts +84 -0
  138. package/server/resolver/modelSchema.ts +52 -0
  139. package/server/resolver/roomAdmission.ts +68 -0
  140. package/server/resolver/signal.resolver.ts +45 -111
  141. package/server/resolver/sliceCrud.ts +63 -0
  142. package/server/resolver/timedQuery.ts +16 -0
  143. package/server/resolver/websocketOf.ts +2 -1
  144. package/server/routeElementComposer.tsx +45 -6
  145. package/server/routeTreeBuilder.ts +23 -9
  146. package/server/routing/apiRouter.ts +53 -28
  147. package/server/routing/builtinRoutes.ts +194 -0
  148. package/server/routing/localRooms.ts +34 -0
  149. package/server/routing/roomReplay.ts +2 -2
  150. package/server/routing/serverLimits.ts +4 -1
  151. package/server/routing/serverListener.ts +194 -0
  152. package/server/rscClient.tsx +121 -204
  153. package/server/rscClientCache.ts +165 -0
  154. package/server/rscClientChunks.ts +126 -8
  155. package/server/rscClientFetch.ts +3 -1
  156. package/server/rscClientPatch.ts +78 -15
  157. package/server/rscDocumentHead.tsx +177 -0
  158. package/server/rscFlightRenderer.ts +83 -0
  159. package/server/rscFlightStream.ts +259 -0
  160. package/server/rscHostReloads.ts +238 -0
  161. package/server/rscHostRenderStream.ts +297 -0
  162. package/server/rscHostRequests.ts +158 -0
  163. package/server/rscHttp.ts +18 -6
  164. package/server/rscNavigationState.ts +24 -1
  165. package/server/rscPagePrompts.ts +65 -14
  166. package/server/rscPrefetchCache.ts +5 -1
  167. package/server/rscRenderControl.ts +33 -0
  168. package/server/rscRenderFallbacks.ts +299 -0
  169. package/server/rscRenderHandler.ts +439 -0
  170. package/server/rscRenderStats.ts +49 -0
  171. package/server/rscResultCaches.ts +74 -0
  172. package/server/rscRouteDocument.tsx +316 -0
  173. package/server/rscSegmentOutletReference.ts +5 -1
  174. package/server/rscStaticApp.tsx +73 -0
  175. package/server/rscWorker.tsx +112 -1341
  176. package/server/rscWorkerHost.ts +175 -803
  177. package/server/rscWorkerProcess.ts +155 -0
  178. package/server/rscWorkerRecycler.ts +128 -0
  179. package/server/serverConfig.ts +128 -0
  180. package/server/serverMetrics.ts +52 -0
  181. package/server/sitemap.ts +1 -0
  182. package/server/ssrFromRscRenderer.tsx +20 -20
  183. package/server/ssrStaticApp.tsx +243 -0
  184. package/server/webArtifact.ts +86 -0
  185. package/server/webAssetRoutes.ts +84 -0
  186. package/server/webCsrSurface.ts +172 -0
  187. package/server/webDocumentRoute.ts +180 -0
  188. package/server/webRouteContext.ts +232 -0
  189. package/server/webRouter.ts +129 -1165
  190. package/server/webRscRoute.ts +155 -0
  191. package/server/webSiteFiles.ts +139 -0
  192. package/server/webStaticApp.ts +62 -0
  193. package/server/wellKnownRoutes.ts +73 -0
  194. package/service/agent.service.ts +14 -2
  195. package/service/agentAccounts.ts +19 -0
  196. package/service/agentLoop/agentLoop.ts +550 -0
  197. package/service/agentLoop/agentLoopTypes.ts +220 -0
  198. package/service/agentLoop/deltaStream.ts +40 -0
  199. package/service/agentLoop/loopAnswer.ts +67 -0
  200. package/service/agentLoop/loopAsk.ts +44 -0
  201. package/service/agentLoop/loopCompaction.ts +146 -0
  202. package/service/agentLoop/loopRemotes.ts +181 -0
  203. package/service/agentLoop/loopRequest.ts +120 -0
  204. package/service/agentLoop/loopStored.ts +24 -0
  205. package/service/agentLoop/loopToolOutput.ts +54 -0
  206. package/service/agentLoop/loopToolkits.ts +155 -0
  207. package/service/agentLoop/loopTranscript.ts +138 -0
  208. package/{signal → service}/agentMeter.ts +2 -1
  209. package/{signal → service}/agentRelayPolicy.ts +43 -8
  210. package/service/endpointCacheKeys.ts +14 -2
  211. package/service/index.ts +6 -0
  212. package/service/injectInfo.ts +2 -1
  213. package/service/ipcTypes.ts +8 -2
  214. package/service/liveRoomLimit.ts +68 -0
  215. package/service/liveRoomLimitError.ts +16 -0
  216. package/service/liveSyncHub.ts +24 -2
  217. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  218. package/service/predefinedAdaptor/anthropicLlm.ts +33 -14
  219. package/service/predefinedAdaptor/compress.adaptor.ts +2 -2
  220. package/service/predefinedAdaptor/database.adaptor.ts +62 -19
  221. package/service/predefinedAdaptor/index.ts +1 -0
  222. package/service/predefinedAdaptor/llm.adaptor.ts +24 -1
  223. package/service/predefinedAdaptor/openaiDialect.ts +72 -23
  224. package/service/predefinedAdaptor/openaiLlm.ts +1 -1
  225. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  226. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  227. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  228. package/service/predefinedAdaptor/solidSqlite.ts +6 -3
  229. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  230. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  231. package/service/predefinedAdaptor/sql/DocumentWriter.ts +298 -0
  232. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  233. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  234. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +127 -1069
  235. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +357 -0
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/TransactionScope.ts +14 -7
  238. package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
  239. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
  240. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +20 -9
  241. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  242. package/service/predefinedAdaptor/sql/types.ts +28 -4
  243. package/service/predefinedAdaptor/sseData.ts +88 -0
  244. package/service/predefinedAdaptor/storage.adaptor.ts +2 -1
  245. package/service/predefinedAdaptor/websocket.adaptor.ts +74 -44
  246. package/service/serviceRegistry.ts +1 -0
  247. package/signal/SignalFailure.ts +35 -0
  248. package/signal/agent.signal.ts +15 -9
  249. package/signal/agentTurnStream.ts +23 -9
  250. package/signal/byIdRead.ts +18 -0
  251. package/signal/carriedClientIps.ts +1 -0
  252. package/signal/endpointCache.ts +61 -6
  253. package/signal/endpointErrorContract.ts +1 -1
  254. package/signal/endpointRateLimit.ts +84 -3
  255. package/signal/index.ts +322 -32
  256. package/signal/mcp/McpDocument.ts +8 -1
  257. package/signal/mcp/mcpProtocol.ts +6 -1
  258. package/signal/mcp/pagePrompt.ts +15 -0
  259. package/signal/middleware.ts +10 -3
  260. package/signal/openapi/openapi.ts +10 -1
  261. package/signal/resolveFieldContext.ts +34 -0
  262. package/signal/serializer/fetch.serializer.ts +22 -15
  263. package/signal/signalContext.ts +15 -42
  264. package/signal/slice.ts +22 -19
  265. package/signal/trace.ts +44 -5
  266. package/signal/types.ts +46 -8
  267. package/store/action.ts +32 -1057
  268. package/store/actionErrorMessage.ts +20 -0
  269. package/store/actionOption.ts +22 -0
  270. package/store/baseSt.ts +1 -0
  271. package/store/formFieldSetters.ts +229 -0
  272. package/store/index.ts +125 -17
  273. package/store/modelActionContext.ts +65 -0
  274. package/store/modelOpenActions.ts +158 -0
  275. package/store/modelWriteActions.ts +240 -0
  276. package/store/modelWriteGuard.ts +3 -12
  277. package/store/openSeq.ts +34 -0
  278. package/store/sliceListActions.ts +370 -0
  279. package/store/sliceLiveActions.ts +140 -0
  280. package/store/stateBuilder.ts +2 -0
  281. package/store/storeInstance.ts +4 -18
  282. package/store/storeRegistry.ts +1 -1
  283. package/test/conformance.ts +25 -5
  284. package/types/base/base.d.ts +2 -1
  285. package/types/client/clientRuntime.d.ts +1 -0
  286. package/types/client/cn.d.ts +2 -2
  287. package/types/client/csrTypes.d.ts +2 -0
  288. package/types/client/frameConfig.d.ts +1 -0
  289. package/types/client/index.d.ts +25 -26
  290. package/types/client/locale.d.ts +1 -0
  291. package/types/client/makePageProto.d.ts +5 -13
  292. package/types/client/nativeThemeColor.d.ts +6 -0
  293. package/types/client/route/PageDefinition.d.ts +5 -2
  294. package/types/client/route/RouteDefinition.d.ts +2 -2
  295. package/types/client/route/routeArgs.d.ts +7 -0
  296. package/types/client/router.d.ts +3 -1
  297. package/types/client/rscNavigation.d.ts +1 -0
  298. package/types/client/viewportMeta.d.ts +5 -2
  299. package/types/common/CodeTranscript.d.ts +1 -1
  300. package/types/common/clientAddress.d.ts +5 -0
  301. package/types/common/err.d.ts +48 -0
  302. package/types/common/eventStream.d.ts +5 -1
  303. package/types/common/facetBarrel.d.ts +4 -0
  304. package/types/common/index.d.ts +6 -3
  305. package/types/common/isGuardRefusal.d.ts +3 -0
  306. package/types/common/loggedFailure.d.ts +2 -0
  307. package/types/common/mcpExposure.d.ts +9 -2
  308. package/types/common/routeConvention.d.ts +2 -0
  309. package/types/common/types.d.ts +18 -1
  310. package/types/constant/constantRegistry.d.ts +3 -1
  311. package/types/constant/crystalize.d.ts +1 -1
  312. package/types/constant/getDefault.d.ts +1 -1
  313. package/types/constant/immerify.d.ts +1 -1
  314. package/types/constant/index.d.ts +21 -21
  315. package/types/constant/purify.d.ts +2 -1
  316. package/types/constant/serialize.d.ts +1 -1
  317. package/types/constant/types.d.ts +1 -0
  318. package/types/dictionary/agent.dictionary.d.ts +1 -1
  319. package/types/dictionary/base.dictionary.d.ts +1 -1
  320. package/types/dictionary/dictionary.d.ts +9 -9
  321. package/types/dictionary/locale.d.ts +1 -1
  322. package/types/dictionary/trans.d.ts +3 -26
  323. package/types/document/dataLoader.d.ts +5 -0
  324. package/types/document/databaseRegistry.d.ts +2 -1
  325. package/types/document/documentSchema.d.ts +1 -0
  326. package/types/document/filterMeta.d.ts +4 -1
  327. package/types/document/into.d.ts +1 -1
  328. package/types/document/loaderInfo.d.ts +2 -1
  329. package/types/document/noDocumentError.d.ts +8 -1
  330. package/types/document/queryEvaluator.d.ts +1 -1
  331. package/types/document/types.d.ts +1 -1
  332. package/types/fetch/client/fetchClient.d.ts +6 -36
  333. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  334. package/types/fetch/client/httpClient.d.ts +2 -0
  335. package/types/fetch/client/remoteError.d.ts +0 -4
  336. package/types/fetch/client/requestScope.d.ts +11 -0
  337. package/types/fetch/client/signalCatalog.d.ts +25 -0
  338. package/types/fetch/client/wsClient.d.ts +2 -0
  339. package/types/fetch/requestStorage.d.ts +1 -0
  340. package/types/server/agentHooks.d.ts +4 -0
  341. package/types/server/akanApp.d.ts +2 -20
  342. package/types/server/akanOption.d.ts +16 -2
  343. package/types/server/akanServer.d.ts +2 -2
  344. package/types/server/assetHeaders.d.ts +1 -0
  345. package/types/server/console.d.ts +4 -3
  346. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  347. package/types/server/di/stageFailedError.d.ts +5 -0
  348. package/types/server/ed25519Key.d.ts +1 -0
  349. package/types/server/flightRowReader.d.ts +8 -2
  350. package/types/server/gateway/childSupervisor.d.ts +35 -0
  351. package/types/server/gateway/devHostChannel.d.ts +14 -0
  352. package/types/server/gateway/gatewayChildren.d.ts +50 -0
  353. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  354. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  355. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  356. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  357. package/types/server/gateway/gatewayStatus.d.ts +63 -0
  358. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  359. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  360. package/types/server/gateway/listeningPort.d.ts +5 -0
  361. package/types/server/htmlResultCache.d.ts +51 -0
  362. package/types/server/index.d.ts +19 -17
  363. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  364. package/types/server/lifecycle/startGuard.d.ts +10 -0
  365. package/types/server/logging/logHub.d.ts +5 -1
  366. package/types/server/logging/logStreamRoute.d.ts +2 -0
  367. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  368. package/types/server/logging/serverLogging.d.ts +12 -0
  369. package/types/server/mcp/AgentTools.d.ts +31 -0
  370. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  371. package/types/server/mcp/McpApps.d.ts +6 -2
  372. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  373. package/types/server/mcp/McpPages.d.ts +2 -1
  374. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  375. package/types/server/mcp/index.d.ts +1 -0
  376. package/types/server/migration/migrationCommand.d.ts +1 -1
  377. package/types/server/migration/migrationRunner.d.ts +9 -1
  378. package/types/server/remote/RemoteFetch.d.ts +42 -0
  379. package/types/server/remote/RemoteMcp.d.ts +52 -0
  380. package/types/server/remote/RemoteOAuth.d.ts +58 -0
  381. package/types/server/remote/RemoteSource.d.ts +51 -0
  382. package/types/server/remote/index.d.ts +5 -0
  383. package/types/server/remote/remoteError.d.ts +12 -0
  384. package/types/server/remote.d.ts +1 -0
  385. package/types/server/resolver/CascadeRunner.d.ts +2 -2
  386. package/types/server/resolver/database.resolver.d.ts +2 -2
  387. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  388. package/types/server/resolver/invalidSignal.d.ts +2 -0
  389. package/types/server/resolver/livePause.d.ts +5 -0
  390. package/types/server/resolver/modelFacade.d.ts +5 -0
  391. package/types/server/resolver/modelLoaders.d.ts +15 -0
  392. package/types/server/resolver/modelSchema.d.ts +6 -0
  393. package/types/server/resolver/roomAdmission.d.ts +7 -0
  394. package/types/server/resolver/signal.resolver.d.ts +1 -1
  395. package/types/server/resolver/sliceCrud.d.ts +8 -0
  396. package/types/server/resolver/timedQuery.d.ts +8 -0
  397. package/types/server/routeElementComposer.d.ts +21 -5
  398. package/types/server/routing/builtinRoutes.d.ts +24 -0
  399. package/types/server/routing/localRooms.d.ts +14 -0
  400. package/types/server/routing/roomReplay.d.ts +2 -2
  401. package/types/server/routing/serverListener.d.ts +31 -0
  402. package/types/server/rscClientCache.d.ts +34 -0
  403. package/types/server/rscClientChunks.d.ts +3 -1
  404. package/types/server/rscClientPatch.d.ts +12 -1
  405. package/types/server/rscDocumentHead.d.ts +33 -0
  406. package/types/server/rscFlightRenderer.d.ts +14 -0
  407. package/types/server/rscFlightStream.d.ts +53 -0
  408. package/types/server/rscHostReloads.d.ts +54 -0
  409. package/types/server/rscHostRenderStream.d.ts +53 -0
  410. package/types/server/rscHostRequests.d.ts +29 -0
  411. package/types/server/rscHttp.d.ts +4 -2
  412. package/types/server/rscNavigationState.d.ts +5 -1
  413. package/types/server/rscPagePrompts.d.ts +13 -0
  414. package/types/server/rscRenderControl.d.ts +12 -0
  415. package/types/server/rscRenderFallbacks.d.ts +41 -0
  416. package/types/server/rscRenderHandler.d.ts +29 -0
  417. package/types/server/rscRenderStats.d.ts +32 -0
  418. package/types/server/rscResultCaches.d.ts +18 -0
  419. package/types/server/rscRouteDocument.d.ts +52 -0
  420. package/types/server/rscStaticApp.d.ts +28 -0
  421. package/types/server/rscWorker.d.ts +1 -3
  422. package/types/server/rscWorkerHost.d.ts +10 -70
  423. package/types/server/rscWorkerProcess.d.ts +31 -0
  424. package/types/server/rscWorkerRecycler.d.ts +22 -0
  425. package/types/server/serverConfig.d.ts +30 -0
  426. package/types/server/serverMetrics.d.ts +11 -0
  427. package/types/server/sitemap.d.ts +1 -0
  428. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  429. package/types/server/ssrStaticApp.d.ts +20 -0
  430. package/types/server/webArtifact.d.ts +7 -0
  431. package/types/server/webAssetRoutes.d.ts +11 -0
  432. package/types/server/webCsrSurface.d.ts +18 -0
  433. package/types/server/webDocumentRoute.d.ts +19 -0
  434. package/types/server/webRouteContext.d.ts +45 -0
  435. package/types/server/webRouter.d.ts +3 -28
  436. package/types/server/webRscRoute.d.ts +24 -0
  437. package/types/server/webSiteFiles.d.ts +12 -0
  438. package/types/server/webStaticApp.d.ts +8 -0
  439. package/types/server/wellKnownRoutes.d.ts +5 -0
  440. package/types/service/agent.service.d.ts +3 -0
  441. package/types/service/agentAccounts.d.ts +8 -0
  442. package/types/service/agentLoop/agentLoop.d.ts +33 -0
  443. package/types/service/agentLoop/agentLoopTypes.d.ts +235 -0
  444. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  445. package/types/service/agentLoop/loopAnswer.d.ts +13 -0
  446. package/types/service/agentLoop/loopAsk.d.ts +12 -0
  447. package/types/service/agentLoop/loopCompaction.d.ts +12 -0
  448. package/types/service/agentLoop/loopRemotes.d.ts +40 -0
  449. package/types/service/agentLoop/loopRequest.d.ts +9 -0
  450. package/types/service/agentLoop/loopStored.d.ts +6 -0
  451. package/types/service/agentLoop/loopToolOutput.d.ts +8 -0
  452. package/types/service/agentLoop/loopToolkits.d.ts +17 -0
  453. package/types/service/agentLoop/loopTranscript.d.ts +13 -0
  454. package/types/{signal → service}/agentMeter.d.ts +1 -1
  455. package/types/{signal → service}/agentRelayPolicy.d.ts +18 -3
  456. package/types/service/index.d.ts +6 -0
  457. package/types/service/injectInfo.d.ts +2 -1
  458. package/types/service/ipcTypes.d.ts +10 -0
  459. package/types/service/liveRoomLimit.d.ts +26 -0
  460. package/types/service/liveRoomLimitError.d.ts +9 -0
  461. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  462. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  463. package/types/service/predefinedAdaptor/database.adaptor.d.ts +9 -7
  464. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  465. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +12 -0
  466. package/types/service/predefinedAdaptor/openaiDialect.d.ts +3 -2
  467. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  468. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  469. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  470. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  471. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  472. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +25 -0
  473. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  474. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  475. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +5 -28
  476. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +22 -0
  477. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  478. package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +3 -1
  479. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -15
  480. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  481. package/types/service/predefinedAdaptor/sql/types.d.ts +27 -4
  482. package/types/service/predefinedAdaptor/sseData.d.ts +13 -0
  483. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -3
  484. package/types/service/serviceRegistry.d.ts +1 -0
  485. package/types/signal/SignalFailure.d.ts +4 -0
  486. package/types/signal/agentTurnStream.d.ts +3 -0
  487. package/types/signal/byIdRead.d.ts +7 -0
  488. package/types/signal/carriedClientIps.d.ts +4 -0
  489. package/types/signal/endpointRateLimit.d.ts +12 -0
  490. package/types/signal/index.d.ts +32 -32
  491. package/types/signal/mcp/McpDocument.d.ts +2 -0
  492. package/types/signal/mcp/mcpProtocol.d.ts +5 -0
  493. package/types/signal/mcp/pagePrompt.d.ts +13 -0
  494. package/types/signal/resolveFieldContext.d.ts +15 -0
  495. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  496. package/types/signal/signalContext.d.ts +2 -14
  497. package/types/signal/slice.d.ts +15 -13
  498. package/types/signal/trace.d.ts +12 -1
  499. package/types/signal/types.d.ts +38 -7
  500. package/types/store/action.d.ts +4 -27
  501. package/types/store/actionErrorMessage.d.ts +1 -0
  502. package/types/store/actionOption.d.ts +24 -0
  503. package/types/store/baseSt.d.ts +1 -0
  504. package/types/store/formFieldSetters.d.ts +80 -0
  505. package/types/store/index.d.ts +17 -16
  506. package/types/store/modelActionContext.d.ts +189 -0
  507. package/types/store/modelOpenActions.d.ts +12 -0
  508. package/types/store/modelWriteActions.d.ts +16 -0
  509. package/types/store/modelWriteGuard.d.ts +2 -5
  510. package/types/store/openSeq.d.ts +17 -0
  511. package/types/store/sliceListActions.d.ts +295 -0
  512. package/types/store/sliceLiveActions.d.ts +6 -0
  513. package/types/store/stateBuilder.d.ts +2 -0
  514. package/types/test/conformance.d.ts +3 -1
  515. package/types/ui/Agent/Chat.d.ts +5 -2
  516. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  517. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  518. package/types/ui/Agent/ToolRow.d.ts +13 -0
  519. package/types/ui/Field/Choice.d.ts +2 -1
  520. package/types/ui/Field/index.d.ts +1 -1
  521. package/types/ui/Reference/origin.d.ts +1 -0
  522. package/types/ui/UiOverride/UiOverride.d.ts +2 -0
  523. package/types/ui/index.d.ts +2 -1
  524. package/types/ui/overlayLayer.d.ts +8 -2
  525. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  526. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  527. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  528. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  529. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  530. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  531. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +22 -13
  532. package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
  533. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  534. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  535. package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
  536. package/types/vendor/use-agentic/Transcript.d.ts +1 -1
  537. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  538. package/types/vendor/use-agentic/index.d.ts +1 -0
  539. package/types/vendor/use-agentic/types.d.ts +12 -3
  540. package/types/webkit/CsrGuards.d.ts +3 -0
  541. package/types/webkit/McpAppHost.d.ts +24 -0
  542. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  543. package/types/webkit/csrRefresh.d.ts +13 -0
  544. package/types/webkit/index.d.ts +3 -0
  545. package/types/webkit/needsBrowser.d.ts +5 -0
  546. package/types/webkit/useCamera.d.ts +1 -1
  547. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  548. package/types/webkit/useCsrLocationState.d.ts +21 -0
  549. package/types/webkit/useCsrNavigation.d.ts +25 -0
  550. package/types/webkit/useCsrRefs.d.ts +33 -0
  551. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  552. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  553. package/types/webkit/useCsrTransitions.d.ts +2 -0
  554. package/types/webkit/useGeoLocation.d.ts +1 -1
  555. package/types/webkit/useHistory.d.ts +2 -3
  556. package/types/webkit/useResolvedFrame.d.ts +38 -0
  557. package/types/webkit/useSyncNavigation.d.ts +22 -0
  558. package/ui/Agent/Bubble.tsx +4 -118
  559. package/ui/Agent/Chat.tsx +402 -235
  560. package/ui/Agent/ChatHeader.tsx +59 -0
  561. package/ui/Agent/ChatPendingCards.tsx +49 -0
  562. package/ui/Agent/ToolRow.tsx +117 -0
  563. package/ui/Agent/fetchRunner.ts +8 -1
  564. package/ui/BottomSheet.tsx +1 -1
  565. package/ui/Data/Item.tsx +2 -2
  566. package/ui/Data/ListContainer.tsx +348 -181
  567. package/ui/Data/useViewModal.ts +10 -4
  568. package/ui/Dialog/LegacyModal.tsx +1 -1
  569. package/ui/Dialog/Modal.tsx +1 -1
  570. package/ui/Field/Choice.tsx +3 -1
  571. package/ui/Load/StreamBoundary.tsx +1 -6
  572. package/ui/Load/View.tsx +2 -1
  573. package/ui/Model/EditModal.tsx +2 -1
  574. package/ui/Popconfirm.tsx +1 -1
  575. package/ui/Reference/origin.ts +1 -0
  576. package/ui/Select.tsx +43 -51
  577. package/ui/Signal/RestApi.tsx +3 -2
  578. package/ui/System/Client.tsx +4 -1
  579. package/ui/UiOverride/UiOverride.tsx +2 -0
  580. package/ui/index.ts +5 -0
  581. package/ui/overlayLayer.ts +25 -2
  582. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +31 -13
  583. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  584. package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
  585. package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
  586. package/vendor/@akanjs/native/native/desktop/src/external.rs +240 -114
  587. package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
  588. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  589. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +696 -0
  590. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  591. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  592. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  593. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  594. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  595. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  596. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  597. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  598. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  599. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  600. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  601. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  602. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  603. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  604. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +22 -13
  605. package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
  606. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  607. package/vendor/use-agentic/AgentSession.ts +35 -73
  608. package/vendor/use-agentic/CHANGELOG.md +0 -43
  609. package/vendor/use-agentic/Compaction.ts +12 -2
  610. package/vendor/use-agentic/SessionQuestion.ts +99 -0
  611. package/vendor/use-agentic/ToolRunner.ts +3 -15
  612. package/vendor/use-agentic/Transcript.ts +8 -5
  613. package/vendor/use-agentic/WIRE.md +28 -9
  614. package/vendor/use-agentic/failureCode.ts +44 -0
  615. package/vendor/use-agentic/httpRunner.ts +22 -8
  616. package/vendor/use-agentic/index.ts +1 -0
  617. package/vendor/use-agentic/types.ts +13 -1
  618. package/webkit/CsrGuards.ts +11 -2
  619. package/webkit/McpAppFetchBridge.ts +3 -1
  620. package/webkit/McpAppHost.ts +122 -0
  621. package/webkit/RenderLayer.tsx +48 -14
  622. package/webkit/RouteLevelBoundary.tsx +37 -0
  623. package/webkit/csrRefresh.ts +33 -0
  624. package/webkit/index.ts +3 -0
  625. package/webkit/lazy.tsx +5 -1
  626. package/webkit/needsBrowser.ts +10 -0
  627. package/webkit/useCamera.tsx +18 -7
  628. package/webkit/useCsrKeyboard.ts +155 -0
  629. package/webkit/useCsrLocationState.ts +58 -0
  630. package/webkit/useCsrNavigation.ts +302 -0
  631. package/webkit/useCsrRefs.ts +52 -0
  632. package/webkit/useCsrRenderTrace.ts +68 -0
  633. package/webkit/useCsrStackLifecycle.ts +120 -0
  634. package/webkit/useCsrTransitions.ts +552 -0
  635. package/webkit/useCsrValues.ts +73 -1235
  636. package/webkit/useGeoLocation.tsx +1 -3
  637. package/webkit/useHistory.ts +2 -2
  638. package/webkit/useLocation.ts +3 -2
  639. package/webkit/useResolvedFrame.ts +116 -0
  640. package/webkit/useSyncNavigation.ts +109 -0
  641. package/vendor/@akanjs/native/CHANGELOG.md +0 -21
package/server/akanApp.ts CHANGED
@@ -1,26 +1,22 @@
1
1
 
2
-
3
2
  import "./lifecycle/loadBuildEnv";
4
- import { mkdir, readdir, rm } from "node:fs/promises";
5
- import path from "node:path";
3
+ import { AkanError } from "akanjs/base";
6
4
  import { Logger, TrustedProxy } from "akanjs/common";
7
- import type { AkanChildRole, AkanChildStatus, AkanIpcMessage, AkanMetricsReport, AkanUpstream } from "akanjs/service";
8
- import { getApiPrefix, getWsPrefix, normalizeRoutePrefix, resetEnvCache } from "../base/baseEnv";
9
- import { type RestartPolicy, RestartSchedule } from "../common/restartSchedule";
10
- import { CrossSiteGuard } from "../signal/CrossSiteGuard";
11
- import { isTraceEnabled } from "../signal/trace";
12
- import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "./akanAppHeaders";
13
- import type { BuilderMessage, BuilderRequest, BuilderResponse } from "./artifact";
14
- import { type AssetHeaderOptions, applySecurityHeaders, assetHeaders } from "./assetHeaders";
15
- import { compressResponse, compressStreamResponse, encodedFileResponse } from "./contentEncoding";
5
+ import type { AkanIpcMessage } from "akanjs/service";
6
+ import { resetEnvCache } from "../base/baseEnv";
7
+ import type { BuilderMessage } from "./artifact";
8
+ import { ChildSupervisor } from "./gateway/childSupervisor";
9
+ import { DevHostChannel } from "./gateway/devHostChannel";
10
+ import { GatewayChildren } from "./gateway/gatewayChildren";
11
+ import { type AkanAppOptions, GatewayConfig } from "./gateway/gatewayConfig";
12
+ import { GatewayHttpProxy } from "./gateway/gatewayHttpProxy";
13
+ import { GatewayLogging } from "./gateway/gatewayLogging";
14
+ import { GatewayRooms } from "./gateway/gatewayRooms";
15
+ import { GatewayStatus } from "./gateway/gatewayStatus";
16
+ import { GatewayWebSocketRelay, type GatewayWsData } from "./gateway/gatewayWebSocketRelay";
17
+ import { ListeningPort } from "./gateway/listeningPort";
16
18
  import { isPortInUseError } from "./lifecycle/portInUse";
17
- import { resolveRuntimeDir } from "./lifecycle/runtimeDir";
18
- import { ChildOutputReader } from "./logging/childOutputReader";
19
- import { HubFileSink } from "./logging/hubFileSink";
20
- import { LogControlSocket } from "./logging/logControlSocket";
21
- import { LogHub } from "./logging/logHub";
22
19
  import { LogStreamRoute } from "./logging/logStreamRoute";
23
- import { RotatingLogWriter } from "./logging/rotatingLogWriter";
24
20
  import { AppInfo } from "./ops/appInfo";
25
21
  import type { OpsHost } from "./ops/opsCommand";
26
22
  import type { OpsRoute } from "./ops/opsRoute";
@@ -29,235 +25,65 @@ import { ProcessMetricsCollector } from "./processMetricsCollector";
29
25
  import { HostAllowlist } from "./routing/hostAllowlist";
30
26
  import { RouteHosts } from "./routing/routeHosts";
31
27
  import { ServerLimits } from "./routing/serverLimits";
32
- import { WsUpgrade } from "./routing/wsUpgrade";
33
28
  import { SelfExec } from "./selfExec";
34
- import { resolveStaticPath } from "./staticPath";
35
- import { getWebConfigFromEnv } from "./types";
36
29
 
37
- interface ChildState {
38
- idx: number;
39
- role: AkanChildRole;
40
- proc: Bun.Subprocess<"ignore", "pipe", "pipe">;
41
- ready: boolean;
42
- status: AkanChildStatus;
43
- pid?: number;
44
- upstream?: AkanUpstream;
45
- wsUpstream?: Extract<AkanUpstream, { type: "tcp" }>;
46
- healthPath?: string;
47
- metrics: AkanMetricsReport;
48
- /** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
49
- lastPongAtMono?: number;
50
- restart: RestartSchedule;
51
- restartCount: number;
52
- restartPending: boolean;
53
- lastExitCode?: number | null;
54
- lastRestartAt?: number;
55
- lastRestartReason?: string;
56
- lastErrorMessage?: string;
57
- }
30
+ export type { AkanAppOptions } from "./gateway/gatewayConfig";
58
31
 
59
32
  interface SoloServer {
60
33
  start: (options: { listen: boolean }) => Promise<unknown>;
61
34
  }
62
35
 
63
- interface GatewayWsData {
64
- childIdx: number;
65
- upstream: WebSocket;
66
- clientIp: string | null;
67
- pending: (string | ArrayBuffer)[];
68
- pendingBytes: number;
69
- }
70
-
71
- type GatewayUpstream = {
72
- http: Extract<AkanUpstream, { type: "unix" }>;
73
- ws?: Extract<AkanUpstream, { type: "tcp" }>;
74
- };
75
-
76
- const relayableCloseCode = (code: number): number => {
77
- if (code >= 3000 && code <= 4999) return code;
78
- if (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) return code;
79
- return 1001;
80
- };
81
-
82
- export interface AkanAppOptions {
83
- replica?: number | string;
84
- serverPath?: string;
85
- runtimeDir?: string;
86
- port?: number;
87
- wsBasePort?: number;
88
- openapi?: boolean;
89
- /** Signal endpoint mount, `/api` by default; handed down as `AKAN_API_PREFIX` (CSR/mobile follow akan.config.ts). */
90
- prefix?: string;
91
- /** Where the websocket upgrade sits under `prefix`, `/ws` by default. Handed down as `AKAN_WS_PREFIX`. */
92
- websocketPrefix?: string;
93
- /** Boot only these modules and what they reach; omitted or empty mounts every enabled one. `AKAN_MODULES`. */
94
- modules?: string[];
95
- /** Mount all but these and whatever reaches them, applied after `modules`. `AKAN_DISABLE_MODULES`. */
96
- disableModules?: string[];
97
- /** Like `disableModules`, by owning lib. `AKAN_DISABLE_LIBS`. */
98
- disableLibs?: string[];
99
- /** In-process replica; default on for one env-set traffic replica, off if `replica` is passed or AKAN_SOLO=false. */
100
- solo?: boolean;
101
- }
102
-
103
- interface AkanReplicaConfig {
104
- federation: number;
105
- batch: number;
106
- all: number;
107
- total: number;
108
- value: string;
109
- }
110
-
111
36
  export class AkanApp {
112
- static readonly #childRestartGraceMs = 5_000;
113
- static readonly #devMaxChildBootFailures = 3;
114
-
115
37
  readonly logger = new Logger("AkanApp");
116
- readonly #devHosted = process.env.AKAN_COMMAND_TYPE === "start";
117
- readonly #childRestartPolicy: RestartPolicy = {
118
- min: 1_000,
119
- max: 30_000,
120
- ...(this.#devHosted ? { maxAttempts: AkanApp.#devMaxChildBootFailures - 1 } : {}),
121
- };
122
- readonly #healthTimeoutMs = AkanApp.#parseHealthTimeoutMs();
123
- readonly #upstreamWaitMs = AkanApp.#parseUpstreamWaitMs();
124
- /** Child stderr is mostly bundler/runtime noise, kept to the log file; with none it may be a crash's only trace. */
125
- readonly #printChildStderr = process.env.AKAN_CHILD_STDERR === "1";
126
- readonly #serverPath: string;
127
- readonly #artifactDir: string;
128
- readonly #replica: AkanReplicaConfig;
129
- readonly #runtimeDir: string;
130
- readonly #socketRunId = `${process.pid}-${Date.now().toString(36)}`;
131
- readonly #port: number;
132
- readonly #wsBasePort: number;
133
- readonly #openapi?: boolean;
134
- readonly #prefix: string;
135
- readonly #websocketPrefix: string;
136
- readonly #web = getWebConfigFromEnv();
137
- readonly #modules: string[];
138
- readonly #disableModules: string[];
139
- readonly #disableLibs: string[];
140
- readonly #solo: boolean;
141
- readonly #children = new Map<number, ChildState>();
142
- readonly #roomChildren = new Map<string, Set<number>>();
143
- readonly #childRooms = new Map<number, Map<string, Set<string>>>();
144
- readonly #socketRooms = new Map<string, { childIdx: number; rooms: Set<string> }>();
145
- readonly #childLiveModels = new Map<number, Set<string>>();
146
- #nextBuilderReqId = 1;
147
- readonly #builderReqMap = new Map<number, { childIdx: number; childLocalId: number }>();
38
+ readonly #config: GatewayConfig;
39
+ readonly #children: GatewayChildren;
40
+ readonly #logging: GatewayLogging;
41
+ readonly #rooms: GatewayRooms;
42
+ readonly #host: DevHostChannel;
43
+ readonly #supervisor: ChildSupervisor;
44
+ readonly #status: GatewayStatus;
45
+ readonly #proxy: GatewayHttpProxy;
46
+ readonly #ws: GatewayWebSocketRelay;
148
47
  #server: Bun.Server<GatewayWsData> | null = null;
149
- #rrIdx = 0;
150
- #federationChildCache: ChildState[] | null = null;
151
48
  #snapshotTimer: Timer | null = null;
152
49
  #healthTimer: Timer | null = null;
153
50
  #metricsTimer: Timer | null = null;
154
- #logWriter: RotatingLogWriter | null = null;
155
- #detachFileLog: (() => void) | null = null;
156
- #logHub: LogHub | null = null;
157
- #logControl: LogControlSocket | null = null;
158
- #logStream: LogStreamRoute | null = null;
159
51
  #ops: OpsRoute | null = null;
160
52
  #hostAllowlist = HostAllowlist.fromEnv();
161
53
  readonly #limits = new ServerLimits();
162
-
163
- static readonly #wsPendingLimitBytes = 1024 * 1024;
164
- static readonly #wsUpstreamOpenTimeoutMs = 10_000;
165
- readonly #wsCaps = {
166
- total: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS"),
167
- perIp: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS_PER_IP"),
168
- };
169
- #wsOpen = 0;
170
- readonly #wsOpenByIp = new Map<string, number>();
171
54
  readonly #statusAccess = StatusAccess.fromEnv();
172
- static readonly #ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
173
- #gatewayMetrics: AkanMetricsReport = {};
174
- #proxyHopCount = 0;
175
- #proxyHopSumMs = 0;
176
- #proxyHopMaxMs = 0;
177
55
  #resolveStopped: (() => void) | null = null;
178
56
  #exitAfterStop = false;
179
- #stopping = false;
180
57
 
181
58
  constructor(serverPathOrOptions: string | AkanAppOptions = "./server", options: AkanAppOptions = {}) {
182
59
  SelfExec.adopt();
183
60
  const resolvedOptions = typeof serverPathOrOptions === "string" ? options : serverPathOrOptions;
184
61
  const serverPath = typeof serverPathOrOptions === "string" ? serverPathOrOptions : "./server";
185
- this.#serverPath = AkanApp.#resolveServerPath(resolvedOptions.serverPath ?? serverPath);
186
- this.#artifactDir = path.resolve(path.dirname(this.#serverPath), ".akan", "artifact");
187
- this.#replica = AkanApp.#parseReplicaConfig(resolvedOptions.replica);
188
- this.#runtimeDir = resolveRuntimeDir(resolvedOptions.runtimeDir);
189
- this.#port = Number(resolvedOptions.port ?? process.env.PORT ?? 8282);
190
- this.#wsBasePort = Number(resolvedOptions.wsBasePort ?? process.env.AKAN_WS_BASE_PORT ?? this.#port + 10_000);
191
- this.#openapi = resolvedOptions.openapi;
192
- this.#prefix = normalizeRoutePrefix(resolvedOptions.prefix) ?? getApiPrefix();
193
- this.#websocketPrefix = normalizeRoutePrefix(resolvedOptions.websocketPrefix) ?? getWsPrefix();
194
- this.#modules = resolvedOptions.modules ?? [];
195
- this.#disableModules = resolvedOptions.disableModules ?? [];
196
- this.#disableLibs = resolvedOptions.disableLibs ?? [];
197
- this.#solo = AkanApp.#resolveSolo(resolvedOptions, this.#replica);
198
- this.#logHub = LogHub.attach();
199
- }
200
-
201
- static #resolveSolo(options: AkanAppOptions, replica: AkanReplicaConfig) {
202
- if (options.solo !== undefined) return options.solo;
203
- if (process.env.AKAN_SOLO === "false" || process.env.AKAN_SOLO === "0") return false;
204
- if (process.env.AKAN_COMMAND_TYPE === "start") return false;
205
- if (options.replica !== undefined) return false;
206
- return replica.total === 1 && replica.batch === 0;
207
- }
208
-
209
- static #resolveServerPath(serverPath: string) {
210
- const baseDir = path.dirname(Bun.main);
211
- const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
212
- if (path.extname(resolved)) return resolved;
213
- return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
214
- }
215
-
216
- static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
217
- const configured = value ?? process.env.AKAN_REPLICA;
218
- const raw = String(configured ?? "0,0,1").trim();
219
- const [federationRaw, batchRaw, allRaw] = raw.split(",");
220
- const federation = AkanApp.#parseReplicaCount(federationRaw, 0);
221
- const batch = AkanApp.#parseReplicaCount(batchRaw, 0);
222
- const all = AkanApp.#parseReplicaCount(allRaw, configured == null ? 1 : 0);
223
- const normalizedAll = federation + batch + all > 0 ? all : 1;
224
- return {
225
- federation,
226
- batch,
227
- all: normalizedAll,
228
- total: federation + batch + normalizedAll,
229
- value: `${federation},${batch},${normalizedAll}`,
230
- };
231
- }
232
-
233
- static #parseReplicaCount(value: string | undefined, fallback: number) {
234
- const parsed = Number.parseInt(value ?? "", 10);
235
- return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
236
- }
237
-
238
- static #defaultChildNodeEnv() {
239
- if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
240
- if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
241
- if (process.env.NODE_ENV) return process.env.NODE_ENV;
242
- return Bun.main.endsWith(".js") ? "production" : "development";
243
- }
244
-
245
- static #parseHealthTimeoutMs() {
246
- const configured = Number(process.env.AKAN_HEALTH_TIMEOUT_MS);
247
- if (Number.isFinite(configured) && configured > 0) return configured;
248
- return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
249
- }
250
-
251
- static #parseUpstreamWaitMs() {
252
- const configured = Number(process.env.AKAN_UPSTREAM_WAIT_MS);
253
- if (Number.isFinite(configured) && configured >= 0) return configured;
254
- return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
255
- }
256
-
257
- static #childShutdownWaitMs() {
258
- const configured = Number(process.env.AKAN_CHILD_SHUTDOWN_WAIT_MS);
259
- if (Number.isFinite(configured) && configured > 0) return configured;
260
- return process.env.AKAN_COMMAND_TYPE === "start" ? 5_000 : 30_000;
62
+ const logger = this.logger;
63
+ const config = new GatewayConfig(serverPath, resolvedOptions);
64
+ const children = new GatewayChildren(logger);
65
+ const logging = new GatewayLogging(config, children, logger);
66
+ const rooms = new GatewayRooms(children, logger);
67
+ const host = new DevHostChannel(children, logger);
68
+ const supervisor = new ChildSupervisor({
69
+ config,
70
+ children,
71
+ rooms,
72
+ logging,
73
+ host,
74
+ logger,
75
+ onMessage: (idx, message, proc) => this.#handleMessage(idx, message, proc),
76
+ });
77
+ const status = new GatewayStatus(config, children, rooms, logger);
78
+ this.#config = config;
79
+ this.#children = children;
80
+ this.#logging = logging;
81
+ this.#rooms = rooms;
82
+ this.#host = host;
83
+ this.#supervisor = supervisor;
84
+ this.#status = status;
85
+ this.#proxy = new GatewayHttpProxy({ config, children, supervisor, status, limits: this.#limits, logger });
86
+ this.#ws = new GatewayWebSocketRelay(config, children);
261
87
  }
262
88
 
263
89
  async start() {
@@ -267,31 +93,36 @@ export class AkanApp {
267
93
  await OpsCommand.run(process.argv.slice(3), { importServer: async () => await this.#importServer() }),
268
94
  );
269
95
  }
270
- if (this.#solo) return await this.#startSolo();
96
+ if (this.#config.solo) return await this.#startSolo();
271
97
  if (SelfExec.carried)
272
- throw new Error(
98
+ throw new AkanError(
99
+ "invalidConfig",
273
100
  "A desktop app's server runs in one process, and this one was asked for a gateway and replicas, which would start with the `bun` on the user's PATH: by `replica` or `solo: false` in main.ts, or by AKAN_SOLO=false, an AKAN_REPLICA other than one traffic replica, or AKAN_COMMAND_TYPE=start in its env. Leave them out of the app the desktop build carries.",
274
101
  );
275
102
  Logger.role = "gateway";
276
- await this.#prepareRuntimeDir();
277
- await this.#startLogHub();
278
- this.#startFileLogging();
103
+ await this.#supervisor.prepareRuntimeDir();
104
+ await this.#logging.start();
279
105
  await this.#startOps();
280
- for (let idx = 0; idx < this.#replica.total; idx++) this.#spawn(idx);
106
+
107
+ if (this.#children.stopping) {
108
+ await this.#logging.stop();
109
+ return;
110
+ }
111
+ for (let idx = 0; idx < this.#config.replica.total; idx++) this.#supervisor.spawn(idx);
281
112
  try {
282
113
  this.#listen();
283
114
  } catch (error) {
284
115
  if (isPortInUseError(error)) {
285
- const message = `Port ${this.#port} is already in use — another \`akan start\` or an orphaned gateway may still be running (try: lsof -ti :${this.#port}).`;
116
+ const message = `Port ${this.#config.port} is already in use — another \`akan start\` or an orphaned gateway may still be running (try: lsof -ti :${this.#config.port}).`;
286
117
  this.logger.error(message);
287
- this.#reportBackendBuildStatus({ ok: false, message });
118
+ this.#host.reportBackendBuildStatus({ ok: false, message });
288
119
  }
289
120
  await this.stop("listen-failed");
290
121
  throw error;
291
122
  }
292
- this.#snapshotTimer = setInterval(() => this.#requestRoomSnapshots(), 30_000);
293
- this.#healthTimer = setInterval(() => this.#checkHealth(), 2_000);
294
- this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#reportMetrics());
123
+ this.#snapshotTimer = setInterval(() => this.#rooms.requestRoomSnapshots(), 30_000);
124
+ this.#healthTimer = setInterval(() => this.#supervisor.checkHealth(), 2_000);
125
+ this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#status.reportMetrics());
295
126
  process.on("message", (message) => this.#handleHostMessage(message as BuilderMessage));
296
127
  process.on("disconnect", () => this.#handleHostDisconnect());
297
128
  process.on("SIGINT", () => this.#handleShutdownSignal("SIGINT"));
@@ -302,55 +133,43 @@ export class AkanApp {
302
133
  }
303
134
 
304
135
  async #importServer() {
305
- Object.assign(process.env, this.#childEnv(0, this.#getRole(0)), { AKAN_COMMAND_TYPE: "script" });
136
+ Object.assign(process.env, this.#config.childEnv(0, this.#config.roleOf(0)), { AKAN_COMMAND_TYPE: "script" });
306
137
  resetEnvCache();
307
- return (await import(this.#serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
138
+ return (await import(this.#config.serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
308
139
  }
309
140
 
310
141
  async #startSolo() {
311
- const role = this.#getRole(0);
142
+ const role = this.#config.roleOf(0);
312
143
 
313
- Object.assign(process.env, this.#childEnv(0, role));
144
+ Object.assign(process.env, this.#config.childEnv(0, role));
314
145
 
315
146
  resetEnvCache();
316
147
  this.logger.info(`Starting ${role} replica in this process (solo); set AKAN_SOLO=false for the gateway`);
317
- const mod = (await import(this.#serverPath)) as { server?: SoloServer; app?: SoloServer };
148
+ const mod = (await import(this.#config.serverPath)) as { server?: SoloServer; app?: SoloServer };
318
149
  const server = mod.server ?? mod.app;
319
- if (!server?.start) throw new Error("server.ts must export server or app with start()");
150
+ if (!server?.start) throw new AkanError("invalidArtifact", "server.ts must export server or app with start()");
320
151
  await server.start({ listen: true });
321
152
  }
322
153
 
323
154
  async stop(signal = "SIGTERM") {
324
- if (this.#stopping) return;
325
- this.#stopping = true;
155
+ if (this.#children.stopping) return;
156
+ this.#children.markStopping();
326
157
  for (const timer of [this.#snapshotTimer, this.#healthTimer, this.#metricsTimer]) if (timer) clearInterval(timer);
327
158
  this.#snapshotTimer = null;
328
159
  this.#healthTimer = null;
329
160
  this.#metricsTimer = null;
330
161
  this.#server?.stop(true);
331
162
  this.#server = null;
332
- for (const child of this.#children.values()) {
333
- child.restart.cancel();
334
- this.#sendToChild(child, { type: "shutdown", signal } satisfies AkanIpcMessage);
335
- }
336
- await Promise.race([
337
- Promise.all([...this.#children.values()].map((child) => child.proc.exited.catch(() => undefined))),
338
- new Promise((resolve) => setTimeout(resolve, AkanApp.#childShutdownWaitMs())),
339
- ]);
340
-
341
- const stragglers = [...this.#children.values()].filter((child) => !child.proc.killed);
342
- for (const child of stragglers) child.proc.kill("SIGKILL");
343
- await Promise.all(stragglers.map((child) => child.proc.exited.catch(() => undefined)));
344
- this.#children.clear();
345
- await this.#stopLogHub();
346
- await this.#stopFileLogging();
163
+ ListeningPort.record(this, undefined);
164
+ await this.#supervisor.stopAll(signal);
165
+ await this.#logging.stop();
347
166
  this.#resolveStopped?.();
348
167
  this.#resolveStopped = null;
349
168
  if (this.#exitAfterStop) process.exit(0);
350
169
  }
351
170
 
352
171
  #handleShutdownSignal(signal: NodeJS.Signals) {
353
- if (this.#stopping) process.exit(1);
172
+ if (this.#children.stopping) process.exit(1);
354
173
  this.#exitAfterStop = true;
355
174
  void this.stop(signal).catch((error) => {
356
175
  this.logger.error(`Failed to shutdown gateway: ${error instanceof Error ? error.message : String(error)}`);
@@ -359,247 +178,13 @@ export class AkanApp {
359
178
  }
360
179
 
361
180
  #handleHostDisconnect() {
362
- if (this.#stopping) return;
181
+ if (this.#children.stopping) return;
363
182
  this.logger.warn("Host IPC channel closed; shutting down gateway and children");
364
183
  this.#exitAfterStop = true;
365
- setTimeout(() => process.exit(1), AkanApp.#childShutdownWaitMs() + 5_000);
184
+ setTimeout(() => process.exit(1), GatewayConfig.childShutdownWaitMs() + 5_000);
366
185
  void this.stop("ipc-disconnect").catch(() => process.exit(1));
367
186
  }
368
187
 
369
- #spawn(idx: number) {
370
- const role = this.#getRole(idx);
371
- const upstream = this.#getChildUpstream(idx, role);
372
-
373
- const childCode = `import(${JSON.stringify(path.resolve(this.#serverPath))}).then((mod)=>{ const server = mod.server ?? mod.app; if (!server?.start) throw new Error("server.ts must export server or app with start()"); return server.start({ listen: process.env.SERVER_MODE !== "batch" }); }).catch((error)=>{ const exit = () => process.exit(1); setTimeout(exit, 2000); if (!process.send) return exit(); process.send({ type: "error", message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, pid: process.pid }, undefined, undefined, exit); });`;
374
- const proc: Bun.Subprocess<"ignore", "pipe", "pipe"> = Bun.spawn(["bun", "-e", childCode], {
375
- cwd: process.cwd(),
376
- env: {
377
- ...process.env,
378
-
379
- ...this.#childEnv(idx, role),
380
- AKAN_CHILD_SOCKET: upstream.http.socketPath,
381
- AKAN_CHILD_WS_PORT: upstream.ws ? String(upstream.ws.port) : "",
382
- ...(this.#printChildStderr || Logger.isNdjson ? {} : { AKAN_CHILD_STDERR_HIDDEN: "1" }),
383
- },
384
- ipc: (message) => this.#handleMessage(idx, message as AkanIpcMessage, proc),
385
- stdout: "pipe",
386
- stderr: "pipe",
387
- stdin: "ignore",
388
- });
389
- const previous = this.#children.get(idx);
390
- this.#children.set(idx, {
391
- idx,
392
- role,
393
- proc,
394
- ready: false,
395
- status: "starting",
396
- metrics: {},
397
-
398
- restart: previous?.restart ?? new RestartSchedule(this.#childRestartPolicy),
399
- restartCount: previous?.restartCount ?? 0,
400
- restartPending: false,
401
- lastExitCode: previous?.lastExitCode,
402
- lastRestartAt: previous?.lastRestartAt,
403
- lastRestartReason: previous?.lastRestartReason,
404
- });
405
- this.#federationChildCache = null;
406
- const output = new ChildOutputReader({
407
- onLine: (line) => this.#writeChildLine(idx, role, proc.pid, "stdout", line),
408
- onBlock: (lines) => this.#writeChildStderrBlock(idx, role, proc.pid, lines),
409
- });
410
- void output.pipe(proc.stdout, "stdout");
411
- void output.pipe(proc.stderr, "stderr");
412
- proc.exited.then((code) => this.#handleChildExit(idx, proc, code));
413
- }
414
-
415
- #childEnv(idx: number, role: AkanChildRole) {
416
- return {
417
- PORT: String(this.#port),
418
- NODE_ENV: AkanApp.#defaultChildNodeEnv(),
419
- AKAN_REPLICA: this.#replica.value,
420
- AKAN_REPLICA_IDX: String(idx),
421
- AKAN_APP_DIR: path.dirname(this.#serverPath),
422
- SERVER_MODE: role,
423
- AKAN_API_PREFIX: this.#prefix,
424
- AKAN_WS_PREFIX: this.#websocketPrefix,
425
- ...(this.#openapi === undefined ? {} : { AKAN_OPENAPI: this.#openapi ? "true" : "false" }),
426
- ...(this.#modules.length ? { AKAN_MODULES: this.#modules.join(",") } : {}),
427
- ...(this.#disableModules.length ? { AKAN_DISABLE_MODULES: this.#disableModules.join(",") } : {}),
428
- ...(this.#disableLibs.length ? { AKAN_DISABLE_LIBS: this.#disableLibs.join(",") } : {}),
429
- };
430
- }
431
-
432
- #handleChildExit(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, code: number | null) {
433
- const child = this.#children.get(idx);
434
- if (!child || child.proc !== proc) return;
435
- if (child.status === "crashed") return;
436
- child.status = "exited";
437
- child.lastExitCode = code;
438
- this.#federationChildCache = null;
439
- this.#removeChildRooms(idx);
440
- if (this.#stopping) return;
441
- void this.#scheduleChildRestart(child, proc, `exit:${code ?? "unknown"}`);
442
- }
443
-
444
- #scheduleChildRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string): void {
445
- if (this.#stopping) return;
446
- if (child.proc !== proc) return;
447
- if (child.restartPending || child.restart.pending) {
448
- child.lastRestartReason = reason;
449
- return;
450
- }
451
- if (child.restart.exhausted && !child.ready) {
452
- this.#markChildCrashed(child, reason);
453
- return;
454
- }
455
-
456
- child.restartPending = true;
457
- child.ready = false;
458
- child.status = reason === "health-timeout" || reason === "upstream-open-failed" ? "unhealthy" : "exited";
459
- child.upstream = undefined;
460
- child.wsUpstream = undefined;
461
- child.healthPath = undefined;
462
- this.#federationChildCache = null;
463
- child.lastRestartReason = reason;
464
- child.lastRestartAt = Date.now();
465
- this.#removeChildRooms(child.idx);
466
-
467
- const delay = child.restart.next();
468
- child.restartCount += 1;
469
- this.logger.error(
470
- `Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restart.attempts})`,
471
- );
472
-
473
- void this.#restartChildAfterDelay(child.idx, proc, reason, delay).catch((error) => {
474
- const current = this.#children.get(child.idx);
475
- if (!current || current.proc !== proc || this.#stopping) return;
476
- current.restartPending = false;
477
- this.logger.error(
478
- `Failed to restart child ${child.idx}/${child.role}: ${error instanceof Error ? error.message : String(error)}`,
479
- );
480
- this.#scheduleChildRestart(current, proc, "restart-failed");
481
- });
482
- }
483
-
484
- async #restartChildAfterDelay(
485
- idx: number,
486
- proc: Bun.Subprocess<"ignore", "pipe", "pipe">,
487
- reason: string,
488
- delay: number,
489
- ) {
490
- const child = this.#children.get(idx);
491
- if (!child || child.proc !== proc || this.#stopping) return;
492
- await this.#stopChildForRestart(child, proc, reason);
493
- if (this.#stopping) return;
494
- const current = this.#children.get(idx);
495
- if (!current || current.proc !== proc) return;
496
- current.restart.arm(delay, () => {
497
- void this.#respawnChild(idx, proc).catch((error) => {
498
- const latest = this.#children.get(idx);
499
- if (!latest || latest.proc !== proc || this.#stopping) return;
500
- latest.restartPending = false;
501
- this.logger.error(
502
- `Failed to respawn child ${idx}/${latest.role}: ${error instanceof Error ? error.message : String(error)}`,
503
- );
504
- this.#scheduleChildRestart(latest, proc, "respawn-failed");
505
- });
506
- });
507
- }
508
-
509
- async #respawnChild(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">) {
510
- if (this.#stopping) return;
511
- const current = this.#children.get(idx);
512
- if (!current || current.proc !== proc) return;
513
- await this.#removeChildSocket(idx, current.role);
514
- if (this.#stopping) return;
515
- current.restartPending = false;
516
- this.#spawn(idx);
517
- }
518
-
519
- #markChildCrashed(child: ChildState, reason: string) {
520
-
521
- if (child.status === "crashed") return;
522
- child.ready = false;
523
- child.status = "crashed";
524
- child.restartPending = false;
525
- child.upstream = undefined;
526
- child.wsUpstream = undefined;
527
- child.healthPath = undefined;
528
- child.lastRestartReason = reason;
529
- this.#federationChildCache = null;
530
- this.#removeChildRooms(child.idx);
531
- const attempts = child.restart.attempts + 1;
532
- const detail = child.lastErrorMessage ?? reason;
533
- const message = `Backend replica ${child.idx}/${child.role} failed ${attempts} consecutive boots; waiting for a code change to retry: ${detail}`;
534
- this.logger.error(`[child-crash-loop] ${message}`);
535
- this.#reportBackendBuildStatus({ ok: false, message });
536
- }
537
-
538
- #reportBackendBuildStatus({ ok, message }: { ok: boolean; message: string }) {
539
- process.send?.({
540
- type: "build-status",
541
- data: { generation: -1, phase: "backend", ok, files: [], message },
542
- } satisfies BuilderMessage);
543
- }
544
-
545
- #isChildUnavailable(child: ChildState): boolean {
546
- return child.proc.killed || child.status === "exited" || child.status === "crashed";
547
- }
548
-
549
- async #stopChildForRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string) {
550
- if (reason.startsWith("exit:") || proc.killed) return;
551
- this.#sendToChild(child, { type: "shutdown", signal: reason } satisfies AkanIpcMessage);
552
- const result = await Promise.race([
553
- proc.exited.then(() => "exited" as const).catch(() => "exited" as const),
554
- new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), AkanApp.#childRestartGraceMs)),
555
- ]);
556
- if (result === "timeout" && !proc.killed) {
557
- this.logger.warn(`Child ${child.idx}/${child.role} did not stop in ${AkanApp.#childRestartGraceMs}ms; killing`);
558
- proc.kill();
559
- await proc.exited.catch(() => undefined);
560
- }
561
- }
562
-
563
- async #prepareRuntimeDir() {
564
- await mkdir(this.#runtimeDir, { recursive: true });
565
-
566
- const entries = await readdir(this.#runtimeDir).catch(() => []);
567
- await Promise.all(
568
- entries
569
- .filter((name) => /^akan-(child-.*|control)\.sock$/.test(name))
570
- .map((name) => rm(path.join(this.#runtimeDir, name), { force: true }).catch(() => undefined)),
571
- );
572
- }
573
-
574
- async #removeChildSocket(idx: number, role: AkanChildRole) {
575
- const socketPath = this.#getChildUpstream(idx, role).http.socketPath;
576
- try {
577
- await rm(socketPath, { force: true });
578
- } catch {
579
- }
580
- }
581
-
582
- #startFileLogging() {
583
- this.#logWriter = RotatingLogWriter.fromRuntimeDir(this.#runtimeDir);
584
- if (this.#logWriter) this.#detachFileLog = HubFileSink.attach(this.#logWriter, this.#logHub, "gateway");
585
- }
586
-
587
- async #stopFileLogging() {
588
- this.#detachFileLog?.();
589
- this.#detachFileLog = null;
590
- const writer = this.#logWriter;
591
- this.#logWriter = null;
592
- await writer?.close();
593
- }
594
-
595
- async #startLogHub() {
596
- const hub = LogHub.attach();
597
- this.#logHub = hub;
598
- hub.onFloorChange((minSev) => this.#fanoutToAll({ type: "log.level", minSev }));
599
- this.#logStream = LogStreamRoute.fromEnv(() => this.#logHub);
600
- this.#logControl = await LogControlSocket.open(hub, this.#runtimeDir, this.logger);
601
- }
602
-
603
188
  async #startOps() {
604
189
  if (!process.env.AKAN_OPS_PUBLIC_KEY?.trim()) return;
605
190
  const { OpsRoute } = await import("./ops/opsRoute");
@@ -608,21 +193,13 @@ export class AkanApp {
608
193
  });
609
194
  }
610
195
 
611
- async #stopLogHub() {
612
- await this.#logControl?.stop();
613
- this.#logControl = null;
614
- this.#logStream = null;
615
- this.#logHub?.close();
616
- this.#logHub = null;
617
- }
618
-
619
196
  #listen() {
620
197
 
621
- if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#artifactDir);
198
+ if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
622
199
  this.#server = Bun.serve({
623
200
  idleTimeout: this.#limits.idleTimeout,
624
201
  maxRequestBodySize: this.#limits.uploadBodyBytes,
625
- port: this.#port,
202
+ port: this.#config.port,
626
203
  hostname: ServerLimits.listenHostname(),
627
204
  fetch: (req, server) =>
628
205
  ServerLimits.holdOpen(server, req, this.#limits.idleTimeout, () => this.#handleFetch(req, server)),
@@ -631,13 +208,14 @@ export class AkanApp {
631
208
  maxPayloadLength: 16 * 1024 * 1024,
632
209
  backpressureLimit: 1024 * 1024,
633
210
  closeOnBackpressureLimit: true,
634
- open: (ws) => this.#handleWsOpen(ws),
635
- message: (ws, message) => this.#handleWsMessage(ws, message),
636
- close: (ws, code, reason) => this.#handleWsClose(ws, code, reason),
211
+ open: (ws) => this.#ws.open(ws),
212
+ message: (ws, message) => this.#ws.message(ws, message),
213
+ close: (ws, code, reason) => this.#ws.close(ws, code, reason),
637
214
  data: {} as GatewayWsData,
638
215
  },
639
216
  });
640
- this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#port}`);
217
+ ListeningPort.record(this, this.#server.port);
218
+ this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#server.port}`);
641
219
  }
642
220
 
643
221
  async #handleFetch(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response | undefined> {
@@ -646,485 +224,26 @@ export class AkanApp {
646
224
  if (oversized) return oversized;
647
225
  const url = new URL(req.url);
648
226
  if (url.pathname === "/_akan/app/health")
649
- return this.#statusAccess.health(req, () => this.#getHealthStatus(), AkanApp.#clientOf(req, server));
227
+ return this.#statusAccess.health(req, () => this.#status.healthStatus(), AkanApp.#clientOf(req, server));
650
228
  if (url.pathname === "/_akan/app/ready")
651
- return this.#statusAccess.ready(req, () => this.#getReadyStatus(), AkanApp.#clientOf(req, server));
229
+ return this.#statusAccess.ready(req, () => this.#status.readyStatus(), AkanApp.#clientOf(req, server));
652
230
  if (url.pathname === "/_akan/app/metrics")
653
- return this.#statusAccess.metrics(req, () => this.#getMetricsStatus(), AkanApp.#clientOf(req, server));
654
- if (url.pathname === LogStreamRoute.path && this.#logStream)
655
- return this.#logStream.handle(req, AkanApp.#clientOf(req, server));
231
+ return this.#statusAccess.metrics(req, () => this.#status.metricsStatus(), AkanApp.#clientOf(req, server));
232
+ const logStream = this.#logging.stream;
233
+ if (url.pathname === LogStreamRoute.path && logStream) return logStream.handle(req, AkanApp.#clientOf(req, server));
656
234
  if (url.pathname === "/_akan/bench/ping") return new Response("ok");
657
235
  if (url.pathname === AppInfo.publicPath) return AppInfo.handlePublic();
658
236
  if (this.#ops?.matches(url.pathname)) return await this.#ops.handle(req, AkanApp.#clientOf(req, server));
659
- if (this.#isWebSocketPath(url.pathname)) return this.#upgradeWebSocket(req, server);
660
- const assetResponse = await this.#serveImmutableArtifact(req, url);
237
+ if (this.#config.isWebSocketPath(url.pathname)) return this.#ws.upgrade(req, server);
238
+ const assetResponse = await this.#proxy.serveImmutableArtifact(req, url);
661
239
  if (assetResponse) return assetResponse;
662
- return await this.#proxyHttp(req, server);
240
+ return await this.#proxy.proxyHttp(req, server);
663
241
  }
664
242
 
665
243
  static #clientOf(req: Request, server: Bun.Server<GatewayWsData>) {
666
244
  return TrustedProxy.clientAddress(req.headers, server.requestIP(req)?.address);
667
245
  }
668
246
 
669
- #isWebSocketPath(pathname: string) {
670
- return pathname === `${this.#prefix}${this.#websocketPrefix}` || pathname === "/_akan/hmr";
671
- }
672
-
673
- static readonly #immutableArtifacts = [
674
- { prefix: "/_akan/client/", root: "client", strip: "/_akan/client/".length, type: "application/javascript" },
675
- { prefix: "/_akan/styles/", root: "styles", strip: "/_akan/styles/".length, type: "text/css; charset=utf-8" },
676
- { prefix: "/_akan/fonts/", root: "fonts", strip: "/_akan/fonts/".length, type: "font/woff2", anyOrigin: true },
677
- { prefix: "/_akan/dict/", root: "dict", strip: "/_akan/dict/".length, type: "text/javascript; charset=utf-8" },
678
- ] as const;
679
-
680
- async #serveImmutableArtifact(req: Request, url: URL): Promise<Response | null> {
681
- if (!this.#web.ssr) return null;
682
- const artifact = AkanApp.#immutableArtifacts.find(({ prefix }) => url.pathname.startsWith(prefix));
683
- if (!artifact) return null;
684
- const filePath = resolveStaticPath(path.join(this.#artifactDir, artifact.root), url.pathname.slice(artifact.strip));
685
- if (!filePath) return new Response("Not Found", { status: 404 });
686
- const file = Bun.file(filePath);
687
- if (!(await file.exists())) return new Response("Not Found", { status: 404 });
688
- return this.#fileResponse(req, filePath, {
689
- contentType: file.type || artifact.type,
690
- cacheControl: "public, max-age=31536000, immutable",
691
- anyOrigin: "anyOrigin" in artifact,
692
- });
693
- }
694
-
695
- #upgradeWebSocket(req: Request, server: Bun.Server<GatewayWsData>): Response | undefined {
696
- const child = this.#pickFederationChild();
697
-
698
- const upstream = child?.upstream ? (child.wsUpstream ?? this.#getChildUpstream(child.idx, child.role).ws) : null;
699
- if (!child || !upstream) return new Response("No websocket upstream is ready", { status: 503 });
700
- const url = new URL(req.url);
701
-
702
- try {
703
- CrossSiteGuard.assertOrigin(req, url, url.pathname === "/_akan/hmr" ? "hmr" : "websocket");
704
- } catch {
705
- return new Response("Forbidden", { status: 403 });
706
- }
707
- if (!WsUpgrade.isRequested(req)) return WsUpgrade.required();
708
- const peer = server.requestIP(req) ?? undefined;
709
- const clientIp = TrustedProxy.clientAddress(req.headers, peer?.address);
710
- const refused = this.#refuseWebSocket(clientIp);
711
- if (refused) return refused;
712
- const upstreamWs = new WebSocket(`ws://${upstream.host}:${upstream.port}${url.pathname}${url.search}`, {
713
- headers: makeAkanChildProxyHeaders(req, child.idx, peer),
714
- } as unknown as string[]);
715
-
716
- const upgraded = server.upgrade(req, {
717
- data: { childIdx: child.idx, upstream: upstreamWs, clientIp, pending: [], pendingBytes: 0 },
718
- });
719
- if (!upgraded) {
720
- upstreamWs.close();
721
- return new Response("WebSocket upgrade failed", { status: 500 });
722
- }
723
- child.metrics.activeWebSockets = (child.metrics.activeWebSockets ?? 0) + 1;
724
- this.#wsOpen += 1;
725
- if (clientIp) this.#wsOpenByIp.set(clientIp, (this.#wsOpenByIp.get(clientIp) ?? 0) + 1);
726
- return undefined;
727
- }
728
-
729
- #refuseWebSocket(clientIp: string | null): Response | null {
730
- const headers = { "cache-control": "no-store" };
731
- if (this.#wsCaps.total && this.#wsOpen >= this.#wsCaps.total)
732
- return new Response("Too many open websockets", { status: 503, headers });
733
- if (this.#wsCaps.perIp && clientIp && (this.#wsOpenByIp.get(clientIp) ?? 0) >= this.#wsCaps.perIp)
734
- return new Response("Too many open websockets from this address", { status: 429, headers });
735
- return null;
736
- }
737
-
738
- static #positiveIntEnv(name: string): number | null {
739
- const value = Number(process.env[name]);
740
- return Number.isInteger(value) && value > 0 ? value : null;
741
- }
742
-
743
- #handleWsOpen(ws: Bun.ServerWebSocket<GatewayWsData>) {
744
- const upstream = ws.data.upstream;
745
- const openTimer =
746
- upstream.readyState === WebSocket.CONNECTING
747
- ? setTimeout(() => {
748
- if (upstream.readyState === WebSocket.OPEN) return;
749
- upstream.close();
750
- ws.close(1013, "upstream websocket did not open");
751
- }, AkanApp.#wsUpstreamOpenTimeoutMs)
752
- : null;
753
- upstream.addEventListener("open", () => {
754
- if (openTimer) clearTimeout(openTimer);
755
- for (const message of ws.data.pending.splice(0)) upstream.send(message);
756
- ws.data.pendingBytes = 0;
757
- });
758
- upstream.addEventListener("message", (event) => {
759
- const result = ws.send(event.data as string | ArrayBuffer);
760
- if (result === 0) upstream.close();
761
- });
762
- upstream.addEventListener("close", (event) => {
763
- if (openTimer) clearTimeout(openTimer);
764
- ws.close(relayableCloseCode(event.code), event.reason);
765
- });
766
- upstream.addEventListener("error", () => ws.close(1011, "upstream websocket error"));
767
- }
768
-
769
- #handleWsMessage(ws: Bun.ServerWebSocket<GatewayWsData>, message: string | ArrayBuffer | Uint8Array) {
770
- const upstream = ws.data.upstream;
771
- const payload =
772
- typeof message === "string"
773
- ? message
774
- : message instanceof ArrayBuffer
775
- ? message
776
- : new Uint8Array(message).slice().buffer;
777
- if (upstream.readyState === WebSocket.OPEN) {
778
- upstream.send(payload);
779
- return;
780
- }
781
- const size = typeof payload === "string" ? Buffer.byteLength(payload) : payload.byteLength;
782
- if (ws.data.pendingBytes + size > AkanApp.#wsPendingLimitBytes) {
783
- ws.data.pending.length = 0;
784
- ws.close(1009, "too much data before the upstream opened");
785
- return;
786
- }
787
- ws.data.pending.push(payload as string | ArrayBuffer);
788
- ws.data.pendingBytes += size;
789
- }
790
-
791
- #handleWsClose(ws: Bun.ServerWebSocket<GatewayWsData>, code: number, reason: string) {
792
- ws.data.upstream.close(relayableCloseCode(code), reason);
793
- const child = this.#children.get(ws.data.childIdx);
794
- if (child) child.metrics.activeWebSockets = Math.max(0, (child.metrics.activeWebSockets ?? 1) - 1);
795
- this.#wsOpen = Math.max(0, this.#wsOpen - 1);
796
- const { clientIp } = ws.data;
797
- const remaining = clientIp ? (this.#wsOpenByIp.get(clientIp) ?? 1) - 1 : 0;
798
- if (clientIp && remaining > 0) this.#wsOpenByIp.set(clientIp, remaining);
799
- else if (clientIp) this.#wsOpenByIp.delete(clientIp);
800
- }
801
-
802
- #getHealthStatus() {
803
- return {
804
- status: this.#stopping ? "stopping" : "running",
805
- pid: process.pid,
806
- children: [...this.#children.values()].map((child) => ({
807
- idx: child.idx,
808
- role: child.role,
809
- status: child.status,
810
- ready: child.ready,
811
- pid: child.pid,
812
- upstream: child.upstream,
813
- restartAttempts: child.restart.attempts,
814
- restartCount: child.restartCount,
815
- restartPending: child.restartPending,
816
- lastExitCode: child.lastExitCode,
817
- lastRestartAt: child.lastRestartAt,
818
- lastRestartReason: child.lastRestartReason,
819
- lastErrorMessage: child.lastErrorMessage,
820
- })),
821
- };
822
- }
823
-
824
- #getReadyStatus() {
825
- return {
826
- ready: this.#isReady(),
827
- pid: process.pid,
828
- children: [...this.#children.values()].map(({ idx, role, status, ready }) => ({ idx, role, status, ready })),
829
- };
830
- }
831
-
832
- #isReady() {
833
- if (this.#stopping) return false;
834
- if (this.#replica.federation + this.#replica.all > 0) return this.#federationCandidates().length > 0;
835
- return [...this.#children.values()].some((child) => child.ready && !this.#isChildUnavailable(child));
836
- }
837
-
838
- #getMetricsStatus() {
839
- return {
840
- rooms: this.#roomChildren.size,
841
- sockets: this.#socketRooms.size,
842
- gateway: this.#gatewayMetrics,
843
- proxyHop: this.#proxyHopCount
844
- ? {
845
- count: this.#proxyHopCount,
846
- meanMs: Math.round((this.#proxyHopSumMs / this.#proxyHopCount) * 1000) / 1000,
847
- maxMs: Math.round(this.#proxyHopMaxMs * 1000) / 1000,
848
- }
849
- : null,
850
- children: [...this.#children.values()].map((child) => ({
851
- idx: child.idx,
852
- role: child.role,
853
- metrics: child.metrics,
854
- rooms: this.#childRooms.get(child.idx)?.size ?? 0,
855
- restartAttempts: child.restart.attempts,
856
- restartCount: child.restartCount,
857
- restartPending: child.restartPending,
858
- lastExitCode: child.lastExitCode,
859
- lastRestartAt: child.lastRestartAt,
860
- lastRestartReason: child.lastRestartReason,
861
- })),
862
- };
863
- }
864
-
865
- async #proxyHttp(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response> {
866
- const child = await this.#pickReadyFederationChild(req);
867
- if (child?.upstream?.type !== "unix") return this.#respondWithUnavailable(req);
868
-
869
- const { socketPath } = child.upstream;
870
- const url = new URL(req.url);
871
- const upstreamUrl = `http://akan-child${url.pathname}${url.search}`;
872
- const headers = makeAkanChildProxyHeaders(req, child.idx, server.requestIP(req) ?? undefined);
873
- child.metrics.activeRequests = (child.metrics.activeRequests ?? 0) + 1;
874
- child.metrics.totalRequests = (child.metrics.totalRequests ?? 0) + 1;
875
- const traced = isTraceEnabled();
876
- const hopStart = traced ? performance.now() : 0;
877
- const chunkedLimit = req.headers.has("content-length") ? null : this.#limits.bodyLimitOf(req);
878
- try {
879
- const upstreamRes = await fetch(upstreamUrl, {
880
- unix: socketPath,
881
- method: req.method,
882
- headers,
883
- body:
884
- req.method === "GET" || req.method === "HEAD"
885
- ? undefined
886
- : chunkedLimit !== null && req.body
887
- ? ServerLimits.limitBody(req.body, chunkedLimit)
888
- : req.body,
889
- signal: req.signal,
890
- redirect: "manual",
891
- decompress: false,
892
- });
893
- return await this.#proxyResponse(req, upstreamRes);
894
- } catch (error) {
895
- if (ServerLimits.isPayloadTooLarge(error)) return ServerLimits.payloadTooLarge();
896
- if (AkanApp.#isUpstreamOpenFailure(error)) {
897
- this.logger.error(`Child ${child.idx}/${child.role} upstream is unreachable (${socketPath}); restarting`);
898
- this.#scheduleChildRestart(child, child.proc, "upstream-open-failed");
899
- return AkanApp.#unavailableResponse(req, "Federation child upstream is unreachable; restarting");
900
- }
901
- if (req.signal.aborted) return AkanApp.#clientClosedResponse();
902
- if (AkanApp.#isUpstreamMidFlightClose(error)) {
903
- this.logger.warn(
904
- `Child ${child.idx}/${child.role} closed the connection mid-request (${req.method} ${new URL(req.url).pathname})`,
905
- );
906
- return AkanApp.#badGatewayResponse(req);
907
- }
908
- throw error;
909
- } finally {
910
- child.metrics.activeRequests = Math.max(0, (child.metrics.activeRequests ?? 1) - 1);
911
- if (traced) this.#recordProxyHop(performance.now() - hopStart);
912
- }
913
- }
914
-
915
- static readonly #upstreamOpenFailureCodes = new Set(["FailedToOpenSocket", "ENOENT", "ECONNREFUSED", "ENOTSOCK"]);
916
-
917
- static #isUpstreamOpenFailure(error: unknown): boolean {
918
- if (!error || typeof error !== "object") return false;
919
- const candidate = error as { code?: unknown; message?: unknown };
920
- if (typeof candidate.code === "string" && AkanApp.#upstreamOpenFailureCodes.has(candidate.code)) return true;
921
- return String(candidate.message ?? "").includes("FailedToOpenSocket");
922
- }
923
-
924
- static #isUpstreamMidFlightClose(error: unknown): boolean {
925
- if (!error || typeof error !== "object") return false;
926
- const candidate = error as { code?: unknown; message?: unknown };
927
- if (candidate.code === "ECONNRESET" || candidate.code === "ConnectionClosed") return true;
928
- return String(candidate.message ?? "").includes("connection was closed");
929
- }
930
-
931
- static #clientClosedResponse(): Response {
932
- return new Response(null, { status: 499, headers: { "cache-control": "no-store" } });
933
- }
934
-
935
- static #badGatewayResponse(req: Request): Response {
936
- const detail = "The replica closed the connection before it finished answering.";
937
- if (req.headers.get("accept")?.includes("text/html")) {
938
- return new Response(
939
- AkanApp.#statusPageHtml({
940
- heading: "Backend dropped the connection",
941
- detail,
942
- note: "The replica is restarting — this page reloads itself as soon as it answers.",
943
- }),
944
- { status: 502, headers: AkanApp.#statusHeaders("text/html; charset=utf-8") },
945
- );
946
- }
947
- return new Response(detail, { status: 502, headers: AkanApp.#statusHeaders("text/plain; charset=utf-8") });
948
- }
949
-
950
- async #pickReadyFederationChild(req: Request): Promise<ChildState | null> {
951
- const ready = this.#pickFederationChild();
952
- if (ready?.upstream) return ready;
953
- const deadline = performance.now() + this.#upstreamWaitMs;
954
- while (performance.now() < deadline) {
955
- if (this.#stopping || req.signal.aborted || this.#getCrashLoopDetail()) return null;
956
- await Bun.sleep(50);
957
- const child = this.#pickFederationChild();
958
- if (child?.upstream) return child;
959
- }
960
- return null;
961
- }
962
-
963
- #getCrashLoopDetail(): string | null {
964
- if (!this.#devHosted) return null;
965
- const trafficChildren = [...this.#children.values()].filter((child) => child.role !== "batch");
966
- if (trafficChildren.length === 0) return null;
967
- if (!trafficChildren.every((child) => child.status === "crashed")) return null;
968
- return (
969
- trafficChildren.map((child) => child.lastErrorMessage ?? child.lastRestartReason).find(Boolean) ??
970
- "unknown boot error"
971
- );
972
- }
973
-
974
- #respondWithUnavailable(req: Request): Response {
975
- const crashDetail = this.#getCrashLoopDetail();
976
- const page = crashDetail
977
- ? {
978
- heading: "Backend failed to start",
979
- detail: crashDetail,
980
- text: `Backend failed to start after ${AkanApp.#devMaxChildBootFailures} boot attempts: ${crashDetail}`,
981
- note: `The dev server stopped retrying after ${AkanApp.#devMaxChildBootFailures} failed boots. Fix the error and save — this page reloads automatically.`,
982
- }
983
- : {
984
- heading: "Backend is starting",
985
- detail: "No healthy federation child is ready",
986
- text: "No healthy federation child is ready",
987
- note: "A replica is booting or restarting — this page reloads itself as soon as it answers.",
988
- };
989
- if (req.headers.get("accept")?.includes("text/html")) {
990
- return new Response(AkanApp.#statusPageHtml(page), {
991
- status: 503,
992
- headers: AkanApp.#statusHeaders("text/html; charset=utf-8"),
993
- });
994
- }
995
- return AkanApp.#unavailableResponse(req, page.text);
996
- }
997
-
998
- static #unavailableResponse(req: Request, detail: string): Response {
999
- const headers = { "cache-control": "no-store" };
1000
- if (!req.headers.get("accept")?.includes("application/json")) return new Response(detail, { status: 503, headers });
1001
- return Response.json(
1002
- { error: "base.error.serverUnavailable", statusCode: 503, data: { status: 503 }, details: detail },
1003
- { status: 503, headers },
1004
- );
1005
- }
1006
-
1007
- static #statusHeaders(contentType: string): Headers {
1008
- const headers = new Headers({ "content-type": contentType, "cache-control": "no-store" });
1009
- return applySecurityHeaders(headers, { html: contentType.startsWith("text/html") });
1010
- }
1011
-
1012
- static #statusPageHtml({ heading, detail, note }: { heading: string; detail: string; note: string }) {
1013
- return `<!doctype html>
1014
- <html>
1015
- <head>
1016
- <meta charset="utf-8" />
1017
- <title>${AkanApp.#escapeHtml(heading)}</title>
1018
- <style>
1019
- body { margin: 0; padding: 48px 24px; background: #111827; color: #e5e7eb; font-family: ui-sans-serif, system-ui, sans-serif; }
1020
- main { max-width: 720px; margin: 0 auto; }
1021
- h1 { font-size: 20px; color: #f87171; }
1022
- pre { padding: 16px; border-radius: 8px; background: #1f2937; color: #fca5a5; white-space: pre-wrap; word-break: break-word; }
1023
- p { color: #9ca3af; font-size: 14px; }
1024
- </style>
1025
- </head>
1026
- <body>
1027
- <main>
1028
- <h1>${AkanApp.#escapeHtml(heading)}</h1>
1029
- <pre>${AkanApp.#escapeHtml(detail)}</pre>
1030
- <p>${AkanApp.#escapeHtml(note)}</p>
1031
- </main>
1032
- <script>
1033
- const poll = async () => {
1034
- try {
1035
- const res = await fetch(location.href, { cache: "no-store" });
1036
- if (res.ok) { location.reload(); return; }
1037
- } catch {}
1038
- setTimeout(poll, 1000);
1039
- };
1040
- setTimeout(poll, 1000);
1041
- </script>
1042
- </body>
1043
- </html>`;
1044
- }
1045
-
1046
- static #escapeHtml(text: string) {
1047
- const replacements: Record<string, string> = {
1048
- "&": "&amp;",
1049
- "<": "&lt;",
1050
- ">": "&gt;",
1051
- '"': "&quot;",
1052
- "'": "&#39;",
1053
- };
1054
- return text.replace(/[&<>"']/g, (ch) => replacements[ch] ?? ch);
1055
- }
1056
-
1057
- #recordProxyHop(durationMs: number) {
1058
- this.#proxyHopCount += 1;
1059
- this.#proxyHopSumMs += durationMs;
1060
- this.#proxyHopMaxMs = Math.max(this.#proxyHopMaxMs, durationMs);
1061
- }
1062
-
1063
- async #proxyResponse(req: Request, upstreamRes: Response): Promise<Response> {
1064
- const headers = new Headers(upstreamRes.headers);
1065
- this.#rewriteInternalLocation(headers);
1066
- const proxied = new Response(upstreamRes.body, {
1067
- status: upstreamRes.status,
1068
- statusText: upstreamRes.statusText,
1069
- headers,
1070
- });
1071
-
1072
- return AkanApp.#isProxiedJson(headers)
1073
- ? await compressResponse(req, proxied)
1074
- : compressStreamResponse(req, proxied);
1075
- }
1076
-
1077
- static #isProxiedJson(headers: Headers): boolean {
1078
- return (headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() === "application/json";
1079
- }
1080
-
1081
- #rewriteInternalLocation(headers: Headers) {
1082
- const location = headers.get("location");
1083
- if (!location) return;
1084
- try {
1085
- const parsed = new URL(location);
1086
- if (parsed.hostname === AKAN_CHILD_HOST)
1087
- headers.set("location", `${parsed.pathname}${parsed.search}${parsed.hash}`);
1088
- } catch {
1089
- }
1090
- }
1091
-
1092
- async #fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
1093
- return await encodedFileResponse(req, filePath, options.contentType, assetHeaders(options));
1094
- }
1095
-
1096
- #federationCandidates() {
1097
- this.#federationChildCache ??= [...this.#children.values()].filter(
1098
- (child) =>
1099
- (child.role === "federation" || child.role === "all") &&
1100
- child.ready &&
1101
- child.status !== "unhealthy" &&
1102
- !this.#isChildUnavailable(child),
1103
- );
1104
- return this.#federationChildCache;
1105
- }
1106
-
1107
- #pickFederationChild() {
1108
- const candidates = this.#federationCandidates();
1109
- if (candidates.length === 0) return null;
1110
- const child = candidates[this.#rrIdx % candidates.length];
1111
- this.#rrIdx++;
1112
- return child;
1113
- }
1114
-
1115
- #getRole(idx: number): AkanChildRole {
1116
- if (idx < this.#replica.federation) return "federation";
1117
- if (idx < this.#replica.federation + this.#replica.batch) return "batch";
1118
- return "all";
1119
- }
1120
-
1121
- #getChildUpstream(idx: number, role: AkanChildRole): GatewayUpstream {
1122
- return {
1123
- http: { type: "unix", socketPath: path.join(this.#runtimeDir, `akan-child-${this.#socketRunId}-${idx}.sock`) },
1124
- ws: role === "batch" ? undefined : { type: "tcp", host: "127.0.0.1", port: this.#wsBasePort + idx },
1125
- };
1126
- }
1127
-
1128
247
  #handleMessage(
1129
248
  idx: number,
1130
249
  message: AkanIpcMessage | BuilderMessage,
@@ -1135,49 +254,49 @@ export class AkanApp {
1135
254
  if (!message || typeof message !== "object") return;
1136
255
  switch (message.type) {
1137
256
  case "ready":
1138
- this.#markReady(idx, message);
257
+ this.#supervisor.markReady(idx, message);
1139
258
  return;
1140
259
  case "pubsub.publish":
1141
- this.#deliverPubsub(idx, message);
260
+ this.#rooms.deliverPubsub(idx, message);
1142
261
  return;
1143
262
  case "pubsub.subscribe":
1144
- this.#addRoomMembership(idx, message.roomId, message.socketId);
263
+ this.#rooms.subscribe(idx, message);
1145
264
  return;
1146
265
  case "pubsub.unsubscribe":
1147
- this.#removeRoomMembership(idx, message.roomId, message.socketId);
266
+ this.#rooms.removeRoomMembership(idx, message.roomId, message.socketId);
1148
267
  return;
1149
268
  case "pubsub.snapshot":
1150
- this.#replaceRoomSnapshot(idx, message.rooms);
1151
- if (message.liveModels) this.#setLiveModels(idx, message.liveModels);
269
+ this.#rooms.replaceRoomSnapshot(idx, message.rooms);
270
+ if (message.liveModels) this.#rooms.setLiveModels(idx, message.liveModels);
1152
271
  return;
1153
272
  case "live.change":
1154
- this.#fanoutLiveChange(idx, message);
273
+ this.#rooms.fanoutLiveChange(idx, message);
1155
274
  return;
1156
275
  case "live.models":
1157
- this.#setLiveModels(idx, message.models);
276
+ this.#rooms.setLiveModels(idx, message.models);
1158
277
  return;
1159
278
  case "metrics.report":
1160
- this.#updateMetrics(idx, message.metrics);
279
+ this.#children.updateMetrics(idx, message.metrics);
1161
280
  return;
1162
281
  case "log.records":
1163
- this.#logHub?.ingestMany(message.records);
282
+ this.#logging.hub?.ingestMany(message.records);
1164
283
  if (message.dropped) this.logger.warn(`Child ${idx} dropped ${message.dropped} log records (ipc backpressure)`);
1165
284
  return;
1166
285
  case "health.pong":
1167
- this.#markHealthy(idx);
286
+ this.#supervisor.markHealthy(idx, message);
1168
287
  return;
1169
288
  case "queue.enqueued":
1170
- this.#fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
289
+ this.#children.fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
1171
290
  return;
1172
291
  case "error":
1173
292
  this.logger.error(message.message);
1174
293
  if (child) child.lastErrorMessage = message.message;
1175
- if (child && proc) void this.#scheduleChildRestart(child, proc, "child-error");
294
+ if (child && proc) void this.#supervisor.scheduleRestart(child, proc, "child-error");
1176
295
  return;
1177
296
  case "build-route":
1178
297
  case "build-csr":
1179
298
  case "build-graph":
1180
- this.#forwardBuilderReq(idx, message);
299
+ if (child) this.#host.forwardBuilderReq(child, message);
1181
300
  return;
1182
301
  }
1183
302
  }
@@ -1192,294 +311,13 @@ export class AkanApp {
1192
311
  case "csr-updated":
1193
312
  case "ssr-updated":
1194
313
  case "build-status":
1195
- this.#fanoutToFederation(message);
314
+ this.#children.fanoutToFederation(message);
1196
315
  return;
1197
316
  case "build-route-res":
1198
317
  case "build-csr-res":
1199
318
  case "build-graph-res":
1200
- this.#forwardBuilderRes(message);
319
+ this.#host.forwardBuilderRes(message);
1201
320
  return;
1202
321
  }
1203
322
  }
1204
-
1205
- #markReady(idx: number, message: Extract<AkanIpcMessage, { type: "ready" }>) {
1206
- const child = this.#children.get(idx);
1207
- if (!child) return;
1208
- child.ready = true;
1209
- child.status = "ready";
1210
- child.pid = message.pid;
1211
- child.upstream = message.upstream;
1212
- child.wsUpstream = message.wsUpstream;
1213
- child.healthPath = message.healthPath;
1214
- if (message.crossSite) CrossSiteGuard.configure(message.crossSite);
1215
- child.lastPongAtMono = performance.now();
1216
- child.restart.reset();
1217
-
1218
- if (this.#logHub && this.#logHub.floor !== null)
1219
- this.#sendToChild(child, { type: "log.level", minSev: this.#logHub.floor });
1220
- child.restartPending = false;
1221
- child.lastErrorMessage = undefined;
1222
- this.#federationChildCache = null;
1223
-
1224
- const trafficChildren = [...this.#children.values()].filter((item) => item.role !== "batch");
1225
-
1226
- if (!this.#stopping && child.role !== "batch" && trafficChildren.every((item) => item.ready)) {
1227
- process.send?.({ type: "backend-ready", pid: process.pid } satisfies BuilderMessage);
1228
- }
1229
- if ([...this.#children.values()].every((item) => item.ready)) {
1230
- this.logger.verbose(`All ${this.#children.size} child process(es) are ready`);
1231
- }
1232
- }
1233
-
1234
- #markHealthy(idx: number) {
1235
- const child = this.#children.get(idx);
1236
- if (!child) return;
1237
- child.status = "healthy";
1238
- child.lastPongAtMono = performance.now();
1239
- this.#federationChildCache = null;
1240
- }
1241
-
1242
- #deliverPubsub(originIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.publish" }>) {
1243
- const targets = this.#roomChildren.get(message.roomId);
1244
- if (!targets?.size) {
1245
- const child = this.#children.get(originIdx);
1246
- if (child) child.metrics.pubsubDropCount = (child.metrics.pubsubDropCount ?? 0) + 1;
1247
- this.logger.verbose(`Dropping pubsub ${message.roomId}; no subscribers`);
1248
- return;
1249
- }
1250
- for (const childIdx of targets) {
1251
- if (childIdx === originIdx) continue;
1252
- const child = this.#children.get(childIdx);
1253
- if (!child || this.#isChildUnavailable(child)) continue;
1254
- if (
1255
- !this.#sendToChild(child, {
1256
- type: "pubsub.deliver",
1257
- roomId: message.roomId,
1258
- data: message.data,
1259
- origin: message.origin,
1260
- } satisfies AkanIpcMessage)
1261
- )
1262
- continue;
1263
- child.metrics.pubsubDeliverCount = (child.metrics.pubsubDeliverCount ?? 0) + 1;
1264
- }
1265
- }
1266
-
1267
- #addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
1268
- const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
1269
- roomChildren.add(childIdx);
1270
- this.#roomChildren.set(roomId, roomChildren);
1271
-
1272
- const childRooms = this.#childRooms.get(childIdx) ?? new Map<string, Set<string>>();
1273
- const roomSockets = childRooms.get(roomId) ?? new Set<string>();
1274
- childRooms.set(roomId, roomSockets);
1275
- this.#childRooms.set(childIdx, childRooms);
1276
-
1277
- if (socketId) {
1278
- roomSockets.add(socketId);
1279
- const socketRooms = this.#socketRooms.get(socketId) ?? { childIdx, rooms: new Set<string>() };
1280
- socketRooms.rooms.add(roomId);
1281
- this.#socketRooms.set(socketId, socketRooms);
1282
- }
1283
- }
1284
-
1285
- #leaveRoom(childIdx: number, roomId: string) {
1286
- const roomChildren = this.#roomChildren.get(roomId);
1287
- roomChildren?.delete(childIdx);
1288
- if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
1289
- }
1290
-
1291
- #removeRoomMembership(childIdx: number, roomId: string, socketId?: string) {
1292
- const childRooms = this.#childRooms.get(childIdx);
1293
- const roomSockets = childRooms?.get(roomId);
1294
- if (socketId) {
1295
- this.#forgetSocketRoom(socketId, roomId);
1296
- roomSockets?.delete(socketId);
1297
- if (roomSockets?.size) return;
1298
- }
1299
-
1300
- for (const staleSocketId of roomSockets ?? []) this.#forgetSocketRoom(staleSocketId, roomId);
1301
- this.#leaveRoom(childIdx, roomId);
1302
- childRooms?.delete(roomId);
1303
- if (childRooms?.size === 0) this.#childRooms.delete(childIdx);
1304
- }
1305
-
1306
- #forgetSocketRoom(socketId: string, roomId: string) {
1307
- const socketRooms = this.#socketRooms.get(socketId);
1308
- socketRooms?.rooms.delete(roomId);
1309
- if (!socketRooms || socketRooms.rooms.size === 0) this.#socketRooms.delete(socketId);
1310
- }
1311
-
1312
- #replaceRoomSnapshot(childIdx: number, rooms: string[]) {
1313
- const held = new Set(rooms);
1314
- for (const roomId of [...(this.#childRooms.get(childIdx)?.keys() ?? [])])
1315
- if (!held.has(roomId)) this.#removeRoomMembership(childIdx, roomId);
1316
- for (const roomId of held) this.#addRoomMembership(childIdx, roomId);
1317
- }
1318
-
1319
- #removeChildRooms(childIdx: number) {
1320
- for (const roomId of this.#childRooms.get(childIdx)?.keys() ?? []) this.#leaveRoom(childIdx, roomId);
1321
- this.#childRooms.delete(childIdx);
1322
- for (const [socketId, socket] of this.#socketRooms.entries()) {
1323
- if (socket.childIdx === childIdx) this.#socketRooms.delete(socketId);
1324
- }
1325
- this.#setLiveModels(childIdx, []);
1326
- }
1327
-
1328
- #setLiveModels(childIdx: number, models: string[]) {
1329
- if (models.length) this.#childLiveModels.set(childIdx, new Set(models));
1330
- else this.#childLiveModels.delete(childIdx);
1331
- }
1332
-
1333
- #updateMetrics(childIdx: number, metrics: AkanMetricsReport) {
1334
- const child = this.#children.get(childIdx);
1335
- if (!child) return;
1336
- child.metrics = { ...child.metrics, pid: metrics.pid ?? child.pid, ...metrics };
1337
- }
1338
-
1339
- async #reportMetrics() {
1340
- this.#gatewayMetrics = await ProcessMetricsCollector.collect({ role: "gateway" });
1341
- if (process.env.AKAN_MEMORY_LOG !== "1") return;
1342
- this.logger.verbose(
1343
- `memory role=gateway ${ProcessMetricsCollector.format(this.#gatewayMetrics)} children=${this.#children.size}`,
1344
- );
1345
- for (const child of this.#children.values()) {
1346
- if (!child.metrics.rssBytes) continue;
1347
- const rooms = this.#childRooms.get(child.idx)?.size ?? 0;
1348
- this.logger.verbose(
1349
- `memory role=${child.role} idx=${child.idx} ${ProcessMetricsCollector.format({
1350
- ...child.metrics,
1351
- pid: child.metrics.pid ?? child.pid,
1352
- })} activeRequests=${child.metrics.activeRequests ?? 0} activeWebSockets=${
1353
- child.metrics.activeWebSockets ?? 0
1354
- } rooms=${rooms} rscPending=${child.metrics.rscPendingRenderCount ?? 0} rscModules=${
1355
- child.metrics.rscLoadedRouteModuleCount ?? 0
1356
- }`,
1357
- );
1358
- }
1359
- }
1360
-
1361
- #requestRoomSnapshots() {
1362
- for (const child of this.#children.values()) {
1363
- if (this.#isChildUnavailable(child)) continue;
1364
- this.#sendToChild(child, { type: "pubsub.snapshot.request" } satisfies AkanIpcMessage);
1365
- }
1366
- }
1367
-
1368
- #checkHealth() {
1369
- const nowMono = performance.now();
1370
- for (const child of this.#children.values()) {
1371
- if (this.#isChildUnavailable(child)) continue;
1372
- if (child.lastPongAtMono && nowMono - child.lastPongAtMono > this.#healthTimeoutMs) {
1373
- child.status = "unhealthy";
1374
- this.#federationChildCache = null;
1375
- void this.#scheduleChildRestart(child, child.proc, "health-timeout");
1376
- continue;
1377
- }
1378
- const sent = this.#sendToChild(child, {
1379
- type: "health.ping",
1380
- nonce: crypto.randomUUID(),
1381
- sentAt: Date.now(),
1382
- } satisfies AkanIpcMessage);
1383
- if (!sent) {
1384
- child.status = "unhealthy";
1385
- this.#federationChildCache = null;
1386
- void this.#scheduleChildRestart(child, child.proc, "health-send-failed");
1387
- }
1388
- }
1389
- }
1390
-
1391
- #forwardBuilderReq(childIdx: number, message: BuilderRequest) {
1392
- const gatewayReqId = this.#nextBuilderReqId++;
1393
- this.#builderReqMap.set(gatewayReqId, { childIdx, childLocalId: message.id });
1394
- process.send?.({ ...message, id: gatewayReqId } satisfies BuilderRequest);
1395
- }
1396
-
1397
- #forwardBuilderRes(message: BuilderResponse) {
1398
- const request = this.#builderReqMap.get(message.id);
1399
- if (!request) {
1400
- this.logger.warn(`No child found for ${message.type} id=${message.id}`);
1401
- return;
1402
- }
1403
- this.#builderReqMap.delete(message.id);
1404
- const child = this.#children.get(request.childIdx);
1405
- if (!child || child.proc.killed) return;
1406
- this.#sendToChild(child, { ...message, id: request.childLocalId } satisfies BuilderResponse);
1407
- }
1408
-
1409
- #fanoutToFederation(message: AkanIpcMessage | BuilderMessage, exceptIdx?: number) {
1410
- for (const child of this.#children.values()) {
1411
- if (child.idx === exceptIdx) continue;
1412
- if (child.role === "federation" || child.role === "all") this.#sendToChild(child, message);
1413
- }
1414
- }
1415
-
1416
- #fanoutToAll(message: AkanIpcMessage) {
1417
- for (const child of this.#children.values()) this.#sendToChild(child, message);
1418
- }
1419
-
1420
- #fanoutLiveChange(originIdx: number, message: Extract<AkanIpcMessage, { type: "live.change" }>) {
1421
- for (const [childIdx, models] of this.#childLiveModels) {
1422
- const child = this.#children.get(childIdx);
1423
- if (child && childIdx !== originIdx && models.has(message.change.refName)) this.#sendToChild(child, message);
1424
- }
1425
- }
1426
-
1427
- #fanoutToBatch(message: AkanIpcMessage) {
1428
- for (const child of this.#children.values()) {
1429
- if (child.role === "batch" || child.role === "all") {
1430
- if (this.#sendToChild(child, message) && message.type === "queue.wake") {
1431
- child.metrics.queueWakeCount = (child.metrics.queueWakeCount ?? 0) + 1;
1432
- }
1433
- }
1434
- }
1435
- }
1436
-
1437
- #sendToChild(child: ChildState, message: AkanIpcMessage | BuilderMessage): boolean {
1438
- if (this.#isChildUnavailable(child)) return false;
1439
- try {
1440
- child.proc.send(message);
1441
- return true;
1442
- } catch (error) {
1443
- this.logger.warn(
1444
- `Failed to send ${message.type} to child ${child.idx}/${child.role}: ${
1445
- error instanceof Error ? error.message : String(error)
1446
- }`,
1447
- );
1448
- return false;
1449
- }
1450
- }
1451
-
1452
- #writeChildLine(idx: number, role: AkanChildRole, pid: number | null, type: "stdout" | "stderr", line: string) {
1453
- if (Logger.isNdjson) {
1454
- this.#logHub?.ingest(ChildOutputReader.toRecord({ type, text: line, name: "child", role, replicaIdx: idx, pid }));
1455
- return;
1456
- }
1457
- const prefixedLine = `[child:${idx} ${role}] [${type}] ${line}`;
1458
- if (type === "stdout" || this.#printChildStderr || !this.#logWriter) process[type].write(prefixedLine);
1459
- this.#logWriter?.write(`${idx}-${role}`, AkanApp.#stripAnsi(prefixedLine));
1460
- }
1461
-
1462
- #writeChildStderrBlock(idx: number, role: AkanChildRole, pid: number | null, lines: string[]) {
1463
- const text = lines.join("");
1464
- if (AkanApp.#isBenignRsdwConnectionClosedBlock(text)) return;
1465
- if (Logger.isNdjson) {
1466
- this.#logHub?.ingest(
1467
- ChildOutputReader.toRecord({ type: "stderr", text, name: "child", role, replicaIdx: idx, pid }),
1468
- );
1469
- return;
1470
- }
1471
- for (const line of lines) this.#writeChildLine(idx, role, pid, "stderr", line);
1472
- }
1473
-
1474
- static #isBenignRsdwConnectionClosedBlock(text: string): boolean {
1475
- return (
1476
- text.includes('reportGlobalError(weakResponse, Error("Connection closed."))') &&
1477
- text.includes("error: Connection closed.") &&
1478
- text.includes("react-server-dom-webpack")
1479
- );
1480
- }
1481
-
1482
- static #stripAnsi(msg: string) {
1483
- return msg.replace(AkanApp.#ansiPattern, "");
1484
- }
1485
323
  }