@phins/engine 0.0.0-stage → 0.1.2

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 +10 -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 +54 -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,1466 @@
1
+ /**
2
+ * Durable LLM runner của Core session V2.
3
+ *
4
+ * Luồng F2-F7/7: đọc work/history, dựng context epoch và tool definitions,
5
+ * stream một provider turn, persist events, settle tool rồi chạy continuation.
6
+ * @module
7
+ */
8
+ import { ToolAdmission } from "../../tools/admission"
9
+ import * as CodingWorkflow from "./coding-workflow"
10
+ import * as LocalVerification from "../../verification/local"
11
+ import * as LocalPolicy from "../../security/launcher-policy"
12
+ import { ProcessRunner } from "../../execution/process/runner"
13
+ import path from "node:path"
14
+ import { selectContext } from "../context/selection"
15
+ import {
16
+ LLM,
17
+ LLMClient,
18
+ LLMError,
19
+ LLMEvent,
20
+ LLMRequest,
21
+ HttpOptions,
22
+ SystemPart,
23
+ isContextOverflowFailure,
24
+ type ProviderErrorEvent,
25
+ type ToolResultValue,
26
+ } from "../../inference/api"
27
+ import { ExecutionBoundary, RequestExecutor } from "../../inference/request/api"
28
+ import { and, desc, eq } from "drizzle-orm"
29
+ import { Cause, Context, DateTime, Effect, Exit, FiberSet, Layer, Option, Schema, Semaphore, Stream } from "effect"
30
+ import { isDeepStrictEqual } from "node:util"
31
+ import { AgentRegistry } from "../../agents/registry"
32
+ import { Config } from "../../settings/config"
33
+ import { Database } from "../../storage/database"
34
+ import { EventBus } from "../../runtime/events/bus"
35
+ import { EventSequenceTable } from "../../storage/tables/events"
36
+ import { Location } from "../../workspace/location"
37
+ import { CatalogModel } from "../../inference/catalog/model"
38
+ import { PermissionPolicy } from "../../security/permissions/service"
39
+ import { CatalogProvider } from "../../inference/catalog/provider"
40
+ import { UserQuestions } from "../../agents/questions"
41
+ import { SystemContext } from "../../agents/context/system"
42
+ import { SystemContextRegistry } from "../../agents/context/registry"
43
+ import { SkillGuidance } from "../../agents/skills/guidance"
44
+ import { ReferenceGuidance } from "../../agents/references/guidance"
45
+ import { ToolRegistry } from "../../tools/registry"
46
+ import { ToolOutputStore } from "../../tools/output-store"
47
+ import { VerifierContainment } from "../../verification/containment"
48
+ import { VerifierRegistry } from "../../verification/registry"
49
+ import { VerifierSettlementAdmission } from "../../verification/settlement-admission"
50
+ import { VerificationSettlementPublisher } from "../../runtime/events/verification-publisher"
51
+ import { SessionContextEpoch } from "../context/epoch"
52
+ import { SessionCompaction } from "../context/compaction"
53
+ import { SessionEvent } from "../../contracts/events/session"
54
+ import { SessionHistory } from "../messages/history"
55
+ import { SessionInput } from "../input/inbox"
56
+ import { SessionInputOrigin } from "../input/origin"
57
+ import * as SessionInputTurns from "../input/turns"
58
+ import { SessionMessage } from "../messages/service"
59
+ import { Session as SessionSchema } from "../../contracts/session/info"
60
+ import { SessionMessageTable, SessionTable } from "../../storage/tables/sessions"
61
+ import { SessionStore } from "../store"
62
+ import { SessionRunState } from "./state"
63
+ import { SessionVerification } from "../verification/service"
64
+ import { type RunError, Service } from "./loop"
65
+ import { SessionRunnerModel } from "./model"
66
+ import { boundedTerminalMessage, createLLMEventPublisher, MAX_TOOL_CALLS_PER_TURN } from "./events"
67
+ import { toLLMMessages } from "./messages"
68
+ import { Snapshot } from "../../workspace/repository/snapshot"
69
+ import { PermissionOrigin } from "../../security/permissions/origin"
70
+ import * as Delegation from "../../security/permissions/delegation"
71
+ import { NodeCommandRunner } from "../../execution/commands/runner"
72
+ import * as CommandProvider from "../../execution/commands/provider"
73
+ import { restoreContinuation } from "../../execution/control/restoration"
74
+ import * as RunBudget from "./budget"
75
+
76
+ const WORKSPACE_PROXY_ROUTE_PATH = /\/v2\/llm(?:\/|$)/
77
+ const SECURITY_SIGNAL_PATTERN = /\b(security|vulnerab|exploit|secret|credential|token|auth|permission)\b/i
78
+ const DOOM_LOOP_THRESHOLD = 3
79
+
80
+ type DoomLoopTail = {
81
+ readonly name: string
82
+ readonly input: Record<string, unknown>
83
+ readonly count: number
84
+ }
85
+
86
+ const normalizedToolInput = (value: unknown): Record<string, unknown> =>
87
+ typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : { value }
88
+
89
+ const advanceDoomLoopTail = (
90
+ tail: DoomLoopTail | undefined,
91
+ input: {
92
+ readonly name: string
93
+ readonly value: unknown
94
+ readonly local: boolean
95
+ },
96
+ ): DoomLoopTail | undefined => {
97
+ if (!input.local) return undefined
98
+ const value = normalizedToolInput(input.value)
99
+ if (tail?.name === input.name && isDeepStrictEqual(tail.input, value))
100
+ return { name: input.name, input: value, count: tail.count + 1 }
101
+ return { name: input.name, input: value, count: 1 }
102
+ }
103
+
104
+ /** Rebuild the local-call tail from durable projected history after resume/replay. */
105
+ const doomLoopTailFromHistory = (messages: ReadonlyArray<SessionMessage.Message>) => {
106
+ let tail: DoomLoopTail | undefined
107
+ for (const message of messages) {
108
+ if (message.type === "user" || message.type === "compaction") {
109
+ tail = undefined
110
+ continue
111
+ }
112
+ if (message.type !== "assistant") continue
113
+ for (const part of message.content) {
114
+ if (part.type !== "tool") continue
115
+ if (part.state.status === "pending" || part.provider?.executed === true) {
116
+ tail = undefined
117
+ continue
118
+ }
119
+ tail = advanceDoomLoopTail(tail, {
120
+ name: part.name,
121
+ value: part.state.input,
122
+ local: true,
123
+ })
124
+ }
125
+ }
126
+ return tail
127
+ }
128
+
129
+ type VerifierObservation = {
130
+ readonly selection?: VerifierRegistry.Selection
131
+ readonly reason?: SessionVerification.MissingReason
132
+ }
133
+
134
+ type VerificationBoundaryProfile = "verification" | "observation" | "legacy"
135
+
136
+ const isWorkspaceProxyRequest = (request: LLMRequest) => {
137
+ const baseURL = request.model.route.endpoint.baseURL
138
+ if (!baseURL) return false
139
+ try {
140
+ return WORKSPACE_PROXY_ROUTE_PATH.test(new URL(baseURL).pathname)
141
+ } catch {
142
+ return WORKSPACE_PROXY_ROUTE_PATH.test(baseURL)
143
+ }
144
+ }
145
+
146
+ const requestText = (request: LLMRequest) => {
147
+ try {
148
+ return JSON.stringify({
149
+ system: request.system,
150
+ messages: request.messages,
151
+ })
152
+ } catch {
153
+ return ""
154
+ }
155
+ }
156
+
157
+ const estimateRequestTokens = (request: LLMRequest) => {
158
+ try {
159
+ return Math.max(
160
+ 1,
161
+ Math.ceil(
162
+ JSON.stringify({
163
+ system: request.system,
164
+ messages: request.messages,
165
+ tools: request.tools,
166
+ }).length / 4,
167
+ ),
168
+ )
169
+ } catch {
170
+ return undefined
171
+ }
172
+ }
173
+
174
+ const inferWorkspaceRoutingPhase = (input: { readonly agent: AgentRegistry.Selection; readonly toolCount: number }) => {
175
+ const name = `${input.agent.id} ${input.agent.info?.mode ?? ""} ${input.agent.info?.system ?? ""}`.toLowerCase()
176
+ if (name.includes("compact")) return "compact"
177
+ if (name.includes("security")) return "security"
178
+ if (name.includes("audit")) return "audit"
179
+ if (name.includes("review")) return "review"
180
+ if (name.includes("plan")) return "plan"
181
+ if (input.toolCount > 0) return "code"
182
+ return "chat"
183
+ }
184
+
185
+ const withWorkspaceRoutingMetadata = (
186
+ request: LLMRequest,
187
+ input: {
188
+ readonly session: SessionSchema.Info
189
+ readonly agent: AgentRegistry.Selection
190
+ readonly contextSize: number
191
+ readonly toolCount: number
192
+ },
193
+ ) => {
194
+ if (!isWorkspaceProxyRequest(request)) return request
195
+ const phase = inferWorkspaceRoutingPhase({
196
+ agent: input.agent,
197
+ toolCount: input.toolCount,
198
+ })
199
+ const contextEstimateTokens = estimateRequestTokens(request)
200
+ const securitySensitive = SECURITY_SIGNAL_PATTERN.test(requestText(request))
201
+ const routing = {
202
+ phase,
203
+ agent: String(input.agent.id),
204
+ agentMode: input.agent.info?.mode,
205
+ taskSignals: {
206
+ messageCount: input.contextSize,
207
+ toolCount: input.toolCount,
208
+ contextEstimateTokens,
209
+ securitySensitive,
210
+ },
211
+ policyHints: {
212
+ requireTools: input.toolCount > 0,
213
+ requireLargeContext: typeof contextEstimateTokens === "number" && contextEstimateTokens >= 48_000,
214
+ deepAudit: phase === "audit" || phase === "review" || phase === "security",
215
+ },
216
+ }
217
+ return LLMRequest.update(request, {
218
+ metadata: {
219
+ ...request.metadata,
220
+ phins: {
221
+ ...(request.metadata?.phins && typeof request.metadata.phins === "object" ? request.metadata.phins : {}),
222
+ ...routing,
223
+ sessionId: input.session.id,
224
+ },
225
+ },
226
+ http: new HttpOptions({
227
+ body: {
228
+ ...request.http?.body,
229
+ metadata: {
230
+ ...(request.http?.body?.metadata && typeof request.http.body.metadata === "object"
231
+ ? request.http.body.metadata
232
+ : {}),
233
+ phins: routing,
234
+ },
235
+ phase: routing.phase,
236
+ taskSignals: routing.taskSignals,
237
+ policyHints: routing.policyHints,
238
+ sessionId: input.session.id,
239
+ },
240
+ headers: request.http?.headers,
241
+ query: request.http?.query,
242
+ }),
243
+ })
244
+ }
245
+
246
+ /**
247
+ * Local drains and native commands share turns, tools and durable settlement.
248
+ * Local drains may promote queued/steered inputs; a native run stays bound to
249
+ * one authenticated input/run and rechecks its ceiling at effect boundaries.
250
+ * Client detach never owns interruption. Transport retries are acquisition-only;
251
+ * uncertain tool side effects are terminalized, never automatically replayed.
252
+ * Capability qualification and consumer cutover are tracked in node-service.md.
253
+ */
254
+
255
+ export const layer = Layer.effectContext(
256
+ Effect.gen(function* () {
257
+ const events = yield* EventBus.Service
258
+ const llm = yield* LLMClient.Service
259
+ const agents = yield* AgentRegistry.Service
260
+ const tools = yield* ToolRegistry.Service
261
+ const permission = yield* PermissionPolicy.Service
262
+ const models = yield* SessionRunnerModel.Service
263
+ const store = yield* SessionStore.Service
264
+ const location = yield* Location.Service
265
+ const systemContext = yield* SystemContextRegistry.Service
266
+ const skillGuidance = yield* SkillGuidance.Service
267
+ const referenceGuidance = yield* ReferenceGuidance.Service
268
+ const config = yield* Config.Service
269
+ const snapshots = yield* Snapshot.Service
270
+ const verifierRegistry = yield* VerifierRegistry.Registry
271
+ const verifierContainment = yield* VerifierContainment.Service
272
+ const appProcess = Option.getOrUndefined(yield* Effect.serviceOption(ProcessRunner.Service))
273
+ const verificationSettlements = yield* VerificationSettlementPublisher.Service
274
+ const verifierSettlementAdmission = Option.getOrUndefined(
275
+ yield* Effect.serviceOption(VerifierSettlementAdmission.Service),
276
+ )
277
+ const db = (yield* Database.Service).db
278
+ const verifierRoot = SessionVerification.selectionRoot(location)
279
+ // Private, fiber-local authority: public local resume never enters it.
280
+ const NativeOwner = Context.Reference<
281
+ { readonly target: NodeCommandRunner.Target; readonly check: Effect.Effect<void> } | undefined
282
+ >("@phins/SessionRunner/NativeOwner", { defaultValue: () => undefined })
283
+ const checkNative = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, runID: SessionRunState.ID) {
284
+ const owner = yield* NativeOwner
285
+ if (!owner) return
286
+ if (owner.target.sessionID !== sessionID || owner.target.runID !== runID)
287
+ return yield* Effect.die(new SessionInputOrigin.UnavailableError({ sessionID }))
288
+ yield* owner.check
289
+ })
290
+ const authorizeTurn = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, runID: SessionRunState.ID) {
291
+ if (yield* NativeOwner) return yield* checkNative(sessionID, runID)
292
+ yield* SessionInputOrigin.requireLocalRun(db, sessionID)
293
+ })
294
+ const compaction = SessionCompaction.make({
295
+ events,
296
+ llm: {
297
+ stream: (request) =>
298
+ Stream.unwrap(
299
+ Effect.gen(function* () {
300
+ const owner = yield* NativeOwner
301
+ const budget = yield* RunBudget.Active
302
+ yield* Effect.sync(() => budget?.attempt(request))
303
+ if (owner) {
304
+ yield* owner.check
305
+ yield* CommandProvider.check(owner.target.sessionID, request).pipe(Effect.orDie)
306
+ }
307
+ return llm.stream(request).pipe(Stream.tap((event) => Effect.sync(() => budget?.observe(event))))
308
+ }),
309
+ ),
310
+ },
311
+ config: yield* config.entries(),
312
+ })
313
+ const getSession = Effect.fn("SessionRunner.getSession")(function* (sessionID: SessionSchema.ID) {
314
+ const session = yield* store.get(sessionID)
315
+ if (!session) return yield* Effect.die(`Session not found: ${sessionID}`)
316
+ return session
317
+ })
318
+
319
+ const prepareIndependentCheck = Effect.fn("SessionRunner.prepareIndependentCheck")(function* (
320
+ sessionID: SessionSchema.ID,
321
+ checkOwner: Effect.Effect<void>,
322
+ ) {
323
+ if (!LocalVerification.enabled) return undefined
324
+ if (process.platform !== "darwin")
325
+ return yield* Effect.die(new Error("Independent local checks are qualified only on macOS"))
326
+ yield* checkOwner
327
+ const startSnapshot = yield* snapshots.captureVerification()
328
+ if (!startSnapshot) return yield* Effect.die(new Error("Independent checks require a capturable Git repository"))
329
+ const rootIdentity = yield* VerifierRegistry.inspectProjectRoot(verifierRoot).pipe(Effect.orDie)
330
+ const commands = LocalPolicy.commands()
331
+ const selection = LocalVerification.select(location, commands)
332
+ return Effect.gen(function* () {
333
+ yield* checkOwner
334
+ const workflow = yield* CodingWorkflow.Active
335
+ yield* Effect.sync(() => workflow?.finish())
336
+ const endSnapshot = yield* snapshots.captureVerification()
337
+ if (!endSnapshot) return yield* Effect.die(new Error("Independent check snapshot is unavailable"))
338
+ if (startSnapshot === endSnapshot) return
339
+ const changed = yield* snapshots.files({ from: startSnapshot, to: endSnapshot }).pipe(Effect.orDie)
340
+ const protectedPaths = LocalPolicy.protectedPaths(location.project.directory)
341
+ if (changed.some((file) => protectedPaths.some((protectedPath) =>
342
+ LocalPolicy.inside(protectedPath, path.resolve(location.project.directory, file)))))
343
+ return yield* Effect.die(new Error("Protected verification input changed during the task"))
344
+ const session = yield* getSession(sessionID)
345
+ const agent = yield* agents.select(session.agent)
346
+ // Launcher selection never expands the current owner's command grants.
347
+ const authorize = Effect.gen(function* () {
348
+ yield* checkOwner
349
+ yield* VerifierRegistry.revalidateProjectRoot(rootIdentity)
350
+ for (const command of commands)
351
+ yield* permission.assert({ action: "bash", resources: [command], sessionID, agent: agent.id,
352
+ metadata: { purpose: "independent-verification" } })
353
+ yield* checkOwner
354
+ })
355
+ if (!appProcess) return yield* Effect.die(new Error("Independent check process executor is unavailable"))
356
+ const containment = LocalVerification.make({ selection, snapshots, process: appProcess, authorize })
357
+ const recorded = yield* SessionVerification.record(db, events, {
358
+ sessionID, location, snapshot: endSnapshot, selection, containment,
359
+ captureSnapshot: snapshots.captureVerification,
360
+ }).pipe(Effect.provideService(VerificationSettlementPublisher.Service, verificationSettlements))
361
+ if (recorded?.verdict !== "passed")
362
+ return yield* Effect.die(new Error(`Independent checks did not pass: ${recorded?.verdict ?? "unavailable"}`))
363
+ })
364
+ })
365
+
366
+ const getContext = Effect.fn("SessionRunner.getContext")(function* (sessionID: SessionSchema.ID) {
367
+ return yield* store.context(sessionID)
368
+ })
369
+ const failInterruptedTools = Effect.fn("SessionRunner.failInterruptedTools")(function* (
370
+ sessionID: SessionSchema.ID,
371
+ ) {
372
+ let batch = new Array<EventBus.PublishBatchItem>()
373
+ const flush = Effect.fnUntraced(function* () {
374
+ if (batch.length === 0) return
375
+ yield* events.publishBatch(batch)
376
+ batch = []
377
+ })
378
+ for (const message of yield* getContext(sessionID)) {
379
+ if (message.type !== "assistant") continue
380
+ for (const tool of message.content) {
381
+ if (tool.type !== "tool" || (tool.state.status !== "pending" && tool.state.status !== "running")) continue
382
+ batch.push({
383
+ definition: SessionEvent.Tool.Failed,
384
+ data: {
385
+ sessionID,
386
+ timestamp: yield* DateTime.now,
387
+ assistantMessageID: message.id,
388
+ callID: tool.id,
389
+ error: { type: "unknown", message: "Tool execution interrupted" },
390
+ provider: { executed: tool.provider?.executed === true },
391
+ },
392
+ })
393
+ if (batch.length === EventBus.MAX_ATOMIC_BATCH_EVENTS) yield* flush()
394
+ }
395
+ }
396
+ yield* flush()
397
+ })
398
+
399
+ const observeVerification = Effect.fn("SessionRunner.observeVerification")(function* (
400
+ sessionID: SessionSchema.ID,
401
+ profile: VerificationBoundaryProfile,
402
+ startSnapshot: Snapshot.ID | undefined,
403
+ endSnapshot: Snapshot.ID | undefined,
404
+ verifier: VerifierObservation,
405
+ fallbackEndSnapshot: Snapshot.ID | undefined,
406
+ ) {
407
+ let observationSnapshot = endSnapshot ?? fallbackEndSnapshot
408
+ let admittedVerifier = verifier
409
+ if (profile === "verification") {
410
+ if (!startSnapshot || !endSnapshot) {
411
+ admittedVerifier = {
412
+ reason: "Unable to capture complete verifier subject",
413
+ }
414
+ } else {
415
+ // Exact full-root tree IDs are content-addressed. Comparing the IDs
416
+ // directly avoids every legacy location/ignore/diff configuration.
417
+ if (startSnapshot === endSnapshot) return
418
+ admittedVerifier = yield* revalidateVerifier(verifier)
419
+ }
420
+ } else if (profile === "observation") {
421
+ if (!startSnapshot || !endSnapshot) {
422
+ yield* Effect.logWarning("Strict verification observation unavailable", {
423
+ reason: !startSnapshot ? "strict-location-start-unavailable" : "strict-location-end-unavailable",
424
+ sessionID,
425
+ })
426
+ return
427
+ }
428
+ // These trees contain only the active Location, so direct identity
429
+ // comparison detects cross-boundary renames without observing siblings.
430
+ if (startSnapshot === endSnapshot) return
431
+ } else {
432
+ if (!startSnapshot || !endSnapshot) {
433
+ yield* Effect.logWarning("Verification shadow observation unavailable", {
434
+ reason: !startSnapshot ? "drain-start-snapshot-unavailable" : "drain-end-snapshot-unavailable",
435
+ sessionID,
436
+ })
437
+ return undefined
438
+ }
439
+ const files = yield* snapshots.files({ from: startSnapshot, to: endSnapshot }).pipe(
440
+ Effect.catch((cause) =>
441
+ Effect.logWarning("Verification shadow observation unavailable", {
442
+ cause,
443
+ reason: "snapshot-comparison-failed",
444
+ sessionID,
445
+ }).pipe(Effect.as(undefined)),
446
+ ),
447
+ )
448
+ if (!files || files.length === 0) return
449
+ }
450
+ if (!observationSnapshot) {
451
+ yield* Effect.logWarning("Verification shadow observation unavailable", {
452
+ reason: "drain-end-subject-unavailable",
453
+ sessionID,
454
+ })
455
+ return
456
+ }
457
+ const assistant = yield* db
458
+ .select({ id: SessionMessageTable.id })
459
+ .from(SessionMessageTable)
460
+ .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "assistant")))
461
+ .orderBy(desc(SessionMessageTable.seq))
462
+ .limit(1)
463
+ .get()
464
+ .pipe(Effect.orDie)
465
+ yield* SessionVerification.record(db, events, {
466
+ sessionID,
467
+ location,
468
+ snapshot: observationSnapshot,
469
+ assistantMessageID: assistant?.id,
470
+ selection: admittedVerifier.selection,
471
+ reason: admittedVerifier.reason,
472
+ containment: verifierContainment,
473
+ captureSnapshot: snapshots.captureVerification,
474
+ ...(verifierSettlementAdmission ? { settlementAdmission: verifierSettlementAdmission } : {}),
475
+ }).pipe(Effect.provideService(VerificationSettlementPublisher.Service, verificationSettlements))
476
+ })
477
+
478
+ const selectVerifier = Effect.fn("SessionRunner.selectVerifier")(function* () {
479
+ const selected = yield* Effect.suspend(() =>
480
+ verifierRegistry.select({
481
+ projectID: location.project.id,
482
+ projectRoot: verifierRoot,
483
+ }),
484
+ ).pipe(Effect.exit)
485
+ if (selected._tag === "Failure") {
486
+ if (Cause.hasInterrupts(selected.cause)) return yield* Effect.failCause(selected.cause)
487
+ yield* Effect.logError("Trusted verifier selection failed", {
488
+ projectID: location.project.id,
489
+ })
490
+ return {
491
+ reason: "Trusted verifier registry selection failed",
492
+ } satisfies VerifierObservation
493
+ }
494
+ const selection = selected.value
495
+ if (!selection) return {} satisfies VerifierObservation
496
+
497
+ const canonical = yield* Effect.gen(function* () {
498
+ const identity = selection.projectRootIdentity
499
+ if (identity) {
500
+ const current = yield* VerifierRegistry.inspectProjectRoot(verifierRoot)
501
+ if (!isDeepStrictEqual(current, identity))
502
+ return yield* Effect.fail(
503
+ new VerifierRegistry.ProjectRootIdentityError(
504
+ "Trusted verifier project root identity changed during selection",
505
+ ),
506
+ )
507
+ }
508
+ return VerifierRegistry.pin(
509
+ selection.plan,
510
+ {
511
+ projectID: location.project.id,
512
+ projectRoot: identity ? selection.projectRoot : verifierRoot,
513
+ ...(identity ? { projectRootIdentity: identity } : {}),
514
+ },
515
+ selection.verifier.provenance,
516
+ )
517
+ }).pipe(Effect.exit)
518
+ if (canonical._tag === "Failure" || !isDeepStrictEqual(canonical.value, selection)) {
519
+ yield* Effect.logError("Trusted verifier registry returned a non-canonical selection", {
520
+ projectID: location.project.id,
521
+ })
522
+ return {
523
+ reason: "Trusted verifier registry returned a non-canonical selection",
524
+ } satisfies VerifierObservation
525
+ }
526
+ return { selection: canonical.value } satisfies VerifierObservation
527
+ })
528
+
529
+ const revalidateVerifier = Effect.fn("SessionRunner.revalidateVerifier")(function* (verifier: VerifierObservation) {
530
+ if (!verifier.selection) return verifier
531
+ const selected = yield* Effect.suspend(() =>
532
+ verifierRegistry.select({
533
+ projectID: location.project.id,
534
+ projectRoot: verifierRoot,
535
+ }),
536
+ ).pipe(Effect.exit)
537
+ if (selected._tag === "Failure") {
538
+ if (Cause.hasInterrupts(selected.cause)) return yield* Effect.failCause(selected.cause)
539
+ yield* Effect.logError("Trusted verifier authorization revalidation failed", {
540
+ projectID: location.project.id,
541
+ })
542
+ return {
543
+ reason: "Trusted verifier authorization was not valid at verification admission",
544
+ } satisfies VerifierObservation
545
+ }
546
+ if (!selected.value || !isDeepStrictEqual(selected.value, verifier.selection)) {
547
+ yield* Effect.logError("Trusted verifier authorization changed before verification admission", {
548
+ projectID: location.project.id,
549
+ })
550
+ return {
551
+ reason: "Trusted verifier authorization was not valid at verification admission",
552
+ } satisfies VerifierObservation
553
+ }
554
+ return verifier
555
+ })
556
+
557
+ const awaitToolFibers = (fibers: FiberSet.FiberSet<void, ToolOutputStore.Error>) =>
558
+ Effect.raceFirst(FiberSet.join(fibers), FiberSet.awaitEmpty(fibers))
559
+
560
+ // Match V1: dismissing a question halts the loop instead of becoming model-facing tool output.
561
+ const isQuestionRejectedOnly = (cause: Cause.Cause<unknown>) =>
562
+ cause.reasons.length > 0 &&
563
+ cause.reasons.every((reason) => Cause.isDieReason(reason) && reason.defect instanceof UserQuestions.RejectedError)
564
+
565
+ const failAfterTerminalization = <E, E2, R>(
566
+ sourceCause: Cause.Cause<E>,
567
+ terminalization: Effect.Effect<unknown, E2, R>,
568
+ ) =>
569
+ terminalization.pipe(
570
+ Effect.exit,
571
+ Effect.flatMap((terminal) =>
572
+ Effect.failCause(terminal._tag === "Failure" ? Cause.combine(sourceCause, terminal.cause) : sourceCause),
573
+ ),
574
+ )
575
+
576
+ const retryError = (error: LLMError): SessionEvent.RetryError => {
577
+ const reason = error.reason
578
+ const http = "http" in reason ? reason.http : undefined
579
+ const statusCode =
580
+ http?.response?.status ?? ("status" in reason && typeof reason.status === "number" ? reason.status : undefined)
581
+ const metadata = {
582
+ ...(http?.requestId === undefined ? {} : { requestId: http.requestId }),
583
+ ...(http?.bodyTruncated === true ? { responseBodyTruncated: "true" } : {}),
584
+ }
585
+ return {
586
+ message: boundedTerminalMessage(reason.message),
587
+ isRetryable: error.retryable,
588
+ ...(statusCode === undefined ? {} : { statusCode }),
589
+ ...(http?.response === undefined ? {} : { responseHeaders: { ...http.response.headers } }),
590
+ ...(http?.body === undefined ? {} : { responseBody: boundedTerminalMessage(http.body) }),
591
+ ...(Object.keys(metadata).length === 0 ? {} : { metadata }),
592
+ }
593
+ }
594
+
595
+ const terminalFailure = (cause: Cause.Cause<unknown>): SessionRunState.TerminalFailureOutcome => {
596
+ const failure = Cause.squash(cause)
597
+ return {
598
+ type: "terminal-failure",
599
+ error: {
600
+ type: "unknown",
601
+ message: boundedTerminalMessage(
602
+ failure instanceof LLMError
603
+ ? failure.reason.message
604
+ : failure instanceof Error
605
+ ? failure.message
606
+ : String(failure),
607
+ ),
608
+ },
609
+ }
610
+ }
611
+
612
+ type TurnTransition =
613
+ // Automatic compaction completed; rebuild the request from compacted history.
614
+ | { readonly _tag: "ContinueAfterCompaction"; readonly step: number }
615
+ // Overflow compaction completed; rebuild once through the path without overflow recovery.
616
+ | {
617
+ readonly _tag: "ContinueAfterOverflowCompaction"
618
+ readonly step: number
619
+ }
620
+
621
+ class TurnTransitionError extends Error {
622
+ constructor(readonly transition: TurnTransition) {
623
+ super()
624
+ }
625
+ }
626
+
627
+ const continueAfterCompaction = (step: number) => new TurnTransitionError({ _tag: "ContinueAfterCompaction", step })
628
+ const continueAfterOverflowCompaction = (step: number) =>
629
+ new TurnTransitionError({
630
+ _tag: "ContinueAfterOverflowCompaction",
631
+ step,
632
+ })
633
+
634
+ const transitionFromCause = (cause: Cause.Cause<unknown>) => {
635
+ if (cause.reasons.length !== 1) return undefined
636
+ const [reason] = cause.reasons
637
+ return Cause.isDieReason(reason) && reason.defect instanceof TurnTransitionError ? reason.defect : undefined
638
+ }
639
+
640
+ const loadSystemContext = (agent: AgentRegistry.Selection) =>
641
+ Effect.all([systemContext.load(), skillGuidance.load(agent), referenceGuidance.load()], {
642
+ concurrency: "unbounded",
643
+ }).pipe(Effect.map(SystemContext.combine))
644
+
645
+ /** Chạy đúng một provider attempt trong location/session ownership hiện tại. */
646
+ const runTurnAttempt = Effect.fn("SessionRunner.runTurn")(function* (
647
+ sessionID: SessionSchema.ID,
648
+ runID: SessionRunState.ID,
649
+ retryState: { attempt: number },
650
+ promotion: SessionInput.Delivery | undefined,
651
+ step: number,
652
+ recoverOverflow?: typeof compaction.compactAfterOverflow,
653
+ ) {
654
+ yield* authorizeTurn(sessionID, runID)
655
+ // F2/7: xác nhận session vẫn thuộc location trước khi đọc hoặc ghi event.
656
+ const session = yield* getSession(sessionID)
657
+ if (session.location.directory !== location.directory || session.location.workspaceID !== location.workspaceID)
658
+ return yield* Effect.interrupt
659
+ const agent = yield* agents.select(session.agent)
660
+ yield* checkNative(sessionID, runID)
661
+ const initialized = yield* SessionContextEpoch.initialize(db, loadSystemContext(agent), session.id)
662
+ const toolFibers = yield* FiberSet.make<void, ToolOutputStore.Error>()
663
+ let needsContinuation = false
664
+ let currentStep = step
665
+ if (promotion) {
666
+ // Native loops may continue the same input, never drain another input.
667
+ if (yield* NativeOwner) return yield* Effect.die(new SessionInputOrigin.UnavailableError({ sessionID }))
668
+ const cutoff = yield* EventBus.latestSequence(db, session.id)
669
+ const pending = yield* SessionInputTurns.pending(session.id, cutoff).pipe(
670
+ Effect.provideService(Database.Service, { db }),
671
+ Effect.orDie,
672
+ )
673
+ const boundary = pending.findIndex((turn) => turn.source !== "local")
674
+ const turns = boundary === -1 ? pending : pending.slice(0, boundary)
675
+ let promoted = 0
676
+ // Keep the local steer-first/FIFO policy, but pin every promotion to
677
+ // captured IDs. The plan itself never supplies execution authority.
678
+ if (promotion === "queue") {
679
+ const queued = turns.find((turn) => turn.delivery === "queue" && turn.source === "local")
680
+ if (queued) promoted += yield* SessionInput.promoteSelected(db, events, session.id, queued)
681
+ }
682
+ for (const turn of turns)
683
+ if (turn.delivery === "steer") promoted += yield* SessionInput.promoteSelected(db, events, session.id, turn)
684
+ if (promoted > 0) currentStep = 1
685
+ }
686
+ // F3-F4/7: context epoch, model, history và tool definitions tạo request.
687
+ const system =
688
+ initialized ?? (yield* SessionContextEpoch.prepare(db, events, loadSystemContext(agent), session.id))
689
+ const model = yield* models.resolve(session)
690
+ yield* authorizeTurn(session.id, runID)
691
+ const entries = yield* SessionHistory.entriesForRunner(db, session.id, system.baselineSeq)
692
+ const context = entries.map((entry) => entry.message)
693
+ let doomLoopTail = doomLoopTailFromHistory(context)
694
+ let turnBlocked:
695
+ | {
696
+ readonly message: string
697
+ readonly rejected?: {
698
+ readonly callID: string
699
+ readonly result: ToolResultValue
700
+ }
701
+ }
702
+ | undefined
703
+ const toolMaterialization = yield* tools.materialize(agent.info?.permissions)
704
+ const native = (yield* NativeOwner) !== undefined
705
+ const constrained = native || (yield* Delegation.Current) !== undefined
706
+ const definitions =
707
+ toolMaterialization?.definitions.filter(
708
+ (tool) => !constrained || toolMaterialization.originAware?.(tool.name) === true,
709
+ ) ?? []
710
+ const admitTool = ToolAdmission.make()
711
+ const promptCacheKey = /^ses_[0-9a-f]{64}$/.test(session.id) ? session.id.slice(4) : session.id
712
+ const coding = yield* CodingWorkflow.Active
713
+ const baseRequest = LLM.request({
714
+ model,
715
+ providerOptions: { openai: { promptCacheKey } },
716
+ system: [agent.info?.system, system.baseline, coding?.instruction()]
717
+ .filter((part): part is string => part !== undefined && part.length > 0)
718
+ .map(SystemPart.make),
719
+ messages: selectContext(toLLMMessages(context, model)).messages,
720
+ tools: definitions,
721
+ })
722
+ const request = withWorkspaceRoutingMetadata(baseRequest, {
723
+ session,
724
+ agent,
725
+ contextSize: context.length,
726
+ toolCount: definitions.length,
727
+ })
728
+ yield* authorizeTurn(session.id, runID)
729
+ if (native) yield* CommandProvider.check(sessionID, request).pipe(Effect.orDie)
730
+ if (
731
+ yield* compaction.compactIfNeeded({
732
+ sessionID: session.id,
733
+ entries,
734
+ model,
735
+ request,
736
+ })
737
+ )
738
+ return yield* Effect.die(continueAfterCompaction(currentStep))
739
+ yield* checkNative(session.id, runID)
740
+ const startSnapshot = yield* native ? snapshots.captureObservation() : snapshots.capture()
741
+ yield* authorizeTurn(session.id, runID)
742
+ const publisher = createLLMEventPublisher(events, {
743
+ sessionID: session.id,
744
+ agent: agent.id,
745
+ model: {
746
+ id: CatalogModel.ID.make(model.id),
747
+ providerID: CatalogProvider.ID.make(model.provider),
748
+ ...(session.model?.variant === undefined ? {} : { variant: session.model.variant }),
749
+ },
750
+ snapshot: startSnapshot,
751
+ }, model.cost)
752
+ const withPublication = Semaphore.makeUnsafe(1).withPermit
753
+ const publish = (event: LLMEvent, outputPaths: ReadonlyArray<string> = []) =>
754
+ withPublication(publisher.publish(event, outputPaths))
755
+ let overflowFailure: ProviderErrorEvent | undefined
756
+ let providerFailureMessage: string | undefined
757
+ // F5-F6/7: mỗi event được persist tuần tự; tool execute có thể chạy song song.
758
+ const budget = yield* RunBudget.Active
759
+ yield* Effect.sync(() => budget?.attempt(request))
760
+ const providerStream = llm
761
+ .stream(request, {
762
+ retryPolicy: RequestExecutor.RetryPolicy.default,
763
+ onRetry: (notice) =>
764
+ Effect.sync(() => budget?.attempt(request)).pipe(
765
+ Effect.andThen(checkNative(session.id, runID)),
766
+ Effect.andThen(
767
+ events
768
+ .publish(SessionEvent.Run.Retried, {
769
+ sessionID: session.id,
770
+ runID,
771
+ attempt: ++retryState.attempt,
772
+ nextRetryAt: DateTime.makeUnsafe(notice.retryAt),
773
+ error: retryError(notice.error),
774
+ })
775
+ .pipe(Effect.asVoid),
776
+ ),
777
+ ),
778
+ })
779
+ .pipe(
780
+ Stream.tap((event) =>
781
+ Effect.gen(function* () {
782
+ yield* Effect.sync(() => budget?.observe(event))
783
+ if (overflowFailure || publisher.hasProviderError() || turnBlocked) return
784
+ // Persisting progress is bookkeeping, not another provider call.
785
+ // Check tool admission here; the watchdog handles open streams.
786
+ if (event.type === "tool-call") yield* checkNative(session.id, runID)
787
+ if (constrained && "providerExecuted" in event && event.providerExecuted === true)
788
+ return yield* Effect.die(new SessionInputOrigin.UnavailableError({ sessionID }))
789
+ if (LLMEvent.is.providerError(event)) {
790
+ providerFailureMessage = event.message
791
+ if (isContextOverflowFailure(event) && !publisher.hasAssistantStarted()) {
792
+ overflowFailure = event
793
+ return
794
+ }
795
+ }
796
+ if (
797
+ (event.type === "tool-input-start" || event.type === "tool-call") &&
798
+ !publisher.canRegisterTool(event.id)
799
+ ) {
800
+ turnBlocked = {
801
+ message: `Provider exceeded the ${MAX_TOOL_CALLS_PER_TURN} tool-call limit for one turn`,
802
+ }
803
+ return
804
+ }
805
+ yield* publish(event)
806
+ if (event.type !== "tool-call") return
807
+ doomLoopTail = advanceDoomLoopTail(doomLoopTail, {
808
+ name: event.name,
809
+ value: event.input,
810
+ local: event.providerExecuted !== true,
811
+ })
812
+ if (event.providerExecuted) return
813
+ if (!toolMaterialization) {
814
+ yield* withPublication(publisher.failUnsettledTools("Tools are not available for this agent"))
815
+ return
816
+ }
817
+ if (constrained && toolMaterialization.originAware?.(event.name) !== true) {
818
+ yield* publish(
819
+ LLMEvent.toolResult({
820
+ id: event.id,
821
+ name: event.name,
822
+ result: { type: "error", value: "Tool is not available for permission-constrained execution" },
823
+ }),
824
+ )
825
+ needsContinuation = true
826
+ return
827
+ }
828
+ const assistantMessageID = yield* publisher.assistantMessageID(event.id)
829
+ if (doomLoopTail && doomLoopTail.count >= DOOM_LOOP_THRESHOLD) {
830
+ const blocked = yield* permission
831
+ .assert({
832
+ action: "doom_loop",
833
+ resources: [event.name],
834
+ save: [event.name],
835
+ sessionID: session.id,
836
+ agent: agent.id,
837
+ metadata: {
838
+ tool: event.name,
839
+ input: doomLoopTail.input,
840
+ repeatCount: doomLoopTail.count,
841
+ },
842
+ source: {
843
+ type: "tool",
844
+ messageID: assistantMessageID,
845
+ callID: event.id,
846
+ },
847
+ })
848
+ .pipe(
849
+ Effect.as<string | undefined>(undefined),
850
+ Effect.catch((error) => {
851
+ if (error instanceof PermissionPolicy.CorrectedError)
852
+ return Effect.succeed(`Repeated identical tool call rejected: ${error.feedback}`)
853
+ if (error instanceof PermissionPolicy.DeniedError)
854
+ return Effect.succeed(`Repeated identical tool call denied: ${event.name}`)
855
+ if (error instanceof PermissionPolicy.RejectedError)
856
+ return Effect.succeed(`Repeated identical tool call rejected: ${event.name}`)
857
+ return Effect.die(error)
858
+ }),
859
+ )
860
+ if (blocked) {
861
+ turnBlocked = {
862
+ message: blocked,
863
+ rejected: {
864
+ callID: event.id,
865
+ result: { type: "error", value: blocked },
866
+ },
867
+ }
868
+ return
869
+ }
870
+ }
871
+ // F7/7: local tool result tạo điều kiện cho provider continuation.
872
+ needsContinuation = true
873
+ yield* Effect.uninterruptibleMask((restore) =>
874
+ restore(
875
+ admitTool(
876
+ checkNative(session.id, runID).pipe(
877
+ Effect.andThen(
878
+ Effect.suspend(() => {
879
+ const blocked = coding?.before(event)
880
+ if (blocked) return Effect.succeed({ result: { type: "error" as const, value: blocked } })
881
+ return toolMaterialization.settle({
882
+ sessionID: session.id,
883
+ agent: agent.id,
884
+ assistantMessageID,
885
+ call: event,
886
+ }).pipe(Effect.tap((settled) => Effect.sync(() => coding?.observe(event, settled.result, settled.output?.structured))))
887
+ }),
888
+ ),
889
+ ),
890
+ toolMaterialization.parallel?.(event.name),
891
+ ),
892
+ ).pipe(
893
+ Effect.flatMap((settlement) =>
894
+ publish(
895
+ LLMEvent.toolResult({
896
+ id: event.id,
897
+ name: event.name,
898
+ result: settlement.result,
899
+ output: settlement.output,
900
+ }),
901
+ settlement.outputPaths ?? [],
902
+ ),
903
+ ),
904
+ ),
905
+ ).pipe(FiberSet.run(toolFibers))
906
+ }),
907
+ ),
908
+ Stream.takeUntil(
909
+ () => turnBlocked !== undefined || overflowFailure !== undefined || publisher.hasProviderError(),
910
+ ),
911
+ Stream.runDrain,
912
+ Effect.ensuring(withPublication(publisher.flush())),
913
+ )
914
+
915
+ return yield* Effect.uninterruptibleMask((restore) =>
916
+ Effect.gen(function* () {
917
+ const stream = yield* restore(providerStream).pipe(Effect.exit)
918
+ const failure =
919
+ stream._tag === "Failure" ? Option.getOrUndefined(Cause.findErrorOption(stream.cause)) : undefined
920
+ if (
921
+ recoverOverflow &&
922
+ !publisher.hasAssistantStarted() &&
923
+ isContextOverflowFailure(overflowFailure ?? failure) &&
924
+ (yield* restore(
925
+ recoverOverflow({
926
+ sessionID: session.id,
927
+ entries,
928
+ model,
929
+ request,
930
+ }).pipe(Effect.tap(() => checkNative(session.id, runID))),
931
+ ))
932
+ )
933
+ return yield* Effect.die(continueAfterOverflowCompaction(currentStep))
934
+ if (overflowFailure) yield* publish(overflowFailure)
935
+ if (turnBlocked) {
936
+ yield* FiberSet.clear(toolFibers)
937
+ const terminalization = withPublication(
938
+ publisher.failTurnAtomically({
939
+ stepMessage: turnBlocked.message,
940
+ toolMessage: "Tool execution interrupted after turn rejection",
941
+ ...(turnBlocked.rejected === undefined
942
+ ? {}
943
+ : {
944
+ rejected: {
945
+ ...turnBlocked.rejected,
946
+ message: turnBlocked.message,
947
+ },
948
+ }),
949
+ }),
950
+ )
951
+ if (stream._tag === "Failure") return yield* failAfterTerminalization(stream.cause, terminalization)
952
+ yield* terminalization
953
+ return { needsContinuation: false, step: currentStep }
954
+ }
955
+ const llmFailure = failure instanceof LLMError ? failure : undefined
956
+ if (stream._tag === "Failure" && llmFailure && !publisher.hasProviderError()) {
957
+ yield* FiberSet.clear(toolFibers)
958
+ return yield* failAfterTerminalization(
959
+ stream.cause,
960
+ withPublication(
961
+ publisher.failTurnAtomically({
962
+ stepMessage: llmFailure.reason.message,
963
+ toolMessage: `Tool execution interrupted after provider failure: ${llmFailure.reason.message}`,
964
+ }),
965
+ ),
966
+ )
967
+ }
968
+ if (publisher.hasProviderError()) {
969
+ yield* FiberSet.clear(toolFibers)
970
+ const stepMessage = providerFailureMessage ?? "Provider failed"
971
+ const terminalization = withPublication(
972
+ publisher.failTurnAtomically({
973
+ stepMessage,
974
+ toolMessage: providerFailureMessage
975
+ ? `Tool execution interrupted after provider failure: ${providerFailureMessage}`
976
+ : "Tool execution interrupted after provider failure",
977
+ }),
978
+ )
979
+ if (stream._tag === "Failure") return yield* failAfterTerminalization(stream.cause, terminalization)
980
+ yield* terminalization
981
+ return { needsContinuation: false, step: currentStep }
982
+ }
983
+ if (stream._tag === "Failure" && !Cause.hasInterrupts(stream.cause)) {
984
+ yield* FiberSet.clear(toolFibers)
985
+ return yield* failAfterTerminalization(
986
+ stream.cause,
987
+ withPublication(
988
+ publisher.failTurnAtomically({
989
+ stepMessage: "Provider stream failed unexpectedly",
990
+ toolMessage: "Tool execution interrupted after unexpected provider stream failure",
991
+ }),
992
+ ),
993
+ )
994
+ }
995
+ if (stream._tag === "Failure" && Cause.hasInterrupts(stream.cause)) {
996
+ yield* FiberSet.clear(toolFibers)
997
+ if (publisher.hasAssistantStarted())
998
+ return yield* failAfterTerminalization(
999
+ stream.cause,
1000
+ withPublication(
1001
+ publisher.failTurnAtomically({
1002
+ stepMessage: "Provider turn interrupted",
1003
+ toolMessage: "Tool execution interrupted",
1004
+ }),
1005
+ ),
1006
+ )
1007
+ return yield* Effect.failCause(stream.cause)
1008
+ }
1009
+ const settled = yield* restore(awaitToolFibers(toolFibers)).pipe(Effect.exit)
1010
+ if (settled._tag === "Failure" && isQuestionRejectedOnly(settled.cause)) {
1011
+ yield* FiberSet.clear(toolFibers)
1012
+ return yield* failAfterTerminalization(
1013
+ Cause.interrupt(),
1014
+ withPublication(
1015
+ publisher.failTurnAtomically({
1016
+ stepMessage: "Provider turn interrupted",
1017
+ toolMessage: "Tool execution interrupted",
1018
+ }),
1019
+ ),
1020
+ )
1021
+ }
1022
+ if (settled._tag === "Failure" && Cause.hasInterrupts(settled.cause)) {
1023
+ yield* FiberSet.clear(toolFibers)
1024
+ return yield* failAfterTerminalization(
1025
+ settled.cause,
1026
+ withPublication(
1027
+ publisher.failTurnAtomically({
1028
+ stepMessage: "Provider turn interrupted",
1029
+ toolMessage: "Tool execution interrupted",
1030
+ }),
1031
+ ),
1032
+ )
1033
+ }
1034
+ if (settled._tag === "Failure" && !Cause.hasInterrupts(settled.cause)) {
1035
+ yield* FiberSet.clear(toolFibers)
1036
+ const failure = Cause.squash(settled.cause)
1037
+ const message = failure instanceof Error ? failure.message : String(failure)
1038
+ return yield* failAfterTerminalization(
1039
+ settled.cause,
1040
+ withPublication(
1041
+ publisher.failTurnAtomically({
1042
+ stepMessage: `Tool execution failed: ${message}`,
1043
+ toolMessage: `Tool execution failed: ${message}`,
1044
+ }),
1045
+ ),
1046
+ )
1047
+ }
1048
+ const stepSettlement = publisher.stepSettlement()
1049
+ if (stepSettlement) {
1050
+ yield* checkNative(session.id, runID)
1051
+ const endSnapshot = yield* native ? snapshots.captureObservation() : snapshots.capture()
1052
+ yield* checkNative(session.id, runID)
1053
+ const files =
1054
+ startSnapshot && endSnapshot
1055
+ ? yield* snapshots
1056
+ .files({ from: startSnapshot, to: endSnapshot })
1057
+ .pipe(Effect.catch(() => Effect.succeed(undefined)))
1058
+ : undefined
1059
+ yield* withPublication(
1060
+ publisher.endTurnAtomically({
1061
+ finish: stepSettlement.finish,
1062
+ tokens: stepSettlement.tokens,
1063
+ snapshot: endSnapshot,
1064
+ files,
1065
+ unresolvedToolMessage: "Provider did not return a tool result",
1066
+ }),
1067
+ )
1068
+ } else if (publisher.hasAssistantStarted()) {
1069
+ yield* withPublication(
1070
+ publisher.failTurnAtomically({
1071
+ stepMessage: "Provider stream ended without a step settlement",
1072
+ toolMessage: "Provider did not return a tool result",
1073
+ }),
1074
+ )
1075
+ return { needsContinuation: false, step: currentStep }
1076
+ }
1077
+ return {
1078
+ needsContinuation,
1079
+ step: currentStep,
1080
+ }
1081
+ }),
1082
+ )
1083
+ }, Effect.scoped)
1084
+ type RunTurn = (
1085
+ sessionID: SessionSchema.ID,
1086
+ runID: SessionRunState.ID,
1087
+ retryState: { attempt: number },
1088
+ promotion: SessionInput.Delivery | undefined,
1089
+ step: number,
1090
+ ) => Effect.Effect<{ readonly needsContinuation: boolean; readonly step: number }, RunError>
1091
+
1092
+ const runAfterOverflowCompaction: RunTurn = Effect.fnUntraced(
1093
+ function* (sessionID, runID, retryState, promotion, step) {
1094
+ return yield* runTurnAttempt(sessionID, runID, retryState, promotion, step).pipe(
1095
+ Effect.catchCause(
1096
+ Effect.fnUntraced(function* (cause) {
1097
+ const transition = transitionFromCause(cause)
1098
+ if (!transition) return yield* Effect.failCause(cause)
1099
+ if (transition.transition._tag === "ContinueAfterOverflowCompaction")
1100
+ return yield* Effect.die("Post-compaction provider attempt cannot recover another overflow")
1101
+ yield* Effect.yieldNow
1102
+ return yield* runAfterOverflowCompaction(
1103
+ sessionID,
1104
+ runID,
1105
+ retryState,
1106
+ undefined,
1107
+ transition.transition.step,
1108
+ )
1109
+ }),
1110
+ ),
1111
+ )
1112
+ },
1113
+ )
1114
+
1115
+ const runTurn: RunTurn = Effect.fnUntraced(function* (sessionID, runID, retryState, promotion, step) {
1116
+ return yield* runTurnAttempt(sessionID, runID, retryState, promotion, step, compaction.compactAfterOverflow).pipe(
1117
+ Effect.catchCause(
1118
+ Effect.fnUntraced(function* (cause) {
1119
+ const transition = transitionFromCause(cause)
1120
+ if (!transition) return yield* Effect.failCause(cause)
1121
+ yield* Effect.yieldNow
1122
+ if (transition.transition._tag === "ContinueAfterOverflowCompaction")
1123
+ return yield* runAfterOverflowCompaction(
1124
+ sessionID,
1125
+ runID,
1126
+ retryState,
1127
+ undefined,
1128
+ transition.transition.step,
1129
+ )
1130
+ return yield* runTurn(sessionID, runID, retryState, undefined, transition.transition.step)
1131
+ }),
1132
+ ),
1133
+ )
1134
+ })
1135
+
1136
+ const hasLocalPending = (sessionID: SessionSchema.ID, delivery: SessionInput.Delivery) =>
1137
+ SessionInputTurns.pending(sessionID).pipe(
1138
+ Effect.provideService(Database.Service, { db }), Effect.orDie,
1139
+ Effect.map((turns) => {
1140
+ for (const turn of turns) {
1141
+ if (turn.source !== "local") return false
1142
+ if (turn.delivery === delivery) return true
1143
+ }
1144
+ return false
1145
+ }),
1146
+ )
1147
+
1148
+ /**
1149
+ * Drain steer trước queue; trong mỗi input, lặp provider turn đến khi mọi
1150
+ * local tool result đã được model tiêu thụ hoặc step kết thúc.
1151
+ */
1152
+ const run = Effect.fn("SessionRunner.run")(function* (input: {
1153
+ readonly sessionID: SessionSchema.ID
1154
+ readonly force: boolean
1155
+ }) {
1156
+ yield* SessionInputOrigin.requireLocalRun(db, input.sessionID)
1157
+ const recoveryOwner = yield* db
1158
+ .select({
1159
+ ownerID: EventSequenceTable.owner_id,
1160
+ ownerGeneration: EventSequenceTable.owner_generation,
1161
+ projectID: SessionTable.project_id,
1162
+ workspaceID: SessionTable.workspace_id,
1163
+ })
1164
+ .from(SessionTable)
1165
+ .innerJoin(EventSequenceTable, eq(EventSequenceTable.aggregate_id, SessionTable.id))
1166
+ .where(eq(EventSequenceTable.aggregate_id, input.sessionID))
1167
+ .get()
1168
+ .pipe(Effect.orDie)
1169
+ const processWorkspaceID = location.workspaceID ?? undefined
1170
+ const sessionWorkspaceID = recoveryOwner?.workspaceID ?? undefined
1171
+ const ownerID = recoveryOwner?.ownerID ?? undefined
1172
+ const ownsRecoveryLocation =
1173
+ recoveryOwner !== undefined &&
1174
+ recoveryOwner.projectID === location.project.id &&
1175
+ sessionWorkspaceID === processWorkspaceID &&
1176
+ (processWorkspaceID
1177
+ ? ownerID === undefined || ownerID === processWorkspaceID
1178
+ : ownerID === undefined || ownerID === recoveryOwner.projectID)
1179
+ if (ownsRecoveryLocation) {
1180
+ yield* SessionVerification.recoverPendingForSession(db, events, {
1181
+ sessionID: input.sessionID,
1182
+ ownerID,
1183
+ ownerGeneration: recoveryOwner.ownerGeneration,
1184
+ }).pipe(
1185
+ Effect.provideService(VerificationSettlementPublisher.Service, verificationSettlements),
1186
+ Effect.tap((result) =>
1187
+ result.failures > 0
1188
+ ? Effect.logWarning("Verification recovery left pending work for a later retry", {
1189
+ failures: result.failures,
1190
+ sessionID: input.sessionID,
1191
+ })
1192
+ : Effect.void,
1193
+ ),
1194
+ Effect.catchCauseIf(
1195
+ (cause) => !Cause.hasInterrupts(cause),
1196
+ () =>
1197
+ Effect.logError("Verification recovery scan failed", {
1198
+ sessionID: input.sessionID,
1199
+ }),
1200
+ ),
1201
+ )
1202
+ }
1203
+ const hasSteer = yield* hasLocalPending(input.sessionID, "steer")
1204
+ const hasQueue = hasSteer ? false : yield* hasLocalPending(input.sessionID, "queue")
1205
+ if (!input.force && !hasSteer && !hasQueue) return
1206
+ return yield* Effect.uninterruptibleMask((restore) =>
1207
+ Effect.gen(function* () {
1208
+ const runID = SessionRunState.ID.create()
1209
+ const previous = yield* store.runState(input.sessionID).pipe(Effect.orDie)
1210
+ const now = yield* DateTime.now
1211
+ const startedAt =
1212
+ previous?.status === "busy" || previous?.status === "retrying"
1213
+ ? DateTime.makeUnsafe(
1214
+ Math.max(DateTime.toEpochMillis(now), DateTime.toEpochMillis(previous.time.started)),
1215
+ )
1216
+ : now
1217
+ yield* SessionInputOrigin.requireLocalRun(db, input.sessionID)
1218
+ if (previous?.status === "busy" || previous?.status === "retrying") {
1219
+ yield* events.publishBatch([
1220
+ {
1221
+ definition: SessionEvent.Run.Settled,
1222
+ data: {
1223
+ sessionID: input.sessionID,
1224
+ runID: previous.runID,
1225
+ timestamp: startedAt,
1226
+ outcome: { type: "interrupted" },
1227
+ },
1228
+ },
1229
+ {
1230
+ definition: SessionEvent.Run.Started,
1231
+ data: {
1232
+ sessionID: input.sessionID,
1233
+ runID,
1234
+ timestamp: startedAt,
1235
+ },
1236
+ },
1237
+ ])
1238
+ } else {
1239
+ yield* events.publish(SessionEvent.Run.Started, {
1240
+ sessionID: input.sessionID,
1241
+ runID,
1242
+ timestamp: startedAt,
1243
+ })
1244
+ }
1245
+
1246
+ const eligibleDrain = Effect.gen(function* () {
1247
+ yield* SessionInputOrigin.requireLocalRun(db, input.sessionID)
1248
+ // Pin trusted verifier identity after the run is durable and before
1249
+ // any drain-owned mutation or model call.
1250
+ const independentCheck = yield* prepareIndependentCheck(input.sessionID,
1251
+ SessionInputOrigin.requireLocalRun(db, input.sessionID).pipe(Effect.orDie))
1252
+ const verifier = independentCheck ? {} : yield* selectVerifier()
1253
+ let boundaryProfile: VerificationBoundaryProfile
1254
+ let startSnapshot: Snapshot.ID | undefined
1255
+ if (independentCheck) {
1256
+ boundaryProfile = "observation"
1257
+ } else if (verifier.selection) {
1258
+ boundaryProfile = "verification"
1259
+ startSnapshot = yield* snapshots.captureVerification()
1260
+ } else {
1261
+ const observation = yield* snapshots.captureObservation()
1262
+ if (observation) {
1263
+ boundaryProfile = "observation"
1264
+ startSnapshot = observation
1265
+ } else {
1266
+ boundaryProfile = "legacy"
1267
+ startSnapshot = yield* snapshots.capture()
1268
+ }
1269
+ }
1270
+ const drain = Effect.gen(function* () {
1271
+ const retryState = { attempt: 0 }
1272
+ yield* SessionInputOrigin.requireLocalRun(db, input.sessionID)
1273
+ yield* failInterruptedTools(input.sessionID)
1274
+ let promotion: SessionInput.Delivery | undefined = hasSteer ? "steer" : hasQueue ? "queue" : undefined
1275
+ let shouldRun = input.force || hasSteer || hasQueue
1276
+ while (shouldRun) {
1277
+ let needsContinuation = true
1278
+ let step = 1
1279
+ while (needsContinuation) {
1280
+ const result = yield* runTurn(input.sessionID, runID, retryState, promotion, step)
1281
+ needsContinuation = result.needsContinuation
1282
+ step = result.step + 1
1283
+ promotion = "steer"
1284
+ if (!needsContinuation)
1285
+ needsContinuation = yield* hasLocalPending(input.sessionID, "steer")
1286
+ }
1287
+ shouldRun = yield* hasLocalPending(input.sessionID, "queue")
1288
+ promotion = shouldRun ? "queue" : undefined
1289
+ }
1290
+ })
1291
+ if (independentCheck) return yield* drain.pipe(Effect.andThen(independentCheck))
1292
+ return yield* Effect.onExitPrimitive(drain, (drainExit) => {
1293
+ const observation = Effect.gen(function* () {
1294
+ const endSnapshot =
1295
+ boundaryProfile === "verification"
1296
+ ? yield* snapshots.captureVerification()
1297
+ : boundaryProfile === "observation"
1298
+ ? yield* snapshots.captureObservation()
1299
+ : yield* snapshots.capture()
1300
+ const fallbackEndSnapshot =
1301
+ boundaryProfile === "verification" && !endSnapshot ? yield* snapshots.capture() : undefined
1302
+ yield* observeVerification(
1303
+ input.sessionID,
1304
+ boundaryProfile,
1305
+ startSnapshot,
1306
+ endSnapshot,
1307
+ verifier,
1308
+ fallbackEndSnapshot,
1309
+ )
1310
+ }).pipe(
1311
+ Effect.exit,
1312
+ Effect.flatMap((observationExit) => {
1313
+ if (Exit.isSuccess(observationExit)) return Effect.void
1314
+ if (!Cause.hasInterrupts(observationExit.cause))
1315
+ return Effect.logError("Verification shadow recording failed", {
1316
+ cause: observationExit.cause,
1317
+ sessionID: input.sessionID,
1318
+ })
1319
+ if (Exit.isFailure(drainExit))
1320
+ return Effect.logWarning("Verification interruption did not replace the failed drain", {
1321
+ sessionID: input.sessionID,
1322
+ })
1323
+ return Effect.failCause(observationExit.cause)
1324
+ }),
1325
+ )
1326
+ // An already-interrupted drain still receives its terminal shadow
1327
+ // receipt. Otherwise observation remains externally cancellable, and
1328
+ // SessionVerification masks only its durable settlement sections.
1329
+ return Exit.isFailure(drainExit) && Cause.hasInterrupts(drainExit.cause)
1330
+ ? observation
1331
+ : Effect.interruptible(observation)
1332
+ })
1333
+ })
1334
+
1335
+ const budget = (yield* RunBudget.Active) ?? RunBudget.createRunBudget(Config.latest(yield* config.entries(), "run_budget"))
1336
+ const drainExit = yield* restore(CodingWorkflow.wrap(eligibleDrain).pipe(
1337
+ Effect.provideService(RunBudget.Active, budget),
1338
+ Effect.timeoutOrElse({ duration: budget.remainingDurationMs(),
1339
+ orElse: () => Effect.die(new RunBudget.RunBudgetExceeded("time")) }),
1340
+ )).pipe(Effect.exit)
1341
+ const outcome: SessionRunState.Outcome = Exit.isSuccess(drainExit)
1342
+ ? { type: "idle" }
1343
+ : Cause.hasInterruptsOnly(drainExit.cause)
1344
+ ? { type: "interrupted" }
1345
+ : terminalFailure(drainExit.cause)
1346
+ const settledNow = yield* DateTime.now
1347
+ const settledAt = DateTime.makeUnsafe(
1348
+ Math.max(DateTime.toEpochMillis(startedAt), DateTime.toEpochMillis(settledNow)),
1349
+ )
1350
+ const settlementExit = yield* events
1351
+ .publish(SessionEvent.Run.Settled, {
1352
+ sessionID: input.sessionID,
1353
+ runID,
1354
+ timestamp: settledAt,
1355
+ outcome,
1356
+ })
1357
+ .pipe(Effect.exit)
1358
+ if (Exit.isFailure(drainExit)) {
1359
+ if (Exit.isFailure(settlementExit))
1360
+ return yield* Effect.failCause(Cause.combine(drainExit.cause, settlementExit.cause))
1361
+ return yield* Effect.failCause(drainExit.cause)
1362
+ }
1363
+ if (Exit.isFailure(settlementExit)) return yield* Effect.failCause(settlementExit.cause)
1364
+ return drainExit.value
1365
+ }),
1366
+ )
1367
+ })
1368
+
1369
+ const runCommand: NodeCommandRunner.Interface["run"] = Effect.fn("SessionRunner.runCommand")(function* (
1370
+ node,
1371
+ value,
1372
+ ) {
1373
+ const parsed = Schema.decodeUnknownExit(NodeCommandRunner.Target, { onExcessProperty: "error" })(value)
1374
+ if (parsed._tag === "Failure" || (yield* PermissionOrigin.capture).length > 0)
1375
+ return yield* new SessionInputOrigin.UnavailableError({ sessionID: value.sessionID })
1376
+ const target = Object.freeze({ ...parsed.value })
1377
+ const state = yield* SessionRunState.load(db, target.sessionID).pipe(
1378
+ Effect.mapError(() => new SessionInputOrigin.UnavailableError({ sessionID: target.sessionID })),
1379
+ )
1380
+ if (
1381
+ state?.runID !== target.runID ||
1382
+ state.inputID !== target.messageID ||
1383
+ (state.status !== "busy" && state.status !== "retrying")
1384
+ )
1385
+ return yield* new SessionInputOrigin.UnavailableError({ sessionID: target.sessionID })
1386
+
1387
+ const work = Effect.gen(function* () {
1388
+ const constraint = yield* restoreContinuation(node, target).pipe(
1389
+ Effect.provideService(Database.Service, { db }),
1390
+ Effect.provideService(Location.Service, location),
1391
+ )
1392
+ const check = constraint.valid.pipe(
1393
+ Effect.flatMap((valid) =>
1394
+ valid ? Effect.void : Effect.die(new SessionInputOrigin.UnavailableError({ sessionID: target.sessionID })),
1395
+ ),
1396
+ )
1397
+ const drain = Effect.gen(function* () {
1398
+ yield* check
1399
+ const independentCheck = yield* prepareIndependentCheck(target.sessionID, check)
1400
+ const startSnapshot = independentCheck ? undefined : yield* snapshots.captureObservation()
1401
+ yield* check
1402
+ // Recovery only terminalizes uncertain tools; it never replays their side effects.
1403
+ yield* failInterruptedTools(target.sessionID)
1404
+ const retryState = { attempt: state.status === "retrying" ? state.attempt : 0 }
1405
+ let needsContinuation = true
1406
+ let step = 1
1407
+ while (needsContinuation) {
1408
+ yield* check
1409
+ const turn = yield* runTurn(target.sessionID, target.runID, retryState, undefined, step)
1410
+ needsContinuation = turn.needsContinuation
1411
+ step = turn.step + 1
1412
+ }
1413
+ yield* check
1414
+ const endSnapshot = independentCheck ? undefined : yield* snapshots.captureObservation()
1415
+ yield* check
1416
+ if (independentCheck) yield* independentCheck
1417
+ else yield* observeVerification(target.sessionID, "observation", startSnapshot, endSnapshot, {}, undefined)
1418
+ yield* check
1419
+ })
1420
+ return yield* PermissionOrigin.restrict(
1421
+ constraint,
1422
+ ExecutionBoundary.restrict(
1423
+ {
1424
+ attempt: check,
1425
+ request: (request) =>
1426
+ check.pipe(Effect.andThen(CommandProvider.check(target.sessionID, request).pipe(Effect.orDie))),
1427
+ },
1428
+ Effect.raceFirst(drain, Effect.forever(Effect.sleep("1 second").pipe(Effect.andThen(check)))).pipe(
1429
+ Effect.provideService(NativeOwner, { target, check }),
1430
+ ),
1431
+ ),
1432
+ )
1433
+ })
1434
+ const budget = RunBudget.createRunBudget(Config.latest(yield* config.entries(), "run_budget"))
1435
+ const exit = yield* CodingWorkflow.wrap(work).pipe(
1436
+ Effect.provideService(RunBudget.Active, budget),
1437
+ Effect.timeoutOrElse({ duration: budget.remainingDurationMs(),
1438
+ orElse: () => Effect.die(new RunBudget.RunBudgetExceeded("time")) }), Effect.interruptible, Effect.exit,
1439
+ )
1440
+ const outcome: SessionRunState.Outcome = Exit.isSuccess(exit)
1441
+ ? { type: "idle" }
1442
+ : Cause.hasInterruptsOnly(exit.cause)
1443
+ ? { type: "interrupted" }
1444
+ : terminalFailure(exit.cause)
1445
+ const timestamp = DateTime.makeUnsafe(
1446
+ Math.max(DateTime.toEpochMillis(state.time.started), DateTime.toEpochMillis(yield* DateTime.now)),
1447
+ )
1448
+ const settlement = events
1449
+ .publish(SessionEvent.Run.Settled, {
1450
+ sessionID: target.sessionID,
1451
+ runID: target.runID,
1452
+ timestamp,
1453
+ outcome,
1454
+ })
1455
+ .pipe(Effect.asVoid)
1456
+ if (Exit.isFailure(exit)) return yield* failAfterTerminalization(exit.cause, settlement)
1457
+ yield* settlement
1458
+ }, Effect.uninterruptible)
1459
+
1460
+ return Context.make(Service, Service.of({ run })).pipe(
1461
+ Context.add(NodeCommandRunner.Service, NodeCommandRunner.Service.of({ run: runCommand })),
1462
+ )
1463
+ }),
1464
+ )
1465
+
1466
+ export const defaultLayer = layer