@phins/engine 0.0.0-stage → 0.1.3

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 (512) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/PROVENANCE.md +28 -0
  4. package/README.md +44 -2
  5. package/THIRD_PARTY.md +40 -0
  6. package/notices/bun-LICENSE.md +74 -0
  7. package/notices/dependency-licenses.json +2314 -0
  8. package/notices/drizzle-LICENSE +201 -0
  9. package/notices/fff-LICENSE +21 -0
  10. package/notices/node-forge-LICENSE +331 -0
  11. package/notices/opentui-spinner-MIT.txt +27 -0
  12. package/notices/packages__http-recorder__LICENSE +21 -0
  13. package/notices/remeda-LICENSE +21 -0
  14. package/notices/runtime-sources.json +7081 -0
  15. package/notices/seq-queue-LICENSE +22 -0
  16. package/notices/supplemental-notices.json +61 -0
  17. package/notices/third-party-source-LICENSE +21 -0
  18. package/package.json +65 -4
  19. package/src/agents/commands.ts +67 -0
  20. package/src/agents/context/builtins.ts +47 -0
  21. package/src/agents/context/instructions.ts +92 -0
  22. package/src/agents/context/registry.ts +53 -0
  23. package/src/agents/context/system.ts +329 -0
  24. package/src/agents/questions.ts +219 -0
  25. package/src/agents/references/guidance.ts +71 -0
  26. package/src/agents/references/registry.ts +122 -0
  27. package/src/agents/registry.ts +108 -0
  28. package/src/agents/resources/client.ts +185 -0
  29. package/src/agents/resources/contract.ts +71 -0
  30. package/src/agents/resources/error.ts +7 -0
  31. package/src/agents/skills/discovery.ts +167 -0
  32. package/src/agents/skills/guidance.ts +76 -0
  33. package/src/agents/skills/registry.ts +131 -0
  34. package/src/contracts/agents/agent.ts +36 -0
  35. package/src/contracts/agents/command.ts +14 -0
  36. package/src/contracts/agents/question-compat.ts +66 -0
  37. package/src/contracts/agents/question.ts +79 -0
  38. package/src/contracts/agents/reference.ts +36 -0
  39. package/src/contracts/agents/skill.ts +54 -0
  40. package/src/contracts/events/durable-manifest.ts +10 -0
  41. package/src/contracts/events/event.ts +125 -0
  42. package/src/contracts/events/filesystem.ts +13 -0
  43. package/src/contracts/events/installation.ts +20 -0
  44. package/src/contracts/events/legacy.ts +18 -0
  45. package/src/contracts/events/manifest.ts +82 -0
  46. package/src/contracts/events/mcp.ts +21 -0
  47. package/src/contracts/events/server.ts +8 -0
  48. package/src/contracts/events/session-compaction.ts +13 -0
  49. package/src/contracts/events/session-status.ts +50 -0
  50. package/src/contracts/events/session.ts +734 -0
  51. package/src/contracts/events/tui.ts +58 -0
  52. package/src/contracts/events/vcs.ts +13 -0
  53. package/src/contracts/events/workspace.ts +32 -0
  54. package/src/contracts/events/worktree.ts +21 -0
  55. package/src/contracts/execution/terminal-ticket.ts +9 -0
  56. package/src/contracts/execution/terminal.ts +55 -0
  57. package/src/contracts/execution/verification-receipt.ts +281 -0
  58. package/src/contracts/extensions/connection.ts +22 -0
  59. package/src/contracts/extensions/integration-id.ts +7 -0
  60. package/src/contracts/extensions/integration.ts +128 -0
  61. package/src/contracts/extensions/plugin.ts +15 -0
  62. package/src/contracts/identifier.ts +30 -0
  63. package/src/contracts/inference/catalog.ts +6 -0
  64. package/src/contracts/inference/llm.ts +23 -0
  65. package/src/contracts/inference/model.ts +103 -0
  66. package/src/contracts/inference/models-dev.ts +9 -0
  67. package/src/contracts/inference/provider.ts +69 -0
  68. package/src/contracts/schema.ts +30 -0
  69. package/src/contracts/security/credential.ts +34 -0
  70. package/src/contracts/security/permission-compat.ts +71 -0
  71. package/src/contracts/security/permission-saved.ts +20 -0
  72. package/src/contracts/security/permission.ts +64 -0
  73. package/src/contracts/session/compat.ts +676 -0
  74. package/src/contracts/session/delivery.ts +6 -0
  75. package/src/contracts/session/id.ts +20 -0
  76. package/src/contracts/session/info.ts +52 -0
  77. package/src/contracts/session/input-origin.ts +43 -0
  78. package/src/contracts/session/input.ts +24 -0
  79. package/src/contracts/session/live.ts +43 -0
  80. package/src/contracts/session/message-id.ts +11 -0
  81. package/src/contracts/session/message.ts +206 -0
  82. package/src/contracts/session/prompt.ts +56 -0
  83. package/src/contracts/session/revert.ts +23 -0
  84. package/src/contracts/session/run-state.ts +109 -0
  85. package/src/contracts/session/todo.ts +24 -0
  86. package/src/contracts/workspace/file-diff.ts +12 -0
  87. package/src/contracts/workspace/filesystem.ts +39 -0
  88. package/src/contracts/workspace/location.ts +30 -0
  89. package/src/contracts/workspace/project-copy.ts +29 -0
  90. package/src/contracts/workspace/project-directories.ts +11 -0
  91. package/src/contracts/workspace/project-id.ts +8 -0
  92. package/src/contracts/workspace/project.ts +41 -0
  93. package/src/contracts/workspace/workspace-id.ts +19 -0
  94. package/src/contracts/workspace/workspace.ts +9 -0
  95. package/src/execution/commands/executor.ts +44 -0
  96. package/src/execution/commands/provider.ts +54 -0
  97. package/src/execution/commands/runner.ts +26 -0
  98. package/src/execution/control/command.ts +55 -0
  99. package/src/execution/control/grant.ts +123 -0
  100. package/src/execution/control/promotion.ts +113 -0
  101. package/src/execution/control/receiver.ts +153 -0
  102. package/src/execution/control/restoration.ts +264 -0
  103. package/src/execution/identity.ts +432 -0
  104. package/src/execution/process/runner.ts +243 -0
  105. package/src/execution/process/sessions.ts +239 -0
  106. package/src/execution/process/spawner.ts +508 -0
  107. package/src/execution/sandbox.ts +143 -0
  108. package/src/execution/shell.ts +226 -0
  109. package/src/execution/terminal/native.ts +26 -0
  110. package/src/execution/terminal/protocol.ts +37 -0
  111. package/src/execution/terminal/schema.ts +1 -0
  112. package/src/execution/terminal/service.ts +318 -0
  113. package/src/execution/terminal/ticket.ts +57 -0
  114. package/src/execution/terminal/types.ts +25 -0
  115. package/src/extensions/agents.ts +211 -0
  116. package/src/extensions/api/agent.ts +14 -0
  117. package/src/extensions/api/catalog.ts +29 -0
  118. package/src/extensions/api/command.ts +13 -0
  119. package/src/extensions/api/context.ts +27 -0
  120. package/src/extensions/api/integration.ts +63 -0
  121. package/src/extensions/api/plugin.ts +17 -0
  122. package/src/extensions/api/reference.ts +12 -0
  123. package/src/extensions/api/registration.ts +16 -0
  124. package/src/extensions/api/skill.ts +11 -0
  125. package/src/extensions/api/tool.ts +58 -0
  126. package/src/extensions/api.ts +6 -0
  127. package/src/extensions/definition.ts +13 -0
  128. package/src/extensions/host.ts +225 -0
  129. package/src/extensions/integrations/service.ts +517 -0
  130. package/src/extensions/internal.ts +117 -0
  131. package/src/extensions/mcp/local.ts +352 -0
  132. package/src/extensions/mcp/schema.ts +21 -0
  133. package/src/extensions/mcp/tool-names.ts +26 -0
  134. package/src/extensions/mcp/tool.ts +149 -0
  135. package/src/extensions/models-dev.ts +135 -0
  136. package/src/extensions/options.ts +1 -0
  137. package/src/extensions/service.ts +152 -0
  138. package/src/extensions/skills/customize-phins.md +106 -0
  139. package/src/extensions/skills.ts +31 -0
  140. package/src/extensions/tools.ts +88 -0
  141. package/src/inference/api.ts +34 -0
  142. package/src/inference/cache-policy.ts +111 -0
  143. package/src/inference/catalog/discovery.ts +163 -0
  144. package/src/inference/catalog/metadata.ts +249 -0
  145. package/src/inference/catalog/model.ts +41 -0
  146. package/src/inference/catalog/provider.ts +25 -0
  147. package/src/inference/catalog/registry.ts +437 -0
  148. package/src/inference/errors.ts +32 -0
  149. package/src/inference/protocols/openai-chat.ts +497 -0
  150. package/src/inference/protocols/openai-compatible-chat.ts +24 -0
  151. package/src/inference/protocols/shared.ts +483 -0
  152. package/src/inference/protocols/utils/lifecycle.ts +102 -0
  153. package/src/inference/protocols/utils/openai-options.ts +93 -0
  154. package/src/inference/protocols/utils/tool-stream.ts +214 -0
  155. package/src/inference/provider.ts +37 -0
  156. package/src/inference/request/api.ts +27 -0
  157. package/src/inference/request/auth-options.ts +57 -0
  158. package/src/inference/request/auth.ts +161 -0
  159. package/src/inference/request/client.ts +490 -0
  160. package/src/inference/request/endpoint.ts +55 -0
  161. package/src/inference/request/execution-boundary.ts +41 -0
  162. package/src/inference/request/executor.ts +478 -0
  163. package/src/inference/request/framing.ts +27 -0
  164. package/src/inference/request/protocol.ts +90 -0
  165. package/src/inference/request/spending.ts +159 -0
  166. package/src/inference/requests.ts +193 -0
  167. package/src/inference/schema/errors.ts +194 -0
  168. package/src/inference/schema/events.ts +372 -0
  169. package/src/inference/schema/ids.ts +43 -0
  170. package/src/inference/schema/messages.ts +312 -0
  171. package/src/inference/schema/options.ts +247 -0
  172. package/src/inference/schema.ts +5 -0
  173. package/src/inference/tools/definition.ts +253 -0
  174. package/src/inference/tools/dispatcher.ts +83 -0
  175. package/src/inference/tools/failure.ts +19 -0
  176. package/src/inference/transports/http.ts +115 -0
  177. package/src/inference/transports/transport.ts +34 -0
  178. package/src/inference/transports/websocket.ts +322 -0
  179. package/src/runtime/effect/keyed-mutex.ts +45 -0
  180. package/src/runtime/effect/platform.ts +12 -0
  181. package/src/runtime/effect/service-access.ts +43 -0
  182. package/src/runtime/effect/service-graph.ts +102 -0
  183. package/src/runtime/events/bus.ts +1222 -0
  184. package/src/runtime/events/session-deltas.ts +128 -0
  185. package/src/runtime/events/verification-publisher.ts +9 -0
  186. package/src/runtime/flags.ts +78 -0
  187. package/src/runtime/markdown.d.ts +4 -0
  188. package/src/runtime/paths.ts +87 -0
  189. package/src/runtime/services.ts +240 -0
  190. package/src/runtime/state.ts +128 -0
  191. package/src/runtime/vendor.d.ts +25 -0
  192. package/src/runtime/version.ts +8 -0
  193. package/src/security/credentials.ts +137 -0
  194. package/src/security/launcher-policy.ts +68 -0
  195. package/src/security/permissions/delegation.ts +32 -0
  196. package/src/security/permissions/origin.ts +70 -0
  197. package/src/security/permissions/saved.ts +78 -0
  198. package/src/security/permissions/service.ts +533 -0
  199. package/src/security/policy.ts +46 -0
  200. package/src/sessions/actions/administration.ts +109 -0
  201. package/src/sessions/actions/command-template.ts +23 -0
  202. package/src/sessions/actions/commands.ts +258 -0
  203. package/src/sessions/actions/errors.ts +16 -0
  204. package/src/sessions/actions/operations.ts +271 -0
  205. package/src/sessions/actions/revert.ts +121 -0
  206. package/src/sessions/context/checkpoint.ts +330 -0
  207. package/src/sessions/context/compaction.ts +268 -0
  208. package/src/sessions/context/epoch.ts +173 -0
  209. package/src/sessions/context/selection.ts +30 -0
  210. package/src/sessions/errors.ts +38 -0
  211. package/src/sessions/identifiers.ts +25 -0
  212. package/src/sessions/info.ts +90 -0
  213. package/src/sessions/input/inbox.ts +514 -0
  214. package/src/sessions/input/origin.ts +131 -0
  215. package/src/sessions/input/turns.ts +125 -0
  216. package/src/sessions/messages/history.ts +101 -0
  217. package/src/sessions/messages/service.ts +2 -0
  218. package/src/sessions/messages/updater.ts +420 -0
  219. package/src/sessions/projector.ts +699 -0
  220. package/src/sessions/run/budget.ts +62 -0
  221. package/src/sessions/run/chat-scope.ts +62 -0
  222. package/src/sessions/run/coding-workflow.ts +82 -0
  223. package/src/sessions/run/coordinator.ts +192 -0
  224. package/src/sessions/run/events.ts +572 -0
  225. package/src/sessions/run/execution.ts +57 -0
  226. package/src/sessions/run/inference.ts +1466 -0
  227. package/src/sessions/run/lifecycle.ts +316 -0
  228. package/src/sessions/run/local-executor.ts +307 -0
  229. package/src/sessions/run/loop.ts +33 -0
  230. package/src/sessions/run/messages.ts +161 -0
  231. package/src/sessions/run/model.ts +232 -0
  232. package/src/sessions/run/state.ts +288 -0
  233. package/src/sessions/run/subtasks.ts +190 -0
  234. package/src/sessions/runtime.ts +40 -0
  235. package/src/sessions/service.ts +686 -0
  236. package/src/sessions/store.ts +129 -0
  237. package/src/sessions/tasks.ts +78 -0
  238. package/src/sessions/title.ts +23 -0
  239. package/src/sessions/usage/contribution-value.ts +48 -0
  240. package/src/sessions/usage/contribution.ts +511 -0
  241. package/src/sessions/usage/cost.ts +21 -0
  242. package/src/sessions/verification/history.ts +79 -0
  243. package/src/sessions/verification/recovery.ts +971 -0
  244. package/src/sessions/verification/service.ts +671 -0
  245. package/src/settings/agents.ts +23 -0
  246. package/src/settings/attachments.ts +15 -0
  247. package/src/settings/commands.ts +12 -0
  248. package/src/settings/compaction.ts +15 -0
  249. package/src/settings/config.ts +234 -0
  250. package/src/settings/experimental.ts +18 -0
  251. package/src/settings/formatters.ts +12 -0
  252. package/src/settings/markdown.ts +36 -0
  253. package/src/settings/mcp.ts +39 -0
  254. package/src/settings/plugins/agent.ts +108 -0
  255. package/src/settings/plugins/command.ts +82 -0
  256. package/src/settings/plugins/provider.ts +113 -0
  257. package/src/settings/plugins/reference.ts +68 -0
  258. package/src/settings/plugins/skill.ts +50 -0
  259. package/src/settings/plugins.ts +13 -0
  260. package/src/settings/providers.ts +71 -0
  261. package/src/settings/references.ts +22 -0
  262. package/src/settings/tool-output.ts +9 -0
  263. package/src/settings/watchers.ts +7 -0
  264. package/src/shared/effect-flock.ts +93 -0
  265. package/src/shared/encode.ts +51 -0
  266. package/src/shared/flock.ts +584 -0
  267. package/src/shared/glob.ts +34 -0
  268. package/src/shared/hash.ts +11 -0
  269. package/src/shared/lazy.ts +26 -0
  270. package/src/shared/prefixed-id.ts +47 -0
  271. package/src/shared/record.ts +3 -0
  272. package/src/shared/schema.ts +87 -0
  273. package/src/shared/slug.ts +74 -0
  274. package/src/shared/token.ts +5 -0
  275. package/src/shared/which.ts +14 -0
  276. package/src/shared/wildcard.ts +48 -0
  277. package/src/storage/database.ts +63 -0
  278. package/src/storage/drizzle/effect-sqlite/driver.ts +77 -0
  279. package/src/storage/drizzle/effect-sqlite/migrator.ts +14 -0
  280. package/src/storage/drizzle/effect-sqlite/session.ts +218 -0
  281. package/src/storage/drizzle/index.ts +10 -0
  282. package/src/storage/drizzle/internal/drizzle-utils.ts +127 -0
  283. package/src/storage/drizzle/sqlite-core/effect/count.ts +58 -0
  284. package/src/storage/drizzle/sqlite-core/effect/db.ts +296 -0
  285. package/src/storage/drizzle/sqlite-core/effect/delete.ts +261 -0
  286. package/src/storage/drizzle/sqlite-core/effect/insert.ts +349 -0
  287. package/src/storage/drizzle/sqlite-core/effect/query.ts +198 -0
  288. package/src/storage/drizzle/sqlite-core/effect/raw.ts +49 -0
  289. package/src/storage/drizzle/sqlite-core/effect/select.ts +279 -0
  290. package/src/storage/drizzle/sqlite-core/effect/session.ts +490 -0
  291. package/src/storage/drizzle/sqlite-core/effect/update.ts +402 -0
  292. package/src/storage/drizzle/up-migrations/effect-sqlite.ts +102 -0
  293. package/src/storage/drizzle/up-migrations/sqlite.ts +253 -0
  294. package/src/storage/drizzle/up-migrations/utils.ts +45 -0
  295. package/src/storage/migration.gen.ts +62 -0
  296. package/src/storage/migration.ts +168 -0
  297. package/src/storage/migrations/20260127222353_familiar_lady_ursula.ts +107 -0
  298. package/src/storage/migrations/20260211171708_add_project_commands.ts +11 -0
  299. package/src/storage/migrations/20260213144116_wakeful_the_professor.ts +23 -0
  300. package/src/storage/migrations/20260225215848_workspace.ts +19 -0
  301. package/src/storage/migrations/20260227213759_add_session_workspace_id.ts +12 -0
  302. package/src/storage/migrations/20260228203230_blue_harpoon.ts +30 -0
  303. package/src/storage/migrations/20260303231226_add_workspace_fields.ts +15 -0
  304. package/src/storage/migrations/20260309230000_move_org_to_state.ts +15 -0
  305. package/src/storage/migrations/20260312043431_session_message_cursor.ts +16 -0
  306. package/src/storage/migrations/20260323234822_events.ts +26 -0
  307. package/src/storage/migrations/20260410174513_workspace-name.ts +29 -0
  308. package/src/storage/migrations/20260413175956_chief_energizer.ts +24 -0
  309. package/src/storage/migrations/20260423070820_add_icon_url_override.ts +14 -0
  310. package/src/storage/migrations/20260427172553_slow_nightmare.ts +30 -0
  311. package/src/storage/migrations/20260428004200_add_session_path.ts +11 -0
  312. package/src/storage/migrations/20260501142318_next_venus.ts +12 -0
  313. package/src/storage/migrations/20260504145000_add_sync_owner.ts +11 -0
  314. package/src/storage/migrations/20260507164347_add_workspace_time.ts +11 -0
  315. package/src/storage/migrations/20260510033149_session_usage.ts +56 -0
  316. package/src/storage/migrations/20260511000411_data_migration_state.ts +16 -0
  317. package/src/storage/migrations/20260511173437_session-metadata.ts +16 -0
  318. package/src/storage/migrations/20260601010001_normalize_storage_paths.ts +22 -0
  319. package/src/storage/migrations/20260601202201_amazing_prowler.ts +11 -0
  320. package/src/storage/migrations/20260602002951_lowly_union_jack.ts +24 -0
  321. package/src/storage/migrations/20260602182828_add_project_directories.ts +20 -0
  322. package/src/storage/migrations/20260603001617_session_message_projection_indexes.ts +19 -0
  323. package/src/storage/migrations/20260603040000_session_message_projection_order.ts +19 -0
  324. package/src/storage/migrations/20260603141458_session_input_inbox.ts +25 -0
  325. package/src/storage/migrations/20260603160727_jittery_ezekiel_stane.ts +20 -0
  326. package/src/storage/migrations/20260604172448_event_sourced_session_input.ts +47 -0
  327. package/src/storage/migrations/20260605003541_add_session_context_snapshot.ts +21 -0
  328. package/src/storage/migrations/20260605042240_add_context_epoch_agent.ts +11 -0
  329. package/src/storage/migrations/20260611035744_credential.ts +25 -0
  330. package/src/storage/migrations/20260611192811_lush_chimera.ts +25 -0
  331. package/src/storage/migrations/20260612174303_project_dir_strategy.ts +29 -0
  332. package/src/storage/migrations/20260622142730_simplify_session_context_epoch.ts +13 -0
  333. package/src/storage/migrations/20260622170816_reset_v2_session_state.ts +17 -0
  334. package/src/storage/migrations/20260622202450_simplify_session_input.ts +17 -0
  335. package/src/storage/migrations/20260722030810_rolling_work_context_epoch.ts +44 -0
  336. package/src/storage/migrations/20260729010558_verification_receipt.ts +45 -0
  337. package/src/storage/migrations/20260729040943_verification_request_outbox.ts +35 -0
  338. package/src/storage/migrations/20260731015112_verification_attempt_lease.ts +16 -0
  339. package/src/storage/migrations/20260731022945_verification_attempt_timeout.ts +11 -0
  340. package/src/storage/migrations/20260731023300_event_owner_generation.ts +11 -0
  341. package/src/storage/migrations/20260731031224_session_warp_outbox.ts +38 -0
  342. package/src/storage/migrations/20260731073410_workspace-mutation-lease.ts +28 -0
  343. package/src/storage/migrations/20260731074831_verification-execution-attestation.ts +11 -0
  344. package/src/storage/migrations/20260731081000_workspace-session-mutation-fences.ts +67 -0
  345. package/src/storage/migrations/20260801155612_session_run_state.ts +33 -0
  346. package/src/storage/migrations/20260801162000_session_usage_contribution.ts +46 -0
  347. package/src/storage/migrations/20260801163000_backfill_session_transcript.ts +551 -0
  348. package/src/storage/migrations/20260913045944_session_tree_budget.ts +20 -0
  349. package/src/storage/migrations/20261005065909_session_input_origin.ts +25 -0
  350. package/src/storage/migrations/20261005143808_session_run_input_owner.ts +13 -0
  351. package/src/storage/migrations/20261006020515_node_command_receipt.ts +19 -0
  352. package/src/storage/migrations/20261009151628_session_command_receipt.ts +21 -0
  353. package/src/storage/offline.ts +34 -0
  354. package/src/storage/path.ts +91 -0
  355. package/src/storage/schema.gen.ts +490 -0
  356. package/src/storage/schema.sql.ts +10 -0
  357. package/src/storage/sqlite.bun.ts +195 -0
  358. package/src/storage/sqlite.ts +8 -0
  359. package/src/storage/tables/commands.ts +19 -0
  360. package/src/storage/tables/credentials.ts +14 -0
  361. package/src/storage/tables/events.ts +26 -0
  362. package/src/storage/tables/permissions.ts +20 -0
  363. package/src/storage/tables/projects.ts +35 -0
  364. package/src/storage/tables/sessions.ts +358 -0
  365. package/src/storage/tables/workspaces.ts +87 -0
  366. package/src/tools/admission.ts +29 -0
  367. package/src/tools/application.ts +54 -0
  368. package/src/tools/builtins.ts +50 -0
  369. package/src/tools/definition.ts +198 -0
  370. package/src/tools/files/edit.ts +200 -0
  371. package/src/tools/files/format.ts +46 -0
  372. package/src/tools/files/glob.ts +102 -0
  373. package/src/tools/files/grep.ts +134 -0
  374. package/src/tools/files/patch.ts +179 -0
  375. package/src/tools/files/read.ts +146 -0
  376. package/src/tools/files/reader.ts +363 -0
  377. package/src/tools/files/write.ts +94 -0
  378. package/src/tools/output-store.ts +217 -0
  379. package/src/tools/planning.ts +56 -0
  380. package/src/tools/process/session.ts +44 -0
  381. package/src/tools/process/shell.ts +271 -0
  382. package/src/tools/question.ts +107 -0
  383. package/src/tools/registration.ts +13 -0
  384. package/src/tools/registry.ts +248 -0
  385. package/src/tools/skill.ts +103 -0
  386. package/src/tools/task.ts +100 -0
  387. package/src/tools/web/body.ts +30 -0
  388. package/src/tools/web/fetch.ts +211 -0
  389. package/src/tools/web/search.ts +253 -0
  390. package/src/transport/api/definition.ts +103 -0
  391. package/src/transport/api/errors.ts +112 -0
  392. package/src/transport/api/middleware/authorization.ts +7 -0
  393. package/src/transport/api/middleware/schema-error.ts +8 -0
  394. package/src/transport/api/middleware/service-admission.ts +8 -0
  395. package/src/transport/api/resources/agent.ts +21 -0
  396. package/src/transport/api/resources/command.ts +28 -0
  397. package/src/transport/api/resources/credential.ts +38 -0
  398. package/src/transport/api/resources/event.ts +61 -0
  399. package/src/transport/api/resources/fs.ts +69 -0
  400. package/src/transport/api/resources/health.ts +65 -0
  401. package/src/transport/api/resources/integration.ts +131 -0
  402. package/src/transport/api/resources/location.ts +43 -0
  403. package/src/transport/api/resources/message.ts +69 -0
  404. package/src/transport/api/resources/model.ts +33 -0
  405. package/src/transport/api/resources/permission.ts +96 -0
  406. package/src/transport/api/resources/project-copy.ts +57 -0
  407. package/src/transport/api/resources/project.ts +19 -0
  408. package/src/transport/api/resources/provider.ts +46 -0
  409. package/src/transport/api/resources/pty.ts +143 -0
  410. package/src/transport/api/resources/question.ts +85 -0
  411. package/src/transport/api/resources/reference.ts +28 -0
  412. package/src/transport/api/resources/service.ts +46 -0
  413. package/src/transport/api/resources/session.ts +477 -0
  414. package/src/transport/api/resources/skill.ts +28 -0
  415. package/src/transport/api/resources/tui.ts +100 -0
  416. package/src/transport/client/connection.ts +389 -0
  417. package/src/transport/client/create.ts +112 -0
  418. package/src/transport/client/errors.ts +51 -0
  419. package/src/transport/client/events.ts +218 -0
  420. package/src/transport/client/generated/client/client.gen.ts +311 -0
  421. package/src/transport/client/generated/client/index.ts +25 -0
  422. package/src/transport/client/generated/client/types.gen.ts +241 -0
  423. package/src/transport/client/generated/client/utils.gen.ts +337 -0
  424. package/src/transport/client/generated/client.gen.ts +25 -0
  425. package/src/transport/client/generated/core/auth.gen.ts +42 -0
  426. package/src/transport/client/generated/core/bodySerializer.gen.ts +100 -0
  427. package/src/transport/client/generated/core/params.gen.ts +176 -0
  428. package/src/transport/client/generated/core/pathSerializer.gen.ts +181 -0
  429. package/src/transport/client/generated/core/queryKeySerializer.gen.ts +136 -0
  430. package/src/transport/client/generated/core/serverSentEvents.gen.ts +266 -0
  431. package/src/transport/client/generated/core/types.gen.ts +118 -0
  432. package/src/transport/client/generated/core/utils.gen.ts +143 -0
  433. package/src/transport/client/generated/sdk.gen.ts +6695 -0
  434. package/src/transport/client/generated/types.gen.ts +16571 -0
  435. package/src/transport/client/session-state.ts +341 -0
  436. package/src/transport/host/api.ts +9 -0
  437. package/src/transport/host/auth.ts +64 -0
  438. package/src/transport/host/cors.ts +35 -0
  439. package/src/transport/host/handlers/agent.ts +14 -0
  440. package/src/transport/host/handlers/command.ts +9 -0
  441. package/src/transport/host/handlers/credential.ts +23 -0
  442. package/src/transport/host/handlers/event.ts +39 -0
  443. package/src/transport/host/handlers/fs.ts +40 -0
  444. package/src/transport/host/handlers/health.ts +11 -0
  445. package/src/transport/host/handlers/integration.ts +105 -0
  446. package/src/transport/host/handlers/location.ts +19 -0
  447. package/src/transport/host/handlers/message.ts +65 -0
  448. package/src/transport/host/handlers/model.ts +25 -0
  449. package/src/transport/host/handlers/permission.ts +68 -0
  450. package/src/transport/host/handlers/project-copy.ts +69 -0
  451. package/src/transport/host/handlers/project.ts +32 -0
  452. package/src/transport/host/handlers/provider.ts +33 -0
  453. package/src/transport/host/handlers/pty.ts +224 -0
  454. package/src/transport/host/handlers/question.ts +63 -0
  455. package/src/transport/host/handlers/reference.ts +9 -0
  456. package/src/transport/host/handlers/service.ts +24 -0
  457. package/src/transport/host/handlers/session.ts +581 -0
  458. package/src/transport/host/handlers/skill.ts +9 -0
  459. package/src/transport/host/handlers/tui.ts +136 -0
  460. package/src/transport/host/handlers.ts +68 -0
  461. package/src/transport/host/location.ts +66 -0
  462. package/src/transport/host/middleware/authorization.ts +59 -0
  463. package/src/transport/host/middleware/schema-error.ts +17 -0
  464. package/src/transport/host/middleware/service-admission.ts +22 -0
  465. package/src/transport/host/middleware/session-location.ts +72 -0
  466. package/src/transport/host/pty-environment.ts +17 -0
  467. package/src/transport/host/routes.ts +67 -0
  468. package/src/transport/host/runtime.ts +22 -0
  469. package/src/transport/host/service-control.ts +143 -0
  470. package/src/transport/host/sse.ts +415 -0
  471. package/src/transport/host/utf8.ts +26 -0
  472. package/src/verification/authority.ts +547 -0
  473. package/src/verification/canonical-signature.ts +145 -0
  474. package/src/verification/containment.ts +197 -0
  475. package/src/verification/enforcement.ts +255 -0
  476. package/src/verification/execution-attestation.ts +321 -0
  477. package/src/verification/key-lifecycle.ts +456 -0
  478. package/src/verification/local.ts +87 -0
  479. package/src/verification/oci/containment.ts +529 -0
  480. package/src/verification/oci/lease.ts +1549 -0
  481. package/src/verification/oci/runtime.ts +309 -0
  482. package/src/verification/oci/supervisor.ts +429 -0
  483. package/src/verification/registry.ts +379 -0
  484. package/src/verification/settlement-admission.ts +322 -0
  485. package/src/verification/trusted-file.ts +372 -0
  486. package/src/workspace/files/access.ts +257 -0
  487. package/src/workspace/files/diff.ts +6 -0
  488. package/src/workspace/files/formatter.ts +130 -0
  489. package/src/workspace/files/ignore.ts +67 -0
  490. package/src/workspace/files/mutation.ts +203 -0
  491. package/src/workspace/files/patch.ts +197 -0
  492. package/src/workspace/files/protected.ts +53 -0
  493. package/src/workspace/files/service.ts +115 -0
  494. package/src/workspace/files/watcher.ts +138 -0
  495. package/src/workspace/location.ts +35 -0
  496. package/src/workspace/media/image.ts +78 -0
  497. package/src/workspace/media/photon.ts +95 -0
  498. package/src/workspace/mutations.ts +158 -0
  499. package/src/workspace/projects/copy-strategies.ts +35 -0
  500. package/src/workspace/projects/copy.ts +282 -0
  501. package/src/workspace/projects/directories.ts +159 -0
  502. package/src/workspace/projects/schema.ts +16 -0
  503. package/src/workspace/projects/service.ts +136 -0
  504. package/src/workspace/repository/cache.ts +261 -0
  505. package/src/workspace/repository/git.ts +4272 -0
  506. package/src/workspace/repository/reference.ts +217 -0
  507. package/src/workspace/repository/retention-barrier.ts +18 -0
  508. package/src/workspace/repository/snapshot.ts +791 -0
  509. package/src/workspace/search/binary.ts +134 -0
  510. package/src/workspace/search/native.ts +140 -0
  511. package/src/workspace/search/ripgrep.ts +282 -0
  512. package/src/workspace/search/service.ts +239 -0
@@ -0,0 +1,1222 @@
1
+ export * as EventBus from "./bus"
2
+
3
+ import { Cause, Context, Effect, Layer, Option, PubSub, Schema, Stream } from "effect"
4
+ import { Event } from "../../contracts/events/event"
5
+ import type { Data, Definition, Payload } from "../../contracts/events/event"
6
+ import { and, asc, eq, gt, isNull, ne, or, sql } from "drizzle-orm"
7
+ import { Database } from "../../storage/database"
8
+ import { EventSequenceTable, EventTable } from "../../storage/tables/events"
9
+ import { Location } from "../../workspace/location"
10
+ import { ServiceGraph } from "../effect/service-graph"
11
+ import { isDeepStrictEqual } from "node:util"
12
+ import { Durable } from "../../contracts/events/durable-manifest"
13
+ import { SessionEvent } from "../../contracts/events/session"
14
+ import { SessionLive } from "../../contracts/session/live"
15
+ import { SessionID } from "../../contracts/session/id"
16
+ import * as SessionDeltas from "./session-deltas"
17
+
18
+ export const ID = Event.ID
19
+ export type ID = import("../../contracts/events/event").ID
20
+ export type { Data, Definition, Payload } from "../../contracts/events/event"
21
+
22
+ export type Subscriber<D extends Definition = Definition> = (event: Payload<D>) => Effect.Effect<void>
23
+ export type Unsubscribe = Effect.Effect<void>
24
+
25
+ export const latestSequence = Effect.fn("EventV2.latestSequence")(function* (
26
+ db: Database.Interface["db"],
27
+ aggregateID: string,
28
+ ) {
29
+ const row = yield* db
30
+ .select({ seq: EventSequenceTable.seq })
31
+ .from(EventSequenceTable)
32
+ .where(eq(EventSequenceTable.aggregate_id, aggregateID))
33
+ .get()
34
+ .pipe(Effect.orDie)
35
+ return row?.seq ?? -1
36
+ })
37
+
38
+ export type SerializedEvent = {
39
+ readonly id: ID
40
+ readonly type: string
41
+ readonly seq: number
42
+ readonly aggregateID: string
43
+ readonly data: Record<string, unknown>
44
+ }
45
+
46
+ export class InvalidDurableEventError extends Schema.TaggedErrorClass<InvalidDurableEventError>()(
47
+ "EventV2.InvalidDurableEvent",
48
+ {
49
+ type: Schema.String,
50
+ message: Schema.String,
51
+ },
52
+ ) {}
53
+
54
+ export class UnauthorizedEventOperationError extends Schema.TaggedErrorClass<UnauthorizedEventOperationError>()(
55
+ "EventV2.UnauthorizedOperation",
56
+ {
57
+ operation: Schema.Literals(["publish", "replay"]),
58
+ type: Schema.String,
59
+ message: Schema.String,
60
+ },
61
+ ) {}
62
+
63
+ export const define = Event.define
64
+ export const versionedType = Event.versionedType
65
+
66
+ export interface PublishOptions {
67
+ readonly id?: ID
68
+ readonly metadata?: Record<string, unknown>
69
+ readonly location?: Location.Ref
70
+ /** Local operational projection committed atomically with a new durable event. Not replayed or serialized. */
71
+ readonly commit?: (seq: number) => Effect.Effect<void>
72
+ }
73
+
74
+ export interface PublishBatchOptions {
75
+ readonly id?: ID
76
+ readonly metadata?: Record<string, unknown>
77
+ readonly location?: Location.Ref
78
+ }
79
+
80
+ export interface PublishBatchItem<D extends Definition = Definition> {
81
+ readonly definition: D
82
+ readonly data: Data<D>
83
+ readonly options?: PublishBatchOptions
84
+ }
85
+
86
+ export const MAX_ATOMIC_BATCH_EVENTS = 256
87
+
88
+ export interface ReplayOptions {
89
+ readonly publish?: boolean
90
+ readonly ownerID?: string
91
+ readonly strictOwner?: boolean
92
+ /** Rotate ownership only when this exact durable event commits. */
93
+ readonly ownerRotation?: {
94
+ readonly eventID: ID
95
+ readonly nextOwnerID: string
96
+ }
97
+ }
98
+
99
+ export interface Interface {
100
+ readonly publish: <D extends Definition>(
101
+ definition: D,
102
+ data: Data<D>,
103
+ options?: PublishOptions,
104
+ ) => Effect.Effect<Payload<D>>
105
+ readonly publishBatch: (items: readonly PublishBatchItem[]) => Effect.Effect<readonly Payload[]>
106
+ readonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>>
107
+ readonly all: () => Stream.Stream<Payload>
108
+ readonly durable: (input: { readonly aggregateID: string; readonly after?: number }) => Stream.Stream<Payload>
109
+ readonly sessionDeltas: (sessionID: SessionID) => Stream.Stream<SessionLive.Frame>
110
+ /** @deprecated Use `all()` and consume the returned stream. */
111
+ readonly listen: (listener: Subscriber) => Effect.Effect<Unsubscribe>
112
+ readonly project: <D extends Definition>(definition: D, projector: Subscriber<D>) => Effect.Effect<void>
113
+ readonly replay: (event: SerializedEvent, options?: ReplayOptions) => Effect.Effect<void>
114
+ readonly replayAll: (events: SerializedEvent[], options?: ReplayOptions) => Effect.Effect<string | undefined>
115
+ readonly remove: (aggregateID: string) => Effect.Effect<void>
116
+ readonly claim: (aggregateID: string, ownerID: string) => Effect.Effect<void>
117
+ }
118
+
119
+ export class Service extends Context.Service<Service, Interface>()("@phins/Event") {}
120
+
121
+ export interface VerificationSettlementPublisherInterface {
122
+ readonly settle: (
123
+ data: Data<typeof SessionEvent.VerificationSettled>,
124
+ options?: PublishOptions,
125
+ ) => Effect.Effect<Payload<typeof SessionEvent.VerificationSettled>>
126
+ }
127
+
128
+ export class VerificationSettlementPublisherService extends Context.Service<
129
+ VerificationSettlementPublisherService,
130
+ VerificationSettlementPublisherInterface
131
+ >()("@phins/VerificationSettlementPublisher") {}
132
+
133
+ export interface ProtectedEventReplayInterface {
134
+ readonly replay: (event: SerializedEvent, options?: ReplayOptions) => Effect.Effect<void>
135
+ readonly replayAll: (events: SerializedEvent[], options?: ReplayOptions) => Effect.Effect<string | undefined>
136
+ }
137
+
138
+ export class ProtectedEventReplayService extends Context.Service<
139
+ ProtectedEventReplayService,
140
+ ProtectedEventReplayInterface
141
+ >()("@phins/ProtectedEventReplay") {}
142
+
143
+ const liveSettlementCapability = Object.freeze({})
144
+ const protectedReplayCapability = Object.freeze({})
145
+ const authorizedOperations = Symbol("@phins/Event/authorizedOperations")
146
+
147
+ interface AuthorizedOperations {
148
+ readonly publish: <D extends Definition>(
149
+ capability: object,
150
+ definition: D,
151
+ data: Data<D>,
152
+ options?: PublishOptions,
153
+ ) => Effect.Effect<Payload<D>>
154
+ readonly replay: (capability: object, event: SerializedEvent, options?: ReplayOptions) => Effect.Effect<void>
155
+ readonly replayAll: (
156
+ capability: object,
157
+ events: SerializedEvent[],
158
+ options?: ReplayOptions,
159
+ ) => Effect.Effect<string | undefined>
160
+ }
161
+
162
+ type InternalInterface = Interface & {
163
+ readonly [authorizedOperations]: AuthorizedOperations
164
+ }
165
+
166
+ type DefinitionSnapshot = {
167
+ readonly type: string
168
+ readonly durable:
169
+ | {
170
+ readonly version: number
171
+ readonly aggregate: string
172
+ }
173
+ | undefined
174
+ readonly data: Definition["data"]
175
+ }
176
+
177
+ type SerializedEventSnapshot = Readonly<SerializedEvent>
178
+
179
+ type ReplayOptionsSnapshot = {
180
+ readonly publish: boolean | undefined
181
+ readonly ownerID: string | undefined
182
+ readonly strictOwner: boolean | undefined
183
+ readonly ownerRotation:
184
+ | {
185
+ readonly eventID: ID
186
+ readonly nextOwnerID: string
187
+ }
188
+ | undefined
189
+ }
190
+
191
+ const snapshotDefinition = (definition: Definition): DefinitionSnapshot => {
192
+ const type: unknown = definition.type
193
+ if (typeof type !== "string") {
194
+ throw new InvalidDurableEventError({
195
+ type: "unknown",
196
+ message: "Event definition type must be a primitive string",
197
+ })
198
+ }
199
+ const durable: unknown = definition.durable
200
+ let durableSnapshot: DefinitionSnapshot["durable"]
201
+ if (durable !== undefined) {
202
+ if (typeof durable !== "object" || durable === null) {
203
+ throw new InvalidDurableEventError({
204
+ type,
205
+ message: "Durable event definition must be an object",
206
+ })
207
+ }
208
+ const version: unknown = (durable as { readonly version?: unknown }).version
209
+ const aggregate: unknown = (durable as { readonly aggregate?: unknown }).aggregate
210
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1) {
211
+ throw new InvalidDurableEventError({
212
+ type,
213
+ message: "Durable event version must be a positive safe integer",
214
+ })
215
+ }
216
+ if (typeof aggregate !== "string") {
217
+ throw new InvalidDurableEventError({
218
+ type,
219
+ message: "Durable event aggregate must be a primitive string",
220
+ })
221
+ }
222
+ durableSnapshot = { version, aggregate }
223
+ }
224
+ const data = definition.data
225
+ return {
226
+ type,
227
+ durable: durableSnapshot,
228
+ data,
229
+ }
230
+ }
231
+
232
+ const projectorKey = (definition: DefinitionSnapshot) =>
233
+ definition.durable
234
+ ? versionedType(definition.type, definition.durable.version)
235
+ : definition.type
236
+
237
+ const snapshotSerializedEvent = (event: SerializedEvent): SerializedEventSnapshot => {
238
+ const type: unknown = event.type
239
+ if (typeof type !== "string") {
240
+ throw new InvalidDurableEventError({
241
+ type: "unknown",
242
+ message: "Serialized event type must be a primitive string",
243
+ })
244
+ }
245
+ const id: unknown = event.id
246
+ if (typeof id !== "string" || !id.startsWith("evt_")) {
247
+ throw new InvalidDurableEventError({
248
+ type,
249
+ message: "Serialized event id must be a primitive event ID string",
250
+ })
251
+ }
252
+ const seq: unknown = event.seq
253
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) {
254
+ throw new InvalidDurableEventError({
255
+ type,
256
+ message: "Serialized event sequence must be a nonnegative safe integer",
257
+ })
258
+ }
259
+ const aggregateID: unknown = event.aggregateID
260
+ if (typeof aggregateID !== "string") {
261
+ throw new InvalidDurableEventError({
262
+ type,
263
+ message: "Serialized event aggregate ID must be a primitive string",
264
+ })
265
+ }
266
+ const data: unknown = event.data
267
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
268
+ throw new InvalidDurableEventError({
269
+ type,
270
+ message: "Serialized event data must be a record",
271
+ })
272
+ }
273
+ return {
274
+ id: id as ID,
275
+ type,
276
+ seq,
277
+ aggregateID,
278
+ data: data as Record<string, unknown>,
279
+ }
280
+ }
281
+
282
+ const snapshotSerializedEvents = (events: readonly SerializedEvent[]) => {
283
+ if (!Array.isArray(events)) {
284
+ throw new InvalidDurableEventError({
285
+ type: "unknown",
286
+ message: "Replay events must be an array",
287
+ })
288
+ }
289
+ const length: unknown = events.length
290
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0) {
291
+ throw new InvalidDurableEventError({
292
+ type: "unknown",
293
+ message: "Replay event array length must be a nonnegative safe integer",
294
+ })
295
+ }
296
+ const captured = new Array<SerializedEventSnapshot>()
297
+ for (let index = 0; index < length; index++) {
298
+ const event = events[index]
299
+ if (event === undefined) {
300
+ throw new InvalidDurableEventError({
301
+ type: captured[0]?.type ?? "unknown",
302
+ message: `Replay event is missing at index ${index}`,
303
+ })
304
+ }
305
+ captured.push(snapshotSerializedEvent(event))
306
+ }
307
+ return captured as readonly SerializedEventSnapshot[]
308
+ }
309
+
310
+ const snapshotReplayOptions = (options: ReplayOptions | undefined, type: string): ReplayOptionsSnapshot => {
311
+ if (options === undefined) {
312
+ return { publish: undefined, ownerID: undefined, strictOwner: undefined, ownerRotation: undefined }
313
+ }
314
+ if (typeof options !== "object" || options === null) {
315
+ throw new InvalidDurableEventError({ type, message: "Replay options must be an object" })
316
+ }
317
+ const publish: unknown = options.publish
318
+ const ownerID: unknown = options.ownerID
319
+ const strictOwner: unknown = options.strictOwner
320
+ const ownerRotation: unknown = options.ownerRotation
321
+ if (publish !== undefined && typeof publish !== "boolean") {
322
+ throw new InvalidDurableEventError({ type, message: "Replay publish option must be a boolean" })
323
+ }
324
+ if (ownerID !== undefined && typeof ownerID !== "string") {
325
+ throw new InvalidDurableEventError({ type, message: "Replay owner ID must be a primitive string" })
326
+ }
327
+ if (strictOwner !== undefined && typeof strictOwner !== "boolean") {
328
+ throw new InvalidDurableEventError({ type, message: "Replay strict-owner option must be a boolean" })
329
+ }
330
+ if (ownerRotation === undefined) {
331
+ return { publish, ownerID, strictOwner, ownerRotation: undefined }
332
+ }
333
+ if (typeof ownerRotation !== "object" || ownerRotation === null) {
334
+ throw new InvalidDurableEventError({ type, message: "Replay owner rotation must be an object" })
335
+ }
336
+ const eventID: unknown = (ownerRotation as { readonly eventID?: unknown }).eventID
337
+ const nextOwnerID: unknown = (ownerRotation as { readonly nextOwnerID?: unknown }).nextOwnerID
338
+ if (typeof eventID !== "string" || !eventID.startsWith("evt_")) {
339
+ throw new InvalidDurableEventError({ type, message: "Replay owner-rotation event ID must be an event ID string" })
340
+ }
341
+ if (typeof nextOwnerID !== "string") {
342
+ throw new InvalidDurableEventError({
343
+ type,
344
+ message: "Replay next-owner ID must be a primitive string",
345
+ })
346
+ }
347
+ return {
348
+ publish,
349
+ ownerID,
350
+ strictOwner,
351
+ ownerRotation: { eventID: eventID as ID, nextOwnerID },
352
+ }
353
+ }
354
+
355
+ const protectedLiveType = SessionEvent.VerificationSettled.type
356
+ const protectedReplayType = versionedType(
357
+ SessionEvent.VerificationSettled.type,
358
+ SessionEvent.VerificationSettled.durable!.version,
359
+ )
360
+
361
+ const assertPublishAuthority = (type: string, capability?: object) =>
362
+ type !== protectedLiveType || capability === liveSettlementCapability
363
+ ? Effect.void
364
+ : Effect.die(
365
+ new UnauthorizedEventOperationError({
366
+ operation: "publish",
367
+ type,
368
+ message: `Publishing protected event ${type} requires verification settlement authority`,
369
+ }),
370
+ )
371
+
372
+ const assertReplayAuthority = (type: string, capability?: object) =>
373
+ type !== protectedReplayType || capability === protectedReplayCapability
374
+ ? Effect.void
375
+ : Effect.die(
376
+ new UnauthorizedEventOperationError({
377
+ operation: "replay",
378
+ type,
379
+ message: `Replaying protected event ${type} requires protected replay authority`,
380
+ }),
381
+ )
382
+
383
+ const assertReplayAllAuthority = (events: readonly SerializedEventSnapshot[], capability?: object) => {
384
+ const protectedEvent = events.find((event) => event.type === protectedReplayType)
385
+ return protectedEvent ? assertReplayAuthority(protectedEvent.type, capability) : Effect.void
386
+ }
387
+
388
+ export interface LayerOptions {
389
+ readonly beforeAggregateRead?: (aggregateID: string) => Effect.Effect<void>
390
+ }
391
+
392
+ export const layerWith = (options?: LayerOptions) =>
393
+ Layer.effect(
394
+ Service,
395
+ Effect.gen(function* () {
396
+ const pubsub = {
397
+ all: yield* PubSub.unbounded<Payload>(),
398
+ durable: new Map<string, Set<PubSub.PubSub<void>>>(),
399
+ typed: new Map<string, PubSub.PubSub<Payload>>(),
400
+ }
401
+ const projectors = new Map<string, Subscriber[]>()
402
+ const listeners = new Array<Subscriber>()
403
+ const deltas = yield* SessionDeltas.make()
404
+ const { db } = yield* Database.Service
405
+
406
+ const getOrCreate = (definition: Definition) =>
407
+ Effect.gen(function* () {
408
+ const existing = pubsub.typed.get(definition.type)
409
+ if (existing) return existing
410
+ const created = yield* PubSub.unbounded<Payload>()
411
+ pubsub.typed.set(definition.type, created)
412
+ return created
413
+ })
414
+
415
+ yield* Effect.addFinalizer(() =>
416
+ Effect.gen(function* () {
417
+ yield* PubSub.shutdown(pubsub.all)
418
+ yield* Effect.forEach(
419
+ pubsub.durable.values(),
420
+ (pubsubs) => Effect.forEach(pubsubs, PubSub.shutdown, { discard: true }),
421
+ {
422
+ discard: true,
423
+ },
424
+ )
425
+ yield* Effect.forEach(pubsub.typed.values(), PubSub.shutdown, {
426
+ discard: true,
427
+ })
428
+ }),
429
+ )
430
+
431
+ function commitDurableEvent(
432
+ definition: DefinitionSnapshot,
433
+ event: Payload,
434
+ input?: {
435
+ readonly seq: number
436
+ readonly aggregateID: string
437
+ readonly ownerID?: string
438
+ readonly strictOwner?: boolean
439
+ readonly nextOwnerID?: string
440
+ },
441
+ commit?: (seq: number) => Effect.Effect<void>,
442
+ ) {
443
+ return Effect.gen(function* () {
444
+ const durable = definition?.durable
445
+ if (durable) {
446
+ const type = definition.type
447
+ const dataSchema = definition.data
448
+ const aggregateID = (event.data as Record<string, unknown>)[durable.aggregate]
449
+ if (typeof aggregateID !== "string") {
450
+ yield* Effect.die(
451
+ new InvalidDurableEventError({
452
+ type: event.type,
453
+ message: `Expected string aggregate field ${durable.aggregate}`,
454
+ }),
455
+ )
456
+ } else {
457
+ if (input && input.aggregateID !== aggregateID) {
458
+ yield* Effect.die(
459
+ new InvalidDurableEventError({
460
+ type: event.type,
461
+ message: `Aggregate mismatch: expected ${input.aggregateID}, got ${aggregateID}`,
462
+ }),
463
+ )
464
+ }
465
+ const list = projectors.get(projectorKey(definition)) ?? []
466
+ return yield* Effect.uninterruptible(
467
+ Effect.gen(function* () {
468
+ const committed = yield* db
469
+ .transaction(
470
+ () =>
471
+ Effect.gen(function* () {
472
+ const row = yield* db
473
+ .select({
474
+ seq: EventSequenceTable.seq,
475
+ ownerID: EventSequenceTable.owner_id,
476
+ })
477
+ .from(EventSequenceTable)
478
+ .where(eq(EventSequenceTable.aggregate_id, aggregateID))
479
+ .get()
480
+ .pipe(Effect.orDie)
481
+ const latest = row?.seq ?? -1
482
+ const encoded = Schema.encodeUnknownSync(dataSchema)(event.data) as Record<string, unknown>
483
+ if (input && input.seq <= latest) {
484
+ const stored = yield* db
485
+ .select()
486
+ .from(EventTable)
487
+ .where(and(eq(EventTable.aggregate_id, aggregateID), eq(EventTable.seq, input.seq)))
488
+ .get()
489
+ .pipe(Effect.orDie)
490
+ if (
491
+ stored?.id === event.id &&
492
+ stored.type === versionedType(type, durable.version) &&
493
+ isDeepStrictEqual(stored.data, encoded)
494
+ ) {
495
+ if (
496
+ input.nextOwnerID &&
497
+ input.strictOwner &&
498
+ row?.ownerID &&
499
+ row.ownerID !== input.ownerID &&
500
+ row.ownerID !== input.nextOwnerID
501
+ ) {
502
+ yield* Effect.die(
503
+ new InvalidDurableEventError({
504
+ type: event.type,
505
+ message: `Replay owner mismatch for aggregate ${aggregateID}: expected ${row.ownerID}, got ${input.ownerID ?? "none"}`,
506
+ }),
507
+ )
508
+ }
509
+ const replayOwnerID = input.nextOwnerID ?? input.ownerID
510
+ if (
511
+ replayOwnerID &&
512
+ row?.ownerID !== replayOwnerID &&
513
+ (row?.ownerID == null || row.ownerID === input.ownerID)
514
+ ) {
515
+ yield* db
516
+ .update(EventSequenceTable)
517
+ .set({
518
+ owner_id: replayOwnerID,
519
+ owner_generation: sql`${EventSequenceTable.owner_generation} + 1`,
520
+ })
521
+ .where(eq(EventSequenceTable.aggregate_id, aggregateID))
522
+ .run()
523
+ .pipe(Effect.orDie)
524
+ }
525
+ return
526
+ }
527
+ yield* Effect.die(
528
+ new InvalidDurableEventError({
529
+ type: event.type,
530
+ message: `Replay diverged at aggregate ${aggregateID} sequence ${input.seq}`,
531
+ }),
532
+ )
533
+ }
534
+ if (input?.strictOwner && row?.ownerID && row.ownerID !== input.ownerID) {
535
+ yield* Effect.die(
536
+ new InvalidDurableEventError({
537
+ type: event.type,
538
+ message: `Replay owner mismatch for aggregate ${aggregateID}: expected ${row.ownerID}, got ${input.ownerID ?? "none"}`,
539
+ }),
540
+ )
541
+ }
542
+ if (input && row?.ownerID && row.ownerID !== input.ownerID) {
543
+ return
544
+ }
545
+ const seq = input?.seq ?? latest + 1
546
+ if (input && seq !== latest + 1) {
547
+ yield* Effect.die(
548
+ new InvalidDurableEventError({
549
+ type: event.type,
550
+ message: `Sequence mismatch for aggregate ${aggregateID}: expected ${latest + 1}, got ${seq}`,
551
+ }),
552
+ )
553
+ }
554
+ const stored = yield* db
555
+ .select({
556
+ aggregateID: EventTable.aggregate_id,
557
+ seq: EventTable.seq,
558
+ })
559
+ .from(EventTable)
560
+ .where(eq(EventTable.id, event.id))
561
+ .get()
562
+ .pipe(Effect.orDie)
563
+ if (stored)
564
+ yield* Effect.die(
565
+ new InvalidDurableEventError({
566
+ type: event.type,
567
+ message: `Event ${event.id} already exists at aggregate ${stored.aggregateID} sequence ${stored.seq}`,
568
+ }),
569
+ )
570
+ const committed = {
571
+ ...event,
572
+ durable: {
573
+ aggregateID,
574
+ seq,
575
+ version: durable.version,
576
+ },
577
+ } as Payload
578
+ for (const projector of list) {
579
+ yield* projector(committed)
580
+ }
581
+ if (commit) yield* commit(seq)
582
+ const replayOwnerID = input?.nextOwnerID ?? input?.ownerID
583
+ const ownerChanged = replayOwnerID !== undefined && replayOwnerID !== row?.ownerID
584
+ yield* db
585
+ .insert(EventSequenceTable)
586
+ .values([
587
+ {
588
+ aggregate_id: aggregateID,
589
+ seq,
590
+ owner_id: replayOwnerID,
591
+ owner_generation: input?.nextOwnerID && input.nextOwnerID !== input.ownerID ? 1 : 0,
592
+ },
593
+ ])
594
+ .onConflictDoUpdate({
595
+ target: EventSequenceTable.aggregate_id,
596
+ set: {
597
+ seq,
598
+ ...(ownerChanged
599
+ ? {
600
+ owner_id: replayOwnerID,
601
+ owner_generation: sql`${EventSequenceTable.owner_generation} + 1`,
602
+ }
603
+ : {}),
604
+ },
605
+ })
606
+ .run()
607
+ .pipe(Effect.orDie)
608
+ yield* db
609
+ .insert(EventTable)
610
+ .values([
611
+ {
612
+ id: event.id,
613
+ aggregate_id: aggregateID,
614
+ seq,
615
+ type: versionedType(type, durable.version),
616
+ data: encoded,
617
+ },
618
+ ])
619
+ .run()
620
+ .pipe(Effect.orDie)
621
+ return { aggregateID, seq }
622
+ }),
623
+ { behavior: "immediate" },
624
+ )
625
+ .pipe(Effect.orDie)
626
+ if (committed) {
627
+ yield* Effect.forEach(
628
+ pubsub.durable.get(committed.aggregateID) ?? [],
629
+ (wake) => PubSub.publish(wake, undefined),
630
+ {
631
+ discard: true,
632
+ },
633
+ )
634
+ }
635
+ return committed
636
+ }),
637
+ )
638
+ }
639
+ }
640
+ })
641
+ }
642
+
643
+ function publishEvent<D extends Definition>(
644
+ definition: DefinitionSnapshot,
645
+ event: Payload<D>,
646
+ commit?: PublishOptions["commit"],
647
+ ) {
648
+ return Effect.gen(function* () {
649
+ const durable = definition.durable
650
+ if (!durable && commit)
651
+ return yield* Effect.die(
652
+ new InvalidDurableEventError({
653
+ type: event.type,
654
+ message: "Local commit hooks require a durable event",
655
+ }),
656
+ )
657
+ if (durable) {
658
+ const committed = yield* commitDurableEvent(definition, event as Payload, undefined, commit)
659
+ if (committed) {
660
+ event = {
661
+ ...event,
662
+ durable: {
663
+ aggregateID: committed.aggregateID,
664
+ seq: committed.seq,
665
+ version: durable.version,
666
+ },
667
+ }
668
+ yield* notify(event as Payload, true)
669
+ return event
670
+ }
671
+ }
672
+ yield* notify(event as Payload, false)
673
+ return event
674
+ })
675
+ }
676
+
677
+ const observe = (event: Payload, observer: (event: Payload) => Effect.Effect<void>) =>
678
+ Effect.suspend(() => observer(event)).pipe(
679
+ Effect.catchCauseIf(
680
+ (cause) => !Cause.hasInterrupts(cause),
681
+ (cause) =>
682
+ Effect.logError("Event listener failed", {
683
+ eventID: event.id,
684
+ eventType: event.type,
685
+ cause,
686
+ }),
687
+ ),
688
+ )
689
+
690
+ function notify(event: Payload, isolateListeners: boolean) {
691
+ return Effect.gen(function* () {
692
+ yield* Effect.forEach(
693
+ listeners,
694
+ (listener) => (isolateListeners ? observe(event, listener) : listener(event)),
695
+ { discard: true },
696
+ )
697
+ const typed = pubsub.typed.get(event.type)
698
+ if (typed) yield* PubSub.publish(typed, event)
699
+ deltas.publish(event)
700
+ yield* PubSub.publish(pubsub.all, event)
701
+ })
702
+ }
703
+
704
+ function publishWithCapability<D extends Definition>(
705
+ definition: D,
706
+ data: Data<D>,
707
+ options?: PublishOptions,
708
+ capability?: object,
709
+ ) {
710
+ return Effect.gen(function* () {
711
+ const captured = snapshotDefinition(definition)
712
+ yield* assertPublishAuthority(captured.type, capability)
713
+ const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
714
+ const location =
715
+ options?.location ??
716
+ (serviceLocation
717
+ ? {
718
+ directory: serviceLocation.directory,
719
+ workspaceID: serviceLocation.workspaceID,
720
+ }
721
+ : undefined)
722
+ return yield* publishEvent(
723
+ captured,
724
+ {
725
+ id: options?.id ?? ID.create(),
726
+ ...(options?.metadata ? { metadata: options.metadata } : {}),
727
+ type: captured.type,
728
+ ...(location ? { location } : {}),
729
+ data,
730
+ } as Payload<D>,
731
+ options?.commit,
732
+ )
733
+ })
734
+ }
735
+
736
+ function publish<D extends Definition>(definition: D, data: Data<D>, options?: PublishOptions) {
737
+ return publishWithCapability(definition, data, options)
738
+ }
739
+
740
+ function publishBatch(items: readonly PublishBatchItem[]) {
741
+ return Effect.gen(function* () {
742
+ // Capture and authorize the exact definitions that the batch will use.
743
+ const capturedItems = new Array<{
744
+ readonly definition: DefinitionSnapshot
745
+ readonly data: unknown
746
+ readonly options: PublishBatchOptions | undefined
747
+ }>()
748
+ for (const item of items) {
749
+ if (capturedItems.length >= MAX_ATOMIC_BATCH_EVENTS) {
750
+ return yield* Effect.die(
751
+ new InvalidDurableEventError({
752
+ type: capturedItems[0]?.definition.type ?? "unknown",
753
+ message: `Atomic batches are limited to ${MAX_ATOMIC_BATCH_EVENTS} events`,
754
+ }),
755
+ )
756
+ }
757
+ const definition = snapshotDefinition(item.definition)
758
+ const captured = {
759
+ definition,
760
+ data: item.data,
761
+ options: item.options,
762
+ }
763
+ yield* assertPublishAuthority(definition.type)
764
+ capturedItems.push(captured)
765
+ }
766
+ if (capturedItems.length === 0) return [] as readonly Payload[]
767
+
768
+ const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
769
+ const eventIDs = new Set<ID>()
770
+ const prepared = capturedItems.map((item) => {
771
+ const durable = item.definition.durable
772
+ if (!durable) {
773
+ throw new InvalidDurableEventError({
774
+ type: item.definition.type,
775
+ message: "Atomic batches require durable events",
776
+ })
777
+ }
778
+ const aggregateID = (item.data as Record<string, unknown>)[durable.aggregate]
779
+ if (typeof aggregateID !== "string") {
780
+ throw new InvalidDurableEventError({
781
+ type: item.definition.type,
782
+ message: `Expected string aggregate field ${durable.aggregate}`,
783
+ })
784
+ }
785
+ const id = item.options?.id ?? ID.create()
786
+ if (eventIDs.has(id)) {
787
+ throw new InvalidDurableEventError({
788
+ type: item.definition.type,
789
+ message: `Event ${id} appears more than once in the batch`,
790
+ })
791
+ }
792
+ eventIDs.add(id)
793
+ const location =
794
+ item.options?.location ??
795
+ (serviceLocation
796
+ ? {
797
+ directory: serviceLocation.directory,
798
+ workspaceID: serviceLocation.workspaceID,
799
+ }
800
+ : undefined)
801
+ const event = {
802
+ id,
803
+ ...(item.options?.metadata ? { metadata: item.options.metadata } : {}),
804
+ type: item.definition.type,
805
+ ...(location ? { location } : {}),
806
+ data: item.data,
807
+ } as Payload
808
+ return {
809
+ definition: item.definition,
810
+ durable,
811
+ aggregateID,
812
+ event,
813
+ encoded: Schema.encodeUnknownSync(item.definition.data)(item.data) as Record<string, unknown>,
814
+ }
815
+ })
816
+ const aggregateID = prepared[0]!.aggregateID
817
+ const crossAggregate = prepared.find((item) => item.aggregateID !== aggregateID)
818
+ if (crossAggregate) {
819
+ return yield* Effect.die(
820
+ new InvalidDurableEventError({
821
+ type: crossAggregate.definition.type,
822
+ message: "Atomic batch events must belong to the same aggregate",
823
+ }),
824
+ )
825
+ }
826
+
827
+ const committed = yield* Effect.uninterruptible(
828
+ Effect.gen(function* () {
829
+ const result = yield* db
830
+ .transaction(
831
+ () =>
832
+ Effect.gen(function* () {
833
+ const row = yield* db
834
+ .select({ seq: EventSequenceTable.seq })
835
+ .from(EventSequenceTable)
836
+ .where(eq(EventSequenceTable.aggregate_id, aggregateID))
837
+ .get()
838
+ .pipe(Effect.orDie)
839
+ let seq = row?.seq ?? -1
840
+ const events = new Array<Payload>()
841
+ for (const item of prepared) {
842
+ seq += 1
843
+ const stored = yield* db
844
+ .select({
845
+ aggregateID: EventTable.aggregate_id,
846
+ seq: EventTable.seq,
847
+ })
848
+ .from(EventTable)
849
+ .where(eq(EventTable.id, item.event.id))
850
+ .get()
851
+ .pipe(Effect.orDie)
852
+ if (stored) {
853
+ return yield* Effect.die(
854
+ new InvalidDurableEventError({
855
+ type: item.event.type,
856
+ message: `Event ${item.event.id} already exists at aggregate ${stored.aggregateID} sequence ${stored.seq}`,
857
+ }),
858
+ )
859
+ }
860
+ const event = {
861
+ ...item.event,
862
+ durable: {
863
+ aggregateID,
864
+ seq,
865
+ version: item.durable.version,
866
+ },
867
+ } as Payload
868
+ for (const projector of projectors.get(projectorKey(item.definition)) ?? []) {
869
+ yield* projector(event)
870
+ }
871
+ yield* db
872
+ .insert(EventSequenceTable)
873
+ .values([{ aggregate_id: aggregateID, seq }])
874
+ .onConflictDoUpdate({
875
+ target: EventSequenceTable.aggregate_id,
876
+ set: { seq },
877
+ })
878
+ .run()
879
+ .pipe(Effect.orDie)
880
+ yield* db
881
+ .insert(EventTable)
882
+ .values([
883
+ {
884
+ id: event.id,
885
+ aggregate_id: aggregateID,
886
+ seq,
887
+ type: versionedType(item.definition.type, item.durable.version),
888
+ data: item.encoded,
889
+ },
890
+ ])
891
+ .run()
892
+ .pipe(Effect.orDie)
893
+ events.push(event)
894
+ }
895
+ return events as readonly Payload[]
896
+ }),
897
+ { behavior: "immediate" },
898
+ )
899
+ .pipe(Effect.orDie)
900
+ yield* Effect.forEach(pubsub.durable.get(aggregateID) ?? [], (wake) => PubSub.publish(wake, undefined), {
901
+ discard: true,
902
+ })
903
+ return result
904
+ }),
905
+ )
906
+ for (const event of committed) yield* notify(event, true)
907
+ return committed
908
+ })
909
+ }
910
+
911
+ function replayCapturedWithCapability(
912
+ event: SerializedEventSnapshot,
913
+ options: ReplayOptionsSnapshot,
914
+ capability?: object,
915
+ authorize = true,
916
+ ) {
917
+ return Effect.gen(function* () {
918
+ if (authorize) yield* assertReplayAuthority(event.type, capability)
919
+ const definition = Durable.get(event.type)
920
+ if (!definition?.durable) {
921
+ yield* Effect.die(
922
+ new InvalidDurableEventError({
923
+ type: event.type,
924
+ message: `Unknown durable event type ${event.type}`,
925
+ }),
926
+ )
927
+ } else {
928
+ const payload = {
929
+ id: event.id,
930
+ type: definition.type,
931
+ data: Schema.decodeUnknownSync(definition.data)(event.data),
932
+ } as Payload
933
+ const committed = yield* commitDurableEvent(snapshotDefinition(definition), payload, {
934
+ seq: event.seq,
935
+ aggregateID: event.aggregateID,
936
+ ownerID: options.ownerID,
937
+ strictOwner: options.strictOwner,
938
+ nextOwnerID: options.ownerRotation?.eventID === event.id ? options.ownerRotation.nextOwnerID : undefined,
939
+ })
940
+ if (committed && options.publish) {
941
+ yield* notify(
942
+ {
943
+ ...payload,
944
+ durable: {
945
+ aggregateID: committed.aggregateID,
946
+ seq: committed.seq,
947
+ version: definition.durable.version,
948
+ },
949
+ },
950
+ true,
951
+ )
952
+ }
953
+ }
954
+ })
955
+ }
956
+
957
+ function replayWithCapability(event: SerializedEvent, options?: ReplayOptions, capability?: object) {
958
+ return Effect.gen(function* () {
959
+ const capturedEvent = snapshotSerializedEvent(event)
960
+ const capturedOptions = snapshotReplayOptions(options, capturedEvent.type)
961
+ yield* replayCapturedWithCapability(capturedEvent, capturedOptions, capability)
962
+ })
963
+ }
964
+
965
+ function replay(event: SerializedEvent, options?: ReplayOptions) {
966
+ return replayWithCapability(event, options)
967
+ }
968
+
969
+ function replayAllWithCapability(events: SerializedEvent[], options?: ReplayOptions, capability?: object) {
970
+ return Effect.gen(function* () {
971
+ const capturedEvents = snapshotSerializedEvents(events)
972
+ const capturedOptions = snapshotReplayOptions(options, capturedEvents[0]?.type ?? "unknown")
973
+ // Authorization is deliberately checked for the whole batch before
974
+ // any replay can project or commit an earlier event.
975
+ yield* assertReplayAllAuthority(capturedEvents, capability)
976
+ const source = capturedEvents[0]?.aggregateID
977
+ if (!source) return undefined
978
+ if (capturedEvents.some((event) => event.aggregateID !== source)) {
979
+ yield* Effect.die(
980
+ new InvalidDurableEventError({
981
+ type: capturedEvents[0]?.type ?? "unknown",
982
+ message: "Replay events must belong to the same aggregate",
983
+ }),
984
+ )
985
+ }
986
+ const start = capturedEvents[0]?.seq ?? 0
987
+ for (const [index, event] of capturedEvents.entries()) {
988
+ const seq = start + index
989
+ if (event.seq !== seq) {
990
+ yield* Effect.die(
991
+ new InvalidDurableEventError({
992
+ type: event.type,
993
+ message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`,
994
+ }),
995
+ )
996
+ }
997
+ }
998
+ if (capturedOptions.ownerRotation && capturedEvents.at(-1)?.id !== capturedOptions.ownerRotation.eventID) {
999
+ yield* Effect.die(
1000
+ new InvalidDurableEventError({
1001
+ type: capturedEvents.at(-1)?.type ?? "unknown",
1002
+ message: "Replay owner rotation must target the final event",
1003
+ }),
1004
+ )
1005
+ }
1006
+ for (const event of capturedEvents) {
1007
+ yield* replayCapturedWithCapability(event, capturedOptions, capability, false)
1008
+ }
1009
+ return source
1010
+ })
1011
+ }
1012
+
1013
+ function replayAll(events: SerializedEvent[], options?: ReplayOptions) {
1014
+ return replayAllWithCapability(events, options)
1015
+ }
1016
+
1017
+ function remove(aggregateID: string) {
1018
+ return db
1019
+ .transaction(() =>
1020
+ Effect.gen(function* () {
1021
+ yield* db.delete(EventSequenceTable).where(eq(EventSequenceTable.aggregate_id, aggregateID)).run()
1022
+ yield* db.delete(EventTable).where(eq(EventTable.aggregate_id, aggregateID)).run()
1023
+ }),
1024
+ )
1025
+ .pipe(Effect.orDie)
1026
+ }
1027
+
1028
+ function claim(aggregateID: string, ownerID: string) {
1029
+ return db
1030
+ .update(EventSequenceTable)
1031
+ .set({
1032
+ owner_id: ownerID,
1033
+ owner_generation: sql`${EventSequenceTable.owner_generation} + 1`,
1034
+ })
1035
+ .where(
1036
+ and(
1037
+ eq(EventSequenceTable.aggregate_id, aggregateID),
1038
+ or(isNull(EventSequenceTable.owner_id), ne(EventSequenceTable.owner_id, ownerID)),
1039
+ ),
1040
+ )
1041
+ .run()
1042
+ .pipe(Effect.orDie)
1043
+ }
1044
+
1045
+ const subscribe = <D extends Definition>(definition: D): Stream.Stream<Payload<D>> =>
1046
+ Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe(
1047
+ Stream.map((event) => event as Payload<D>),
1048
+ )
1049
+
1050
+ const streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(pubsub.all)
1051
+
1052
+ const decodeSerializedEvent = (event: SerializedEvent) => {
1053
+ const definition = Durable.get(event.type)
1054
+ if (!definition?.durable) {
1055
+ throw new InvalidDurableEventError({
1056
+ type: event.type,
1057
+ message: `Unknown durable event type ${event.type}`,
1058
+ })
1059
+ }
1060
+ return {
1061
+ id: event.id,
1062
+ type: definition.type,
1063
+ durable: {
1064
+ aggregateID: event.aggregateID,
1065
+ seq: event.seq,
1066
+ version: definition.durable.version,
1067
+ },
1068
+ data: Schema.decodeUnknownSync(definition.data)(event.data),
1069
+ }
1070
+ }
1071
+
1072
+ const durablePageSize = 128
1073
+ const readAfter = (aggregateID: string, after: number) =>
1074
+ (options?.beforeAggregateRead?.(aggregateID) ?? Effect.void).pipe(
1075
+ Effect.andThen(
1076
+ db
1077
+ .select()
1078
+ .from(EventTable)
1079
+ .where(and(eq(EventTable.aggregate_id, aggregateID), gt(EventTable.seq, after)))
1080
+ .orderBy(asc(EventTable.seq))
1081
+ .limit(durablePageSize)
1082
+ .all(),
1083
+ ),
1084
+ Effect.orDie,
1085
+ Effect.map((rows) =>
1086
+ rows.map((event) =>
1087
+ decodeSerializedEvent({
1088
+ id: event.id,
1089
+ aggregateID: event.aggregate_id,
1090
+ seq: event.seq,
1091
+ type: event.type,
1092
+ data: event.data,
1093
+ }),
1094
+ ),
1095
+ ),
1096
+ )
1097
+
1098
+ const subscribeDurable = (aggregateID: string) =>
1099
+ Effect.gen(function* () {
1100
+ const wake = yield* PubSub.sliding<void>(1)
1101
+ const subscription = yield* PubSub.subscribe(wake)
1102
+ yield* Effect.acquireRelease(
1103
+ Effect.sync(() => {
1104
+ const wakes = pubsub.durable.get(aggregateID) ?? new Set()
1105
+ wakes.add(wake)
1106
+ pubsub.durable.set(aggregateID, wakes)
1107
+ }),
1108
+ () =>
1109
+ Effect.sync(() => {
1110
+ const wakes = pubsub.durable.get(aggregateID)
1111
+ wakes?.delete(wake)
1112
+ if (wakes?.size === 0) pubsub.durable.delete(aggregateID)
1113
+ }).pipe(Effect.andThen(PubSub.shutdown(wake))),
1114
+ )
1115
+ return subscription
1116
+ })
1117
+
1118
+ const durable = (input: { readonly aggregateID: string; readonly after?: number }): Stream.Stream<Payload> =>
1119
+ Stream.unwrap(
1120
+ Effect.gen(function* () {
1121
+ const wakes = yield* subscribeDurable(input.aggregateID)
1122
+ let sequence = input.after ?? -1
1123
+ const read = Effect.suspend(() => readAfter(input.aggregateID, sequence)).pipe(
1124
+ Effect.tap((events) =>
1125
+ Effect.sync(() => {
1126
+ sequence = events.at(-1)?.durable?.seq ?? sequence
1127
+ }),
1128
+ ),
1129
+ )
1130
+ const catchUp = () =>
1131
+ Stream.paginate(undefined, () =>
1132
+ read.pipe(
1133
+ Effect.map((events) => [
1134
+ events,
1135
+ events.length === durablePageSize ? Option.some(undefined) : Option.none(),
1136
+ ] as const),
1137
+ ),
1138
+ )
1139
+ const live = Stream.fromSubscription(wakes).pipe(Stream.flatMap(() => catchUp()))
1140
+ return Stream.concat(catchUp(), live)
1141
+ }),
1142
+ )
1143
+
1144
+ const listen = (listener: Subscriber): Effect.Effect<Unsubscribe> =>
1145
+ Effect.sync(() => {
1146
+ listeners.push(listener)
1147
+ return Effect.sync(() => {
1148
+ const index = listeners.indexOf(listener)
1149
+ if (index >= 0) listeners.splice(index, 1)
1150
+ })
1151
+ })
1152
+
1153
+ const project = <D extends Definition>(definition: D, projector: Subscriber<D>): Effect.Effect<void> =>
1154
+ Effect.sync(() => {
1155
+ const key = projectorKey(snapshotDefinition(definition))
1156
+ const list = projectors.get(key) ?? []
1157
+ list.push((event) => projector(event as Payload<D>))
1158
+ projectors.set(key, list)
1159
+ })
1160
+
1161
+ const implementation: InternalInterface = {
1162
+ publish,
1163
+ publishBatch,
1164
+ subscribe,
1165
+ all: streamAll,
1166
+ durable,
1167
+ sessionDeltas: deltas.stream,
1168
+ listen,
1169
+ project,
1170
+ replay,
1171
+ replayAll,
1172
+ remove,
1173
+ claim,
1174
+ [authorizedOperations]: {
1175
+ publish: (capability, definition, data, options) =>
1176
+ publishWithCapability(definition, data, options, capability),
1177
+ replay: (capability, event, options) => replayWithCapability(event, options, capability),
1178
+ replayAll: (capability, events, options) => replayAllWithCapability(events, options, capability),
1179
+ },
1180
+ }
1181
+ return Service.of(implementation)
1182
+ }),
1183
+ )
1184
+
1185
+ export const layer = layerWith()
1186
+ export const node = ServiceGraph.node(layer, [Database.node])
1187
+
1188
+ export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer))
1189
+
1190
+ const internalOperations = (events: Interface) => (events as InternalInterface)[authorizedOperations]
1191
+
1192
+ export const verificationSettlementPublisherLayer = Layer.effect(
1193
+ VerificationSettlementPublisherService,
1194
+ Effect.gen(function* () {
1195
+ const operations = internalOperations(yield* Service)
1196
+ return VerificationSettlementPublisherService.of({
1197
+ settle: (data, options) =>
1198
+ operations.publish(liveSettlementCapability, SessionEvent.VerificationSettled, data, options),
1199
+ })
1200
+ }),
1201
+ )
1202
+
1203
+ export const verificationSettlementPublisherNode = ServiceGraph.node(verificationSettlementPublisherLayer, [node])
1204
+
1205
+ export const verificationSettlementPublisherDefaultLayer = verificationSettlementPublisherLayer.pipe(
1206
+ Layer.provide(defaultLayer),
1207
+ )
1208
+
1209
+ export const protectedEventReplayLayer = Layer.effect(
1210
+ ProtectedEventReplayService,
1211
+ Effect.gen(function* () {
1212
+ const operations = internalOperations(yield* Service)
1213
+ return ProtectedEventReplayService.of({
1214
+ replay: (event, options) => operations.replay(protectedReplayCapability, event, options),
1215
+ replayAll: (events, options) => operations.replayAll(protectedReplayCapability, events, options),
1216
+ })
1217
+ }),
1218
+ )
1219
+
1220
+ export const protectedEventReplayNode = ServiceGraph.node(protectedEventReplayLayer, [node])
1221
+
1222
+ export const protectedEventReplayDefaultLayer = protectedEventReplayLayer.pipe(Layer.provide(defaultLayer))