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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (667) hide show
  1. package/ARCHITECTURE.md +42 -41
  2. package/CHANGELOG.md +593 -3
  3. package/CONTRIBUTING.md +26 -0
  4. package/base/base.ts +2 -1
  5. package/client/clientRuntime.ts +1 -0
  6. package/client/cn.ts +2 -2
  7. package/client/csrTypes.ts +15 -1
  8. package/client/frameConfig.ts +5 -2
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +33 -82
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/RouteDefinition.ts +24 -7
  14. package/client/route/RouteGuards.ts +2 -1
  15. package/client/route/RouteHead.ts +11 -2
  16. package/client/route/routeArgs.ts +7 -0
  17. package/client/router.ts +25 -6
  18. package/client/rscNavigation.ts +3 -3
  19. package/client/rscRoutePatch.ts +42 -0
  20. package/client/viewportMeta.ts +34 -4
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/PipelinePlanSchema.ts +2 -2
  23. package/common/akanGraph.ts +1 -1
  24. package/common/err.ts +122 -0
  25. package/common/facetBarrel.ts +38 -0
  26. package/common/failureCode.ts +18 -0
  27. package/common/index.ts +9 -0
  28. package/common/isGuardRefusal.ts +14 -0
  29. package/common/mcpExposure.ts +17 -4
  30. package/common/mcpFailure.ts +9 -0
  31. package/common/pipelinePlan.ts +1 -1
  32. package/common/restartSchedule.ts +55 -0
  33. package/common/routeConvention.ts +3 -1
  34. package/common/types.ts +18 -1
  35. package/constant/constantRegistry.ts +4 -8
  36. package/constant/crystalize.ts +1 -2
  37. package/constant/getDefault.ts +1 -1
  38. package/constant/immerify.ts +1 -1
  39. package/constant/index.ts +78 -21
  40. package/constant/purify.ts +4 -9
  41. package/constant/serialize.ts +4 -2
  42. package/constant/types.ts +1 -0
  43. package/constant/via.ts +1 -2
  44. package/dictionary/agent.dictionary.ts +4 -0
  45. package/dictionary/base.dictionary.ts +1 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/databaseRegistry.ts +2 -1
  49. package/document/documentSchema.ts +1 -0
  50. package/document/filterMeta.ts +4 -1
  51. package/document/into.ts +2 -1
  52. package/document/loaderInfo.ts +2 -1
  53. package/document/noDocumentError.ts +4 -1
  54. package/document/queryEvaluator.ts +1 -1
  55. package/document/types.ts +1 -1
  56. package/fetch/client/fetchClient.ts +87 -270
  57. package/fetch/client/fetchClientTypes.ts +49 -0
  58. package/fetch/client/fetchHandle.ts +11 -1
  59. package/fetch/client/httpClient.ts +14 -2
  60. package/fetch/client/inflightQueries.ts +17 -0
  61. package/fetch/client/remoteError.ts +4 -20
  62. package/fetch/client/requestScope.ts +32 -0
  63. package/fetch/client/signalCatalog.ts +131 -0
  64. package/fetch/client/wsClient.ts +11 -0
  65. package/fetch/index.ts +1 -0
  66. package/fetch/staleReads.ts +27 -0
  67. package/fetch/streamedRead.ts +23 -0
  68. package/package.json +1 -1
  69. package/server/agentHooks.ts +16 -0
  70. package/server/akanApp.ts +107 -1272
  71. package/server/akanOption.ts +17 -4
  72. package/server/akanServer.ts +167 -675
  73. package/server/artifact/builderRpc.ts +33 -10
  74. package/server/artifact/ipcTypes.ts +9 -3
  75. package/server/artifact/routeSeedIndexStore.ts +4 -2
  76. package/server/assetHeaders.ts +6 -0
  77. package/server/console.ts +6 -4
  78. package/server/decorators.ts +2 -2
  79. package/server/devtools/README.md +4 -3
  80. package/server/devtools/devtoolsRouter.ts +9 -5
  81. package/server/devtools/studio/studioRoute.ts +18 -11
  82. package/server/di/diLifecycle.ts +24 -35
  83. package/server/di/predefinedAdaptor.ts +24 -1
  84. package/server/di/resolveHierarchy.ts +19 -6
  85. package/server/di/utils.ts +7 -3
  86. package/server/ed25519Key.ts +31 -15
  87. package/server/flightRowReader.ts +95 -18
  88. package/server/gateway/childSupervisor.ts +326 -0
  89. package/server/gateway/devHostChannel.ts +47 -0
  90. package/server/gateway/gatewayChildren.ts +135 -0
  91. package/server/gateway/gatewayConfig.ts +182 -0
  92. package/server/gateway/gatewayHttpProxy.ts +231 -0
  93. package/server/gateway/gatewayLogging.ts +111 -0
  94. package/server/gateway/gatewayRooms.ts +141 -0
  95. package/server/gateway/gatewayStatus.ts +116 -0
  96. package/server/gateway/gatewayStatusPage.ts +54 -0
  97. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  98. package/server/head.tsx +4 -19
  99. package/server/hmr/devHmrController.ts +10 -1
  100. package/server/htmlResultCache.ts +234 -0
  101. package/server/imageOptimizer.ts +4 -1
  102. package/server/index.ts +257 -17
  103. package/server/lifecycle/parentChannel.ts +78 -0
  104. package/server/lifecycle/shutdownManager.ts +6 -3
  105. package/server/lifecycle/startGuard.ts +90 -0
  106. package/server/logging/logControlSocket.ts +42 -3
  107. package/server/logging/serverLogging.ts +74 -0
  108. package/server/machine/machineToken.ts +10 -3
  109. package/server/mcp/AgentTools.ts +149 -0
  110. package/server/mcp/AgentToolsAccount.ts +26 -0
  111. package/server/mcp/McpDispatcher.ts +48 -19
  112. package/server/mcp/McpPages.ts +21 -6
  113. package/server/mcp/McpRateLimiter.ts +14 -0
  114. package/server/mcp/McpRouter.ts +52 -23
  115. package/server/mcp/McpUiSession.ts +2 -1
  116. package/server/mcp/index.ts +1 -0
  117. package/server/nativeFile.ts +30 -11
  118. package/server/nativeSecret.ts +12 -3
  119. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  120. package/server/ops/opsRoute.ts +5 -1
  121. package/server/ops/opsToken.ts +3 -1
  122. package/server/resolver/CascadeRunner.ts +10 -4
  123. package/server/resolver/database.resolver.ts +10 -417
  124. package/server/resolver/databaseModelInstance.ts +200 -0
  125. package/server/resolver/invalidSignal.ts +7 -0
  126. package/server/resolver/livePause.ts +34 -0
  127. package/server/resolver/modelFacade.ts +136 -0
  128. package/server/resolver/modelLoaders.ts +52 -0
  129. package/server/resolver/modelSchema.ts +52 -0
  130. package/server/resolver/signal.resolver.ts +92 -116
  131. package/server/resolver/timedQuery.ts +16 -0
  132. package/server/resolver/websocketOf.ts +23 -0
  133. package/server/routeElementComposer.tsx +131 -9
  134. package/server/routeState.ts +5 -1
  135. package/server/routeTreeBuilder.ts +22 -9
  136. package/server/routing/apiRouter.ts +44 -25
  137. package/server/routing/builtinRoutes.ts +194 -0
  138. package/server/routing/localRooms.ts +34 -0
  139. package/server/routing/roomReplay.ts +2 -2
  140. package/server/routing/serverLimits.ts +4 -1
  141. package/server/routing/serverListener.ts +194 -0
  142. package/server/rscClient.tsx +210 -227
  143. package/server/rscClientCache.ts +165 -0
  144. package/server/rscClientChunks.ts +209 -0
  145. package/server/rscClientFetch.ts +15 -3
  146. package/server/rscClientPatch.ts +78 -15
  147. package/server/rscDocumentHead.tsx +170 -0
  148. package/server/rscFlightRenderer.ts +83 -0
  149. package/server/rscFlightStream.ts +257 -0
  150. package/server/rscHeadPatch.ts +17 -56
  151. package/server/rscHostReloads.ts +238 -0
  152. package/server/rscHostRenderStream.ts +297 -0
  153. package/server/rscHostRequests.ts +158 -0
  154. package/server/rscHttp.ts +18 -6
  155. package/server/rscInlineStream.ts +34 -0
  156. package/server/rscNavigationState.ts +21 -1
  157. package/server/rscPagePrompts.ts +11 -5
  158. package/server/rscParkedRedirect.ts +23 -0
  159. package/server/rscPatchPlanner.ts +220 -0
  160. package/server/rscPrefetchCache.ts +68 -32
  161. package/server/rscRenderControl.ts +33 -0
  162. package/server/rscRenderFallbacks.ts +297 -0
  163. package/server/rscRenderHandler.ts +439 -0
  164. package/server/rscRenderStats.ts +49 -0
  165. package/server/rscResponse.ts +78 -0
  166. package/server/rscResultCaches.ts +74 -0
  167. package/server/rscRouteDocument.tsx +299 -0
  168. package/server/rscSegmentOutlet.tsx +24 -5
  169. package/server/rscSegmentOutletReference.ts +14 -12
  170. package/server/rscWorker.tsx +86 -1392
  171. package/server/rscWorkerCache.ts +56 -0
  172. package/server/rscWorkerHost.ts +145 -811
  173. package/server/rscWorkerProcess.ts +155 -0
  174. package/server/rscWorkerRecycler.ts +128 -0
  175. package/server/serverConfig.ts +128 -0
  176. package/server/serverMetrics.ts +52 -0
  177. package/server/sitemap.ts +1 -0
  178. package/server/ssrFromRscRenderer.tsx +20 -20
  179. package/server/ssrTypes.ts +9 -0
  180. package/server/webArtifact.ts +86 -0
  181. package/server/webAssetRoutes.ts +84 -0
  182. package/server/webCsrSurface.ts +172 -0
  183. package/server/webDocumentRoute.ts +180 -0
  184. package/server/webRouteContext.ts +232 -0
  185. package/server/webRouter.ts +126 -1242
  186. package/server/webRscRoute.ts +155 -0
  187. package/server/webSiteFiles.ts +139 -0
  188. package/server/wellKnownRoutes.ts +73 -0
  189. package/service/agent.service.ts +59 -5
  190. package/service/agentAccounts.ts +19 -0
  191. package/service/agentLoop/agentLoop.ts +387 -0
  192. package/service/agentLoop/agentLoopTypes.ts +112 -0
  193. package/service/agentLoop/deltaStream.ts +40 -0
  194. package/service/agentLoop/loopCompaction.ts +135 -0
  195. package/service/agentLoop/loopRequest.ts +62 -0
  196. package/service/agentLoop/loopToolOutput.ts +54 -0
  197. package/service/agentLoop/loopToolkits.ts +107 -0
  198. package/service/agentLoop/loopTranscript.ts +102 -0
  199. package/{signal → service}/agentMeter.ts +83 -15
  200. package/{signal → service}/agentRelayPolicy.ts +30 -7
  201. package/service/documentStoreError.ts +16 -0
  202. package/service/index.ts +7 -0
  203. package/service/injectError.ts +5 -0
  204. package/service/injectInfo.ts +30 -18
  205. package/service/insightQueryError.ts +19 -0
  206. package/service/ipcTypes.ts +3 -1
  207. package/service/liveSyncHub.ts +5 -2
  208. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  209. package/service/predefinedAdaptor/anthropicLlm.ts +52 -21
  210. package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
  211. package/service/predefinedAdaptor/compress.adaptor.ts +7 -3
  212. package/service/predefinedAdaptor/database.adaptor.ts +3 -1
  213. package/service/predefinedAdaptor/documentTransfer.ts +2 -1
  214. package/service/predefinedAdaptor/index.ts +2 -0
  215. package/service/predefinedAdaptor/insightQuery.ts +35 -11
  216. package/service/predefinedAdaptor/llm.adaptor.ts +22 -2
  217. package/service/predefinedAdaptor/llmSpend.ts +80 -0
  218. package/service/predefinedAdaptor/openaiDialect.ts +52 -17
  219. package/service/predefinedAdaptor/openaiLlm.ts +17 -9
  220. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  221. package/service/predefinedAdaptor/searchIndex.ts +5 -1
  222. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  223. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  224. package/service/predefinedAdaptor/solidSqlite.ts +3 -2
  225. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  226. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  227. package/service/predefinedAdaptor/sql/DocumentWriter.ts +292 -0
  228. package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
  229. package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
  230. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  231. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  232. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
  233. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +83 -1124
  234. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +319 -0
  235. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
  238. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
  239. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  240. package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
  241. package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
  242. package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
  243. package/service/predefinedAdaptor/sql/values.ts +8 -4
  244. package/service/predefinedAdaptor/sseData.ts +14 -0
  245. package/service/predefinedAdaptor/storage.adaptor.ts +9 -4
  246. package/service/predefinedAdaptor/websocket.adaptor.ts +199 -43
  247. package/service/serve.ts +3 -2
  248. package/service/serviceModule.ts +2 -2
  249. package/service/serviceRegistry.ts +1 -0
  250. package/signal/SignalFailure.ts +30 -1
  251. package/signal/agent.signal.ts +30 -9
  252. package/signal/agentTurnStream.ts +12 -8
  253. package/signal/byIdRead.ts +18 -0
  254. package/signal/carriedClientIps.ts +1 -0
  255. package/signal/endpointErrorContract.ts +20 -2
  256. package/signal/endpointInfo.ts +6 -5
  257. package/signal/exception.ts +1 -0
  258. package/signal/index.ts +314 -30
  259. package/signal/internalInfo.ts +6 -4
  260. package/signal/mcp/McpDocument.ts +8 -1
  261. package/signal/mcp/Msg.ts +23 -10
  262. package/signal/mcp/index.ts +1 -0
  263. package/signal/mcp/promptError.ts +9 -0
  264. package/signal/middleware.ts +12 -3
  265. package/signal/openapi/openapi.ts +10 -1
  266. package/signal/resolveFieldContext.ts +34 -0
  267. package/signal/serializer/fetch.serializer.ts +23 -15
  268. package/signal/signalContext.ts +24 -57
  269. package/signal/signalContractError.ts +10 -0
  270. package/signal/signalDeclarationError.ts +13 -0
  271. package/signal/signalRegistry.ts +3 -1
  272. package/signal/slice.ts +24 -20
  273. package/signal/sliceInfo.ts +12 -9
  274. package/signal/trace.ts +3 -0
  275. package/signal/types.ts +35 -6
  276. package/store/action.ts +44 -1086
  277. package/store/actionErrorKey.ts +9 -0
  278. package/store/actionOption.ts +22 -0
  279. package/store/baseSt.ts +1 -0
  280. package/store/draftFlush.ts +5 -0
  281. package/store/draftStore.ts +2 -0
  282. package/store/formDrafts.ts +115 -0
  283. package/store/formFieldSetters.ts +229 -0
  284. package/store/index.ts +125 -17
  285. package/store/modelActionContext.ts +65 -0
  286. package/store/modelListPatch.ts +53 -0
  287. package/store/modelOpenActions.ts +158 -0
  288. package/store/modelWriteActions.ts +240 -0
  289. package/store/modelWriteGuard.ts +82 -0
  290. package/store/openSeq.ts +34 -0
  291. package/store/rootStore.ts +2 -0
  292. package/store/sliceListActions.ts +370 -0
  293. package/store/sliceLiveActions.ts +130 -0
  294. package/store/stateBuilder.ts +2 -0
  295. package/store/storeInstance.ts +9 -10
  296. package/store/uploadPoll.ts +52 -0
  297. package/store/withSelector.ts +6 -4
  298. package/types/base/base.d.ts +2 -1
  299. package/types/client/clientRuntime.d.ts +1 -0
  300. package/types/client/cn.d.ts +2 -2
  301. package/types/client/csrTypes.d.ts +15 -1
  302. package/types/client/frameConfig.d.ts +1 -0
  303. package/types/client/index.d.ts +25 -26
  304. package/types/client/locale.d.ts +1 -0
  305. package/types/client/makePageProto.d.ts +28 -26091
  306. package/types/client/nativeThemeColor.d.ts +6 -0
  307. package/types/client/route/RouteDefinition.d.ts +2 -2
  308. package/types/client/route/RouteHead.d.ts +5 -1
  309. package/types/client/route/routeArgs.d.ts +6 -0
  310. package/types/client/router.d.ts +6 -3
  311. package/types/client/rscNavigation.d.ts +3 -2
  312. package/types/client/rscRoutePatch.d.ts +22 -0
  313. package/types/client/viewportMeta.d.ts +3 -1
  314. package/types/common/CodeTranscript.d.ts +1 -1
  315. package/types/common/akanGraph.d.ts +1 -1
  316. package/types/common/err.d.ts +48 -0
  317. package/types/common/facetBarrel.d.ts +4 -0
  318. package/types/common/failureCode.d.ts +6 -0
  319. package/types/common/index.d.ts +8 -2
  320. package/types/common/isGuardRefusal.d.ts +3 -0
  321. package/types/common/mcpExposure.d.ts +9 -2
  322. package/types/common/mcpFailure.d.ts +6 -0
  323. package/types/common/restartSchedule.d.ts +16 -0
  324. package/types/common/routeConvention.d.ts +2 -0
  325. package/types/common/types.d.ts +18 -1
  326. package/types/constant/constantRegistry.d.ts +3 -1
  327. package/types/constant/crystalize.d.ts +1 -1
  328. package/types/constant/getDefault.d.ts +1 -1
  329. package/types/constant/immerify.d.ts +1 -1
  330. package/types/constant/index.d.ts +21 -21
  331. package/types/constant/purify.d.ts +2 -1
  332. package/types/constant/serialize.d.ts +1 -1
  333. package/types/constant/types.d.ts +1 -0
  334. package/types/dictionary/agent.dictionary.d.ts +1 -1
  335. package/types/dictionary/base.dictionary.d.ts +1 -1
  336. package/types/dictionary/dictionary.d.ts +9 -9
  337. package/types/dictionary/locale.d.ts +1 -1
  338. package/types/dictionary/trans.d.ts +3 -26
  339. package/types/document/databaseRegistry.d.ts +2 -1
  340. package/types/document/documentSchema.d.ts +1 -0
  341. package/types/document/filterMeta.d.ts +4 -1
  342. package/types/document/into.d.ts +1 -1
  343. package/types/document/loaderInfo.d.ts +2 -1
  344. package/types/document/noDocumentError.d.ts +8 -1
  345. package/types/document/queryEvaluator.d.ts +1 -1
  346. package/types/document/types.d.ts +1 -1
  347. package/types/fetch/client/fetchClient.d.ts +6 -36
  348. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  349. package/types/fetch/client/fetchHandle.d.ts +1 -0
  350. package/types/fetch/client/httpClient.d.ts +2 -0
  351. package/types/fetch/client/inflightQueries.d.ts +2 -0
  352. package/types/fetch/client/remoteError.d.ts +0 -4
  353. package/types/fetch/client/requestScope.d.ts +6 -0
  354. package/types/fetch/client/signalCatalog.d.ts +25 -0
  355. package/types/fetch/client/wsClient.d.ts +1 -0
  356. package/types/fetch/index.d.ts +1 -0
  357. package/types/fetch/staleReads.d.ts +8 -0
  358. package/types/fetch/streamedRead.d.ts +8 -0
  359. package/types/server/agentHooks.d.ts +4 -0
  360. package/types/server/akanApp.d.ts +2 -20
  361. package/types/server/akanOption.d.ts +9 -3
  362. package/types/server/akanServer.d.ts +1 -1
  363. package/types/server/artifact/builderRpc.d.ts +8 -0
  364. package/types/server/artifact/ipcTypes.d.ts +8 -0
  365. package/types/server/assetHeaders.d.ts +1 -0
  366. package/types/server/console.d.ts +4 -3
  367. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  368. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  369. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  370. package/types/server/ed25519Key.d.ts +1 -0
  371. package/types/server/flightRowReader.d.ts +3 -1
  372. package/types/server/gateway/childSupervisor.d.ts +33 -0
  373. package/types/server/gateway/devHostChannel.d.ts +14 -0
  374. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  375. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  376. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  377. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  378. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  379. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  380. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  381. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  382. package/types/server/head.d.ts +2 -2
  383. package/types/server/htmlResultCache.d.ts +51 -0
  384. package/types/server/index.d.ts +17 -17
  385. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  386. package/types/server/lifecycle/startGuard.d.ts +10 -0
  387. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  388. package/types/server/logging/serverLogging.d.ts +12 -0
  389. package/types/server/mcp/AgentTools.d.ts +31 -0
  390. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  391. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  392. package/types/server/mcp/McpPages.d.ts +2 -1
  393. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  394. package/types/server/mcp/index.d.ts +1 -0
  395. package/types/server/resolver/database.resolver.d.ts +2 -2
  396. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  397. package/types/server/resolver/invalidSignal.d.ts +2 -0
  398. package/types/server/resolver/livePause.d.ts +5 -0
  399. package/types/server/resolver/modelFacade.d.ts +5 -0
  400. package/types/server/resolver/modelLoaders.d.ts +9 -0
  401. package/types/server/resolver/modelSchema.d.ts +6 -0
  402. package/types/server/resolver/signal.resolver.d.ts +2 -2
  403. package/types/server/resolver/timedQuery.d.ts +8 -0
  404. package/types/server/resolver/websocketOf.d.ts +2 -0
  405. package/types/server/routeElementComposer.d.ts +45 -6
  406. package/types/server/routeState.d.ts +2 -0
  407. package/types/server/routing/builtinRoutes.d.ts +24 -0
  408. package/types/server/routing/localRooms.d.ts +14 -0
  409. package/types/server/routing/roomReplay.d.ts +2 -2
  410. package/types/server/routing/serverListener.d.ts +31 -0
  411. package/types/server/rscClient.d.ts +1 -5
  412. package/types/server/rscClientCache.d.ts +34 -0
  413. package/types/server/rscClientChunks.d.ts +18 -0
  414. package/types/server/rscClientFetch.d.ts +1 -1
  415. package/types/server/rscClientPatch.d.ts +12 -1
  416. package/types/server/rscDocumentHead.d.ts +32 -0
  417. package/types/server/rscFlightRenderer.d.ts +14 -0
  418. package/types/server/rscFlightStream.d.ts +52 -0
  419. package/types/server/rscHeadPatch.d.ts +5 -4
  420. package/types/server/rscHostReloads.d.ts +54 -0
  421. package/types/server/rscHostRenderStream.d.ts +53 -0
  422. package/types/server/rscHostRequests.d.ts +29 -0
  423. package/types/server/rscHttp.d.ts +4 -2
  424. package/types/server/rscInlineStream.d.ts +9 -0
  425. package/types/server/rscNavigationState.d.ts +8 -3
  426. package/types/server/rscParkedRedirect.d.ts +12 -0
  427. package/types/server/rscPatchPlanner.d.ts +49 -0
  428. package/types/server/rscPrefetchCache.d.ts +8 -7
  429. package/types/server/rscRenderControl.d.ts +12 -0
  430. package/types/server/rscRenderFallbacks.d.ts +41 -0
  431. package/types/server/rscRenderHandler.d.ts +29 -0
  432. package/types/server/rscRenderStats.d.ts +32 -0
  433. package/types/server/rscResponse.d.ts +9 -0
  434. package/types/server/rscResultCaches.d.ts +18 -0
  435. package/types/server/rscRouteDocument.d.ts +52 -0
  436. package/types/server/rscSegmentOutlet.d.ts +5 -0
  437. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  438. package/types/server/rscWorker.d.ts +1 -3
  439. package/types/server/rscWorkerCache.d.ts +33 -1
  440. package/types/server/rscWorkerHost.d.ts +9 -76
  441. package/types/server/rscWorkerProcess.d.ts +31 -0
  442. package/types/server/rscWorkerRecycler.d.ts +22 -0
  443. package/types/server/serverConfig.d.ts +30 -0
  444. package/types/server/serverMetrics.d.ts +11 -0
  445. package/types/server/sitemap.d.ts +1 -0
  446. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  447. package/types/server/ssrTypes.d.ts +8 -0
  448. package/types/server/webArtifact.d.ts +7 -0
  449. package/types/server/webAssetRoutes.d.ts +11 -0
  450. package/types/server/webCsrSurface.d.ts +18 -0
  451. package/types/server/webDocumentRoute.d.ts +19 -0
  452. package/types/server/webRouteContext.d.ts +45 -0
  453. package/types/server/webRouter.d.ts +4 -35
  454. package/types/server/webRscRoute.d.ts +24 -0
  455. package/types/server/webSiteFiles.d.ts +12 -0
  456. package/types/server/wellKnownRoutes.d.ts +5 -0
  457. package/types/service/agent.service.d.ts +13 -4
  458. package/types/service/agentAccounts.d.ts +8 -0
  459. package/types/service/agentLoop/agentLoop.d.ts +31 -0
  460. package/types/service/agentLoop/agentLoopTypes.d.ts +126 -0
  461. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  462. package/types/service/agentLoop/loopCompaction.d.ts +11 -0
  463. package/types/service/agentLoop/loopRequest.d.ts +6 -0
  464. package/types/service/agentLoop/loopToolOutput.d.ts +7 -0
  465. package/types/service/agentLoop/loopToolkits.d.ts +14 -0
  466. package/types/service/agentLoop/loopTranscript.d.ts +12 -0
  467. package/types/service/agentMeter.d.ts +50 -0
  468. package/types/service/agentRelayPolicy.d.ts +45 -0
  469. package/types/service/documentStoreError.d.ts +7 -0
  470. package/types/service/index.d.ts +7 -0
  471. package/types/service/injectError.d.ts +4 -0
  472. package/types/service/injectInfo.d.ts +2 -1
  473. package/types/service/insightQueryError.d.ts +9 -0
  474. package/types/service/ipcTypes.d.ts +6 -0
  475. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  476. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  477. package/types/service/predefinedAdaptor/index.d.ts +2 -0
  478. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +18 -2
  479. package/types/service/predefinedAdaptor/llmSpend.d.ts +22 -0
  480. package/types/service/predefinedAdaptor/openaiDialect.d.ts +2 -1
  481. package/types/service/predefinedAdaptor/openaiLlm.d.ts +1 -1
  482. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  483. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  484. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  485. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  486. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  487. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +24 -0
  488. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  489. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  490. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -32
  491. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +20 -0
  492. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  493. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
  494. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  495. package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
  496. package/types/service/predefinedAdaptor/sseData.d.ts +5 -0
  497. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +14 -5
  498. package/types/service/serviceModule.d.ts +1 -1
  499. package/types/service/serviceRegistry.d.ts +1 -0
  500. package/types/signal/SignalFailure.d.ts +2 -0
  501. package/types/signal/agentTurnStream.d.ts +2 -1
  502. package/types/signal/byIdRead.d.ts +7 -0
  503. package/types/signal/carriedClientIps.d.ts +4 -0
  504. package/types/signal/endpointErrorContract.d.ts +3 -0
  505. package/types/signal/exception.d.ts +1 -0
  506. package/types/signal/index.d.ts +32 -30
  507. package/types/signal/mcp/McpDocument.d.ts +2 -0
  508. package/types/signal/mcp/index.d.ts +1 -0
  509. package/types/signal/mcp/promptError.d.ts +5 -0
  510. package/types/signal/resolveFieldContext.d.ts +15 -0
  511. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  512. package/types/signal/signalContext.d.ts +1 -13
  513. package/types/signal/signalContractError.d.ts +4 -0
  514. package/types/signal/signalDeclarationError.d.ts +4 -0
  515. package/types/signal/slice.d.ts +15 -13
  516. package/types/signal/trace.d.ts +3 -0
  517. package/types/signal/types.d.ts +33 -6
  518. package/types/store/action.d.ts +8 -27
  519. package/types/store/actionErrorKey.d.ts +1 -0
  520. package/types/store/actionOption.d.ts +24 -0
  521. package/types/store/baseSt.d.ts +2 -295
  522. package/types/store/draftFlush.d.ts +4 -0
  523. package/types/store/formDrafts.d.ts +21 -0
  524. package/types/store/formFieldSetters.d.ts +80 -0
  525. package/types/store/index.d.ts +17 -16
  526. package/types/store/modelActionContext.d.ts +189 -0
  527. package/types/store/modelListPatch.d.ts +34 -0
  528. package/types/store/modelOpenActions.d.ts +12 -0
  529. package/types/store/modelWriteActions.d.ts +16 -0
  530. package/types/store/modelWriteGuard.d.ts +42 -0
  531. package/types/store/openSeq.d.ts +17 -0
  532. package/types/store/rootStore.d.ts +6 -0
  533. package/types/store/sliceListActions.d.ts +295 -0
  534. package/types/store/sliceLiveActions.d.ts +6 -0
  535. package/types/store/stateBuilder.d.ts +2 -0
  536. package/types/store/uploadPoll.d.ts +16 -0
  537. package/types/store/withSelector.d.ts +1 -1
  538. package/types/ui/Agent/Chat.d.ts +5 -2
  539. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  540. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  541. package/types/ui/Field/Choice.d.ts +2 -1
  542. package/types/ui/Field/index.d.ts +1 -1
  543. package/types/ui/Link/inputModality.d.ts +5 -0
  544. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  545. package/types/ui/Load/Edit_Client.d.ts +2 -0
  546. package/types/ui/Load/Pagination.d.ts +4 -1
  547. package/types/ui/Load/Stream.d.ts +7 -1
  548. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  549. package/types/ui/Load/Units.d.ts +2 -0
  550. package/types/ui/Load/View.d.ts +2 -0
  551. package/types/ui/Reference/origin.d.ts +1 -0
  552. package/types/ui/index.d.ts +1 -1
  553. package/types/ui/overlayLayer.d.ts +6 -1
  554. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  555. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  556. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  557. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  558. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  559. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  560. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +18 -11
  561. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  562. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  563. package/types/vendor/use-agentic/index.d.ts +1 -0
  564. package/types/vendor/use-agentic/types.d.ts +11 -0
  565. package/types/webkit/CsrGuards.d.ts +2 -0
  566. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  567. package/types/webkit/nativeCore.d.ts +1 -0
  568. package/types/webkit/nativePurchase.d.ts +2 -1
  569. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  570. package/types/webkit/useCsrLocationState.d.ts +21 -0
  571. package/types/webkit/useCsrNavigation.d.ts +25 -0
  572. package/types/webkit/useCsrRefs.d.ts +33 -0
  573. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  574. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  575. package/types/webkit/useCsrTransitions.d.ts +2 -0
  576. package/types/webkit/useFrameRuntime.d.ts +1 -0
  577. package/types/webkit/useGeoLocation.d.ts +1 -1
  578. package/types/webkit/useHistory.d.ts +2 -3
  579. package/types/webkit/usePurchase.d.ts +1 -1
  580. package/types/webkit/useResolvedFrame.d.ts +38 -0
  581. package/types/webkit/useSyncNavigation.d.ts +22 -0
  582. package/types/webkit/useTransitionStore.d.ts +1 -0
  583. package/ui/Agent/Chat.tsx +392 -235
  584. package/ui/Agent/ChatHeader.tsx +59 -0
  585. package/ui/Agent/ChatPendingCards.tsx +49 -0
  586. package/ui/Agent/fetchRunner.ts +8 -1
  587. package/ui/BottomSheet.tsx +1 -1
  588. package/ui/Button.tsx +1 -0
  589. package/ui/Data/Item.tsx +2 -2
  590. package/ui/Data/ListContainer.tsx +348 -181
  591. package/ui/Data/useViewModal.ts +10 -4
  592. package/ui/Dialog/LegacyModal.tsx +1 -1
  593. package/ui/Dialog/Modal.tsx +1 -1
  594. package/ui/Field/Choice.tsx +3 -1
  595. package/ui/Link/inputModality.ts +21 -0
  596. package/ui/Link/prefetchIntent.ts +7 -25
  597. package/ui/Link/viewportPrefetch.ts +30 -0
  598. package/ui/Load/Edit_Client.tsx +7 -1
  599. package/ui/Load/Pagination.tsx +10 -2
  600. package/ui/Load/Stream.tsx +24 -4
  601. package/ui/Load/StreamBoundary.tsx +65 -0
  602. package/ui/Load/Units.tsx +3 -0
  603. package/ui/Load/View.tsx +5 -1
  604. package/ui/Model/EditModal.tsx +2 -1
  605. package/ui/Popconfirm.tsx +1 -1
  606. package/ui/Reference/origin.ts +1 -0
  607. package/ui/Select.tsx +43 -51
  608. package/ui/Signal/RestApi.tsx +3 -2
  609. package/ui/System/Client.tsx +32 -8
  610. package/ui/index.ts +4 -0
  611. package/ui/overlayLayer.ts +22 -1
  612. package/vendor/@akanjs/native/CHANGELOG.md +7 -1
  613. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +27 -12
  614. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  615. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  616. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  617. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +509 -0
  618. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  619. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  620. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  621. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  622. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  623. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  624. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  625. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  626. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  627. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  628. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  629. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  630. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  631. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  632. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +18 -11
  633. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  634. package/vendor/use-agentic/AgentSession.ts +11 -11
  635. package/vendor/use-agentic/CHANGELOG.md +46 -1
  636. package/vendor/use-agentic/Compaction.ts +2 -1
  637. package/vendor/use-agentic/ToolRunner.ts +6 -3
  638. package/vendor/use-agentic/Transcript.ts +6 -3
  639. package/vendor/use-agentic/WIRE.md +29 -7
  640. package/vendor/use-agentic/failureCode.ts +44 -0
  641. package/vendor/use-agentic/httpRunner.ts +15 -4
  642. package/vendor/use-agentic/index.ts +1 -0
  643. package/vendor/use-agentic/types.ts +11 -0
  644. package/webkit/CsrGuards.ts +7 -2
  645. package/webkit/McpAppAgent.ts +8 -3
  646. package/webkit/McpAppFetchBridge.ts +11 -5
  647. package/webkit/RouteLevelBoundary.tsx +37 -0
  648. package/webkit/nativeCore.ts +1 -0
  649. package/webkit/nativePurchase.ts +6 -3
  650. package/webkit/useCamera.tsx +22 -21
  651. package/webkit/useCsrKeyboard.ts +155 -0
  652. package/webkit/useCsrLocationState.ts +58 -0
  653. package/webkit/useCsrNavigation.ts +302 -0
  654. package/webkit/useCsrRefs.ts +52 -0
  655. package/webkit/useCsrRenderTrace.ts +68 -0
  656. package/webkit/useCsrStackLifecycle.ts +120 -0
  657. package/webkit/useCsrTransitions.ts +552 -0
  658. package/webkit/useCsrValues.ts +69 -1234
  659. package/webkit/useGeoLocation.tsx +4 -1
  660. package/webkit/useHistory.ts +2 -2
  661. package/webkit/useLocation.ts +3 -2
  662. package/webkit/usePurchase.tsx +4 -2
  663. package/webkit/useResolvedFrame.ts +116 -0
  664. package/webkit/useSyncNavigation.ts +109 -0
  665. package/webkit/useTransitionStore.ts +13 -0
  666. package/types/signal/agentMeter.d.ts +0 -27
  667. package/types/signal/agentRelayPolicy.d.ts +0 -25
package/server/akanApp.ts CHANGED
@@ -1,25 +1,21 @@
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 { CrossSiteGuard } from "../signal/CrossSiteGuard";
10
- import { isTraceEnabled } from "../signal/trace";
11
- import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "./akanAppHeaders";
12
- import type { BuilderMessage, BuilderRequest, BuilderResponse } from "./artifact";
13
- import { type AssetHeaderOptions, applySecurityHeaders, assetHeaders } from "./assetHeaders";
14
- 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";
15
17
  import { isPortInUseError } from "./lifecycle/portInUse";
16
- import { resolveRuntimeDir } from "./lifecycle/runtimeDir";
17
- import { ChildOutputReader } from "./logging/childOutputReader";
18
- import { HubFileSink } from "./logging/hubFileSink";
19
- import { LogControlSocket } from "./logging/logControlSocket";
20
- import { LogHub } from "./logging/logHub";
21
18
  import { LogStreamRoute } from "./logging/logStreamRoute";
22
- import { RotatingLogWriter } from "./logging/rotatingLogWriter";
23
19
  import { AppInfo } from "./ops/appInfo";
24
20
  import type { OpsHost } from "./ops/opsCommand";
25
21
  import type { OpsRoute } from "./ops/opsRoute";
@@ -28,233 +24,65 @@ import { ProcessMetricsCollector } from "./processMetricsCollector";
28
24
  import { HostAllowlist } from "./routing/hostAllowlist";
29
25
  import { RouteHosts } from "./routing/routeHosts";
30
26
  import { ServerLimits } from "./routing/serverLimits";
31
- import { WsUpgrade } from "./routing/wsUpgrade";
32
27
  import { SelfExec } from "./selfExec";
33
- import { resolveStaticPath } from "./staticPath";
34
- import { getWebConfigFromEnv } from "./types";
35
28
 
36
- interface ChildState {
37
- idx: number;
38
- role: AkanChildRole;
39
- proc: Bun.Subprocess<"ignore", "pipe", "pipe">;
40
- ready: boolean;
41
- status: AkanChildStatus;
42
- pid?: number;
43
- upstream?: AkanUpstream;
44
- wsUpstream?: Extract<AkanUpstream, { type: "tcp" }>;
45
- healthPath?: string;
46
- metrics: AkanMetricsReport;
47
- /** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
48
- lastPongAtMono?: number;
49
- restartAttempts: number;
50
- restartCount: number;
51
- restartTimer: Timer | null;
52
- restartPending: boolean;
53
- lastExitCode?: number | null;
54
- lastRestartAt?: number;
55
- lastRestartReason?: string;
56
- lastErrorMessage?: string;
57
- }
29
+ export type { AkanAppOptions } from "./gateway/gatewayConfig";
58
30
 
59
31
  interface SoloServer {
60
32
  start: (options: { listen: boolean }) => Promise<unknown>;
61
33
  }
62
34
 
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
35
  export class AkanApp {
112
- static readonly #childRestartBaseDelayMs = 1_000;
113
- static readonly #childRestartMaxDelayMs = 30_000;
114
- static readonly #childRestartGraceMs = 5_000;
115
- static readonly #devMaxChildBootFailures = 3;
116
-
117
36
  readonly logger = new Logger("AkanApp");
118
- readonly #devHosted = process.env.AKAN_COMMAND_TYPE === "start";
119
- readonly #healthTimeoutMs = AkanApp.#parseHealthTimeoutMs();
120
- readonly #upstreamWaitMs = AkanApp.#parseUpstreamWaitMs();
121
- /** Child stderr is mostly bundler/runtime noise, kept to the log file; with none it may be a crash's only trace. */
122
- readonly #printChildStderr = process.env.AKAN_CHILD_STDERR === "1";
123
- readonly #serverPath: string;
124
- readonly #artifactDir: string;
125
- readonly #replica: AkanReplicaConfig;
126
- readonly #runtimeDir: string;
127
- readonly #socketRunId = `${process.pid}-${Date.now().toString(36)}`;
128
- readonly #port: number;
129
- readonly #wsBasePort: number;
130
- readonly #openapi?: boolean;
131
- readonly #prefix: string;
132
- readonly #websocketPrefix: string;
133
- readonly #web = getWebConfigFromEnv();
134
- readonly #modules: string[];
135
- readonly #disableModules: string[];
136
- readonly #disableLibs: string[];
137
- readonly #solo: boolean;
138
- readonly #children = new Map<number, ChildState>();
139
- readonly #roomChildren = new Map<string, Set<number>>();
140
- readonly #childRooms = new Map<number, Map<string, Set<string>>>();
141
- readonly #socketRooms = new Map<string, { childIdx: number; rooms: Set<string> }>();
142
- readonly #childLiveModels = new Map<number, Set<string>>();
143
- #nextBuilderReqId = 1;
144
- readonly #builderReqMap = new Map<number, { childIdx: number; childLocalId: number }>();
37
+ readonly #config: GatewayConfig;
38
+ readonly #children: GatewayChildren;
39
+ readonly #logging: GatewayLogging;
40
+ readonly #rooms: GatewayRooms;
41
+ readonly #host: DevHostChannel;
42
+ readonly #supervisor: ChildSupervisor;
43
+ readonly #status: GatewayStatus;
44
+ readonly #proxy: GatewayHttpProxy;
45
+ readonly #ws: GatewayWebSocketRelay;
145
46
  #server: Bun.Server<GatewayWsData> | null = null;
146
- #rrIdx = 0;
147
- #federationChildCache: ChildState[] | null = null;
148
47
  #snapshotTimer: Timer | null = null;
149
48
  #healthTimer: Timer | null = null;
150
49
  #metricsTimer: Timer | null = null;
151
- #logWriter: RotatingLogWriter | null = null;
152
- #detachFileLog: (() => void) | null = null;
153
- #logHub: LogHub | null = null;
154
- #logControl: LogControlSocket | null = null;
155
- #logStream: LogStreamRoute | null = null;
156
50
  #ops: OpsRoute | null = null;
157
51
  #hostAllowlist = HostAllowlist.fromEnv();
158
52
  readonly #limits = new ServerLimits();
159
-
160
- static readonly #wsPendingLimitBytes = 1024 * 1024;
161
- static readonly #wsUpstreamOpenTimeoutMs = 10_000;
162
- readonly #wsCaps = {
163
- total: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS"),
164
- perIp: AkanApp.#positiveIntEnv("AKAN_MAX_WEBSOCKETS_PER_IP"),
165
- };
166
- #wsOpen = 0;
167
- readonly #wsOpenByIp = new Map<string, number>();
168
53
  readonly #statusAccess = StatusAccess.fromEnv();
169
- static readonly #ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
170
- #gatewayMetrics: AkanMetricsReport = {};
171
- #proxyHopCount = 0;
172
- #proxyHopSumMs = 0;
173
- #proxyHopMaxMs = 0;
174
54
  #resolveStopped: (() => void) | null = null;
175
55
  #exitAfterStop = false;
176
- #stopping = false;
177
56
 
178
57
  constructor(serverPathOrOptions: string | AkanAppOptions = "./server", options: AkanAppOptions = {}) {
179
58
  SelfExec.adopt();
180
59
  const resolvedOptions = typeof serverPathOrOptions === "string" ? options : serverPathOrOptions;
181
60
  const serverPath = typeof serverPathOrOptions === "string" ? serverPathOrOptions : "./server";
182
- this.#serverPath = AkanApp.#resolveServerPath(resolvedOptions.serverPath ?? serverPath);
183
- this.#artifactDir = path.resolve(path.dirname(this.#serverPath), ".akan", "artifact");
184
- this.#replica = AkanApp.#parseReplicaConfig(resolvedOptions.replica);
185
- this.#runtimeDir = resolveRuntimeDir(resolvedOptions.runtimeDir);
186
- this.#port = Number(resolvedOptions.port ?? process.env.PORT ?? 8282);
187
- this.#wsBasePort = Number(resolvedOptions.wsBasePort ?? process.env.AKAN_WS_BASE_PORT ?? this.#port + 10_000);
188
- this.#openapi = resolvedOptions.openapi;
189
- this.#prefix = normalizeRoutePrefix(resolvedOptions.prefix) ?? getApiPrefix();
190
- this.#websocketPrefix = normalizeRoutePrefix(resolvedOptions.websocketPrefix) ?? getWsPrefix();
191
- this.#modules = resolvedOptions.modules ?? [];
192
- this.#disableModules = resolvedOptions.disableModules ?? [];
193
- this.#disableLibs = resolvedOptions.disableLibs ?? [];
194
- this.#solo = AkanApp.#resolveSolo(resolvedOptions, this.#replica);
195
- this.#logHub = LogHub.attach();
196
- }
197
-
198
- static #resolveSolo(options: AkanAppOptions, replica: AkanReplicaConfig) {
199
- if (options.solo !== undefined) return options.solo;
200
- if (process.env.AKAN_SOLO === "false" || process.env.AKAN_SOLO === "0") return false;
201
- if (process.env.AKAN_COMMAND_TYPE === "start") return false;
202
- if (options.replica !== undefined) return false;
203
- return replica.total === 1 && replica.batch === 0;
204
- }
205
-
206
- static #resolveServerPath(serverPath: string) {
207
- const baseDir = path.dirname(Bun.main);
208
- const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
209
- if (path.extname(resolved)) return resolved;
210
- return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
211
- }
212
-
213
- static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
214
- const configured = value ?? process.env.AKAN_REPLICA;
215
- const raw = String(configured ?? "0,0,1").trim();
216
- const [federationRaw, batchRaw, allRaw] = raw.split(",");
217
- const federation = AkanApp.#parseReplicaCount(federationRaw, 0);
218
- const batch = AkanApp.#parseReplicaCount(batchRaw, 0);
219
- const all = AkanApp.#parseReplicaCount(allRaw, configured == null ? 1 : 0);
220
- const normalizedAll = federation + batch + all > 0 ? all : 1;
221
- return {
222
- federation,
223
- batch,
224
- all: normalizedAll,
225
- total: federation + batch + normalizedAll,
226
- value: `${federation},${batch},${normalizedAll}`,
227
- };
228
- }
229
-
230
- static #parseReplicaCount(value: string | undefined, fallback: number) {
231
- const parsed = Number.parseInt(value ?? "", 10);
232
- return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
233
- }
234
-
235
- static #defaultChildNodeEnv() {
236
- if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
237
- if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
238
- if (process.env.NODE_ENV) return process.env.NODE_ENV;
239
- return Bun.main.endsWith(".js") ? "production" : "development";
240
- }
241
-
242
- static #parseHealthTimeoutMs() {
243
- const configured = Number(process.env.AKAN_HEALTH_TIMEOUT_MS);
244
- if (Number.isFinite(configured) && configured > 0) return configured;
245
- return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
246
- }
247
-
248
- static #parseUpstreamWaitMs() {
249
- const configured = Number(process.env.AKAN_UPSTREAM_WAIT_MS);
250
- if (Number.isFinite(configured) && configured >= 0) return configured;
251
- return process.env.AKAN_COMMAND_TYPE === "start" ? 15_000 : 5_000;
252
- }
253
-
254
- static #childShutdownWaitMs() {
255
- const configured = Number(process.env.AKAN_CHILD_SHUTDOWN_WAIT_MS);
256
- if (Number.isFinite(configured) && configured > 0) return configured;
257
- return process.env.AKAN_COMMAND_TYPE === "start" ? 5_000 : 30_000;
61
+ const logger = this.logger;
62
+ const config = new GatewayConfig(serverPath, resolvedOptions);
63
+ const children = new GatewayChildren(logger);
64
+ const logging = new GatewayLogging(config, children, logger);
65
+ const rooms = new GatewayRooms(children, logger);
66
+ const host = new DevHostChannel(children, logger);
67
+ const supervisor = new ChildSupervisor({
68
+ config,
69
+ children,
70
+ rooms,
71
+ logging,
72
+ host,
73
+ logger,
74
+ onMessage: (idx, message, proc) => this.#handleMessage(idx, message, proc),
75
+ });
76
+ const status = new GatewayStatus(config, children, rooms, logger);
77
+ this.#config = config;
78
+ this.#children = children;
79
+ this.#logging = logging;
80
+ this.#rooms = rooms;
81
+ this.#host = host;
82
+ this.#supervisor = supervisor;
83
+ this.#status = status;
84
+ this.#proxy = new GatewayHttpProxy({ config, children, supervisor, status, limits: this.#limits, logger });
85
+ this.#ws = new GatewayWebSocketRelay(config, children);
258
86
  }
259
87
 
260
88
  async start() {
@@ -264,31 +92,36 @@ export class AkanApp {
264
92
  await OpsCommand.run(process.argv.slice(3), { importServer: async () => await this.#importServer() }),
265
93
  );
266
94
  }
267
- if (this.#solo) return await this.#startSolo();
95
+ if (this.#config.solo) return await this.#startSolo();
268
96
  if (SelfExec.carried)
269
- throw new Error(
97
+ throw new AkanError(
98
+ "invalidConfig",
270
99
  "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.",
271
100
  );
272
101
  Logger.role = "gateway";
273
- await this.#prepareRuntimeDir();
274
- await this.#startLogHub();
275
- this.#startFileLogging();
102
+ await this.#supervisor.prepareRuntimeDir();
103
+ await this.#logging.start();
276
104
  await this.#startOps();
277
- for (let idx = 0; idx < this.#replica.total; idx++) this.#spawn(idx);
105
+
106
+ if (this.#children.stopping) {
107
+ await this.#logging.stop();
108
+ return;
109
+ }
110
+ for (let idx = 0; idx < this.#config.replica.total; idx++) this.#supervisor.spawn(idx);
278
111
  try {
279
112
  this.#listen();
280
113
  } catch (error) {
281
114
  if (isPortInUseError(error)) {
282
- 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}).`;
115
+ 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}).`;
283
116
  this.logger.error(message);
284
- this.#reportBackendBuildStatus({ ok: false, message });
117
+ this.#host.reportBackendBuildStatus({ ok: false, message });
285
118
  }
286
119
  await this.stop("listen-failed");
287
120
  throw error;
288
121
  }
289
- this.#snapshotTimer = setInterval(() => this.#requestRoomSnapshots(), 30_000);
290
- this.#healthTimer = setInterval(() => this.#checkHealth(), 2_000);
291
- this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#reportMetrics());
122
+ this.#snapshotTimer = setInterval(() => this.#rooms.requestRoomSnapshots(), 30_000);
123
+ this.#healthTimer = setInterval(() => this.#supervisor.checkHealth(), 2_000);
124
+ this.#metricsTimer ??= ProcessMetricsCollector.startReporting(() => this.#status.reportMetrics());
292
125
  process.on("message", (message) => this.#handleHostMessage(message as BuilderMessage));
293
126
  process.on("disconnect", () => this.#handleHostDisconnect());
294
127
  process.on("SIGINT", () => this.#handleShutdownSignal("SIGINT"));
@@ -299,56 +132,42 @@ export class AkanApp {
299
132
  }
300
133
 
301
134
  async #importServer() {
302
- Object.assign(process.env, this.#childEnv(0, this.#getRole(0)), { AKAN_COMMAND_TYPE: "script" });
135
+ Object.assign(process.env, this.#config.childEnv(0, this.#config.roleOf(0)), { AKAN_COMMAND_TYPE: "script" });
303
136
  resetEnvCache();
304
- return (await import(this.#serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
137
+ return (await import(this.#config.serverPath)) as Awaited<ReturnType<OpsHost["importServer"]>>;
305
138
  }
306
139
 
307
140
  async #startSolo() {
308
- const role = this.#getRole(0);
141
+ const role = this.#config.roleOf(0);
309
142
 
310
- Object.assign(process.env, this.#childEnv(0, role));
143
+ Object.assign(process.env, this.#config.childEnv(0, role));
311
144
 
312
145
  resetEnvCache();
313
146
  this.logger.info(`Starting ${role} replica in this process (solo); set AKAN_SOLO=false for the gateway`);
314
- const mod = (await import(this.#serverPath)) as { server?: SoloServer; app?: SoloServer };
147
+ const mod = (await import(this.#config.serverPath)) as { server?: SoloServer; app?: SoloServer };
315
148
  const server = mod.server ?? mod.app;
316
- if (!server?.start) throw new Error("server.ts must export server or app with start()");
149
+ if (!server?.start) throw new AkanError("invalidArtifact", "server.ts must export server or app with start()");
317
150
  await server.start({ listen: true });
318
151
  }
319
152
 
320
153
  async stop(signal = "SIGTERM") {
321
- if (this.#stopping) return;
322
- this.#stopping = true;
154
+ if (this.#children.stopping) return;
155
+ this.#children.markStopping();
323
156
  for (const timer of [this.#snapshotTimer, this.#healthTimer, this.#metricsTimer]) if (timer) clearInterval(timer);
324
157
  this.#snapshotTimer = null;
325
158
  this.#healthTimer = null;
326
159
  this.#metricsTimer = null;
327
160
  this.#server?.stop(true);
328
161
  this.#server = null;
329
- for (const child of this.#children.values()) {
330
- if (child.restartTimer) clearTimeout(child.restartTimer);
331
- child.restartTimer = null;
332
- this.#sendToChild(child, { type: "shutdown", signal } satisfies AkanIpcMessage);
333
- }
334
- await Promise.race([
335
- Promise.all([...this.#children.values()].map((child) => child.proc.exited.catch(() => undefined))),
336
- new Promise((resolve) => setTimeout(resolve, AkanApp.#childShutdownWaitMs())),
337
- ]);
338
-
339
- const stragglers = [...this.#children.values()].filter((child) => !child.proc.killed);
340
- for (const child of stragglers) child.proc.kill("SIGKILL");
341
- await Promise.all(stragglers.map((child) => child.proc.exited.catch(() => undefined)));
342
- this.#children.clear();
343
- await this.#stopLogHub();
344
- await this.#stopFileLogging();
162
+ await this.#supervisor.stopAll(signal);
163
+ await this.#logging.stop();
345
164
  this.#resolveStopped?.();
346
165
  this.#resolveStopped = null;
347
166
  if (this.#exitAfterStop) process.exit(0);
348
167
  }
349
168
 
350
169
  #handleShutdownSignal(signal: NodeJS.Signals) {
351
- if (this.#stopping) process.exit(1);
170
+ if (this.#children.stopping) process.exit(1);
352
171
  this.#exitAfterStop = true;
353
172
  void this.stop(signal).catch((error) => {
354
173
  this.logger.error(`Failed to shutdown gateway: ${error instanceof Error ? error.message : String(error)}`);
@@ -357,249 +176,13 @@ export class AkanApp {
357
176
  }
358
177
 
359
178
  #handleHostDisconnect() {
360
- if (this.#stopping) return;
179
+ if (this.#children.stopping) return;
361
180
  this.logger.warn("Host IPC channel closed; shutting down gateway and children");
362
181
  this.#exitAfterStop = true;
363
- setTimeout(() => process.exit(1), AkanApp.#childShutdownWaitMs() + 5_000);
182
+ setTimeout(() => process.exit(1), GatewayConfig.childShutdownWaitMs() + 5_000);
364
183
  void this.stop("ipc-disconnect").catch(() => process.exit(1));
365
184
  }
366
185
 
367
- #spawn(idx: number) {
368
- const role = this.#getRole(idx);
369
- const upstream = this.#getChildUpstream(idx, role);
370
-
371
- 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); });`;
372
- const proc: Bun.Subprocess<"ignore", "pipe", "pipe"> = Bun.spawn(["bun", "-e", childCode], {
373
- cwd: process.cwd(),
374
- env: {
375
- ...process.env,
376
-
377
- ...this.#childEnv(idx, role),
378
- AKAN_CHILD_SOCKET: upstream.http.socketPath,
379
- AKAN_CHILD_WS_PORT: upstream.ws ? String(upstream.ws.port) : "",
380
- ...(this.#printChildStderr || Logger.isNdjson ? {} : { AKAN_CHILD_STDERR_HIDDEN: "1" }),
381
- },
382
- ipc: (message) => this.#handleMessage(idx, message as AkanIpcMessage, proc),
383
- stdout: "pipe",
384
- stderr: "pipe",
385
- stdin: "ignore",
386
- });
387
- const previous = this.#children.get(idx);
388
- this.#children.set(idx, {
389
- idx,
390
- role,
391
- proc,
392
- ready: false,
393
- status: "starting",
394
- metrics: {},
395
- restartAttempts: previous?.restartAttempts ?? 0,
396
- restartCount: previous?.restartCount ?? 0,
397
- restartTimer: null,
398
- restartPending: false,
399
- lastExitCode: previous?.lastExitCode,
400
- lastRestartAt: previous?.lastRestartAt,
401
- lastRestartReason: previous?.lastRestartReason,
402
- });
403
- this.#federationChildCache = null;
404
- const output = new ChildOutputReader({
405
- onLine: (line) => this.#writeChildLine(idx, role, proc.pid, "stdout", line),
406
- onBlock: (lines) => this.#writeChildStderrBlock(idx, role, proc.pid, lines),
407
- });
408
- void output.pipe(proc.stdout, "stdout");
409
- void output.pipe(proc.stderr, "stderr");
410
- proc.exited.then((code) => this.#handleChildExit(idx, proc, code));
411
- }
412
-
413
- #childEnv(idx: number, role: AkanChildRole) {
414
- return {
415
- PORT: String(this.#port),
416
- NODE_ENV: AkanApp.#defaultChildNodeEnv(),
417
- AKAN_REPLICA: this.#replica.value,
418
- AKAN_REPLICA_IDX: String(idx),
419
- AKAN_APP_DIR: path.dirname(this.#serverPath),
420
- SERVER_MODE: role,
421
- AKAN_API_PREFIX: this.#prefix,
422
- AKAN_WS_PREFIX: this.#websocketPrefix,
423
- ...(this.#openapi === undefined ? {} : { AKAN_OPENAPI: this.#openapi ? "true" : "false" }),
424
- ...(this.#modules.length ? { AKAN_MODULES: this.#modules.join(",") } : {}),
425
- ...(this.#disableModules.length ? { AKAN_DISABLE_MODULES: this.#disableModules.join(",") } : {}),
426
- ...(this.#disableLibs.length ? { AKAN_DISABLE_LIBS: this.#disableLibs.join(",") } : {}),
427
- };
428
- }
429
-
430
- #handleChildExit(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, code: number | null) {
431
- const child = this.#children.get(idx);
432
- if (!child || child.proc !== proc) return;
433
- if (child.status === "crashed") return;
434
- child.status = "exited";
435
- child.lastExitCode = code;
436
- this.#federationChildCache = null;
437
- this.#removeChildRooms(idx);
438
- if (this.#stopping) return;
439
- void this.#scheduleChildRestart(child, proc, `exit:${code ?? "unknown"}`);
440
- }
441
-
442
- #scheduleChildRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string): void {
443
- if (this.#stopping) return;
444
- if (child.proc !== proc) return;
445
- if (child.restartPending || child.restartTimer) {
446
- child.lastRestartReason = reason;
447
- return;
448
- }
449
- if (this.#devHosted && child.restartAttempts >= AkanApp.#devMaxChildBootFailures - 1 && !child.ready) {
450
- this.#markChildCrashed(child, reason);
451
- return;
452
- }
453
-
454
- child.restartPending = true;
455
- child.ready = false;
456
- child.status = reason === "health-timeout" || reason === "upstream-open-failed" ? "unhealthy" : "exited";
457
- child.upstream = undefined;
458
- child.wsUpstream = undefined;
459
- child.healthPath = undefined;
460
- this.#federationChildCache = null;
461
- child.lastRestartReason = reason;
462
- child.lastRestartAt = Date.now();
463
- this.#removeChildRooms(child.idx);
464
-
465
- const attempt = child.restartAttempts;
466
- const delay = Math.min(AkanApp.#childRestartBaseDelayMs * 2 ** attempt, AkanApp.#childRestartMaxDelayMs);
467
- child.restartAttempts = attempt + 1;
468
- child.restartCount += 1;
469
- this.logger.error(
470
- `Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restartAttempts})`,
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.restartTimer = setTimeout(() => {
497
- current.restartTimer = null;
498
- void this.#respawnChild(idx, proc).catch((error) => {
499
- const latest = this.#children.get(idx);
500
- if (!latest || latest.proc !== proc || this.#stopping) return;
501
- latest.restartPending = false;
502
- this.logger.error(
503
- `Failed to respawn child ${idx}/${latest.role}: ${error instanceof Error ? error.message : String(error)}`,
504
- );
505
- this.#scheduleChildRestart(latest, proc, "respawn-failed");
506
- });
507
- }, delay);
508
- }
509
-
510
- async #respawnChild(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">) {
511
- if (this.#stopping) return;
512
- const current = this.#children.get(idx);
513
- if (!current || current.proc !== proc) return;
514
- await this.#removeChildSocket(idx, current.role);
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.restartAttempts + 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
186
  async #startOps() {
604
187
  if (!process.env.AKAN_OPS_PUBLIC_KEY?.trim()) return;
605
188
  const { OpsRoute } = await import("./ops/opsRoute");
@@ -608,21 +191,13 @@ export class AkanApp {
608
191
  });
609
192
  }
610
193
 
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
194
  #listen() {
620
195
 
621
- if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#artifactDir);
196
+ if (this.#hostAllowlist?.devDefault) RouteHosts.declare(this.#config.artifactDir);
622
197
  this.#server = Bun.serve({
623
198
  idleTimeout: this.#limits.idleTimeout,
624
199
  maxRequestBodySize: this.#limits.uploadBodyBytes,
625
- port: this.#port,
200
+ port: this.#config.port,
626
201
  hostname: ServerLimits.listenHostname(),
627
202
  fetch: (req, server) =>
628
203
  ServerLimits.holdOpen(server, req, this.#limits.idleTimeout, () => this.#handleFetch(req, server)),
@@ -631,13 +206,13 @@ export class AkanApp {
631
206
  maxPayloadLength: 16 * 1024 * 1024,
632
207
  backpressureLimit: 1024 * 1024,
633
208
  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),
209
+ open: (ws) => this.#ws.open(ws),
210
+ message: (ws, message) => this.#ws.message(ws, message),
211
+ close: (ws, code, reason) => this.#ws.close(ws, code, reason),
637
212
  data: {} as GatewayWsData,
638
213
  },
639
214
  });
640
- this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#port}`);
215
+ this.logger.info(`AkanApp gateway is running on port http://localhost:${this.#config.port}`);
641
216
  }
642
217
 
643
218
  async #handleFetch(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response | undefined> {
@@ -646,485 +221,26 @@ export class AkanApp {
646
221
  if (oversized) return oversized;
647
222
  const url = new URL(req.url);
648
223
  if (url.pathname === "/_akan/app/health")
649
- return this.#statusAccess.health(req, () => this.#getHealthStatus(), AkanApp.#clientOf(req, server));
224
+ return this.#statusAccess.health(req, () => this.#status.healthStatus(), AkanApp.#clientOf(req, server));
650
225
  if (url.pathname === "/_akan/app/ready")
651
- return this.#statusAccess.ready(req, () => this.#getReadyStatus(), AkanApp.#clientOf(req, server));
226
+ return this.#statusAccess.ready(req, () => this.#status.readyStatus(), AkanApp.#clientOf(req, server));
652
227
  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));
228
+ return this.#statusAccess.metrics(req, () => this.#status.metricsStatus(), AkanApp.#clientOf(req, server));
229
+ const logStream = this.#logging.stream;
230
+ if (url.pathname === LogStreamRoute.path && logStream) return logStream.handle(req, AkanApp.#clientOf(req, server));
656
231
  if (url.pathname === "/_akan/bench/ping") return new Response("ok");
657
232
  if (url.pathname === AppInfo.publicPath) return AppInfo.handlePublic();
658
233
  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);
234
+ if (this.#config.isWebSocketPath(url.pathname)) return this.#ws.upgrade(req, server);
235
+ const assetResponse = await this.#proxy.serveImmutableArtifact(req, url);
661
236
  if (assetResponse) return assetResponse;
662
- return await this.#proxyHttp(req, server);
237
+ return await this.#proxy.proxyHttp(req, server);
663
238
  }
664
239
 
665
240
  static #clientOf(req: Request, server: Bun.Server<GatewayWsData>) {
666
241
  return TrustedProxy.clientAddress(req.headers, server.requestIP(req)?.address);
667
242
  }
668
243
 
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.restartAttempts,
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.restartAttempts,
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
244
  #handleMessage(
1129
245
  idx: number,
1130
246
  message: AkanIpcMessage | BuilderMessage,
@@ -1135,49 +251,49 @@ export class AkanApp {
1135
251
  if (!message || typeof message !== "object") return;
1136
252
  switch (message.type) {
1137
253
  case "ready":
1138
- this.#markReady(idx, message);
254
+ this.#supervisor.markReady(idx, message);
1139
255
  return;
1140
256
  case "pubsub.publish":
1141
- this.#deliverPubsub(idx, message);
257
+ this.#rooms.deliverPubsub(idx, message);
1142
258
  return;
1143
259
  case "pubsub.subscribe":
1144
- this.#addRoomMembership(idx, message.roomId, message.socketId);
260
+ this.#rooms.subscribe(idx, message);
1145
261
  return;
1146
262
  case "pubsub.unsubscribe":
1147
- this.#removeRoomMembership(idx, message.roomId, message.socketId);
263
+ this.#rooms.removeRoomMembership(idx, message.roomId, message.socketId);
1148
264
  return;
1149
265
  case "pubsub.snapshot":
1150
- this.#replaceRoomSnapshot(idx, message.rooms);
1151
- if (message.liveModels) this.#setLiveModels(idx, message.liveModels);
266
+ this.#rooms.replaceRoomSnapshot(idx, message.rooms);
267
+ if (message.liveModels) this.#rooms.setLiveModels(idx, message.liveModels);
1152
268
  return;
1153
269
  case "live.change":
1154
- this.#fanoutLiveChange(idx, message);
270
+ this.#rooms.fanoutLiveChange(idx, message);
1155
271
  return;
1156
272
  case "live.models":
1157
- this.#setLiveModels(idx, message.models);
273
+ this.#rooms.setLiveModels(idx, message.models);
1158
274
  return;
1159
275
  case "metrics.report":
1160
- this.#updateMetrics(idx, message.metrics);
276
+ this.#children.updateMetrics(idx, message.metrics);
1161
277
  return;
1162
278
  case "log.records":
1163
- this.#logHub?.ingestMany(message.records);
279
+ this.#logging.hub?.ingestMany(message.records);
1164
280
  if (message.dropped) this.logger.warn(`Child ${idx} dropped ${message.dropped} log records (ipc backpressure)`);
1165
281
  return;
1166
282
  case "health.pong":
1167
- this.#markHealthy(idx);
283
+ this.#supervisor.markHealthy(idx);
1168
284
  return;
1169
285
  case "queue.enqueued":
1170
- this.#fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
286
+ this.#children.fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
1171
287
  return;
1172
288
  case "error":
1173
289
  this.logger.error(message.message);
1174
290
  if (child) child.lastErrorMessage = message.message;
1175
- if (child && proc) void this.#scheduleChildRestart(child, proc, "child-error");
291
+ if (child && proc) void this.#supervisor.scheduleRestart(child, proc, "child-error");
1176
292
  return;
1177
293
  case "build-route":
1178
294
  case "build-csr":
1179
295
  case "build-graph":
1180
- this.#forwardBuilderReq(idx, message);
296
+ if (child) this.#host.forwardBuilderReq(child, message);
1181
297
  return;
1182
298
  }
1183
299
  }
@@ -1192,294 +308,13 @@ export class AkanApp {
1192
308
  case "csr-updated":
1193
309
  case "ssr-updated":
1194
310
  case "build-status":
1195
- this.#fanoutToFederation(message);
311
+ this.#children.fanoutToFederation(message);
1196
312
  return;
1197
313
  case "build-route-res":
1198
314
  case "build-csr-res":
1199
315
  case "build-graph-res":
1200
- this.#forwardBuilderRes(message);
316
+ this.#host.forwardBuilderRes(message);
1201
317
  return;
1202
318
  }
1203
319
  }
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.restartAttempts = 0;
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
320
  }