@diffra-ai/durable 0.0.0-stage → 0.2.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 (411) hide show
  1. package/CHANGELOG.md +442 -0
  2. package/README.md +1153 -2
  3. package/dist/codemode/codemode.d.ts +174 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +884 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +127 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/models.d.ts +29 -0
  16. package/dist/codemode/models.d.ts.map +1 -0
  17. package/dist/codemode/models.js +242 -0
  18. package/dist/codemode/models.js.map +1 -0
  19. package/dist/codemode/output.d.ts +43 -0
  20. package/dist/codemode/output.d.ts.map +1 -0
  21. package/dist/codemode/output.js +168 -0
  22. package/dist/codemode/output.js.map +1 -0
  23. package/dist/documents.d.ts +66 -0
  24. package/dist/documents.d.ts.map +1 -0
  25. package/dist/documents.js +98 -0
  26. package/dist/documents.js.map +1 -0
  27. package/dist/entries.d.ts +31 -0
  28. package/dist/entries.d.ts.map +1 -0
  29. package/dist/entries.js +31 -0
  30. package/dist/entries.js.map +1 -0
  31. package/dist/env/decode.d.ts +16 -0
  32. package/dist/env/decode.d.ts.map +1 -0
  33. package/dist/env/decode.js +28 -0
  34. package/dist/env/decode.js.map +1 -0
  35. package/dist/env/index.d.ts +308 -0
  36. package/dist/env/index.d.ts.map +1 -0
  37. package/dist/env/index.js +49 -0
  38. package/dist/env/index.js.map +1 -0
  39. package/dist/env/line-scan.d.ts +13 -0
  40. package/dist/env/line-scan.d.ts.map +1 -0
  41. package/dist/env/line-scan.js +147 -0
  42. package/dist/env/line-scan.js.map +1 -0
  43. package/dist/env/node-watch.d.ts +29 -0
  44. package/dist/env/node-watch.d.ts.map +1 -0
  45. package/dist/env/node-watch.js +487 -0
  46. package/dist/env/node-watch.js.map +1 -0
  47. package/dist/env/node.d.ts +56 -0
  48. package/dist/env/node.d.ts.map +1 -0
  49. package/dist/env/node.js +1185 -0
  50. package/dist/env/node.js.map +1 -0
  51. package/dist/errors.d.ts +48 -0
  52. package/dist/errors.d.ts.map +1 -0
  53. package/dist/errors.js +76 -0
  54. package/dist/errors.js.map +1 -0
  55. package/dist/harness/agent.d.ts +46 -0
  56. package/dist/harness/agent.d.ts.map +1 -0
  57. package/dist/harness/agent.js +334 -0
  58. package/dist/harness/agent.js.map +1 -0
  59. package/dist/harness/compaction.d.ts +68 -0
  60. package/dist/harness/compaction.d.ts.map +1 -0
  61. package/dist/harness/compaction.js +431 -0
  62. package/dist/harness/compaction.js.map +1 -0
  63. package/dist/harness/context.d.ts +84 -0
  64. package/dist/harness/context.d.ts.map +1 -0
  65. package/dist/harness/context.js +301 -0
  66. package/dist/harness/context.js.map +1 -0
  67. package/dist/harness/define.d.ts +25 -0
  68. package/dist/harness/define.d.ts.map +1 -0
  69. package/dist/harness/define.js +32 -0
  70. package/dist/harness/define.js.map +1 -0
  71. package/dist/harness/generation.d.ts +117 -0
  72. package/dist/harness/generation.d.ts.map +1 -0
  73. package/dist/harness/generation.js +1098 -0
  74. package/dist/harness/generation.js.map +1 -0
  75. package/dist/harness/harness.d.ts +22 -0
  76. package/dist/harness/harness.d.ts.map +1 -0
  77. package/dist/harness/harness.js +438 -0
  78. package/dist/harness/harness.js.map +1 -0
  79. package/dist/harness/inbox.d.ts +84 -0
  80. package/dist/harness/inbox.d.ts.map +1 -0
  81. package/dist/harness/inbox.js +135 -0
  82. package/dist/harness/inbox.js.map +1 -0
  83. package/dist/harness/json.d.ts +26 -0
  84. package/dist/harness/json.d.ts.map +1 -0
  85. package/dist/harness/json.js +51 -0
  86. package/dist/harness/json.js.map +1 -0
  87. package/dist/harness/live.d.ts +285 -0
  88. package/dist/harness/live.d.ts.map +1 -0
  89. package/dist/harness/live.js +257 -0
  90. package/dist/harness/live.js.map +1 -0
  91. package/dist/harness/parks.d.ts +23 -0
  92. package/dist/harness/parks.d.ts.map +1 -0
  93. package/dist/harness/parks.js +52 -0
  94. package/dist/harness/parks.js.map +1 -0
  95. package/dist/harness/partial-changes.d.ts +54 -0
  96. package/dist/harness/partial-changes.d.ts.map +1 -0
  97. package/dist/harness/partial-changes.js +163 -0
  98. package/dist/harness/partial-changes.js.map +1 -0
  99. package/dist/harness/prompt.d.ts +27 -0
  100. package/dist/harness/prompt.d.ts.map +1 -0
  101. package/dist/harness/prompt.js +131 -0
  102. package/dist/harness/prompt.js.map +1 -0
  103. package/dist/harness/provider.d.ts +16 -0
  104. package/dist/harness/provider.d.ts.map +1 -0
  105. package/dist/harness/provider.js +33 -0
  106. package/dist/harness/provider.js.map +1 -0
  107. package/dist/harness/registry-reader.d.ts +11 -0
  108. package/dist/harness/registry-reader.d.ts.map +1 -0
  109. package/dist/harness/registry-reader.js +25 -0
  110. package/dist/harness/registry-reader.js.map +1 -0
  111. package/dist/harness/registry.d.ts +6 -0
  112. package/dist/harness/registry.d.ts.map +1 -0
  113. package/dist/harness/registry.js +101 -0
  114. package/dist/harness/registry.js.map +1 -0
  115. package/dist/harness/scheduler.d.ts +195 -0
  116. package/dist/harness/scheduler.d.ts.map +1 -0
  117. package/dist/harness/scheduler.js +3073 -0
  118. package/dist/harness/scheduler.js.map +1 -0
  119. package/dist/harness/submissions.d.ts +44 -0
  120. package/dist/harness/submissions.d.ts.map +1 -0
  121. package/dist/harness/submissions.js +265 -0
  122. package/dist/harness/submissions.js.map +1 -0
  123. package/dist/harness/task-graph.d.ts +75 -0
  124. package/dist/harness/task-graph.d.ts.map +1 -0
  125. package/dist/harness/task-graph.js +224 -0
  126. package/dist/harness/task-graph.js.map +1 -0
  127. package/dist/harness/telemetry.d.ts +307 -0
  128. package/dist/harness/telemetry.d.ts.map +1 -0
  129. package/dist/harness/telemetry.js +140 -0
  130. package/dist/harness/telemetry.js.map +1 -0
  131. package/dist/harness/tool.d.ts +106 -0
  132. package/dist/harness/tool.d.ts.map +1 -0
  133. package/dist/harness/tool.js +1182 -0
  134. package/dist/harness/tool.js.map +1 -0
  135. package/dist/harness/transcript.d.ts +72 -0
  136. package/dist/harness/transcript.d.ts.map +1 -0
  137. package/dist/harness/transcript.js +264 -0
  138. package/dist/harness/transcript.js.map +1 -0
  139. package/dist/harness/types.d.ts +1146 -0
  140. package/dist/harness/types.d.ts.map +1 -0
  141. package/dist/harness/types.js +2 -0
  142. package/dist/harness/types.js.map +1 -0
  143. package/dist/harness/usage.d.ts +19 -0
  144. package/dist/harness/usage.d.ts.map +1 -0
  145. package/dist/harness/usage.js +57 -0
  146. package/dist/harness/usage.js.map +1 -0
  147. package/dist/harness/util.d.ts +25 -0
  148. package/dist/harness/util.d.ts.map +1 -0
  149. package/dist/harness/util.js +76 -0
  150. package/dist/harness/util.js.map +1 -0
  151. package/dist/harness/view.d.ts +69 -0
  152. package/dist/harness/view.d.ts.map +1 -0
  153. package/dist/harness/view.js +265 -0
  154. package/dist/harness/view.js.map +1 -0
  155. package/dist/ids.d.ts +6 -0
  156. package/dist/ids.d.ts.map +1 -0
  157. package/dist/ids.js +9 -0
  158. package/dist/ids.js.map +1 -0
  159. package/dist/images/cloudflare.d.ts +4 -0
  160. package/dist/images/cloudflare.d.ts.map +1 -0
  161. package/dist/images/cloudflare.js +9 -0
  162. package/dist/images/cloudflare.js.map +1 -0
  163. package/dist/images/exif.d.ts +3 -0
  164. package/dist/images/exif.d.ts.map +1 -0
  165. package/dist/images/exif.js +71 -0
  166. package/dist/images/exif.js.map +1 -0
  167. package/dist/images/fit.d.ts +41 -0
  168. package/dist/images/fit.d.ts.map +1 -0
  169. package/dist/images/fit.js +108 -0
  170. package/dist/images/fit.js.map +1 -0
  171. package/dist/images/index.d.ts +18 -0
  172. package/dist/images/index.d.ts.map +1 -0
  173. package/dist/images/index.js +125 -0
  174. package/dist/images/index.js.map +1 -0
  175. package/dist/images/node-worker.d.ts +19 -0
  176. package/dist/images/node-worker.d.ts.map +1 -0
  177. package/dist/images/node-worker.js +17 -0
  178. package/dist/images/node-worker.js.map +1 -0
  179. package/dist/images/node.d.ts +21 -0
  180. package/dist/images/node.d.ts.map +1 -0
  181. package/dist/images/node.js +121 -0
  182. package/dist/images/node.js.map +1 -0
  183. package/dist/index.d.ts +29 -0
  184. package/dist/index.d.ts.map +1 -0
  185. package/dist/index.js +23 -0
  186. package/dist/index.js.map +1 -0
  187. package/dist/search.d.ts +29 -0
  188. package/dist/search.d.ts.map +1 -0
  189. package/dist/search.js +148 -0
  190. package/dist/search.js.map +1 -0
  191. package/dist/session/cached-storage.d.ts +72 -0
  192. package/dist/session/cached-storage.d.ts.map +1 -0
  193. package/dist/session/cached-storage.js +269 -0
  194. package/dist/session/cached-storage.js.map +1 -0
  195. package/dist/session/conversation-tails.d.ts +33 -0
  196. package/dist/session/conversation-tails.d.ts.map +1 -0
  197. package/dist/session/conversation-tails.js +101 -0
  198. package/dist/session/conversation-tails.js.map +1 -0
  199. package/dist/session/forks.d.ts +10 -0
  200. package/dist/session/forks.d.ts.map +1 -0
  201. package/dist/session/forks.js +42 -0
  202. package/dist/session/forks.js.map +1 -0
  203. package/dist/session/keys.d.ts +69 -0
  204. package/dist/session/keys.d.ts.map +1 -0
  205. package/dist/session/keys.js +161 -0
  206. package/dist/session/keys.js.map +1 -0
  207. package/dist/session/session.d.ts +287 -0
  208. package/dist/session/session.d.ts.map +1 -0
  209. package/dist/session/session.js +1701 -0
  210. package/dist/session/session.js.map +1 -0
  211. package/dist/session/transaction.d.ts +205 -0
  212. package/dist/session/transaction.d.ts.map +1 -0
  213. package/dist/session/transaction.js +1059 -0
  214. package/dist/session/transaction.js.map +1 -0
  215. package/dist/session/writer.d.ts +74 -0
  216. package/dist/session/writer.d.ts.map +1 -0
  217. package/dist/session/writer.js +294 -0
  218. package/dist/session/writer.js.map +1 -0
  219. package/dist/signals.d.ts +180 -0
  220. package/dist/signals.d.ts.map +1 -0
  221. package/dist/signals.js +236 -0
  222. package/dist/signals.js.map +1 -0
  223. package/dist/storage/indexeddb.d.ts +69 -0
  224. package/dist/storage/indexeddb.d.ts.map +1 -0
  225. package/dist/storage/indexeddb.js +883 -0
  226. package/dist/storage/indexeddb.js.map +1 -0
  227. package/dist/storage/jsonl/index.d.ts +2 -0
  228. package/dist/storage/jsonl/index.d.ts.map +1 -0
  229. package/dist/storage/jsonl/index.js +2 -0
  230. package/dist/storage/jsonl/index.js.map +1 -0
  231. package/dist/storage/jsonl/node.d.ts +6 -0
  232. package/dist/storage/jsonl/node.d.ts.map +1 -0
  233. package/dist/storage/jsonl/node.js +8 -0
  234. package/dist/storage/jsonl/node.js.map +1 -0
  235. package/dist/storage/jsonl/storage.d.ts +206 -0
  236. package/dist/storage/jsonl/storage.d.ts.map +1 -0
  237. package/dist/storage/jsonl/storage.js +799 -0
  238. package/dist/storage/jsonl/storage.js.map +1 -0
  239. package/dist/storage/memory.d.ts +68 -0
  240. package/dist/storage/memory.d.ts.map +1 -0
  241. package/dist/storage/memory.js +761 -0
  242. package/dist/storage/memory.js.map +1 -0
  243. package/dist/storage/scan.d.ts +18 -0
  244. package/dist/storage/scan.d.ts.map +1 -0
  245. package/dist/storage/scan.js +29 -0
  246. package/dist/storage/scan.js.map +1 -0
  247. package/dist/storage/sqlite/cloudflare.d.ts +9 -0
  248. package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
  249. package/dist/storage/sqlite/cloudflare.js +11 -0
  250. package/dist/storage/sqlite/cloudflare.js.map +1 -0
  251. package/dist/storage/sqlite/commit.d.ts +52 -0
  252. package/dist/storage/sqlite/commit.d.ts.map +1 -0
  253. package/dist/storage/sqlite/commit.js +371 -0
  254. package/dist/storage/sqlite/commit.js.map +1 -0
  255. package/dist/storage/sqlite/database.d.ts +2 -0
  256. package/dist/storage/sqlite/database.d.ts.map +1 -0
  257. package/dist/storage/sqlite/database.js +2 -0
  258. package/dist/storage/sqlite/database.js.map +1 -0
  259. package/dist/storage/sqlite/index.d.ts +4 -0
  260. package/dist/storage/sqlite/index.d.ts.map +1 -0
  261. package/dist/storage/sqlite/index.js +3 -0
  262. package/dist/storage/sqlite/index.js.map +1 -0
  263. package/dist/storage/sqlite/migrations.d.ts +12 -0
  264. package/dist/storage/sqlite/migrations.d.ts.map +1 -0
  265. package/dist/storage/sqlite/migrations.js +121 -0
  266. package/dist/storage/sqlite/migrations.js.map +1 -0
  267. package/dist/storage/sqlite/node.d.ts +8 -0
  268. package/dist/storage/sqlite/node.d.ts.map +1 -0
  269. package/dist/storage/sqlite/node.js +12 -0
  270. package/dist/storage/sqlite/node.js.map +1 -0
  271. package/dist/storage/sqlite/rows.d.ts +33 -0
  272. package/dist/storage/sqlite/rows.d.ts.map +1 -0
  273. package/dist/storage/sqlite/rows.js +53 -0
  274. package/dist/storage/sqlite/rows.js.map +1 -0
  275. package/dist/storage/sqlite/schema.d.ts +45 -0
  276. package/dist/storage/sqlite/schema.d.ts.map +1 -0
  277. package/dist/storage/sqlite/schema.js +50 -0
  278. package/dist/storage/sqlite/schema.js.map +1 -0
  279. package/dist/storage/sqlite/statements.d.ts +13 -0
  280. package/dist/storage/sqlite/statements.d.ts.map +1 -0
  281. package/dist/storage/sqlite/statements.js +88 -0
  282. package/dist/storage/sqlite/statements.js.map +1 -0
  283. package/dist/storage/sqlite/storage.d.ts +86 -0
  284. package/dist/storage/sqlite/storage.d.ts.map +1 -0
  285. package/dist/storage/sqlite/storage.js +534 -0
  286. package/dist/storage/sqlite/storage.js.map +1 -0
  287. package/dist/storage/store/commit.d.ts +33 -0
  288. package/dist/storage/store/commit.d.ts.map +1 -0
  289. package/dist/storage/store/commit.js +286 -0
  290. package/dist/storage/store/commit.js.map +1 -0
  291. package/dist/storage/store/documents.d.ts +43 -0
  292. package/dist/storage/store/documents.d.ts.map +1 -0
  293. package/dist/storage/store/documents.js +102 -0
  294. package/dist/storage/store/documents.js.map +1 -0
  295. package/dist/storage/store/index.d.ts +2 -0
  296. package/dist/storage/store/index.d.ts.map +1 -0
  297. package/dist/storage/store/index.js +2 -0
  298. package/dist/storage/store/index.js.map +1 -0
  299. package/dist/storage/store/queries.d.ts +49 -0
  300. package/dist/storage/store/queries.d.ts.map +1 -0
  301. package/dist/storage/store/queries.js +93 -0
  302. package/dist/storage/store/queries.js.map +1 -0
  303. package/dist/storage/store/storage.d.ts +60 -0
  304. package/dist/storage/store/storage.d.ts.map +1 -0
  305. package/dist/storage/store/storage.js +438 -0
  306. package/dist/storage/store/storage.js.map +1 -0
  307. package/dist/storage/store/tables.d.ts +54 -0
  308. package/dist/storage/store/tables.d.ts.map +1 -0
  309. package/dist/storage/store/tables.js +108 -0
  310. package/dist/storage/store/tables.js.map +1 -0
  311. package/dist/tasks.d.ts +6 -0
  312. package/dist/tasks.d.ts.map +1 -0
  313. package/dist/tasks.js +5 -0
  314. package/dist/tasks.js.map +1 -0
  315. package/dist/testing/assertions.d.ts +5 -0
  316. package/dist/testing/assertions.d.ts.map +1 -0
  317. package/dist/testing/assertions.js +25 -0
  318. package/dist/testing/assertions.js.map +1 -0
  319. package/dist/testing/commit-writes.d.ts +5 -0
  320. package/dist/testing/commit-writes.d.ts.map +1 -0
  321. package/dist/testing/commit-writes.js +12 -0
  322. package/dist/testing/commit-writes.js.map +1 -0
  323. package/dist/testing/env-conformance.d.ts +7 -0
  324. package/dist/testing/env-conformance.d.ts.map +1 -0
  325. package/dist/testing/env-conformance.js +531 -0
  326. package/dist/testing/env-conformance.js.map +1 -0
  327. package/dist/testing/index.d.ts +8 -0
  328. package/dist/testing/index.d.ts.map +1 -0
  329. package/dist/testing/index.js +7 -0
  330. package/dist/testing/index.js.map +1 -0
  331. package/dist/testing/runner.d.ts +12 -0
  332. package/dist/testing/runner.d.ts.map +1 -0
  333. package/dist/testing/runner.js +23 -0
  334. package/dist/testing/runner.js.map +1 -0
  335. package/dist/testing/storage-benchmark.d.ts +41 -0
  336. package/dist/testing/storage-benchmark.d.ts.map +1 -0
  337. package/dist/testing/storage-benchmark.js +351 -0
  338. package/dist/testing/storage-benchmark.js.map +1 -0
  339. package/dist/testing/storage-conformance.d.ts +4 -0
  340. package/dist/testing/storage-conformance.d.ts.map +1 -0
  341. package/dist/testing/storage-conformance.js +1554 -0
  342. package/dist/testing/storage-conformance.js.map +1 -0
  343. package/dist/testing/types.d.ts +39 -0
  344. package/dist/testing/types.d.ts.map +1 -0
  345. package/dist/testing/types.js +2 -0
  346. package/dist/testing/types.js.map +1 -0
  347. package/dist/timers.d.ts +21 -0
  348. package/dist/timers.d.ts.map +1 -0
  349. package/dist/timers.js +72 -0
  350. package/dist/timers.js.map +1 -0
  351. package/dist/tool-search/index.d.ts +2 -0
  352. package/dist/tool-search/index.d.ts.map +1 -0
  353. package/dist/tool-search/index.js +2 -0
  354. package/dist/tool-search/index.js.map +1 -0
  355. package/dist/tool-search/tool-search.d.ts +17 -0
  356. package/dist/tool-search/tool-search.d.ts.map +1 -0
  357. package/dist/tool-search/tool-search.js +96 -0
  358. package/dist/tool-search/tool-search.js.map +1 -0
  359. package/dist/tools/bash.d.ts +55 -0
  360. package/dist/tools/bash.d.ts.map +1 -0
  361. package/dist/tools/bash.js +139 -0
  362. package/dist/tools/bash.js.map +1 -0
  363. package/dist/tools/edit-diff.d.ts +89 -0
  364. package/dist/tools/edit-diff.d.ts.map +1 -0
  365. package/dist/tools/edit-diff.js +386 -0
  366. package/dist/tools/edit-diff.js.map +1 -0
  367. package/dist/tools/edit.d.ts +18 -0
  368. package/dist/tools/edit.d.ts.map +1 -0
  369. package/dist/tools/edit.js +117 -0
  370. package/dist/tools/edit.js.map +1 -0
  371. package/dist/tools/env.d.ts +5 -0
  372. package/dist/tools/env.d.ts.map +1 -0
  373. package/dist/tools/env.js +7 -0
  374. package/dist/tools/env.js.map +1 -0
  375. package/dist/tools/file-mutation-queue.d.ts +9 -0
  376. package/dist/tools/file-mutation-queue.d.ts.map +1 -0
  377. package/dist/tools/file-mutation-queue.js +52 -0
  378. package/dist/tools/file-mutation-queue.js.map +1 -0
  379. package/dist/tools/image-processor.d.ts +57 -0
  380. package/dist/tools/image-processor.d.ts.map +1 -0
  381. package/dist/tools/image-processor.js +49 -0
  382. package/dist/tools/image-processor.js.map +1 -0
  383. package/dist/tools/image.d.ts +20 -0
  384. package/dist/tools/image.d.ts.map +1 -0
  385. package/dist/tools/image.js +178 -0
  386. package/dist/tools/image.js.map +1 -0
  387. package/dist/tools/index.d.ts +46 -0
  388. package/dist/tools/index.d.ts.map +1 -0
  389. package/dist/tools/index.js +23 -0
  390. package/dist/tools/index.js.map +1 -0
  391. package/dist/tools/path-utils.d.ts +5 -0
  392. package/dist/tools/path-utils.d.ts.map +1 -0
  393. package/dist/tools/path-utils.js +26 -0
  394. package/dist/tools/path-utils.js.map +1 -0
  395. package/dist/tools/read.d.ts +30 -0
  396. package/dist/tools/read.d.ts.map +1 -0
  397. package/dist/tools/read.js +239 -0
  398. package/dist/tools/read.js.map +1 -0
  399. package/dist/tools/write.d.ts +10 -0
  400. package/dist/tools/write.d.ts.map +1 -0
  401. package/dist/tools/write.js +31 -0
  402. package/dist/tools/write.js.map +1 -0
  403. package/dist/truncate.d.ts +65 -0
  404. package/dist/truncate.d.ts.map +1 -0
  405. package/dist/truncate.js +124 -0
  406. package/dist/truncate.js.map +1 -0
  407. package/dist/types.d.ts +1244 -0
  408. package/dist/types.d.ts.map +1 -0
  409. package/dist/types.js +3 -0
  410. package/dist/types.js.map +1 -0
  411. package/package.json +179 -5
@@ -0,0 +1,3073 @@
1
+ import { awaitWithContext, withAbortSignal, withoutAbortSignal, withTelemetry, } from "@diffra-ai/chord/context";
2
+ import { ownedSlice } from "@diffra-ai/chord/delta";
3
+ import { copyJson } from "@diffra-ai/chord/json";
4
+ import { createTypedMetrics, createTypedSpanStarter, NOOP_TELEMETRY_CONTEXT, NOOP_TELEMETRY_METRICS, } from "@diffra-ai/telemetry";
5
+ import { errorMessage, ReadOnlySession } from "../errors.js";
6
+ import { ALL_KEYS, conversationKey, INTENT_KEY, ownedKey, ROOTS_KEY, taskKey } from "../session/keys.js";
7
+ import { checkSleep, readSignal, sleepDue, sleepWake } from "../signals.js";
8
+ import { agentHooks, DEFAULT_RESTART_LIMIT } from "./agent.js";
9
+ import { advanceRange, rangeEntry, readContextFrom } from "./context.js";
10
+ import { providerSessionsByRuntime } from "./provider.js";
11
+ import { DURABLE_TELEMETRY_SCHEMA } from "./telemetry.js";
12
+ import { closedError, conversationEntries, optionalExtension, scanAll, Waiters } from "./util.js";
13
+ const SCAN_PAGE_SIZE = 256;
14
+ const NO_KEYS = [];
15
+ const LIVE_STATUSES = ["pending", "running", "waiting", "sleeping", "completing"];
16
+ /** The part of a record `blockedReason()` reads. */
17
+ export function blockedSubject(record) {
18
+ return {
19
+ id: record.id,
20
+ kind: record.kind,
21
+ version: record.version,
22
+ abortRequested: record.abortRequested,
23
+ ...(record.abortReason === undefined ? {} : { abortReason: record.abortReason }),
24
+ status: record.state.status,
25
+ };
26
+ }
27
+ /** Continue with the next phase, the first one. */
28
+ const CONTINUE = { kind: "continue" };
29
+ /** Rule 5: the phase made durable progress; `#progress()` decides once the decision stands. */
30
+ const PROGRESS = { kind: "progress" };
31
+ /** End the invocation without a write. */
32
+ const END = { kind: "end" };
33
+ /** End it: an owner's cancellation intent reaches it before its cascade did; schedule the cascade. */
34
+ const CASCADE = { kind: "cascade" };
35
+ function conversationNode(id) {
36
+ return `c${id}`;
37
+ }
38
+ function conversationOf(node) {
39
+ return Number(node.slice(1));
40
+ }
41
+ /** The node a task hangs from: its owner task, or its conversation. */
42
+ function parentNode(node) {
43
+ return node.owner ?? conversationNode(node.conversationId);
44
+ }
45
+ /**
46
+ * Durable task scheduler of one Harness.
47
+ *
48
+ * `#live` mirrors every committed non-terminal task record: pending, running, waiting, sleeping, and completing. The
49
+ * synchronous commit listener updates it on the Session line, so code running on the line reads exactly the committed
50
+ * state from it.
51
+ *
52
+ * Tasks and conversations form one ownership tree (spec §5.5): a task's parent is its owner task, or its conversation;
53
+ * a conversation's parent is its owner task, if any. Walks up that tree decide what reaches one task: a cancelling
54
+ * owner, a scope. `#below` lists the tree downward around live work, so what lies below one node is a walk down from
55
+ * it: a task's live ordinary owned work, which holds its outcome as `completing` and delays its abort handler, a
56
+ * scope's tasks, a cascade's reach. No pass visits every live task; the sets below hold each pass's candidates.
57
+ *
58
+ * The ownership indexes are bounded by live work: an owner edge and an ended task's ownership fields are kept only while
59
+ * something is listed below them in `#below`, so only the chains above live tasks are known, whole. Work that appears
60
+ * later below a dropped node finds it unknown and loads its chain from storage again.
61
+ *
62
+ * Invariant: every task transition is decided and written by one callback serialized on the Session line. That covers
63
+ * reservation, marks, runtime commits, finalization, and the step before each phase, which applies the precedence rules
64
+ * and writes a fault or handover. Handlers and joins run off the line. An invocation ends inside the step that decides
65
+ * its end, so a runtime commit it queued either lands before that decision or is rejected.
66
+ *
67
+ * Decisions stay serialized; their storage overlaps (group commit). The Session stores the commits of several jobs in
68
+ * one call while the line runs on, and this memory changes only as each commit is published. So every decision reads
69
+ * it in a decision region (`#region()`): synchronous, recording the keys it reads (a task's record, the live work below
70
+ * a node, the cancellation intent set), staging nothing; when one of them has an unpublished writer, the region waits
71
+ * for its publication and runs again, and only a region that read nothing unpublished is applied. Every commit writes
72
+ * the memberships its task changes alter (`membershipKeys()`), so a walk that a pending commit would change waits.
73
+ */
74
+ export class TaskScheduler {
75
+ providerSessionIds = new Set();
76
+ #telemetry;
77
+ #activeMetric;
78
+ #durationMetric;
79
+ #resumed = new Set();
80
+ #session;
81
+ #storage;
82
+ #registry;
83
+ #models;
84
+ #agent;
85
+ #settings;
86
+ #env;
87
+ #now;
88
+ #onWake;
89
+ #timers;
90
+ #writeAtClose;
91
+ #report;
92
+ #settleOutcome;
93
+ #limitsRestarts;
94
+ #keepsAbandoned;
95
+ #parkedAtGate;
96
+ #withdrawInputs;
97
+ #conversation;
98
+ #context;
99
+ #live = new Map();
100
+ /**
101
+ * Context range last read through a task runtime, per conversation: a later read, by any of its tasks, scans only
102
+ * newer entries. `idleSince` is the Harness time it was first seen idle. Derived and never persisted; dropped at the
103
+ * first idle check after `settings.contextRetentionMs` of idleness, and at close.
104
+ */
105
+ #contexts = new Map();
106
+ /**
107
+ * The idle kept contexts by `idleSince`, oldest first: the expiry order, so neither an expiry nor finding the next one
108
+ * scans `#contexts`. Kept sorted also when the Harness clock goes back (see `#markIdle`).
109
+ */
110
+ #idleOrder = new Map();
111
+ /** At least the newest `idleSince` in `#idleOrder` (drops do not lower it): an older one added means the clock went back. */
112
+ #idleNewest = Number.NEGATIVE_INFINITY;
113
+ /**
114
+ * A chain load resolved what `#idle()` treats as unknown for a live task whose chain is not loaded, which can make a
115
+ * scope idle without a task change below it; the next idle check then covers every scope.
116
+ */
117
+ #unknownsChanged = false;
118
+ /** Idle checks that covered every scope (`idleState`, a test diagnostic). */
119
+ #fullIdleChecks = 0;
120
+ /** Background timer for the earliest expiry of an idle context, unless the host declined it (see `#scheduleExpiry`). */
121
+ #expiry;
122
+ #invocations = new Map();
123
+ #taskWaiters = new Waiters();
124
+ /** Idle waiters by conversation; `undefined` waits for the whole Harness. */
125
+ #idleWaiters = new Waiters();
126
+ /** Definition whose migration failed per task; retried only once the registry resolves another definition. */
127
+ #failedMigrations = new Map();
128
+ /** Owner task of each known conversation, `null` when ownerless. */
129
+ #edges = new Map();
130
+ /** Ownership fields of the known terminal tasks, which walks pass through. */
131
+ #settled = new Map();
132
+ /**
133
+ * Ended tasks and conversations found unneeded, dropped by `#sweep()` at the end of the commit's publication unless
134
+ * needed again by then: a chain load installs nodes before the work below them is listed.
135
+ */
136
+ #dropQueue = new Set();
137
+ /**
138
+ * The tree downward around live work: each node's child nodes that are live tasks or have nodes listed below them.
139
+ * A conversation's parent is its owner task; ownerless ones with work are in `#roots`.
140
+ */
141
+ #below = new Map();
142
+ #roots = new Set();
143
+ /** Known tasks whose chain may not be loaded; every other known task's chain is, and stays, loaded. */
144
+ #unloaded = new Set();
145
+ /** Live tasks with cancellation intent, the sources of abort cascades (spec §5.4). */
146
+ #intent = new Set();
147
+ /**
148
+ * Live tasks that are not `completing`, the candidates of a reservation pass; ones found waiting leave it. A pass
149
+ * takes the set while it plans, so a task made a candidate meanwhile is not dropped by its stale decision.
150
+ */
151
+ #runnable = new Set();
152
+ /**
153
+ * `completing` tasks the next finalize pass checks: those that started holding, and holders of ended work. A pass
154
+ * takes them before it plans, so a check asked for meanwhile stays for the next pass.
155
+ */
156
+ #finalizeChecks = new Set();
157
+ /** Live waiting tasks by each task in their `on`. */
158
+ #waiters = new Map();
159
+ /**
160
+ * `failFast` waiters the next reconcile checks for a failed task in `on`: at open, when they start waiting, and when
161
+ * one of their tasks fails.
162
+ */
163
+ #failFastChecks = new Set();
164
+ /**
165
+ * Live tasks with `abandonOnRestart` found at open, from an earlier Harness. The first reservation pass abort-marks
166
+ * them with reason `restart`, so nothing of them or below them runs a phase again.
167
+ */
168
+ #abandoned = new Set();
169
+ /** Sleeping live tasks, due or not: the candidates of `#wakeDue()`. */
170
+ #sleeping = new Set();
171
+ /** Registry publications so far: a phase that took its snapshot at an older count ran under a replaced registry. */
172
+ #publications = 0;
173
+ /** Sleeping calls parked at a gate that the registry or open wakes before their time (`#wakeGate()`). */
174
+ #gateWakes = new Set();
175
+ /** Timer for the earliest sleep, without `onWake` while scheduling runs. */
176
+ #timer;
177
+ /** Last value given to `onWake`, so an unchanged one is not repeated. */
178
+ #lastWake;
179
+ #wakeScheduled = false;
180
+ #blockedListeners = new Set();
181
+ /** A registry snapshot that threw for the task graph was reported; it is read per record, so only once. */
182
+ #snapshotReported = false;
183
+ #reconcileScheduled = false;
184
+ /** Reconcile passes underway with work (they may overlap): their commits finalize held outcomes and mark cascades. */
185
+ #reconcilingWork = 0;
186
+ #sweepScheduled = false;
187
+ /**
188
+ * Nodes chain loads installed for jobs whose commits are not published yet, with how many such jobs: the sweep keeps
189
+ * them, as work a pending commit creates below them needs them.
190
+ */
191
+ #pins = new Map();
192
+ /** Keys the decision region underway reads (`#region()`); set only while one runs. */
193
+ #reading;
194
+ #cascadePending = false;
195
+ #unsubscribeRegistry = () => { };
196
+ #enabled = false;
197
+ #readOnly;
198
+ #closing = false;
199
+ /** Aborted at the seal: cancels the cleanups an abort must not cancel (`closeSignal()`). */
200
+ #closed = new AbortController();
201
+ #dirty = false;
202
+ #draining = false;
203
+ constructor(options) {
204
+ this.#telemetry = options.telemetry ?? NOOP_TELEMETRY_CONTEXT;
205
+ const metrics = createTypedMetrics(this.#telemetry.metrics ?? NOOP_TELEMETRY_METRICS, [DURABLE_TELEMETRY_SCHEMA]);
206
+ this.#activeMetric = metrics.upDownCounter("diffra.durable.tasks.active");
207
+ this.#durationMetric = metrics.histogram("diffra.durable.phase.duration");
208
+ this.#session = options.session;
209
+ this.#storage = options.storage;
210
+ this.#registry = options.registry;
211
+ this.#models = options.models;
212
+ this.#agent = options.agent;
213
+ this.#settings = options.settings;
214
+ this.#env = options.env;
215
+ this.#now = options.now;
216
+ this.#onWake = options.onWake;
217
+ this.#timers = options.timers;
218
+ this.#writeAtClose = options.writeAtClose;
219
+ this.#report = options.report;
220
+ this.#settleOutcome = options.settleOutcome;
221
+ this.#limitsRestarts = options.limitsRestarts;
222
+ this.#keepsAbandoned = options.keepsAbandoned;
223
+ this.#parkedAtGate = options.gated;
224
+ this.#withdrawInputs = options.withdrawInputs;
225
+ this.#conversation = options.conversation;
226
+ this.#context = options.context;
227
+ this.#readOnly = options.readOnly === true;
228
+ }
229
+ /**
230
+ * Load live tasks and change surviving `running` tasks back to `pending`, counting the restart. Dispatches nothing;
231
+ * a task cut off `settings.restartLimit` times ends when it is next reserved. Read-only, it only loads them: a
232
+ * `running` task stays as committed, running in another process.
233
+ */
234
+ async open(context) {
235
+ this.#session.followCommits((publication) => this.#observe(publication));
236
+ this.#session.subscribeClose(() => this.#seal());
237
+ this.#unsubscribeRegistry = this.#registry.subscribe(() => {
238
+ this.#publications++;
239
+ this.#notifyBlocked();
240
+ // Calls parked at a gate are asked again: the gates installed now decide (spec suspendable §5.2).
241
+ for (const id of this.#sleeping)
242
+ this.#wakeGate(this.#live.get(id));
243
+ this.#kick();
244
+ });
245
+ await this.#session.commitWith(async (tx) => {
246
+ await this.#published();
247
+ // Every table read before the first write.
248
+ const scans = [];
249
+ for (const status of LIVE_STATUSES) {
250
+ scans.push(await scanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE, cursor)));
251
+ }
252
+ for (const records of scans) {
253
+ for (const record of records) {
254
+ this.#track(undefined, record);
255
+ this.#resumed.add(record.id);
256
+ if (this.#readOnly)
257
+ continue;
258
+ // The registry may differ from the one a call parked at its gates under.
259
+ this.#wakeGate(record);
260
+ if (record.abandonOnRestart === true)
261
+ this.#abandoned.add(record.id);
262
+ if (record.state.status === "running") {
263
+ const restarts = (record.restarts ?? 0) + 1;
264
+ tx.setTask({ ...pendingAgain(record, record.state), restarts });
265
+ }
266
+ if (record.state.status === "waiting" && record.state.policy === "failFast") {
267
+ this.#failFastChecks.add(record.id);
268
+ }
269
+ }
270
+ }
271
+ }, context);
272
+ if (this.#readOnly)
273
+ return;
274
+ // Derive abort marks a crash left unapplied below cancelled owners, and finalize held outcomes.
275
+ this.#cascadePending = true;
276
+ this.#scheduleReconcile();
277
+ this.#scheduleWake();
278
+ }
279
+ /**
280
+ * Enable scheduling, and make sleeping tasks that are due runnable: a host wakeup, such as an alarm, calls this.
281
+ * Idempotent; the kick does nothing once closing.
282
+ */
283
+ resume() {
284
+ if (this.#readOnly)
285
+ throw new ReadOnlySession("running tasks");
286
+ this.#enabled = true;
287
+ this.#wakeDue();
288
+ this.#kick();
289
+ }
290
+ /**
291
+ * Why a live task cannot run here, if it cannot: its definition is missing, too old, or failed to migrate. A running
292
+ * task, an abort-marked one, and one holding its outcome are never blocked.
293
+ */
294
+ blockedReason(record) {
295
+ const status = record.status;
296
+ if (status === "running" || status === "completing" || status === "terminal")
297
+ return undefined;
298
+ // An abort request runs its handler or orphans the task; a `restart` mark waits for the definition, blocked.
299
+ if (record.abortRequested && record.abortReason === undefined)
300
+ return undefined;
301
+ let snapshot;
302
+ try {
303
+ snapshot = this.#registry.snapshot();
304
+ }
305
+ catch (error) {
306
+ if (!this.#snapshotReported)
307
+ this.#report(error, REGISTRY);
308
+ this.#snapshotReported = true;
309
+ return undefined;
310
+ }
311
+ const fit = this.#fit(record, snapshot.task(record.kind));
312
+ if (fit.kind === "blocked")
313
+ return fit.reason;
314
+ return fit.migrates && fit.task.definition.migrate === undefined ? "migration_failed" : undefined;
315
+ }
316
+ /** Call `listener` when blocked reasons may have changed without a commit: a registry change or a failed migration. */
317
+ subscribeBlocked(listener) {
318
+ this.#blockedListeners.add(listener);
319
+ return () => this.#blockedListeners.delete(listener);
320
+ }
321
+ /**
322
+ * When the Session next needs a process: `active` while some task can run now or is running, `at` for the earliest
323
+ * sleep not yet due. Synchronous, from memory; a task whose chain is not loaded yet counts as it would alone.
324
+ */
325
+ wake() {
326
+ // A read-only Harness runs nothing, so it never needs a process.
327
+ if (this.#readOnly)
328
+ return { active: false };
329
+ const now = this.#now();
330
+ // A reconcile pass with work to do is work too: it finalizes held outcomes and marks cascades, at open as
331
+ // recovery. A process that dies before it lands must be woken again. A pass with nothing to do is not.
332
+ const active = this.#invocations.size > 0 || this.#reconcilingWork > 0 || this.#reconcileWork() || this.#runsNow(now);
333
+ // The earliest sleep not yet due: only `#sleeping` holds sleeping tasks, so no pass visits every live task. A sleep
334
+ // without `until` waits only for signals, which a delivery's commit wakes.
335
+ let at;
336
+ for (const id of this.#sleeping) {
337
+ const record = this.#live.get(id);
338
+ if (this.#asleep(record, now) && record.state.until !== undefined) {
339
+ at = at === undefined ? record.state.until : Math.min(at, record.state.until);
340
+ }
341
+ }
342
+ return at === undefined ? { active } : { active, at };
343
+ }
344
+ /** Whether a live task can run now: the scan `wake()` needs only while no invocation runs. */
345
+ #runsNow(now) {
346
+ let snapshot;
347
+ let snapshotFailed = false;
348
+ for (const record of this.#live.values()) {
349
+ const state = record.state;
350
+ if (state.status === "completing")
351
+ continue;
352
+ if (state.status === "waiting" && !record.abortRequested && this.#waitingOn(record, true).length > 0)
353
+ continue;
354
+ if (this.#asleep(record, now))
355
+ continue;
356
+ // An abort invocation waits for the live work below it, which counts itself.
357
+ if (record.abortRequested && this.#waitingOn(record, true).length > 0)
358
+ continue;
359
+ // A task no definition can take waits for a registry change, except an abort-marked one, which is orphaned.
360
+ if (!record.abortRequested || record.abortReason !== undefined) {
361
+ if (snapshot === undefined && !snapshotFailed) {
362
+ try {
363
+ snapshot = this.#registry.snapshot();
364
+ }
365
+ catch (error) {
366
+ snapshotFailed = true;
367
+ this.#report(error, REGISTRY);
368
+ }
369
+ }
370
+ if (snapshot !== undefined && this.#fit(record, snapshot.task(record.kind)).kind === "blocked")
371
+ continue;
372
+ }
373
+ return true;
374
+ }
375
+ return false;
376
+ }
377
+ /**
378
+ * Signal every invocation and wait for them, then write the tasks they ran back as `pending` (`writeAtClose`), as a
379
+ * close is not a crash. Close calls this after every close listener has run, so waits, watches, and streams a task
380
+ * holds end with the Session's reason, not as cancelled by its signal.
381
+ */
382
+ async join() {
383
+ const stopped = [...this.#invocations.values()];
384
+ for (const invocation of stopped)
385
+ invocation.controller.abort();
386
+ await Promise.allSettled(stopped.map((invocation) => invocation.done));
387
+ if (stopped.length === 0)
388
+ return;
389
+ // A close is not a crash: a task it stopped is `pending` again, so the next open counts no restart for it. Read
390
+ // on the line after commits admitted before the seal, such as an abort mark, so the write keeps them. A failure
391
+ // leaves them `running`, counted as if cut off; the Storage guard fails the Session and reports it.
392
+ await this.#writeAtClose(() => stopped.flatMap((invocation) => {
393
+ const record = this.#live.get(invocation.taskId);
394
+ if (record?.state.status !== "running")
395
+ return [];
396
+ return [{ type: "task", value: pendingAgain(record, record.state) }];
397
+ })).catch(() => { });
398
+ }
399
+ /**
400
+ * Commit the abort mark, or settle a task that no registered definition can take as `orphaned` when nothing it owns
401
+ * is live, then join the run invocation seen on the line; the commit listener signalled it. The abort invocation
402
+ * starts once the task's ordinary owned work is gone. A `completing` task is only marked. A request replaces a
403
+ * `restart` mark, so a task abandoned after a restart that waits for its definition is orphaned; with `keepRestart`,
404
+ * as for an owner's own cleanup, such a task keeps its mark and waits on.
405
+ */
406
+ async abort(id, context, keepRestart = false) {
407
+ const marked = await this.#session.commitWith(async (tx) => {
408
+ const current = await tx.task(id);
409
+ if (current === undefined)
410
+ throw new Error(`Task ${id} does not exist`);
411
+ if (current.state.status === "terminal")
412
+ return { result: "terminal" };
413
+ const invocation = this.#invocations.get(id);
414
+ // A restart-marked task has no run invocation; it only waits for its abort.
415
+ if (keepRestart && current.abortReason === "restart")
416
+ return { result: "marked" };
417
+ if (invocation === undefined && current.state.status !== "completing") {
418
+ await this.#loadScopes(false);
419
+ const owns = await this.#region(() => this.#hasOwnedLive(id), this.#reloadScopes);
420
+ // Resolved once that decision stands, as it may run `migrate`.
421
+ const resolution = owns
422
+ ? undefined
423
+ : this.#resolve(current, this.#registry.snapshot());
424
+ if (resolution?.kind === "blocked") {
425
+ await this.#terminate(tx, current, { status: "orphaned", reason: resolution.reason });
426
+ return { result: "marked" };
427
+ }
428
+ }
429
+ if (!current.abortRequested || current.abortReason !== undefined)
430
+ tx.setTask(withAbortMark(current));
431
+ return { result: "marked", run: invocation?.mode === "run" ? invocation : undefined };
432
+ }, context);
433
+ // The commit listener signalled the run; join it. A run that ignores its signal can outlive a failed Session,
434
+ // which ends the wait instead.
435
+ if (marked.run !== undefined) {
436
+ await awaitWithContext(Promise.race([marked.run.done, this.#session.failed]), context);
437
+ }
438
+ return marked.result;
439
+ }
440
+ async waitForTask(id, context) {
441
+ // Check and register on the line so no terminal publication falls between them.
442
+ const found = await this.#session.readOnLine(async (storage) => {
443
+ if (this.#closing)
444
+ throw closedError(this.#session);
445
+ if (await this.#region(() => this.#liveRecord(id) !== undefined)) {
446
+ return { promise: this.#taskWaiters.add(id, context) };
447
+ }
448
+ const record = await storage.task(id, context);
449
+ if (record === undefined)
450
+ throw new Error(`Task ${id} does not exist`);
451
+ return { promise: Promise.resolve(record) };
452
+ });
453
+ return found.promise;
454
+ }
455
+ /**
456
+ * Resolve when ordinary traversal from the conversation, or from every ownerless conversation, reaches no live
457
+ * non-background task.
458
+ */
459
+ waitForIdle(conversationId, context) {
460
+ if (this.#closing)
461
+ return Promise.reject(closedError(this.#session));
462
+ if (this.#idle(conversationId))
463
+ return Promise.resolve();
464
+ this.#scheduleReconcile();
465
+ return this.#idleWaiters.add(conversationId, context);
466
+ }
467
+ /**
468
+ * `Conversation.abort()`: in one commit, withdraw the queued inputs and mark every live non-background task that
469
+ * ordinary traversal from the conversation reaches; resolves once the scope is idle. With `background`, traversal
470
+ * crosses background boundaries, and the wait also covers every task it reached.
471
+ */
472
+ async abortConversation(conversationId, background, context) {
473
+ const reached = await this.#session.commitWith(async (tx) => {
474
+ await this.#published();
475
+ const queued = await this.#loadScopes(true);
476
+ const scope = { kind: "conversation", conversation: conversationId };
477
+ const reached = [];
478
+ const walk = this.#walkDown(conversationNode(conversationId), { crossBackground: background });
479
+ for (const { node, live } of walk) {
480
+ if (live === undefined || (node.background && !background))
481
+ continue;
482
+ reached.push(live.id);
483
+ if (!live.abortRequested || live.abortReason !== undefined)
484
+ tx.setTask(withAbortMark(live));
485
+ }
486
+ for (const id of queued) {
487
+ if (this.#inScope({ kind: "conversation", conversation: id }, scope, background) === true)
488
+ await this.#withdrawInputs(tx, id);
489
+ }
490
+ return reached;
491
+ }, context);
492
+ if (background)
493
+ for (const id of reached)
494
+ await this.waitForTask(id, context);
495
+ await this.waitForIdle(conversationId, context);
496
+ }
497
+ /**
498
+ * The ownership memberships a commit's task and conversation changes write (group commit §4.2), at its admission on
499
+ * the line: for each task created or made terminal, every node from its parent up to and including the nearest live
500
+ * task, or the root conversation, and then the roots too, conservatively, as a pending end may unlist the root a
501
+ * creation finds listed; for each conversation created under a task, that task; and the intent set when
502
+ * a change sets, upgrades, or clears a mark or a held or ended outcome other than `completed`. Loads the chains it
503
+ * walks; the nodes it installs stay until the commit is published.
504
+ */
505
+ membershipKeys(tx) {
506
+ const tasks = tx.stagedTasks();
507
+ const conversations = tx.stagedConversations();
508
+ if (tasks.length === 0 && conversations.every((record) => record.owner === undefined))
509
+ return NO_KEYS;
510
+ return this.#membershipKeys(tx, tasks, conversations);
511
+ }
512
+ async #membershipKeys(tx, tasks, conversations) {
513
+ const keys = new Set();
514
+ const overlay = overlayOf(tx);
515
+ const created = new Set(tx.createdTaskIds());
516
+ const reached = new Map();
517
+ for (const record of tasks) {
518
+ if (intentChanges(this.#live.get(record.id), record))
519
+ keys.add(INTENT_KEY);
520
+ if (!created.has(record.id) && record.state.status !== "terminal")
521
+ continue;
522
+ await this.#loadChain(parentOf(record), overlay);
523
+ if ((await this.#chainKeys(parentNode(record), overlay, keys, reached)) !== undefined)
524
+ keys.add(ROOTS_KEY);
525
+ }
526
+ for (const conversation of conversations) {
527
+ const owner = conversation.owner?.taskId;
528
+ if (owner === undefined)
529
+ continue;
530
+ await this.#loadChain({ kind: "task", task: owner }, overlay);
531
+ await this.#chainKeys(owner, overlay, keys, reached);
532
+ }
533
+ return [...keys];
534
+ }
535
+ /**
536
+ * Add the memberships from `start` up to and including the nearest live task, or the root conversation, which it
537
+ * returns. `reached` keeps, per node walked, where its walk ended, so a chain several tasks of a commit share is
538
+ * walked once. Whether an ancestor is live can change under a pending commit, so it is read after a touch of the
539
+ * ancestor's record: a pending end must not stop the chain early. Ownership fields are immutable, so not keyed.
540
+ */
541
+ async #chainKeys(start, overlay, keys, reached) {
542
+ const walked = [];
543
+ let root;
544
+ let node = start;
545
+ while (node !== undefined && node !== null) {
546
+ const key = ownedKey(node);
547
+ // Walked up from here already, for another task of the commit.
548
+ if (reached.has(key)) {
549
+ root = reached.get(key);
550
+ break;
551
+ }
552
+ keys.add(key);
553
+ walked.push(key);
554
+ if (typeof node === "string") {
555
+ const conversation = conversationOf(node);
556
+ node = this.#edge(conversation, overlay);
557
+ if (node === null)
558
+ root = conversation;
559
+ continue;
560
+ }
561
+ let record = overlay.tasks.get(node);
562
+ if (record === undefined) {
563
+ const gate = this.#session.touch(taskKey(node));
564
+ if (gate !== undefined) {
565
+ await gate;
566
+ // It may have ended meanwhile, and its node been swept: load the chain above it again.
567
+ await this.#loadChain({ kind: "task", task: node }, overlay);
568
+ }
569
+ record = this.#live.get(node);
570
+ }
571
+ if (record !== undefined && record.state.status !== "terminal")
572
+ break;
573
+ const above = record ?? this.#settled.get(node);
574
+ node = above === undefined ? undefined : parentNode(above);
575
+ }
576
+ for (const key of walked)
577
+ reached.set(key, root);
578
+ return root;
579
+ }
580
+ // ─── Scheduling ────────────────────────────────────────────────────────
581
+ #observe(publication) {
582
+ // A commit held in memory changes documents only.
583
+ if (publication.kind === "memory")
584
+ return;
585
+ this.#advanceContexts(publication);
586
+ const updated = [];
587
+ const failed = [];
588
+ let changed = false;
589
+ // The conversations whose idleness the commit's task changes can change; undefined when a chain is not known.
590
+ let dirty = new Set();
591
+ // Edges first, so the tasks a commit creates in a new conversation hang from it.
592
+ for (const change of publication.changes) {
593
+ if (change.type === "conversation" && !this.#edges.has(change.value.id)) {
594
+ this.#setEdge(change.value.id, change.value.owner?.taskId ?? null);
595
+ }
596
+ }
597
+ for (const change of publication.changes) {
598
+ if (change.type !== "task")
599
+ continue;
600
+ changed = true;
601
+ const record = change.value;
602
+ const previous = this.#live.get(record.id);
603
+ if (failedOutcome(record) && (previous === undefined || !failedOutcome(previous)))
604
+ failed.push(record.id);
605
+ this.#track(previous, record);
606
+ // Idleness counts live tasks, so only a task that became live or ended can change it, and the inactivity of kept
607
+ // contexts also a task that parked or woke. Collected before `#sweep()`, which may forget the chain of a task
608
+ // that ended.
609
+ const liveness = previous === undefined || record.state.status === "terminal" || parked(previous) !== parked(record);
610
+ if (liveness && dirty !== undefined && !this.#addScopesAbove(record, dirty))
611
+ dirty = undefined;
612
+ if (record.state.status === "terminal") {
613
+ this.#failedMigrations.delete(record.id);
614
+ this.#failFastChecks.delete(record.id);
615
+ this.#taskWaiters.resolve(record.id, record);
616
+ // Its owner may finalize now.
617
+ this.#scheduleReconcile();
618
+ continue;
619
+ }
620
+ if (record.abortRequested && previous?.abortRequested !== true) {
621
+ this.#cascadePending = true;
622
+ // Signal a run invocation of the newly marked task; its next step ends it. Abort listeners are task code, which
623
+ // never runs inside a publication: the signal follows in a microtask, after host commit listeners.
624
+ const invocation = this.#invocations.get(record.id);
625
+ if (invocation?.mode === "run")
626
+ queueMicrotask(() => invocation.controller.abort());
627
+ }
628
+ // A request replacing a `restart` mark upgrades the marks of the work below.
629
+ if (previous?.abortReason !== undefined && record.abortReason === undefined)
630
+ this.#cascadePending = true;
631
+ const status = record.state.status;
632
+ if (status === "completing" && previous?.state.status !== "completing") {
633
+ if (cancellationIntent(record))
634
+ this.#cascadePending = true;
635
+ this.#scheduleReconcile();
636
+ }
637
+ if (status === "waiting" && record.state.policy === "failFast" && previous?.state.status !== "waiting") {
638
+ this.#failFastChecks.add(record.id);
639
+ this.#scheduleReconcile();
640
+ }
641
+ // Its owners and place never change: what is above it is checked once, when it becomes live.
642
+ if (previous === undefined)
643
+ updated.push(record);
644
+ }
645
+ for (const id of failed) {
646
+ for (const waiter of this.#waiters.get(id) ?? []) {
647
+ const state = this.#live.get(waiter)?.state;
648
+ if (state?.status === "waiting" && state.policy === "failFast") {
649
+ this.#failFastChecks.add(waiter);
650
+ this.#scheduleReconcile();
651
+ }
652
+ }
653
+ }
654
+ for (const change of publication.changes) {
655
+ // A queued input below a cancelled owner is withdrawn, even after its cascade.
656
+ if (change.type !== "submission" || change.value.status !== "queued" || change.value.type !== "input")
657
+ continue;
658
+ // Only an owner with cancellation intent withdraws it; a later intent's mark runs the cascade then.
659
+ if (this.#intent.size === 0)
660
+ continue;
661
+ const conversation = change.value.conversationId;
662
+ if (!this.#known(conversationNode(conversation)) ||
663
+ this.#belowCancelled({ kind: "conversation", conversation })) {
664
+ this.#cascadePending = true;
665
+ }
666
+ }
667
+ for (const record of updated) {
668
+ // Work created below a cancelled owner, even after its cascade, is aborted too.
669
+ if (this.#unloaded.has(record.id))
670
+ this.#scheduleReconcile();
671
+ else if (!record.background && !record.abortRequested && this.#belowCancelled(parentOf(record))) {
672
+ this.#cascadePending = true;
673
+ }
674
+ }
675
+ // A cascade that a reservation or step found pending runs with the next commit of any kind.
676
+ if (this.#cascadePending)
677
+ this.#scheduleReconcile();
678
+ this.#sweep();
679
+ if (!changed)
680
+ return;
681
+ this.#settleIdle(dirty);
682
+ this.#kick();
683
+ }
684
+ /**
685
+ * Add the conversations above `record` to `scopes`: those whose idleness a change of it can change. False when an
686
+ * owner edge or owner task on the way up is not known. A conversation already in `scopes` has everything above it
687
+ * there too.
688
+ */
689
+ #addScopesAbove(record, scopes) {
690
+ // A child task lives in its owner's conversation, so the first conversation above a task is its own: the walk skips
691
+ // the owner chain between, which made a change deep in a long chain cost its depth.
692
+ let conversation = record.conversationId;
693
+ while (!scopes.has(conversation)) {
694
+ scopes.add(conversation);
695
+ const owner = this.#edge(conversation);
696
+ if (owner === undefined)
697
+ return false;
698
+ if (owner === null)
699
+ return true;
700
+ const node = this.#node(owner);
701
+ if (node === undefined)
702
+ return false;
703
+ conversation = node.conversationId;
704
+ }
705
+ return true;
706
+ }
707
+ /**
708
+ * Extend each kept context range with the entries a stored commit appended to its conversation, so a later read
709
+ * needs no Storage scan. Entries are published in ID order.
710
+ */
711
+ #advanceContexts(publication) {
712
+ if (this.#contexts.size === 0)
713
+ return;
714
+ let appended;
715
+ for (const change of publication.changes) {
716
+ if (change.type !== "entry" || !this.#contexts.has(change.value.conversationId))
717
+ continue;
718
+ appended ??= new Map();
719
+ const entries = appended.get(change.value.conversationId);
720
+ if (entries === undefined)
721
+ appended.set(change.value.conversationId, [change.value]);
722
+ else
723
+ entries.push(change.value);
724
+ }
725
+ if (appended === undefined)
726
+ return;
727
+ for (const [conversationId, entries] of appended) {
728
+ const kept = this.#contexts.get(conversationId);
729
+ // An idle range past its retention is dropped here too: entry-only commits do not run `#settleIdle()`, and a
730
+ // host may decline the expiry timer. `expiresAt` was fixed when it went idle, so no settings are read here.
731
+ if (kept.idleSince !== undefined && kept.expiresAt !== undefined && kept.expiresAt <= this.#now()) {
732
+ this.#dropContext(conversationId);
733
+ continue;
734
+ }
735
+ const range = advanceRange(kept.range, entries);
736
+ if (range === undefined)
737
+ this.#dropContext(conversationId);
738
+ else
739
+ kept.range = range;
740
+ }
741
+ }
742
+ /**
743
+ * `settings.contextRetentionMs`, or 0 when the host's settings throw. Kept contexts are only a cache, so dropping them
744
+ * is safe, while a throw here would escape commit listeners, reconciliation, and the expiry timer.
745
+ */
746
+ #contextRetentionMs() {
747
+ try {
748
+ return this.#settings().contextRetentionMs;
749
+ }
750
+ catch (error) {
751
+ this.#report(error, SETTINGS);
752
+ return 0;
753
+ }
754
+ }
755
+ /**
756
+ * After task changes below the conversations in `scopes` (every conversation when undefined): resolve their idle
757
+ * waiters and the Harness-wide ones, drop the kept contexts whose idle period passed the retention, then start or end
758
+ * the idle periods of the kept contexts in `scopes`. A task change can change the idleness only of the conversations
759
+ * above it, so no check visits every conversation.
760
+ */
761
+ #settleIdle(scopes) {
762
+ const all = scopes === undefined || this.#unknownsChanged;
763
+ this.#unknownsChanged = false;
764
+ if (all)
765
+ this.#fullIdleChecks++;
766
+ this.#resolveIdleWaiters(all ? undefined : scopes);
767
+ const now = this.#now();
768
+ const retention = this.#contextRetentionMs();
769
+ // Expired first: a context past its retention is dropped even when the same commit makes it busy again.
770
+ this.#expireContexts(now, retention);
771
+ for (const conversationId of all ? [...this.#contexts.keys()] : scopes) {
772
+ const kept = this.#contexts.get(conversationId);
773
+ if (kept === undefined)
774
+ continue;
775
+ if (!this.#inactive(conversationId)) {
776
+ if (kept.idleSince === undefined)
777
+ continue;
778
+ kept.idleSince = undefined;
779
+ this.#idleOrder.delete(conversationId);
780
+ }
781
+ else if (retention <= 0) {
782
+ this.#dropContext(conversationId);
783
+ }
784
+ else if (kept.idleSince === undefined) {
785
+ kept.idleSince = now;
786
+ kept.expiresAt = now + retention;
787
+ this.#markIdle(conversationId, now);
788
+ }
789
+ }
790
+ this.#scheduleExpiry();
791
+ }
792
+ /** Resolve the idle waiters of the conversations in `scopes` (all when undefined) and the Harness-wide ones. */
793
+ #resolveIdleWaiters(scopes) {
794
+ for (const conversationId of this.#idleWaiters.keys()) {
795
+ if (conversationId !== undefined && scopes !== undefined && !scopes.has(conversationId))
796
+ continue;
797
+ if (this.#idle(conversationId))
798
+ this.#idleWaiters.resolve(conversationId);
799
+ }
800
+ }
801
+ /**
802
+ * Drop the kept contexts idle for at least `retention`, oldest first, with the retention setting of now; with no
803
+ * retention, every idle one, also those whose idle period a clock that went back makes start after now.
804
+ */
805
+ #expireContexts(now, retention) {
806
+ for (const [conversationId, idleSince] of this.#idleOrder) {
807
+ if (retention > 0 && now - idleSince < retention)
808
+ return;
809
+ this.#dropContext(conversationId);
810
+ }
811
+ }
812
+ /**
813
+ * Start the idle period of a kept context in the expiry order. An idle period older than the newest one kept, which
814
+ * a clock that went back starts, sorts the order again, and the newest is taken from what is kept then.
815
+ */
816
+ #markIdle(conversationId, idleSince) {
817
+ this.#idleOrder.delete(conversationId);
818
+ this.#idleOrder.set(conversationId, idleSince);
819
+ if (this.#idleOrder.size === 1 || idleSince >= this.#idleNewest) {
820
+ this.#idleNewest = idleSince;
821
+ return;
822
+ }
823
+ const sorted = [...this.#idleOrder].sort((a, b) => a[1] - b[1]);
824
+ this.#idleOrder.clear();
825
+ for (const [id, since] of sorted)
826
+ this.#idleOrder.set(id, since);
827
+ this.#idleNewest = sorted.at(-1)[1];
828
+ }
829
+ /** Forget a kept context, idle or not, and its place in the expiry order. */
830
+ #dropContext(conversationId) {
831
+ this.#contexts.delete(conversationId);
832
+ this.#idleOrder.delete(conversationId);
833
+ }
834
+ /**
835
+ * Drop the expired contexts when the earliest idle context expires, on a background timer, which never keeps the
836
+ * process alive. Where the host declines it, as the default does in Cloudflare Workers, none is kept: a pending timer
837
+ * could keep a Durable Object from being evicted, and eviction frees the contexts. There, task changes alone check
838
+ * expiry.
839
+ */
840
+ #scheduleExpiry() {
841
+ const oldest = this.#idleOrder.values().next();
842
+ const at = oldest.done === true ? undefined : oldest.value + this.#contextRetentionMs();
843
+ if (this.#expiry !== undefined && this.#expiry.at === at)
844
+ return;
845
+ this.#expiry?.disarm();
846
+ this.#expiry = undefined;
847
+ if (at === undefined || this.#closing)
848
+ return;
849
+ const disarm = this.#timers.background(() => {
850
+ this.#expiry = undefined;
851
+ this.#expireContexts(this.#now(), this.#contextRetentionMs());
852
+ this.#scheduleExpiry();
853
+ }, at - this.#now());
854
+ if (disarm !== undefined)
855
+ this.#expiry = { at, disarm };
856
+ }
857
+ // ─── Ownership ───────────────────────────────────────────────────────────
858
+ #scheduleReconcile() {
859
+ // A read-only reconcile could only fail: what it writes is refused, and its own commits fail the Session.
860
+ if (this.#reconcileScheduled || this.#closing || this.#readOnly)
861
+ return;
862
+ this.#reconcileScheduled = true;
863
+ queueMicrotask(() => void this.#reconcile());
864
+ }
865
+ /**
866
+ * One commit that applies what committed records imply: abort marks below live owners with cancellation intent
867
+ * (spec §5.4), `failFast` marks (spec §5.5), withdrawn queued inputs below cancelled owners, and the final terminal
868
+ * record of every `completing` task whose ordinary owned work is gone. The durable records are the intent, so this
869
+ * also repairs whatever a crash left unapplied. Resolves idle waiters that the loaded edges decide.
870
+ */
871
+ async #reconcile() {
872
+ this.#reconcileScheduled = false;
873
+ const work = this.#reconcileWork();
874
+ if (work)
875
+ this.#reconcilingWork++;
876
+ try {
877
+ await this.#session.commitInternal(async (tx) => {
878
+ if (this.#closing)
879
+ return;
880
+ // A cascade scans the queued inputs, which waits for every unpublished commit: a request made before the scan
881
+ // is covered by it, and none is published while the job holds the line after it.
882
+ const cascade = this.#cascadePending;
883
+ const queued = await this.#loadScopes(cascade);
884
+ if (cascade)
885
+ this.#cascadePending = false;
886
+ const marks = await this.#marks();
887
+ for (const { record, reason } of marks.values())
888
+ tx.setTask(withAbortMark(record, reason));
889
+ const withdrawn = await this.#region(() => queued.filter((id) => this.#belowCancelled({ kind: "conversation", conversation: id })), this.#reloadScopes);
890
+ for (const id of withdrawn)
891
+ await this.#withdrawInputs(tx, id);
892
+ await this.#finalize(tx);
893
+ }, this.#context);
894
+ }
895
+ catch (error) {
896
+ // No extension code runs in this commit: a throw is a storage failure, a host callback, or a bug. None is fixed by
897
+ // running the pass again, so it fails the Session, which reports it.
898
+ this.#failSession(error);
899
+ }
900
+ if (work)
901
+ this.#reconcilingWork--;
902
+ this.#scheduleWake();
903
+ // Its commit's task changes were settled at their publication; a waiter that asked for this pass checks again, and
904
+ // what its chain loads resolved can make any scope idle.
905
+ if (this.#unknownsChanged) {
906
+ this.#settleIdle(undefined);
907
+ return;
908
+ }
909
+ this.#resolveIdleWaiters(undefined);
910
+ // A pass checks expiry too, for hosts that decline the expiry timer.
911
+ this.#expireContexts(this.#now(), this.#contextRetentionMs());
912
+ this.#scheduleExpiry();
913
+ }
914
+ /**
915
+ * The abort marks committed records imply (spec §5.4, §5.5): every live foreground task below a live owner with
916
+ * cancellation intent, which is its nearest one (a walk down from each owner with intent does not enter another,
917
+ * whose own walk covers what is below it), and every other live task in the `on` of a `failFast` waiter one of whose
918
+ * tasks failed. A cascade from an abandoned owner passes its `restart` reason on; any other intent marks, or upgrades
919
+ * a `restart` mark, as a request. Collected first, so a request wins over a `restart` mark of the same pass. Derived
920
+ * again on every pass, as loading edges can reveal a cancelled owner. Takes the `failFast` checks once its decision
921
+ * stands.
922
+ */
923
+ async #marks() {
924
+ // Terminal tasks in a checked `on`, read from Storage: each one's outcome is final.
925
+ const ended = new Map();
926
+ for (;;) {
927
+ const plan = await this.#region(() => this.#planMarks(ended), this.#reloadScopes);
928
+ if (plan.kind === "missing") {
929
+ for (const id of plan.missing)
930
+ ended.set(id, (await this.#session.lineStorage.task(id, this.#context)) ?? null);
931
+ continue;
932
+ }
933
+ for (const id of plan.checked)
934
+ this.#failFastChecks.delete(id);
935
+ return plan.marks;
936
+ }
937
+ }
938
+ /** `#marks()`' decision region; the `failFast` members it needs from Storage first, when `ended` lacks them. */
939
+ #planMarks(ended) {
940
+ const marks = new Map();
941
+ // A mark rewrites the whole record, so the record it copies is read as a task record, keyed: a commit of the task
942
+ // that is not published yet makes the region wait and run again, rather than stage a mark over a stale checkpoint.
943
+ const mark = (found, reason) => {
944
+ const record = this.#liveRecord(found.id);
945
+ const staged = marks.get(record.id);
946
+ if (staged !== undefined && staged.reason === undefined)
947
+ return;
948
+ if (record.abortRequested && (record.abortReason === undefined || reason !== undefined))
949
+ return;
950
+ marks.set(record.id, { record, reason });
951
+ };
952
+ this.#record(INTENT_KEY);
953
+ for (const id of this.#intent) {
954
+ const owner = this.#liveRecord(id);
955
+ // Only an owner abandoned after a restart, and nothing else, passes its reason on.
956
+ const restart = owner.abortReason === "restart" && !failedOutcome(owner);
957
+ for (const { node, live } of this.#walkDown(id, { enter: (below) => !this.#intent.has(below) })) {
958
+ if (live !== undefined && !node.background)
959
+ mark(live, restart ? "restart" : undefined);
960
+ }
961
+ }
962
+ const checked = [...this.#failFastChecks];
963
+ const missing = [];
964
+ for (const id of checked) {
965
+ const waiter = this.#liveRecord(id);
966
+ if (waiter?.state.status !== "waiting")
967
+ continue;
968
+ let failed = false;
969
+ for (const member of waiter.state.on) {
970
+ const record = this.#liveRecord(member) ?? ended.get(member);
971
+ if (record === undefined)
972
+ missing.push(member);
973
+ else if (record !== null && failedOutcome(record))
974
+ failed = true;
975
+ }
976
+ if (!failed)
977
+ continue;
978
+ // Every other live task: the failed one keeps its own outcome.
979
+ for (const member of waiter.state.on) {
980
+ const record = this.#liveRecord(member);
981
+ if (record !== undefined && !failedOutcome(record))
982
+ mark(record, undefined);
983
+ }
984
+ }
985
+ return missing.length > 0 ? { kind: "missing", missing } : { kind: "marks", marks, checked };
986
+ }
987
+ /** Whether a reconcile pass would have work: a cascade to derive, held outcomes to check, or `failFast` waits. */
988
+ #reconcileWork() {
989
+ return this.#cascadePending || this.#finalizeChecks.size > 0 || this.#failFastChecks.size > 0;
990
+ }
991
+ /**
992
+ * Write the terminal record of every `completing` task without live ordinary owned work. Finalizing one can free its
993
+ * owner, so this repeats over the commit's candidates until nothing changes. A held scheduler outcome gets its
994
+ * Harness cleanup here. In rounds, one decision region each: the holders the tasks of one round free are checked once,
995
+ * in the next, so a holder of many tasks that end together is walked once, not once per task. The first round takes
996
+ * the `completing` tasks to check once its decision stands.
997
+ */
998
+ async #finalize(tx) {
999
+ const done = new Set();
1000
+ // The commit's candidates, kept in step with the terminal records each round stages.
1001
+ const overlay = overlayOf(tx);
1002
+ let round = [...this.#finalizeChecks];
1003
+ this.#finalizeChecks.clear();
1004
+ for (;;) {
1005
+ const ids = round;
1006
+ const plan = await this.#region(() => this.#planRound(ids, overlay, done), this.#reloadScopes);
1007
+ for (const { record, terminal } of plan.finalized) {
1008
+ tx.setTask(terminal);
1009
+ overlay.tasks.set(record.id, terminal);
1010
+ done.add(record.id);
1011
+ const outcome = record.state.outcome;
1012
+ // REMINDER: only the scheduler writes `faulted` and `orphaned` (spec §5.4); their cleanup waits for this commit.
1013
+ if (outcome.status === "faulted" || outcome.status === "orphaned") {
1014
+ await this.#settleOutcome(tx, record, outcome);
1015
+ }
1016
+ }
1017
+ if (plan.next.length === 0)
1018
+ return;
1019
+ round = plan.next;
1020
+ }
1021
+ }
1022
+ /**
1023
+ * One finalize round's decision: which of `ids` are `completing` without live ordinary owned work below them, in the
1024
+ * commit's candidates with the round's own finalizations applied in order, and the holders above them to check next.
1025
+ * Tasks finalized have no live work below them, so walks down skip them. It applies the round's terminal records to
1026
+ * `overlay` while it decides and takes them back before it returns, so a run again starts from the same candidates.
1027
+ */
1028
+ #planRound(ids, overlay, finalized) {
1029
+ const tasks = overlay.tasks;
1030
+ // The tasks finalized so far, earlier rounds' and this one's, without copying the former.
1031
+ const round = new Set();
1032
+ const done = { has: (id) => round.has(id) || finalized.has(id) };
1033
+ const ended = [];
1034
+ const next = new Set();
1035
+ try {
1036
+ for (const id of ids) {
1037
+ const staged = tasks.get(id);
1038
+ const record = staged ?? this.#liveRecord(id);
1039
+ if (record?.state.status !== "completing" || done.has(id))
1040
+ continue;
1041
+ if (this.#hasOwnedLive(id, overlay, done))
1042
+ continue;
1043
+ const terminal = withState(record, { status: "terminal", outcome: record.state.outcome });
1044
+ tasks.set(id, terminal);
1045
+ round.add(id);
1046
+ ended.push({ record, terminal, staged: staged !== undefined });
1047
+ const above = this.#nearestLiveAbove(record, overlay);
1048
+ if (above?.state.status === "completing")
1049
+ next.add(above.id);
1050
+ }
1051
+ }
1052
+ finally {
1053
+ for (const { record, staged } of ended) {
1054
+ if (staged)
1055
+ tasks.set(record.id, record);
1056
+ else
1057
+ tasks.delete(record.id);
1058
+ }
1059
+ }
1060
+ return { finalized: ended, next: [...next] };
1061
+ }
1062
+ /**
1063
+ * Load the owner chains of the tasks in `#unloaded` and, with `queued`, of every conversation with queued inputs,
1064
+ * on the Session line; returns the latter. Reads through the line's Storage, so it may run inside a commit callback.
1065
+ */
1066
+ async #loadScopes(queued) {
1067
+ for (const id of [...this.#unloaded]) {
1068
+ // An earlier load in this loop may have passed it.
1069
+ if (this.#unloaded.has(id))
1070
+ await this.#loadChain({ kind: "task", task: id });
1071
+ }
1072
+ if (!queued)
1073
+ return [];
1074
+ // A scan, which cannot be keyed: it waits for every unpublished commit.
1075
+ const submissions = await scanAll((cursor) => this.#session.lineStorage.scanSubmissions({ status: "queued" }, SCAN_PAGE_SIZE, cursor, this.#context));
1076
+ const inputs = submissions.filter((submission) => submission.type === "input");
1077
+ const conversations = [...new Set(inputs.map((submission) => submission.conversationId))];
1078
+ for (const id of conversations)
1079
+ await this.#loadChain({ kind: "conversation", conversation: id });
1080
+ return conversations;
1081
+ }
1082
+ /**
1083
+ * Load the owner edges and task nodes from `start` up to its ownerless root. A known task outside `#unloaded` ends the
1084
+ * walk, as its chain is loaded; the `#unloaded` tasks passed have a loaded chain afterwards. Loading a node can reveal
1085
+ * a cancelled owner, so it makes the next reconcile derive cascade marks. The nodes it installs stay until the job's
1086
+ * commit is published (`#pin()`).
1087
+ */
1088
+ async #loadChain(start, overlay) {
1089
+ const passed = [];
1090
+ let installed = false;
1091
+ let at = start;
1092
+ try {
1093
+ while (at !== undefined) {
1094
+ if (at.kind === "task") {
1095
+ const id = at.task;
1096
+ let node = this.#live.get(id) ?? this.#settled.get(id);
1097
+ // Created in this commit: the load from its own record covers what is above it.
1098
+ if (node === undefined && overlay?.tasks.has(id) === true)
1099
+ break;
1100
+ if (node !== undefined && !this.#unloaded.has(id))
1101
+ break;
1102
+ if (node === undefined) {
1103
+ // Through the line's Storage: a task whose creation or end is not published yet waits for it.
1104
+ const record = await this.#session.lineStorage.task(id, this.#context);
1105
+ if (record === undefined)
1106
+ return;
1107
+ node = nodeOf(record);
1108
+ if (record.state.status === "terminal") {
1109
+ this.#settle(id, node);
1110
+ this.#pin(id);
1111
+ installed = true;
1112
+ }
1113
+ // A loaded node can reveal a cancelling owner: the next reconcile derives marks again.
1114
+ this.#scheduleReconcile();
1115
+ }
1116
+ passed.push(id);
1117
+ at = parentOf(node);
1118
+ }
1119
+ else {
1120
+ let edge = this.#edge(at.conversation, overlay);
1121
+ if (edge === undefined) {
1122
+ // Through the line's Storage: a conversation whose creation is not published yet waits for it, so a missing
1123
+ // record is never mistaken for an ownerless one.
1124
+ const record = await this.#session.lineStorage.conversation(at.conversation, this.#context);
1125
+ edge = record?.owner?.taskId ?? null;
1126
+ this.#setEdge(at.conversation, edge);
1127
+ this.#pin(conversationNode(at.conversation));
1128
+ installed = true;
1129
+ // A loaded node can reveal a cancelling owner: the next reconcile derives marks again.
1130
+ this.#scheduleReconcile();
1131
+ }
1132
+ at = edge === null ? undefined : { kind: "task", task: edge };
1133
+ }
1134
+ }
1135
+ }
1136
+ finally {
1137
+ // `#idle()` counts a live task whose chain is not loaded as inside every scope it may be in: what this load
1138
+ // resolved, also when it stopped early, can make such a scope idle without a task change below it.
1139
+ if (passed.some((id) => this.#live.has(id)) || (installed && this.#liveUnloaded())) {
1140
+ this.#unknownsChanged = true;
1141
+ // A waiter such a task held is checked again at the pass's end, also when this load was not a reconcile's.
1142
+ this.#scheduleReconcile();
1143
+ }
1144
+ }
1145
+ for (const id of passed)
1146
+ this.#unloaded.delete(id);
1147
+ }
1148
+ /** Whether a live task's chain is not loaded yet: one `#idle()` counts as inside every scope it may be in. */
1149
+ #liveUnloaded() {
1150
+ for (const id of this.#unloaded)
1151
+ if (this.#live.has(id))
1152
+ return true;
1153
+ return false;
1154
+ }
1155
+ #setEdge(conversationId, owner) {
1156
+ this.#edges.set(conversationId, owner);
1157
+ // The conversation now hangs from its owner, or is a root; with nothing below it, it waits for the sweep.
1158
+ this.#relist(conversationNode(conversationId));
1159
+ this.#dropIfUnneeded(conversationNode(conversationId));
1160
+ }
1161
+ /** Know a terminal task a chain load read, so walks pass through it; its own chain is not loaded yet. */
1162
+ #settle(id, node) {
1163
+ this.#settled.set(id, node);
1164
+ this.#unloaded.add(id);
1165
+ this.#relist(id);
1166
+ this.#dropIfUnneeded(id);
1167
+ }
1168
+ /** Queue an ended task or a conversation for the sweep when nothing is listed below it. */
1169
+ #dropIfUnneeded(node) {
1170
+ if (typeof node !== "string" && this.#live.has(node))
1171
+ return;
1172
+ if (this.#below.has(node))
1173
+ return;
1174
+ this.#dropQueue.add(node);
1175
+ this.#scheduleSweep();
1176
+ }
1177
+ /**
1178
+ * Sweep in a job of its own on the Session line, after the operation underway: a rejected commit, one with nothing to
1179
+ * write, and a read publish nothing, so the sweep at the end of `#observe` would not run for what they loaded.
1180
+ */
1181
+ #scheduleSweep() {
1182
+ if (this.#sweepScheduled || this.#closing)
1183
+ return;
1184
+ this.#sweepScheduled = true;
1185
+ this.#session
1186
+ .readOnLine(async () => {
1187
+ this.#sweepScheduled = false;
1188
+ this.#sweep();
1189
+ })
1190
+ // Rejected only once the Session is closing or failed, when nothing is kept anyway.
1191
+ .catch(() => { });
1192
+ }
1193
+ /**
1194
+ * Drop the queued nodes that are still unneeded: not live, nothing listed below. Runs once a publication is fully
1195
+ * tracked, and as a job of its own on the line, never inside an operation: work a commit creates below a chain its
1196
+ * own callback loaded keeps that chain. A flat loop: unlisting already queued every node on the way up that lost its
1197
+ * last listed node.
1198
+ */
1199
+ #sweep() {
1200
+ for (const node of this.#dropQueue) {
1201
+ // Queued again once its pins go.
1202
+ if (this.#below.has(node) || this.#pins.has(node))
1203
+ continue;
1204
+ if (typeof node === "string") {
1205
+ this.#edges.delete(conversationOf(node));
1206
+ this.#roots.delete(conversationOf(node));
1207
+ }
1208
+ else if (!this.#live.has(node)) {
1209
+ this.#settled.delete(node);
1210
+ this.#unloaded.delete(node);
1211
+ }
1212
+ }
1213
+ this.#dropQueue.clear();
1214
+ }
1215
+ /**
1216
+ * Run `decide`, a decision region (group commit §6): synchronous, reading scheduler memory and recording the keys it
1217
+ * reads, staging nothing and changing no scheduler state. When a key it read has an unpublished writer, its result,
1218
+ * or its error, is dropped: once that writer is published, `refresh` reloads what the region needs and it runs
1219
+ * again. A waiting job holds the line, so unpublished writes only shrink, and the runs converge. What a region read
1220
+ * that had no unpublished writer gets none for the rest of the job, so its result stands while the job applies it.
1221
+ */
1222
+ async #region(decide, refresh) {
1223
+ for (;;) {
1224
+ const keys = new Set();
1225
+ this.#reading = keys;
1226
+ let result;
1227
+ try {
1228
+ result = { kind: "value", value: decide() };
1229
+ }
1230
+ catch (error) {
1231
+ result = { kind: "error", error };
1232
+ }
1233
+ finally {
1234
+ this.#reading = undefined;
1235
+ }
1236
+ const gates = [];
1237
+ for (const key of keys) {
1238
+ const gate = this.#session.touch(key);
1239
+ if (gate !== undefined)
1240
+ gates.push(gate);
1241
+ }
1242
+ if (gates.length === 0) {
1243
+ if (result.kind === "error")
1244
+ throw result.error;
1245
+ return result.value;
1246
+ }
1247
+ await Promise.all(gates);
1248
+ await refresh?.();
1249
+ }
1250
+ }
1251
+ /** Load the chains a region walks, again after it waited: what was published meanwhile may list new work. */
1252
+ #reloadScopes = () => this.#loadScopes(false);
1253
+ /** In a decision region, note that it reads `key`; anywhere else, nothing. */
1254
+ #record(key) {
1255
+ this.#reading?.add(key);
1256
+ }
1257
+ /** A live task's committed record, read by a decision region. */
1258
+ #liveRecord(id) {
1259
+ this.#record(taskKey(id));
1260
+ return this.#live.get(id);
1261
+ }
1262
+ /**
1263
+ * Keep `node`, which a chain load of the job on the line installed, until that job's commit is published or fails:
1264
+ * work it creates below the node needs it, and the sweep would drop it as unneeded before then.
1265
+ */
1266
+ #pin(node) {
1267
+ this.#pins.set(node, (this.#pins.get(node) ?? 0) + 1);
1268
+ this.#session.onJobEnd(() => {
1269
+ const count = this.#pins.get(node) - 1;
1270
+ if (count > 0) {
1271
+ this.#pins.set(node, count);
1272
+ return;
1273
+ }
1274
+ this.#pins.delete(node);
1275
+ this.#dropIfUnneeded(node);
1276
+ });
1277
+ }
1278
+ /**
1279
+ * Bring the scheduler's sets in line with a task's committed record. A task that ended may free the nearest live task
1280
+ * above it: one holding its outcome finalizes, an abort-marked one runs its abort handler; its waiters may run.
1281
+ */
1282
+ #track(previous, record) {
1283
+ const id = record.id;
1284
+ const invocation = this.#invocations.get(id);
1285
+ if (invocation !== undefined)
1286
+ invocation.record = record;
1287
+ if (record.state.status === "terminal") {
1288
+ if (previous !== undefined && !this.#closing)
1289
+ this.#countActive(-1, record.kind);
1290
+ this.#resumed.delete(id);
1291
+ }
1292
+ else if (previous === undefined && !this.#closing) {
1293
+ this.#countActive(1, record.kind);
1294
+ }
1295
+ if (previous?.state.status === "waiting")
1296
+ for (const on of previous.state.on)
1297
+ deleteFrom(this.#waiters, on, id);
1298
+ if (record.state.status === "terminal") {
1299
+ const node = nodeOf(record);
1300
+ this.#live.delete(id);
1301
+ this.#sleeping.delete(id);
1302
+ this.#gateWakes.delete(id);
1303
+ this.#intent.delete(id);
1304
+ this.#runnable.delete(id);
1305
+ this.#finalizeChecks.delete(id);
1306
+ this.#settled.set(id, node);
1307
+ // Before anything is forgotten: the walk up to the task it held passes the ended tasks between them. Its chain is
1308
+ // loaded, as every commit that ends a task loads the chains of `#unloaded` first.
1309
+ this.#release(node);
1310
+ for (const waiter of this.#waiters.get(id) ?? [])
1311
+ this.#runnable.add(waiter);
1312
+ this.#relist(id);
1313
+ this.#dropIfUnneeded(id);
1314
+ return;
1315
+ }
1316
+ this.#live.set(id, record);
1317
+ if (previous === undefined) {
1318
+ if (!this.#known(parentNode(record)))
1319
+ this.#unloaded.add(id);
1320
+ this.#relist(id);
1321
+ }
1322
+ if (cancellationIntent(record))
1323
+ this.#intent.add(id);
1324
+ else
1325
+ this.#intent.delete(id);
1326
+ if (record.state.status === "completing") {
1327
+ this.#runnable.delete(id);
1328
+ this.#finalizeChecks.add(id);
1329
+ }
1330
+ else {
1331
+ this.#runnable.add(id);
1332
+ }
1333
+ if (record.state.status === "waiting")
1334
+ for (const on of record.state.on)
1335
+ addTo(this.#waiters, on, id);
1336
+ if (record.state.status === "sleeping")
1337
+ this.#sleeping.add(id);
1338
+ else {
1339
+ this.#sleeping.delete(id);
1340
+ this.#gateWakes.delete(id);
1341
+ }
1342
+ }
1343
+ /** The nearest live task above ended ordinary work may be free now: one holding its outcome, or an aborting one. */
1344
+ #release(node, overlay) {
1345
+ const above = this.#nearestLiveAbove(node, overlay);
1346
+ if (above?.state.status === "completing")
1347
+ this.#finalizeChecks.add(above.id);
1348
+ else if (above?.abortRequested === true)
1349
+ this.#runnable.add(above.id);
1350
+ return above;
1351
+ }
1352
+ /**
1353
+ * List `start` under its parent node in `#below` while it is a live task or has nodes listed below it, and unlist it
1354
+ * otherwise; then its parent, as far up as that changes. So `#below` holds exactly the tree around live work; a
1355
+ * parent that loses its last listed node is queued for the sweep. A loop, as ownership chains can be deeper than the
1356
+ * call stack.
1357
+ */
1358
+ #relist(start) {
1359
+ let node = start;
1360
+ for (;;) {
1361
+ const needed = (typeof node !== "string" && this.#live.has(node)) || this.#below.has(node);
1362
+ let parent;
1363
+ if (typeof node === "string") {
1364
+ parent = this.#edges.get(conversationOf(node));
1365
+ }
1366
+ else {
1367
+ const known = this.#live.get(node) ?? this.#settled.get(node);
1368
+ if (known === undefined)
1369
+ return;
1370
+ parent = parentNode(known);
1371
+ }
1372
+ if (parent === undefined)
1373
+ return;
1374
+ if (parent === null) {
1375
+ const root = conversationOf(node);
1376
+ if (needed)
1377
+ this.#roots.add(root);
1378
+ else
1379
+ this.#roots.delete(root);
1380
+ return;
1381
+ }
1382
+ if ((this.#below.get(parent)?.has(node) === true) === needed)
1383
+ return;
1384
+ if (needed) {
1385
+ const first = !this.#below.has(parent);
1386
+ addTo(this.#below, parent, node);
1387
+ if (!first)
1388
+ return;
1389
+ }
1390
+ else {
1391
+ deleteFrom(this.#below, parent, node);
1392
+ if (this.#below.has(parent))
1393
+ return;
1394
+ this.#dropIfUnneeded(parent);
1395
+ }
1396
+ node = parent;
1397
+ }
1398
+ }
1399
+ /**
1400
+ * The nearest live task above ended ordinary work `node`, in the overlay's view: the one that work held, if any. Work
1401
+ * at or below a background task holds nothing above it.
1402
+ */
1403
+ #nearestLiveAbove(node, overlay) {
1404
+ this.#record(INTENT_KEY);
1405
+ for (let current = node; !current.background;) {
1406
+ const owner = current.owner ?? this.#edge(current.conversationId, overlay);
1407
+ if (owner === undefined || owner === null)
1408
+ return undefined;
1409
+ const record = overlay?.tasks.get(owner) ?? this.#liveRecord(owner);
1410
+ if (record !== undefined && record.state.status !== "terminal")
1411
+ return record;
1412
+ const above = record ?? this.#settled.get(owner);
1413
+ if (above === undefined)
1414
+ return undefined;
1415
+ current = above;
1416
+ }
1417
+ return undefined;
1418
+ }
1419
+ /** Whether the chain above `node` is loaded, without walking: known tasks outside `#unloaded` have a loaded chain. */
1420
+ #known(node) {
1421
+ if (typeof node !== "string") {
1422
+ return (this.#live.has(node) || this.#settled.has(node)) && !this.#unloaded.has(node);
1423
+ }
1424
+ const owner = this.#edges.get(conversationOf(node));
1425
+ return owner === null || (owner !== undefined && this.#known(owner));
1426
+ }
1427
+ /** Owner task of a conversation, `null` when ownerless, `undefined` while not loaded. */
1428
+ #edge(id, overlay) {
1429
+ if (overlay?.edges.has(id) === true)
1430
+ return overlay.edges.get(id);
1431
+ this.#record(conversationKey(id));
1432
+ return this.#edges.get(id);
1433
+ }
1434
+ #node(id, overlay) {
1435
+ return overlay?.tasks.get(id) ?? this.#live.get(id) ?? this.#settled.get(id);
1436
+ }
1437
+ /** Walk up from `start`: owner tasks and conversations, ending at an ownerless root or an edge not loaded yet. */
1438
+ *#above(start, overlay) {
1439
+ let at = start;
1440
+ while (at !== undefined) {
1441
+ if (at.kind === "task") {
1442
+ const node = this.#node(at.task, overlay);
1443
+ if (node === undefined) {
1444
+ yield { kind: "unknown" };
1445
+ return;
1446
+ }
1447
+ yield { kind: "task", task: at.task, node };
1448
+ at = parentOf(node);
1449
+ }
1450
+ else {
1451
+ yield { kind: "conversation", conversation: at.conversation };
1452
+ const edge = this.#edge(at.conversation, overlay);
1453
+ if (edge === undefined) {
1454
+ yield { kind: "unknown" };
1455
+ return;
1456
+ }
1457
+ at = edge === null ? undefined : { kind: "task", task: edge };
1458
+ }
1459
+ }
1460
+ }
1461
+ /**
1462
+ * The tasks below `start` that a walk down reaches: those `#below` lists and, under an overlay, the commit's new tasks,
1463
+ * with its candidates in place of committed records. Background tasks are reached but not entered, unless
1464
+ * `crossBackground`, and neither are the tasks `enter` rejects. A loop, as chains can be deeper than the call stack.
1465
+ */
1466
+ *#walkDown(start, options = {}) {
1467
+ const { overlay, crossBackground = false, enter } = options;
1468
+ const links = overlay === undefined ? undefined : this.#links(overlay);
1469
+ const pending = [start];
1470
+ for (let at = pending.pop(); at !== undefined; at = pending.pop()) {
1471
+ this.#record(ownedKey(at));
1472
+ for (const children of [this.#below.get(at), links?.get(at)]) {
1473
+ for (const child of children ?? []) {
1474
+ if (typeof child === "string") {
1475
+ pending.push(child);
1476
+ continue;
1477
+ }
1478
+ const record = overlay?.tasks.get(child) ?? this.#live.get(child);
1479
+ const node = record ?? this.#settled.get(child);
1480
+ if (node === undefined)
1481
+ continue;
1482
+ const live = record !== undefined && record.state.status !== "terminal" ? record : undefined;
1483
+ yield { id: child, node, live };
1484
+ if ((crossBackground || !node.background) && (enter === undefined || enter(child)))
1485
+ pending.push(child);
1486
+ }
1487
+ }
1488
+ }
1489
+ }
1490
+ /**
1491
+ * The links walks down need for the commit's new tasks: each one under its parent node, then each node above it that
1492
+ * `#below` does not list yet, until one it lists, a live task (always listed), or the chain's end.
1493
+ */
1494
+ #links(overlay) {
1495
+ if (overlay.links !== undefined)
1496
+ return overlay.links;
1497
+ const links = new Map();
1498
+ for (const record of overlay.tasks.values()) {
1499
+ if (this.#live.has(record.id) || this.#settled.has(record.id))
1500
+ continue;
1501
+ let child = record.id;
1502
+ let parent = parentNode(record);
1503
+ while (parent !== undefined && parent !== null && links.get(parent)?.has(child) !== true) {
1504
+ addTo(links, parent, child);
1505
+ if (typeof parent !== "string" && (this.#live.has(parent) || overlay.tasks.has(parent)))
1506
+ break;
1507
+ let above;
1508
+ if (typeof parent === "string") {
1509
+ above = this.#edge(conversationOf(parent), overlay);
1510
+ }
1511
+ else {
1512
+ const fields = this.#settled.get(parent);
1513
+ above = fields === undefined ? undefined : parentNode(fields);
1514
+ }
1515
+ if (above !== undefined && above !== null && this.#below.get(above)?.has(parent) === true)
1516
+ break;
1517
+ child = parent;
1518
+ parent = above;
1519
+ }
1520
+ }
1521
+ overlay.links = links;
1522
+ return links;
1523
+ }
1524
+ /**
1525
+ * The live ordinary owned work of `owner` (spec §5.5): the live non-background tasks below it that a walk down reaches
1526
+ * without entering a background task; with `first`, only the first. Candidates in `overlay` replace committed records;
1527
+ * the walk does not enter tasks in `done`, which have none. Owner chains must be loaded.
1528
+ */
1529
+ #ownedLive(owner, options = {}) {
1530
+ const { overlay, first = false, done } = options;
1531
+ const found = [];
1532
+ const walk = this.#walkDown(owner, {
1533
+ ...(overlay === undefined ? {} : { overlay }),
1534
+ ...(done === undefined ? {} : { enter: (id) => !done.has(id) }),
1535
+ });
1536
+ for (const { id, node, live } of walk) {
1537
+ if (live === undefined || node.background)
1538
+ continue;
1539
+ found.push(id);
1540
+ if (first)
1541
+ break;
1542
+ }
1543
+ return found;
1544
+ }
1545
+ #hasOwnedLive(owner, overlay, done) {
1546
+ const options = {
1547
+ first: true,
1548
+ ...(overlay === undefined ? {} : { overlay }),
1549
+ ...(done === undefined ? {} : { done }),
1550
+ };
1551
+ return this.#ownedLive(owner, options).length > 0;
1552
+ }
1553
+ /**
1554
+ * Whether ordinary traversal from `scope` reaches `start`: walking up reaches the scope's conversation, or an
1555
+ * ownerless one for `roots`, without crossing a background owner, unless `crossBackground`. `undefined` while an
1556
+ * edge is not loaded.
1557
+ */
1558
+ #inScope(start, scope, crossBackground = false) {
1559
+ this.#record(INTENT_KEY);
1560
+ for (const step of this.#above(start)) {
1561
+ if (step.kind === "unknown")
1562
+ return undefined;
1563
+ if (step.kind === "conversation") {
1564
+ if (scope.kind === "conversation" && step.conversation === scope.conversation)
1565
+ return true;
1566
+ }
1567
+ else if (step.node.background && !crossBackground) {
1568
+ return false;
1569
+ }
1570
+ }
1571
+ return scope.kind === "roots";
1572
+ }
1573
+ /**
1574
+ * Whether a live owner's cancellation intent reaches `start`: walking up finds an owner with intent before a
1575
+ * background owner without it. Terminal owners never cascade (spec §5.4).
1576
+ */
1577
+ #belowCancelled(start) {
1578
+ return this.#cancellingOwner(start) !== undefined;
1579
+ }
1580
+ /** The nearest live owner above `start` whose cancellation intent reaches it, if any; see `#belowCancelled`. */
1581
+ #cancellingOwner(start) {
1582
+ this.#record(INTENT_KEY);
1583
+ // Nothing cancels, the common case: no walk.
1584
+ if (this.#intent.size === 0)
1585
+ return undefined;
1586
+ for (const step of this.#above(start)) {
1587
+ if (step.kind === "unknown")
1588
+ return undefined;
1589
+ if (step.kind !== "task")
1590
+ continue;
1591
+ const live = this.#live.get(step.task);
1592
+ if (live !== undefined && cancellationIntent(live))
1593
+ return live;
1594
+ if (step.node.background)
1595
+ return undefined;
1596
+ }
1597
+ return undefined;
1598
+ }
1599
+ /**
1600
+ * Count a task in or out of `diffra.durable.tasks.active`. Commit observers count at a commit's publication, which must not
1601
+ * throw, so a throwing adapter is reported.
1602
+ */
1603
+ #countActive(delta, kind) {
1604
+ try {
1605
+ this.#activeMetric.add(delta, { task: kind });
1606
+ }
1607
+ catch (error) {
1608
+ this.#report(error, TELEMETRY);
1609
+ }
1610
+ }
1611
+ /** Fail the Session, which reports it, for a throw in one of the scheduler's own commits; ignored once closing. */
1612
+ #failSession(error, context) {
1613
+ if (!this.#closing)
1614
+ this.#session.fail(error, context);
1615
+ }
1616
+ /** Close listener: runs synchronously once admission is sealed, before `join()`, or when the Session fails. */
1617
+ #seal() {
1618
+ for (const record of this.#live.values())
1619
+ this.#countActive(-1, record.kind);
1620
+ this.#resumed.clear();
1621
+ this.#closing = true;
1622
+ this.#closed.abort(closedError(this.#session));
1623
+ try {
1624
+ this.#unsubscribeRegistry();
1625
+ }
1626
+ catch (error) {
1627
+ this.#report(error, REGISTRY);
1628
+ }
1629
+ const error = closedError(this.#session);
1630
+ this.#taskWaiters.rejectAll(error);
1631
+ this.#idleWaiters.rejectAll(error);
1632
+ this.#contexts.clear();
1633
+ this.#idleOrder.clear();
1634
+ this.#expiry?.disarm();
1635
+ this.#expiry = undefined;
1636
+ this.#timer?.disarm();
1637
+ this.#timer = undefined;
1638
+ }
1639
+ /**
1640
+ * Recompute the wake in a microtask the line never waits for, with no order relative to host commit listeners (one
1641
+ * already queued serves later changes too): arm the built-in timer, or tell `onWake` of a change.
1642
+ */
1643
+ #scheduleWake() {
1644
+ if (this.#wakeScheduled || this.#closing || this.#readOnly)
1645
+ return;
1646
+ this.#wakeScheduled = true;
1647
+ queueMicrotask(() => {
1648
+ this.#wakeScheduled = false;
1649
+ if (this.#closing)
1650
+ return;
1651
+ const wake = this.wake();
1652
+ if (this.#onWake === undefined) {
1653
+ this.#armTimer(this.#enabled ? wake.at : undefined);
1654
+ return;
1655
+ }
1656
+ const last = this.#lastWake;
1657
+ if (last !== undefined && last.active === wake.active && last.at === wake.at)
1658
+ return;
1659
+ try {
1660
+ this.#onWake(wake);
1661
+ // Only a delivered wake counts: after a throw, the next change or kick offers it again.
1662
+ this.#lastWake = wake;
1663
+ }
1664
+ catch (error) {
1665
+ this.#report(error, ON_WAKE);
1666
+ }
1667
+ });
1668
+ }
1669
+ /**
1670
+ * Keep the timer for the earliest sleep. It keeps the process alive, unlike the context expiry timer: a process with a
1671
+ * sleeping task has work left, such as a retry backoff. Rechecks the clock when it fires, so a wake before `until`
1672
+ * only arms it again.
1673
+ */
1674
+ #armTimer(at) {
1675
+ if (this.#timer !== undefined && this.#timer.at === at)
1676
+ return;
1677
+ this.#timer?.disarm();
1678
+ this.#timer = undefined;
1679
+ if (at === undefined || this.#closing)
1680
+ return;
1681
+ const disarm = this.#timers.foreground(() => {
1682
+ this.#timer = undefined;
1683
+ this.#wakeDue();
1684
+ this.#kick();
1685
+ }, at - this.#now());
1686
+ this.#timer = { at, disarm };
1687
+ }
1688
+ /** A sleeping record that cannot wake yet (`asleep()`), unless a gate wake runs it before its time. */
1689
+ #asleep(record, now) {
1690
+ return asleep(record, now) && !this.#gateWakes.has(record.id);
1691
+ }
1692
+ /**
1693
+ * Wake a call parked at a gate, so its gates are asked again; a sleep whose deadline passed takes the deadline path
1694
+ * when reserved (`#woke()`). Other records are left alone.
1695
+ */
1696
+ #wakeGate(record) {
1697
+ if (!this.#parkedAtGate(record))
1698
+ return;
1699
+ this.#gateWakes.add(record.id);
1700
+ this.#runnable.add(record.id);
1701
+ }
1702
+ /** Make every sleeping task whose time has come a reservation candidate. */
1703
+ #wakeDue() {
1704
+ for (const id of this.#sleeping) {
1705
+ if (!this.#asleep(this.#live.get(id), this.#now()))
1706
+ this.#runnable.add(id);
1707
+ }
1708
+ }
1709
+ /**
1710
+ * The report info of a task's failure, with the extension that installed its definition: the code that failed is
1711
+ * that extension's. Built-in tasks have none.
1712
+ */
1713
+ /** What a report about `task`'s code says of it: the task, and `extension`, which installed the definition that ran. */
1714
+ #aboutTask(task, extension) {
1715
+ return { task: reportTask(task), ...optionalExtension(extension) };
1716
+ }
1717
+ /** What a report about `task` says of it: the task, and the extension that installed its current definition. */
1718
+ #aboutCurrentTask(task) {
1719
+ let extension;
1720
+ try {
1721
+ const snapshot = this.#registry.snapshot();
1722
+ extension = installerOf(snapshot, snapshot.task(task.kind));
1723
+ }
1724
+ catch {
1725
+ // A registry that throws is reported where it is read for scheduling; a report goes out without the name.
1726
+ }
1727
+ return this.#aboutTask(task, extension);
1728
+ }
1729
+ /** `settings.restartLimit`, or the default when the host's settings throw. */
1730
+ #restartLimit() {
1731
+ try {
1732
+ return this.#settings().restartLimit;
1733
+ }
1734
+ catch (error) {
1735
+ this.#report(error, SETTINGS);
1736
+ return DEFAULT_RESTART_LIMIT;
1737
+ }
1738
+ }
1739
+ #notifyBlocked() {
1740
+ for (const listener of [...this.#blockedListeners]) {
1741
+ try {
1742
+ listener();
1743
+ }
1744
+ catch (error) {
1745
+ this.#report(error, { kind: "listener_error" });
1746
+ }
1747
+ }
1748
+ }
1749
+ #kick() {
1750
+ this.#scheduleWake();
1751
+ this.#dirty = true;
1752
+ if (this.#draining || !this.#enabled || this.#closing)
1753
+ return;
1754
+ this.#draining = true;
1755
+ // Never commit synchronously from a commit or registry listener.
1756
+ queueMicrotask(() => void this.#drain());
1757
+ }
1758
+ async #drain() {
1759
+ try {
1760
+ while (this.#dirty && this.#enabled && !this.#closing) {
1761
+ this.#dirty = false;
1762
+ for (const reservation of await this.#reserve())
1763
+ this.#start(reservation);
1764
+ }
1765
+ }
1766
+ catch (error) {
1767
+ // As in `#reconcile()`: the reservation commit runs no extension code.
1768
+ this.#failSession(error);
1769
+ }
1770
+ finally {
1771
+ this.#draining = false;
1772
+ // A wakeup that arrived after the loop's last check still needs its pass.
1773
+ if (this.#dirty)
1774
+ this.#kick();
1775
+ }
1776
+ }
1777
+ /**
1778
+ * Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take, unless abandoned after
1779
+ * a restart. The first pass after open only abort-marks the abandoned tasks, so later passes see the marks.
1780
+ */
1781
+ async #reserve() {
1782
+ const reservations = [];
1783
+ const faulted = [];
1784
+ let abandoned = [];
1785
+ try {
1786
+ await this.#session.commitInternal(async (tx) => {
1787
+ if (!this.#enabled || this.#closing)
1788
+ return;
1789
+ if (this.#abandoned.size > 0) {
1790
+ const ids = [...this.#abandoned];
1791
+ const unmarked = await this.#region(() => ids
1792
+ .map((id) => this.#liveRecord(id))
1793
+ .filter((record) => {
1794
+ if (record === undefined || record.abortRequested)
1795
+ return false;
1796
+ const owner = record.owner === undefined ? undefined : this.#liveRecord(record.owner);
1797
+ return owner === undefined || !this.#keepsAbandoned(owner);
1798
+ }));
1799
+ for (const record of unmarked)
1800
+ tx.setTask(withAbortMark(record, "restart"));
1801
+ abandoned = ids;
1802
+ return;
1803
+ }
1804
+ await this.#loadScopes(false);
1805
+ // Every pass picks up sleeps whose time has come: a pass started by any change may be the first to run after
1806
+ // a deadline, and the wake it schedules no longer keeps a timer for a due sleep.
1807
+ this.#wakeDue();
1808
+ const plan = await this.#planCandidates(this.#now());
1809
+ // Work below an owner with cancellation intent waits for its cascade mark instead of running a phase; schedule
1810
+ // the cascade, which may not have run yet.
1811
+ if (plan.cascade) {
1812
+ this.#cascadePending = true;
1813
+ this.#scheduleReconcile();
1814
+ }
1815
+ // Taken once per pass, and only when some task is a candidate.
1816
+ let snapshot;
1817
+ let publication = 0;
1818
+ for (const { record, woke } of plan.ready) {
1819
+ const id = record.id;
1820
+ const mode = record.abortRequested ? "abort" : "run";
1821
+ // Work cut off `restartLimit` times in a row would run forever: an abort handler, or a phase of a kind that
1822
+ // does not end itself at the limit, ends the task `faulted` instead.
1823
+ // The settings are read only for a task that was cut off at all.
1824
+ const cutOff = record.restarts !== undefined && record.restarts >= this.#restartLimit();
1825
+ if (cutOff && (mode === "abort" || !this.#limitsRestarts(record.kind))) {
1826
+ const message = mode === "abort"
1827
+ ? `Abort handler of task ${id} (${record.kind}) was cut off ${record.restarts} times`
1828
+ : `Task ${id} (${record.kind}) was cut off ${record.restarts} times without progress`;
1829
+ await this.#terminate(tx, record, {
1830
+ status: "faulted",
1831
+ error: { message, detail: { reason: "restart_limit" } },
1832
+ });
1833
+ faulted.push({ record, message });
1834
+ continue;
1835
+ }
1836
+ if (snapshot === undefined) {
1837
+ publication = this.#publications;
1838
+ snapshot = this.#registry.snapshot();
1839
+ }
1840
+ const resolution = this.#resolve(record, snapshot);
1841
+ if (resolution.kind === "blocked") {
1842
+ // An abandoned task waits for its definition, so its abort handler can clean up.
1843
+ if (mode === "abort" && record.abortReason === undefined) {
1844
+ await this.#terminate(tx, record, { status: "orphaned", reason: resolution.reason });
1845
+ }
1846
+ continue;
1847
+ }
1848
+ if (resolution.record !== record || record.state.status !== "running") {
1849
+ tx.setTask(reserved(resolution.record, woke));
1850
+ }
1851
+ // Registered on the line, so marks and later reservations see it and close joins it; `#end` makes it a
1852
+ // candidate again.
1853
+ this.#runnable.delete(id);
1854
+ const invocation = this.#createInvocation(record, mode, installerOf(snapshot, resolution.task));
1855
+ reservations.push({ invocation, task: resolution.task, snapshot, publication });
1856
+ }
1857
+ }, this.#context);
1858
+ }
1859
+ catch (error) {
1860
+ for (const { invocation } of reservations) {
1861
+ this.#invocations.delete(invocation.taskId);
1862
+ this.#runnable.add(invocation.taskId);
1863
+ invocation.finish();
1864
+ }
1865
+ throw error;
1866
+ }
1867
+ for (const { record, message } of faulted) {
1868
+ this.#report(new Error(message), {
1869
+ kind: "task_faulted",
1870
+ ...this.#aboutCurrentTask(recordTask(record)),
1871
+ reason: "restart_limit",
1872
+ });
1873
+ }
1874
+ // Marked, or already marked or gone: done with them. Reserve again, now seeing the marks.
1875
+ for (const id of abandoned)
1876
+ this.#abandoned.delete(id);
1877
+ if (abandoned.length > 0)
1878
+ this.#dirty = true;
1879
+ return reservations;
1880
+ }
1881
+ /**
1882
+ * Plan a reservation pass over the candidates, taken out of `#runnable` while it plans: a task made a candidate
1883
+ * meanwhile, such as a waiter whose last task ended, lands in the fresh set, so the pass's decision to drop it cannot
1884
+ * erase that. The candidates not dropped go back in front of the fresh set, unless they ended or hold meanwhile.
1885
+ */
1886
+ async #planCandidates(now) {
1887
+ const candidates = this.#runnable;
1888
+ this.#runnable = new Set();
1889
+ let dropped = new Set();
1890
+ try {
1891
+ const plan = await this.#region(() => this.#planReservation(candidates, now), this.#reloadScopes);
1892
+ dropped = new Set(plan.dropped);
1893
+ return plan;
1894
+ }
1895
+ finally {
1896
+ const merged = new Set();
1897
+ for (const id of candidates) {
1898
+ const status = this.#live.get(id)?.state.status;
1899
+ if (!dropped.has(id) && status !== undefined && status !== "completing")
1900
+ merged.add(id);
1901
+ }
1902
+ for (const id of this.#runnable)
1903
+ merged.add(id);
1904
+ this.#runnable = merged;
1905
+ }
1906
+ }
1907
+ /**
1908
+ * A reservation pass's decision region: the candidates it drops (gone, holding, waiting, asleep, or with an
1909
+ * invocation), whether one waits for a cascade, and the runnable records to resolve. Iterating the candidates is not
1910
+ * keyed: a pass that misses a task a pending commit makes runnable only delays it, as does skipping one with an
1911
+ * invocation without reading its record, or a waiter's check whether what it waits on is still live.
1912
+ */
1913
+ #planReservation(candidates, now) {
1914
+ const dropped = [];
1915
+ const ready = [];
1916
+ let cascade = false;
1917
+ for (const id of candidates) {
1918
+ if (this.#invocations.has(id)) {
1919
+ dropped.push(id);
1920
+ continue;
1921
+ }
1922
+ const record = this.#liveRecord(id);
1923
+ // It returns once what it waits for ends, its record changes, or the work below it ends; a sleep at the first pass
1924
+ // after its time comes, which the timer, `resume()`, or any change starts.
1925
+ if (record === undefined ||
1926
+ record.state.status === "completing" ||
1927
+ this.#waitingOn(record, true).length > 0 ||
1928
+ this.#asleep(record, now)) {
1929
+ dropped.push(id);
1930
+ continue;
1931
+ }
1932
+ if (!record.abortRequested && !record.background && this.#belowCancelled(parentOf(record))) {
1933
+ cascade = true;
1934
+ continue;
1935
+ }
1936
+ ready.push({ record: record, woke: this.#woke(record, now) });
1937
+ }
1938
+ return { dropped, cascade, ready };
1939
+ }
1940
+ /**
1941
+ * How a run-mode reservation ends a record's wait or sleep (spec suspendable §2.4): a wait's wake names the terminal
1942
+ * tasks of its `on` (all of them unless `any`), read as task records; a sleep's, the key that woke it, consumed, or
1943
+ * its deadline, with the keys that hold nothing expired. None for an abort, or for a record that neither waits nor
1944
+ * sleeps.
1945
+ */
1946
+ #woke(record, now) {
1947
+ const state = record.state;
1948
+ if (record.abortRequested)
1949
+ return undefined;
1950
+ if (state.status === "waiting") {
1951
+ const ended = state.policy === "any" ? state.on.filter((id) => this.#liveRecord(id) === undefined) : state.on;
1952
+ return { wake: { reason: "tasks", ended }, memos: {} };
1953
+ }
1954
+ // Not asleep: due, or woken at its gates, which needs no wake unless its deadline passed.
1955
+ return state.status === "sleeping" ? sleepWake(state, record.memos, now) : undefined;
1956
+ }
1957
+ /**
1958
+ * Live tasks a task waits for before its next invocation: its live ordinary owned work when abort-marked, since
1959
+ * abort runs bottom-up, otherwise the live part of the `on` of a wait; none for an `any` wait one of whose tasks ended.
1960
+ */
1961
+ #waitingOn(record, first = false) {
1962
+ if (record.abortRequested)
1963
+ return this.#ownedLive(record.id, { first });
1964
+ if (record.state.status !== "waiting")
1965
+ return [];
1966
+ const on = record.state.on;
1967
+ if (record.state.policy === "any" && !on.every((id) => this.#live.has(id)))
1968
+ return [];
1969
+ if (!first)
1970
+ return on.filter((id) => this.#live.has(id));
1971
+ const live = on.find((id) => this.#live.has(id));
1972
+ return live === undefined ? [] : [live];
1973
+ }
1974
+ /** Resolve the record's definition by kind, migrating an older stored version. */
1975
+ #resolve(record, snapshot) {
1976
+ const fit = this.#fit(record, snapshot.task(record.kind));
1977
+ if (fit.kind === "blocked")
1978
+ return { kind: "blocked", reason: fit.reason };
1979
+ if (!fit.migrates)
1980
+ return { kind: "ready", task: fit.task, record };
1981
+ const definition = erased(fit.task);
1982
+ try {
1983
+ if (definition.migrate === undefined)
1984
+ throw missingMigration(record, definition);
1985
+ const migrated = definition.migrate(record.input, record.state.checkpoint, record.version);
1986
+ const state = { ...record.state, checkpoint: copyJson(migrated.checkpoint) };
1987
+ const migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state };
1988
+ return { kind: "ready", task: fit.task, record: migratedRecord };
1989
+ }
1990
+ catch (error) {
1991
+ this.#failedMigrations.set(record.id, { task: fit.task, error });
1992
+ // Blocked now without a commit: the graph and the host's wake must hear it.
1993
+ queueMicrotask(() => this.#notifyBlocked());
1994
+ this.#scheduleWake();
1995
+ const extension = installerOf(snapshot, fit.task);
1996
+ this.#report(error, { kind: "migration_failed", ...this.#aboutTask(recordTask(record), extension) });
1997
+ return { kind: "blocked", reason: "migration_failed" };
1998
+ }
1999
+ }
2000
+ #fit(record, task) {
2001
+ if (task === undefined)
2002
+ return { kind: "blocked", reason: "missing_task" };
2003
+ const version = task.definition.version;
2004
+ if (version === record.version)
2005
+ return { kind: "fits", task, migrates: false };
2006
+ if (version < record.version)
2007
+ return { kind: "blocked", reason: "task_too_old" };
2008
+ const failed = this.#failedMigrations.get(record.id);
2009
+ if (failed?.task === task)
2010
+ return { kind: "blocked", reason: "migration_failed", error: failed.error };
2011
+ return { kind: "fits", task, migrates: true };
2012
+ }
2013
+ /** Sizes of the ownership indexes, for tests that bound the scheduler's memory. */
2014
+ get indexSizes() {
2015
+ let below = 0;
2016
+ for (const children of this.#below.values())
2017
+ below += children.size;
2018
+ return {
2019
+ live: this.#live.size,
2020
+ settled: this.#settled.size,
2021
+ edges: this.#edges.size,
2022
+ below,
2023
+ roots: this.#roots.size,
2024
+ unloaded: this.#unloaded.size,
2025
+ dropQueue: this.#dropQueue.size,
2026
+ pins: this.#pins.size,
2027
+ };
2028
+ }
2029
+ /**
2030
+ * The kept contexts' idle state, for tests (a diagnostic, computed on demand): how many are kept and how many are
2031
+ * idle, how many disagree with a full recompute (an idle period without `#inactive()`, or `#inactive()` without one; an
2032
+ * expiry order that differs from the idle periods, or is not sorted), and how many idle checks covered every scope.
2033
+ */
2034
+ get idleState() {
2035
+ let mismatches = 0;
2036
+ let idle = 0;
2037
+ for (const [conversationId, kept] of this.#contexts) {
2038
+ if (kept.idleSince !== undefined)
2039
+ idle++;
2040
+ if ((kept.idleSince !== undefined) !== this.#inactive(conversationId))
2041
+ mismatches++;
2042
+ if (this.#idleOrder.get(conversationId) !== kept.idleSince)
2043
+ mismatches++;
2044
+ }
2045
+ let previous = Number.NEGATIVE_INFINITY;
2046
+ for (const [conversationId, idleSince] of this.#idleOrder) {
2047
+ if (idleSince < previous || this.#contexts.get(conversationId)?.idleSince !== idleSince)
2048
+ mismatches++;
2049
+ previous = idleSince;
2050
+ }
2051
+ return {
2052
+ contexts: this.#contexts.size,
2053
+ idleContexts: idle,
2054
+ idleMismatches: mismatches,
2055
+ fullIdleChecks: this.#fullIdleChecks,
2056
+ };
2057
+ }
2058
+ /**
2059
+ * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a
2060
+ * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that
2061
+ * cannot exist, shows as failed.
2062
+ */
2063
+ async inspect(snapshot) {
2064
+ await this.#published();
2065
+ await this.#loadScopes(false);
2066
+ const tasks = [];
2067
+ for (const record of this.#live.values())
2068
+ tasks.push({ record, state: this.#inspectTask(record, snapshot) });
2069
+ const scheduling = this.#closing ? "closing" : this.#enabled ? "running" : "paused";
2070
+ return { scheduling, tasks };
2071
+ }
2072
+ #inspectTask(record, snapshot) {
2073
+ if (this.#invocations.has(record.id))
2074
+ return { kind: "running" };
2075
+ if (record.state.status === "completing")
2076
+ return { kind: "completing" };
2077
+ const on = this.#waitingOn(record);
2078
+ if (on.length > 0)
2079
+ return { kind: "waiting", on };
2080
+ if (this.#asleep(record, this.#now())) {
2081
+ const until = record.state.until;
2082
+ return until === undefined ? { kind: "sleeping" } : { kind: "sleeping", until };
2083
+ }
2084
+ const fit = this.#fit(record, snapshot.task(record.kind));
2085
+ if (fit.kind === "blocked")
2086
+ return fit;
2087
+ if (fit.migrates && fit.task.definition.migrate === undefined) {
2088
+ return { kind: "blocked", reason: "migration_failed", error: missingMigration(record, erased(fit.task)) };
2089
+ }
2090
+ return { kind: "pending", migrates: fit.migrates };
2091
+ }
2092
+ #createInvocation(record, mode, extension) {
2093
+ const controller = new AbortController();
2094
+ const { promise: done, resolve: finish } = Promise.withResolvers();
2095
+ const invocation = {
2096
+ taskId: record.id,
2097
+ kind: record.kind,
2098
+ extension,
2099
+ conversationId: record.conversationId,
2100
+ mode,
2101
+ controller,
2102
+ links: record.startedAt === undefined ? record.links : undefined,
2103
+ context: withAbortSignal(controller.signal, this.#context),
2104
+ record: record,
2105
+ watches: new Set(),
2106
+ timers: new Set(),
2107
+ ended: false,
2108
+ done,
2109
+ finish: () => finish(),
2110
+ };
2111
+ this.#invocations.set(record.id, invocation);
2112
+ return invocation;
2113
+ }
2114
+ #start(reservation) {
2115
+ const invocation = reservation.invocation;
2116
+ void (async () => {
2117
+ try {
2118
+ if (invocation.mode === "run")
2119
+ await this.#run(reservation);
2120
+ else
2121
+ await this.#runAbort(reservation);
2122
+ }
2123
+ catch (error) {
2124
+ this.#report(error, { kind: "task_error", ...this.#aboutTask(invocation, invocation.extension) }, invocation.context);
2125
+ }
2126
+ finally {
2127
+ this.#end(invocation);
2128
+ invocation.record = undefined;
2129
+ invocation.links = undefined;
2130
+ invocation.fault = undefined;
2131
+ invocation.finish();
2132
+ this.#kick();
2133
+ }
2134
+ })();
2135
+ }
2136
+ /** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */
2137
+ async #run(reservation) {
2138
+ const invocation = reservation.invocation;
2139
+ const state = {
2140
+ task: reservation.task,
2141
+ snapshot: reservation.snapshot,
2142
+ publication: reservation.publication,
2143
+ reported: undefined,
2144
+ };
2145
+ const phase = { snapshot: () => state.snapshot, task: () => state.task, agent: undefined };
2146
+ const runtime = this.#runtime(invocation, phase);
2147
+ const progress = (tx, current) => this.#progress(tx, current, state, invocation.extension, invocation.context);
2148
+ let current = await this.#step(invocation, (task) => this.#rules(task, undefined), progress);
2149
+ while (current !== undefined && !this.#closing) {
2150
+ const task = current;
2151
+ current = await this.#phase(invocation, task, async () => {
2152
+ const checkpoint = task.state.checkpoint;
2153
+ // Each phase handler resolves its agent afresh, at first use.
2154
+ phase.agent = undefined;
2155
+ let previous;
2156
+ try {
2157
+ await erased(state.task).phases[checkpoint.phase](task, runtime, invocation.context);
2158
+ previous = { checkpoint };
2159
+ }
2160
+ catch (error) {
2161
+ previous = { checkpoint, failure: { error } };
2162
+ }
2163
+ return this.#step(invocation, (next) => this.#rules(next, previous), progress);
2164
+ });
2165
+ }
2166
+ // A gate's sleep committed under a snapshot the registry has since replaced: the phase could not take a fresh one,
2167
+ // so it is woken as a publication would have woken it.
2168
+ const record = this.#live.get(invocation.taskId);
2169
+ if (record !== undefined && this.#publications !== state.publication) {
2170
+ this.#wakeGate(record);
2171
+ this.#kick();
2172
+ }
2173
+ }
2174
+ /** A phase owns its decision commit, not the next handler, a durable wait, or recovery. */
2175
+ #phase(invocation, task, run) {
2176
+ const parent = task.trace === undefined
2177
+ ? this.#telemetry
2178
+ : (this.#telemetry.propagation?.extract(task.trace) ?? this.#telemetry);
2179
+ const checkpoint = task.state.checkpoint;
2180
+ const attempt = checkpoint.attempt;
2181
+ const resumed = this.#resumed.delete(task.id);
2182
+ return createTypedSpanStarter(parent, [DURABLE_TELEMETRY_SCHEMA])("diffra.durable.phase", {
2183
+ "task.id": task.id,
2184
+ "task.name": task.kind,
2185
+ phase: checkpoint.phase,
2186
+ kind: invocation.mode,
2187
+ resumed,
2188
+ ...(attempt === undefined ? {} : { attempt }),
2189
+ }, async (span) => {
2190
+ if (span.propagation !== undefined && invocation.links !== undefined) {
2191
+ for (const carrier of invocation.links)
2192
+ span.addLink({ context: span.propagation.extract(carrier) });
2193
+ }
2194
+ const previous = invocation.context;
2195
+ invocation.context = withTelemetry(span, previous);
2196
+ const started = performance.now();
2197
+ try {
2198
+ return await run();
2199
+ }
2200
+ finally {
2201
+ invocation.context = previous;
2202
+ const state = invocation.record.state;
2203
+ const terminal = invocation.fault ??
2204
+ (state.status === "terminal" || state.status === "completing" ? state.outcome : undefined);
2205
+ const outcome = terminal !== undefined
2206
+ ? terminal.status === "completed"
2207
+ ? "done"
2208
+ : terminal.status === "aborted"
2209
+ ? "aborted"
2210
+ : "faulted"
2211
+ : state.status === "waiting" || state.status === "sleeping"
2212
+ ? state.status
2213
+ : invocation.ended || this.#closing
2214
+ ? "aborted"
2215
+ : `next=${state.checkpoint.phase}`;
2216
+ span.setAttributes({ outcome });
2217
+ if (terminal?.status === "faulted" || terminal?.status === "failed" || terminal?.status === "orphaned") {
2218
+ const message = terminal.status === "orphaned" ? terminal.reason : terminal.error.message;
2219
+ span.setStatus({
2220
+ status: "error",
2221
+ error: { name: `task_${terminal.status}`, message: ownedSlice(message, 0, 500) },
2222
+ });
2223
+ }
2224
+ else if (outcome === "aborted") {
2225
+ span.setStatus({ status: "ok" });
2226
+ }
2227
+ this.#durationMetric.record(performance.now() - started, { task: task.kind, phase: checkpoint.phase, outcome }, span);
2228
+ }
2229
+ });
2230
+ }
2231
+ /**
2232
+ * Precedence rules for a run invocation, a decision region of its step. Rules 1 (terminal, `completing`, `waiting`, or
2233
+ * `sleeping`) and 2 (closing) are applied by `#step`. Progress (rule 5) is decided by `#progress()` once the decision
2234
+ * stands, as it takes a registry snapshot.
2235
+ */
2236
+ #rules(current, previous) {
2237
+ // 3. abort mark: end; a fresh abort invocation starts once the task's ordinary owned work is gone.
2238
+ if (current.abortRequested)
2239
+ return END;
2240
+ // An owner's cancellation intent ends it too, before its cascade marks it; reservation then holds it back.
2241
+ if (!current.background && this.#belowCancelled(parentOf(current)))
2242
+ return CASCADE;
2243
+ if (previous === undefined)
2244
+ return CONTINUE;
2245
+ // 4. uncaught error.
2246
+ if (previous.failure !== undefined)
2247
+ return { kind: "fault", error: previous.failure.error };
2248
+ // 6. no durable progress.
2249
+ if (jsonEqual(current.state.checkpoint, previous.checkpoint)) {
2250
+ const message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;
2251
+ return { kind: "fault", error: new Error(message) };
2252
+ }
2253
+ return PROGRESS;
2254
+ }
2255
+ /**
2256
+ * Rule 5, progress: refresh the snapshot; hand over to a replacement definition that can take the task, writing it
2257
+ * back as `pending`, or keep running under the old one, reported once per resolved definition. Returns whether the
2258
+ * invocation continues.
2259
+ */
2260
+ #progress(tx, current, state, extension, context) {
2261
+ state.publication = this.#publications;
2262
+ state.snapshot = this.#registry.snapshot();
2263
+ const next = state.snapshot.task(current.kind);
2264
+ if (next === state.task)
2265
+ return true;
2266
+ if (next !== undefined && canReserve(next, current)) {
2267
+ tx.setTask(pendingAgain(current, current.state));
2268
+ return false;
2269
+ }
2270
+ if (state.reported === undefined || state.reported.task !== next) {
2271
+ state.reported = { task: next };
2272
+ this.#report(new Error(`Task ${current.id} keeps running under its old ${current.kind} definition`), {
2273
+ kind: "task_outdated",
2274
+ ...this.#aboutTask(recordTask(current), extension),
2275
+ reason: outdatedReason(next, current),
2276
+ }, context);
2277
+ }
2278
+ return true;
2279
+ }
2280
+ /** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */
2281
+ async #runAbort(reservation) {
2282
+ const invocation = reservation.invocation;
2283
+ const current = this.#live.get(invocation.taskId);
2284
+ if (current === undefined || this.#closing)
2285
+ return;
2286
+ await this.#phase(invocation, current, async () => {
2287
+ let failure;
2288
+ try {
2289
+ const phase = {
2290
+ snapshot: () => reservation.snapshot,
2291
+ task: () => reservation.task,
2292
+ agent: undefined,
2293
+ };
2294
+ const runtime = this.#runtime(invocation, phase);
2295
+ await erased(reservation.task).abort(current, runtime, invocation.context);
2296
+ }
2297
+ catch (error) {
2298
+ failure = { error };
2299
+ }
2300
+ const message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;
2301
+ await this.#step(invocation, () => ({ kind: "fault", error: failure?.error ?? new Error(message) }));
2302
+ });
2303
+ }
2304
+ /**
2305
+ * One decision on the Session line, before a phase: a decision region (`#region()`) that reads the task's record. A
2306
+ * task that is no longer running (rule 1: terminal, `completing`, `waiting`, or `sleeping`) or a closing Harness (rule
2307
+ * 2) ends the invocation without a write; otherwise `plan` decides, and a decision that stands is applied: the
2308
+ * invocation continues, with `progress` for rule 5, or ends, with a fault written. Ending happens inside the callback,
2309
+ * before a fault's Harness cleanup. A rejected step, such as admission after close, also ends the invocation. Its
2310
+ * outcome goes to the invocation only, so it is a scheduler commit (`commitInternal()`).
2311
+ */
2312
+ async #step(invocation, plan, progress) {
2313
+ let fault;
2314
+ try {
2315
+ const continued = await this.#session.commitInternal(async (tx) => {
2316
+ const decided = await this.#region(() => {
2317
+ const found = this.#liveRecord(invocation.taskId);
2318
+ if (found?.state.status !== "running" || this.#closing)
2319
+ return { plan: END };
2320
+ const current = found;
2321
+ return { current, plan: plan(current) };
2322
+ });
2323
+ const { current } = decided;
2324
+ const step = decided.plan;
2325
+ if (step.kind === "continue")
2326
+ return current;
2327
+ if (step.kind === "progress" && progress(tx, current))
2328
+ return current;
2329
+ this.#end(invocation);
2330
+ if (step.kind === "cascade") {
2331
+ this.#cascadePending = true;
2332
+ this.#scheduleReconcile();
2333
+ }
2334
+ if (step.kind === "fault") {
2335
+ fault = { error: step.error };
2336
+ const message = errorMessage(step.error);
2337
+ invocation.fault = { status: "faulted", error: { message } };
2338
+ await this.#terminate(tx, current, invocation.fault);
2339
+ }
2340
+ return undefined;
2341
+ }, withoutAbortSignal(invocation.context));
2342
+ // Reported once the fault is durable: a host may count it, for example toward a breaker.
2343
+ if (fault !== undefined)
2344
+ this.#report(fault.error, { kind: "task_faulted", ...this.#aboutTask(invocation, invocation.extension), reason: "threw" }, invocation.context);
2345
+ return continued;
2346
+ }
2347
+ catch (error) {
2348
+ // The step writes the scheduler's own decision, a fault or a terminal record; a throw there would otherwise
2349
+ // leave the task running, to be reserved and run again.
2350
+ this.#end(invocation);
2351
+ this.#failSession(error, invocation.context);
2352
+ return undefined;
2353
+ }
2354
+ }
2355
+ /**
2356
+ * Write an outcome the scheduler decided. While the task's ordinary owned work is live it holds as `completing` and
2357
+ * its Harness cleanup waits for the final commit (spec §5.5, rule 4); otherwise it is terminal with its cleanup.
2358
+ */
2359
+ async #terminate(tx, record, outcome) {
2360
+ await this.#loadScopes(false);
2361
+ if (await this.#region(() => this.#hasOwnedLive(record.id, overlayOf(tx)), this.#reloadScopes)) {
2362
+ tx.setTask(withState(record, { status: "completing", outcome }));
2363
+ return;
2364
+ }
2365
+ tx.setTask(withState(record, { status: "terminal", outcome }));
2366
+ await this.#settleOutcome(tx, record, outcome);
2367
+ }
2368
+ /**
2369
+ * Replace a running task's state with what it committed. A terminal state holds as `completing` while ordinary owned
2370
+ * work is live, judged on the commit's candidates, so work the same commit creates below the task counts. A wait is
2371
+ * validated first.
2372
+ */
2373
+ async #commitState(tx, invocation, current, next) {
2374
+ if (next.status === "waiting")
2375
+ await this.#validateWait(tx, invocation, current, next.on, next.policy);
2376
+ if (next.status === "sleeping")
2377
+ validateSleep(invocation, current, next);
2378
+ if (next.status === "terminal") {
2379
+ const overlay = overlayOf(tx);
2380
+ await this.#loadScopes(false);
2381
+ for (const record of overlay.tasks.values())
2382
+ await this.#loadChain(parentOf(record), overlay);
2383
+ if (await this.#region(() => this.#hasOwnedLive(current.id, overlayOf(tx)), this.#reloadScopes)) {
2384
+ tx.setTask(withState(progressed(current), { status: "completing", outcome: next.outcome }));
2385
+ return;
2386
+ }
2387
+ }
2388
+ // A state the task committed that differs from its current one is progress: its restart count starts over. The
2389
+ // same checkpoint committed again, for example as intent before an effect, is not, and keeps the wake.
2390
+ const { wake: _wake, ...was } = current.state;
2391
+ const same = jsonEqual(was, next);
2392
+ const state = same ? current.state : next;
2393
+ tx.setTask(withState(same ? current : progressed(current), state));
2394
+ }
2395
+ /**
2396
+ * A wait names existing tasks, and `failFast` only tasks the waiter owns. It may not close a cycle in the wait-for
2397
+ * graph, whose edges run from each task to what it waits on and to its live ordinary owned work (spec §5.5); waiting
2398
+ * on itself or on an owner holding it are the shortest such cycles. An abort handler cannot wait.
2399
+ *
2400
+ * Invariant: the wait-for graph is acyclic. Only a wait adds an edge between existing tasks, as a new task has only
2401
+ * incoming edges, so checking each wait maintains it.
2402
+ */
2403
+ async #validateWait(tx, invocation, current, on, policy) {
2404
+ if (invocation.mode === "abort")
2405
+ throw new Error(`Abort handler of task ${current.id} cannot wait`);
2406
+ // Owned work is found by walks down, which need the chains of every live task loaded.
2407
+ await this.#loadScopes(false);
2408
+ // Tasks in `on` that are not live, read from Storage: terminal, or missing.
2409
+ const ended = new Map();
2410
+ for (;;) {
2411
+ const checked = await this.#region(() => this.#checkWait(current, on, policy, overlayOf(tx), ended), this.#reloadScopes);
2412
+ if (checked === undefined)
2413
+ return;
2414
+ if (checked.kind === "missing") {
2415
+ for (const id of checked.missing)
2416
+ ended.set(id, (await this.#session.lineStorage.task(id, this.#context)) ?? null);
2417
+ continue;
2418
+ }
2419
+ throw checked.error;
2420
+ }
2421
+ }
2422
+ /**
2423
+ * `#validateWait()`'s decision region: why the wait is refused, `undefined` when it may be stored, or the tasks in
2424
+ * `on` it needs from Storage first, when `ended` lacks them.
2425
+ */
2426
+ #checkWait(current, on, policy, overlay, ended) {
2427
+ const targets = [];
2428
+ const missing = [];
2429
+ for (const id of on) {
2430
+ const member = overlay.tasks.get(id) ?? this.#liveRecord(id) ?? ended.get(id);
2431
+ if (member === undefined) {
2432
+ missing.push(id);
2433
+ continue;
2434
+ }
2435
+ if (member === null)
2436
+ return { kind: "refused", error: new Error(`Task ${id} does not exist`) };
2437
+ if (policy === "failFast" && member.owner !== current.id) {
2438
+ return {
2439
+ kind: "refused",
2440
+ error: new Error(`Task ${current.id} can wait failFast only on tasks it owns; ${id} is not one`),
2441
+ };
2442
+ }
2443
+ // A live child already holds the waiter (task-owned tasks are never background): waiting on it adds no edge. A
2444
+ // terminal task has no edges.
2445
+ if (member.state.status !== "terminal" && member.owner !== current.id)
2446
+ targets.push(id);
2447
+ }
2448
+ if (missing.length > 0)
2449
+ return { kind: "missing", missing };
2450
+ if (targets.length === 0)
2451
+ return undefined;
2452
+ const cycle = this.#waitCycle(current.id, targets, overlay);
2453
+ if (cycle === undefined)
2454
+ return undefined;
2455
+ return {
2456
+ kind: "refused",
2457
+ error: new Error(`Task ${current.id} cannot wait on ${cycle[0]}: ${[current.id, ...cycle].join(" -> ")} is a wait cycle`),
2458
+ };
2459
+ }
2460
+ /**
2461
+ * The path from a member of `on` back to `task` in the wait-for graph, if the wait would close a cycle (spec §5.1).
2462
+ * An edge X -> Y means X cannot settle before Y: Y is in the `on` of waiting X that is not abort-marked, or Y is live
2463
+ * ordinary owned work of X, which holds X as `completing`. Each task is visited once and each subtree walked once,
2464
+ * so a check is bounded by the live work it reaches. Part of a decision region: it records every record it reads.
2465
+ * Owned work is found by walks down, which need the chains of every live task loaded.
2466
+ */
2467
+ #waitCycle(task, on, overlay) {
2468
+ const from = new Map();
2469
+ const walked = new Set();
2470
+ const pending = [];
2471
+ const reach = (id, via) => {
2472
+ if (from.has(id))
2473
+ return;
2474
+ from.set(id, via);
2475
+ pending.push(id);
2476
+ };
2477
+ const path = (end) => {
2478
+ const steps = [];
2479
+ for (let at = end; at !== undefined; at = from.get(at))
2480
+ steps.unshift(at);
2481
+ return steps;
2482
+ };
2483
+ for (const id of on)
2484
+ reach(id, undefined);
2485
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
2486
+ if (id === task)
2487
+ return path(id);
2488
+ const record = overlay.tasks.get(id) ?? this.#liveRecord(id);
2489
+ if (record === undefined || record.state.status === "terminal")
2490
+ continue;
2491
+ // An abort-marked task waits only for its owned work, as abort runs bottom-up (`#waitingOn`).
2492
+ if (record.state.status === "waiting" && !record.abortRequested) {
2493
+ for (const member of record.state.on)
2494
+ reach(member, id);
2495
+ }
2496
+ if (walked.has(id))
2497
+ continue;
2498
+ walked.add(id);
2499
+ // Below a walked task the walk does not go again: its own walk covered what lies below.
2500
+ const found = [];
2501
+ const walk = this.#walkDown(id, { overlay, enter: (below) => !walked.has(below) });
2502
+ for (const { id: below, node, live } of walk) {
2503
+ if (live === undefined || node.background)
2504
+ continue;
2505
+ found.push(below);
2506
+ reach(below, id);
2507
+ }
2508
+ for (const below of found)
2509
+ walked.add(below);
2510
+ }
2511
+ return undefined;
2512
+ }
2513
+ /** End an invocation: its runtime operations reject from now on, its signal aborts, its watches stop, and its task is free. */
2514
+ #end(invocation) {
2515
+ if (invocation.ended)
2516
+ return;
2517
+ invocation.ended = true;
2518
+ if (this.#invocations.get(invocation.taskId) === invocation) {
2519
+ this.#invocations.delete(invocation.taskId);
2520
+ if (this.#live.has(invocation.taskId))
2521
+ this.#runnable.add(invocation.taskId);
2522
+ }
2523
+ for (const watch of invocation.watches)
2524
+ void watch.stop();
2525
+ for (const disarm of invocation.timers)
2526
+ disarm();
2527
+ invocation.timers.clear();
2528
+ // Pending waits bound to the invocation, such as a tool's waitForTask(), reject with it.
2529
+ invocation.controller.abort(endedError(invocation));
2530
+ }
2531
+ /** No live non-background task in the scope; a task whose owner edges are not loaded yet counts as inside. */
2532
+ #idle(conversationId) {
2533
+ return this.#quiet(conversationId, () => true);
2534
+ }
2535
+ /**
2536
+ * Whether a kept context's conversation is inactive (spec suspendable §8): idle, or with all its live work parked
2537
+ * (`parked()`), which holds no invocation however long it waits.
2538
+ */
2539
+ #inactive(conversationId) {
2540
+ return this.#quiet(conversationId, (record) => !parked(record));
2541
+ }
2542
+ /** No live non-background task in the scope that `counts`; one whose owner edges are not loaded yet counts as inside. */
2543
+ #quiet(conversationId, counts) {
2544
+ const scope = conversationId === undefined ? { kind: "roots" } : { kind: "conversation", conversation: conversationId };
2545
+ // In a decision region, global idle reads the roots it starts from.
2546
+ if (conversationId === undefined)
2547
+ this.#record(ROOTS_KEY);
2548
+ // Tasks whose chain is not loaded are not listed below their scope yet; one counts as inside unless its walk up
2549
+ // decides otherwise.
2550
+ for (const id of this.#unloaded) {
2551
+ const record = this.#live.get(id);
2552
+ if (record !== undefined &&
2553
+ !record.background &&
2554
+ counts(record) &&
2555
+ this.#inScope(parentOf(record), scope) !== false) {
2556
+ return false;
2557
+ }
2558
+ }
2559
+ const starts = conversationId === undefined ? this.#roots : [conversationId];
2560
+ for (const start of starts) {
2561
+ for (const { node, live } of this.#walkDown(conversationNode(start))) {
2562
+ if (live !== undefined && !node.background && counts(live))
2563
+ return false;
2564
+ }
2565
+ }
2566
+ return true;
2567
+ }
2568
+ // ─── Invocation runtime ──────────────────────────────────────────────────
2569
+ #runtime(invocation, phase) {
2570
+ // Resolved at most once per phase handler, at first use, with the invocation's context; fixed for the phase.
2571
+ const agent = () => {
2572
+ if (invocation.ended)
2573
+ return Promise.reject(endedError(invocation));
2574
+ if (phase.agent === undefined) {
2575
+ phase.agent = this.#agent(invocation.conversationId, phase.snapshot(), invocation.context);
2576
+ // A caller that stops waiting must not leave the shared resolution's failure unobserved.
2577
+ phase.agent.catch(() => { });
2578
+ }
2579
+ return phase.agent;
2580
+ };
2581
+ const hooks = {
2582
+ each: async (name, invoke) => {
2583
+ for (const { extension, handlers } of agentHooks(await agent(), phase.task().definition.name)) {
2584
+ const handler = handlers[name];
2585
+ if (typeof handler !== "function")
2586
+ continue;
2587
+ try {
2588
+ await invoke(handler.bind(handlers));
2589
+ }
2590
+ catch (error) {
2591
+ if (invocation.controller.signal.aborted)
2592
+ throw error;
2593
+ this.#report(error, { kind: "extension_error", extension, task: reportTask(invocation) }, invocation.context);
2594
+ }
2595
+ }
2596
+ },
2597
+ };
2598
+ const settings = this.#settings;
2599
+ const models = this.#models;
2600
+ const runtime = {
2601
+ taskId: invocation.taskId,
2602
+ conversationId: invocation.conversationId,
2603
+ signal: invocation.controller.signal,
2604
+ get models() {
2605
+ return models();
2606
+ },
2607
+ agent: (context) => invocation.ended ? Promise.reject(endedError(invocation)) : awaitWithContext(agent(), context),
2608
+ get settings() {
2609
+ return settings();
2610
+ },
2611
+ env: (context) => this.#read(invocation, () => this.#env(invocation.conversationId, context)),
2612
+ hooks: hooks,
2613
+ get registry() {
2614
+ return phase.snapshot();
2615
+ },
2616
+ commit: async (change, context, options) => {
2617
+ let checkpoint;
2618
+ let interrupted;
2619
+ await this.#gated(invocation, async (tx, current) => {
2620
+ const next = await change(tx, current);
2621
+ if (next !== undefined)
2622
+ await this.#commitState(tx, invocation, current, next);
2623
+ if (next?.status === "running" && current.state.checkpoint.phase !== next.checkpoint.phase) {
2624
+ checkpoint = next.checkpoint.phase;
2625
+ }
2626
+ // A task that ends for crashes says so (`task_interrupted`), so a host keeps a crash-loop signal.
2627
+ if (next?.status === "terminal") {
2628
+ const restarts = current.restarts ?? 0;
2629
+ const reason = next.outcome.status === "failed" ? interruptionOf(next.outcome.error) : undefined;
2630
+ if (reason !== undefined && next.outcome.status === "failed") {
2631
+ interrupted = { message: next.outcome.error.message, reason, restarts };
2632
+ }
2633
+ else {
2634
+ // A task that ended for crashes with another outcome says so itself, as a generation whose run
2635
+ // answered ends `completed` without its after-run tasks.
2636
+ const message = endedByCrashesStates.get(next);
2637
+ if (message !== undefined)
2638
+ interrupted = { message, reason: "restart_limit", restarts };
2639
+ }
2640
+ }
2641
+ }, context, options);
2642
+ if (interrupted !== undefined) {
2643
+ this.#report(new Error(interrupted.message), {
2644
+ kind: "task_interrupted",
2645
+ ...this.#aboutTask(invocation, invocation.extension),
2646
+ reason: interrupted.reason,
2647
+ restarts: interrupted.restarts,
2648
+ }, invocation.context);
2649
+ }
2650
+ if (checkpoint !== undefined) {
2651
+ invocation.context.telemetry.addEvent("diffra.durable.checkpoint", {
2652
+ phase: checkpoint,
2653
+ });
2654
+ }
2655
+ },
2656
+ memo: ((name, ...rest) => {
2657
+ if (rest.length === 1) {
2658
+ return this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));
2659
+ }
2660
+ const candidate = rest[0];
2661
+ return this.#gated(invocation, (tx, current) => {
2662
+ const winner = memoOf(current, name);
2663
+ if (winner !== undefined)
2664
+ return winner;
2665
+ tx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } });
2666
+ return candidate;
2667
+ }, rest[1]);
2668
+ }),
2669
+ readSignal: ((token, key, _context) => this.#read(invocation, async () => readSignal(this.#live.get(invocation.taskId)?.memos, token, key))),
2670
+ sleepUntil: (until, checkpoint, context) => this.#gated(invocation, (tx, current) => this.#commitState(tx, invocation, current, { status: "sleeping", checkpoint, until }), context),
2671
+ watchDoc: ((...args) => this.#watchDoc(invocation, args)),
2672
+ snapshot: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, "snapshot")(...args))),
2673
+ snapshotAsOf: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, "snapshotAsOf")(...args))),
2674
+ getTask: ((id, context) => this.#read(invocation, () => this.#session.readOnLine((storage) => storage.task(id, context)))),
2675
+ waitForTask: ((id, context) => this.#read(invocation, () => this.waitForTask(id, withAbortSignal(invocation.controller.signal, context)))),
2676
+ ownedTasks: (context) => this.#read(invocation, () => this.#session.readOnLine(async () => {
2677
+ // The step that ends the invocation may have run on the line before this.
2678
+ if (invocation.ended)
2679
+ throw endedError(invocation);
2680
+ context.abortSignal?.throwIfAborted();
2681
+ // Every live task is listed under its parent node, its owner task when it has one.
2682
+ const owned = await this.#region(() => {
2683
+ this.#record(ownedKey(invocation.taskId));
2684
+ const records = [];
2685
+ for (const node of this.#below.get(invocation.taskId) ?? []) {
2686
+ const record = typeof node === "string" ? undefined : this.#liveRecord(node);
2687
+ if (record?.owner === invocation.taskId)
2688
+ records.push(record);
2689
+ }
2690
+ return records;
2691
+ });
2692
+ // Copies, as from storage: the scheduler reads its own.
2693
+ return owned
2694
+ .sort((a, b) => a.id - b.id)
2695
+ .map((record) => copyJson(record));
2696
+ })),
2697
+ abortOwned: (id, context) => this.#read(invocation, async () => {
2698
+ const bound = withAbortSignal(invocation.controller.signal, context);
2699
+ const record = await this.#session.readOnLine((storage) => storage.task(id, bound));
2700
+ if (record?.owner !== invocation.taskId) {
2701
+ throw new Error(`Task ${id} is not owned by task ${invocation.taskId}`);
2702
+ }
2703
+ if (record.state.status === "terminal")
2704
+ return;
2705
+ await this.abort(id, bound, true);
2706
+ await this.waitForTask(id, bound);
2707
+ }),
2708
+ outcomes: ((ids, context) => this.#read(invocation, () => this.#session.readOnLine(async (storage) => {
2709
+ const outcomes = [];
2710
+ for (const id of ids) {
2711
+ const state = (await storage.task(id, context))?.state;
2712
+ if (state?.status !== "terminal")
2713
+ throw new Error(`Task ${id} is not terminal`);
2714
+ outcomes.push(state.outcome);
2715
+ }
2716
+ return outcomes;
2717
+ }))),
2718
+ conversation: (id, context) => this.#read(invocation, () => this.#conversation(id, {
2719
+ signal: invocation.controller.signal,
2720
+ check: () => {
2721
+ if (invocation.ended)
2722
+ throw endedError(invocation);
2723
+ },
2724
+ }, context)),
2725
+ entry: ((...args) => {
2726
+ const [token, id, context] = args.length === 2
2727
+ ? [undefined, args[0], args[1]]
2728
+ : [args[0], args[1], args[2]];
2729
+ return this.#read(invocation, async () => {
2730
+ // An entry of the conversation's kept context range is committed and visible: no Storage read.
2731
+ const kept = this.#contexts.get(invocation.conversationId);
2732
+ const entry = (kept === undefined ? undefined : rangeEntry(kept.range, id)) ??
2733
+ (await this.#session.readOnLine((storage) => storage.entry(invocation.conversationId, id, context)))
2734
+ ?.entry;
2735
+ return token === undefined || entry?.kind === token.kind ? entry : undefined;
2736
+ });
2737
+ }),
2738
+ entries: (query, limit, cursor, context) => this.#read(invocation, () => this.#session.readOnLine((storage) => storage.scanEntries(conversationEntries(invocation.conversationId, query), limit, cursor, context))),
2739
+ context: (conversationId, context, options) => this.#read(invocation, async () => {
2740
+ const read = await readContextFrom(this.#session, this.#storage, conversationId, context, options?.at, this.#contexts.get(conversationId)?.range);
2741
+ const { view } = read;
2742
+ // Checked again here, synchronously up to the install below: a commit published since the read returned
2743
+ // was not seen by `#advanceContexts`, so a range that missed it must not be advanced.
2744
+ const range = read.range?.current === true &&
2745
+ this.#session.knownLatestEntryId(conversationId) !== read.range.bounds.tail
2746
+ ? { ...read.range, current: false }
2747
+ : read.range;
2748
+ // Keep it unless the invocation ended or a concurrent read already kept a newer range.
2749
+ const kept = this.#contexts.get(conversationId);
2750
+ if (range !== undefined &&
2751
+ !this.#closing &&
2752
+ !invocation.ended &&
2753
+ (kept === undefined || kept.range.bounds.tail <= range.bounds.tail)) {
2754
+ // A read of another, idle conversation starts or continues its retention period.
2755
+ if (!this.#inactive(conversationId)) {
2756
+ this.#contexts.set(conversationId, { range, idleSince: undefined });
2757
+ this.#idleOrder.delete(conversationId);
2758
+ }
2759
+ else if (this.#contextRetentionMs() > 0) {
2760
+ // An idle period that already started keeps its expiry and its place; a new one starts now.
2761
+ const idleSince = kept?.idleSince ?? this.#now();
2762
+ const expiresAt = kept?.idleSince !== undefined && kept.expiresAt !== undefined
2763
+ ? kept.expiresAt
2764
+ : idleSince + this.#contextRetentionMs();
2765
+ this.#contexts.set(conversationId, { range, idleSince, expiresAt });
2766
+ if (kept?.idleSince === undefined)
2767
+ this.#markIdle(conversationId, idleSince);
2768
+ this.#scheduleExpiry();
2769
+ }
2770
+ }
2771
+ return view;
2772
+ }),
2773
+ now: () => {
2774
+ if (invocation.ended)
2775
+ throw endedError(invocation);
2776
+ return this.#now();
2777
+ },
2778
+ setTimer: (callback, delayMs) => {
2779
+ // An ended invocation's timers never fire.
2780
+ if (invocation.ended)
2781
+ return () => { };
2782
+ const disarm = this.#timers.foreground(() => {
2783
+ invocation.timers.delete(disarm);
2784
+ if (!invocation.ended)
2785
+ callback();
2786
+ }, delayMs);
2787
+ invocation.timers.add(disarm);
2788
+ return () => {
2789
+ invocation.timers.delete(disarm);
2790
+ disarm();
2791
+ };
2792
+ },
2793
+ report: (error, from) => {
2794
+ if (invocation.ended)
2795
+ throw endedError(invocation);
2796
+ // The task's own failure names the task's extension; any other names whose code failed, if anyone's.
2797
+ const task = reportTask(invocation);
2798
+ this.#report(error, from === undefined
2799
+ ? { kind: "task_error", ...this.#aboutTask(invocation, invocation.extension) }
2800
+ : from.kind === "extension"
2801
+ ? { kind: "extension_error", task, ...optionalExtension(from.extension) }
2802
+ : { kind: "host_error", callback: from.callback, task }, invocation.context);
2803
+ },
2804
+ };
2805
+ providerSessionsByRuntime.set(runtime, this.providerSessionIds);
2806
+ closeSignals.set(runtime, this.#closed.signal);
2807
+ return runtime;
2808
+ }
2809
+ /**
2810
+ * On the line: wait until every commit admitted before is published, for a decision that reads what cannot be keyed,
2811
+ * every live task (open, inspection) or every task a conversation abort reaches.
2812
+ */
2813
+ async #published() {
2814
+ const gate = this.#session.touch(ALL_KEYS);
2815
+ if (gate !== undefined)
2816
+ await gate;
2817
+ }
2818
+ /** Run a committed-state read unless the invocation has ended. */
2819
+ async #read(invocation, read) {
2820
+ if (invocation.ended)
2821
+ throw endedError(invocation);
2822
+ return read();
2823
+ }
2824
+ /** Commit after rereading the task on the line and gating the invocation. */
2825
+ #gated(invocation, change, context, options) {
2826
+ if (invocation.ended)
2827
+ return Promise.reject(endedError(invocation));
2828
+ return this.#session.commitWith(async (tx) => {
2829
+ if (invocation.ended)
2830
+ throw endedError(invocation);
2831
+ if (this.#closing)
2832
+ throw closedError(this.#session);
2833
+ const current = await this.#region(() => {
2834
+ const found = this.#liveRecord(invocation.taskId);
2835
+ if (found === undefined)
2836
+ throw new Error(`Task ${invocation.taskId} is terminal`);
2837
+ if (found.state.status !== "running")
2838
+ throw new Error(`Task ${invocation.taskId} is ${found.state.status}`);
2839
+ if (invocation.mode === "run" && found.abortRequested) {
2840
+ throw new Error(`Task ${invocation.taskId} has a durable abort mark`);
2841
+ }
2842
+ return found;
2843
+ });
2844
+ // The step that ends it may have run while the region waited.
2845
+ if (invocation.ended)
2846
+ throw endedError(invocation);
2847
+ return change(tx, current);
2848
+ }, context, { conversationId: invocation.conversationId, taskId: invocation.taskId }, options);
2849
+ }
2850
+ async #watchDoc(invocation, args) {
2851
+ if (invocation.ended)
2852
+ throw endedError(invocation);
2853
+ const watch = (await sessionMethod(this.#session, "watchDoc")(...args));
2854
+ if (watch === undefined)
2855
+ return undefined;
2856
+ if (invocation.ended) {
2857
+ void watch.stop();
2858
+ throw endedError(invocation);
2859
+ }
2860
+ invocation.watches.add(watch);
2861
+ void watch.closed.then(() => invocation.watches.delete(watch));
2862
+ return watch;
2863
+ }
2864
+ }
2865
+ /** The signal of the Harness's close, by task runtime (`closeSignal()`). */
2866
+ const closeSignals = new WeakMap();
2867
+ /**
2868
+ * Aborted once the Harness running `runtime`'s task closes, or its Session fails, unlike the runtime's own signal, which
2869
+ * an abort mark aborts too: for cleanup a run does after its own abort mark, such as a tool's `cancel`.
2870
+ */
2871
+ export function closeSignal(runtime) {
2872
+ return closeSignals.get(runtime);
2873
+ }
2874
+ const REGISTRY = { kind: "host_error", callback: "registry" };
2875
+ const SETTINGS = { kind: "host_error", callback: "settings" };
2876
+ const ON_WAKE = { kind: "host_error", callback: "onWake" };
2877
+ const TELEMETRY = { kind: "host_error", callback: "telemetry" };
2878
+ /** The extension that installed `task` in `snapshot`, the last one that lists it; none for a built-in task. */
2879
+ function installerOf(snapshot, task) {
2880
+ if (task === undefined)
2881
+ return undefined;
2882
+ return snapshot.installed().findLast((installed) => installed.tasks?.includes(task) === true)?.name;
2883
+ }
2884
+ /** The report info of a failure of a task. */
2885
+ function reportTask(task) {
2886
+ return { id: task.taskId, kind: task.kind, conversationId: task.conversationId };
2887
+ }
2888
+ /** A stored task's identity, as an invocation names it. */
2889
+ function recordTask(record) {
2890
+ return { taskId: record.id, kind: record.kind, conversationId: record.conversationId };
2891
+ }
2892
+ /**
2893
+ * The record with an abort mark: `restart` for an abandonment; without a reason, a request, which replaces `restart`.
2894
+ * The restart count starts over: it now counts cut-offs of the abort handler.
2895
+ */
2896
+ /** Why a failed outcome's error says crashes ended the task (`detail.reason`), if it does. */
2897
+ /**
2898
+ * Terminal states a built-in task commits because it was cut off `settings.restartLimit` times, when their outcome does
2899
+ * not say so (a failure with detail `{ reason: "restart_limit" }` does), with the message the scheduler reports them
2900
+ * `task_interrupted` with. Keyed by the state object the task returns, so nothing is added to the stored state.
2901
+ */
2902
+ const endedByCrashesStates = new WeakMap();
2903
+ /** `state`, marked as ending its task for crashes (`task_interrupted` with `message`), whatever its outcome. */
2904
+ export function endedByCrashes(state, message) {
2905
+ endedByCrashesStates.set(state, message);
2906
+ return state;
2907
+ }
2908
+ function interruptionOf(error) {
2909
+ const detail = error.detail;
2910
+ // Stored JSON: an error's detail may be any value.
2911
+ if (typeof detail !== "object" || detail === null || Array.isArray(detail))
2912
+ return undefined;
2913
+ return detail.reason === "restart_limit" || detail.reason === "interrupted" ? detail.reason : undefined;
2914
+ }
2915
+ function withAbortMark(record, reason) {
2916
+ const { abortReason: _reason, restarts: _restarts, ...rest } = record;
2917
+ return { ...rest, abortRequested: true, ...(reason === undefined ? {} : { abortReason: reason }) };
2918
+ }
2919
+ /** A live owner's durable cancellation intent: its abort mark, or a held outcome other than `completed`. */
2920
+ function cancellationIntent(record) {
2921
+ return record.state.status !== "terminal" && (record.abortRequested || failedOutcome(record));
2922
+ }
2923
+ /**
2924
+ * Whether replacing `previous` (absent: a new task) with `next` changes the cancellation intent set or what it means: a
2925
+ * mark set, upgraded, or cleared, or a held or ended outcome other than `completed`.
2926
+ */
2927
+ function intentChanges(previous, next) {
2928
+ return ((previous?.abortRequested ?? false) !== next.abortRequested ||
2929
+ previous?.abortReason !== next.abortReason ||
2930
+ (previous !== undefined && failedOutcome(previous)) !== failedOutcome(next) ||
2931
+ (previous !== undefined && cancellationIntent(previous)) !== cancellationIntent(next));
2932
+ }
2933
+ /** Whether the record holds or ends with an outcome other than `completed`. */
2934
+ function failedOutcome(record) {
2935
+ const state = record.state;
2936
+ return (state.status === "completing" || state.status === "terminal") && state.outcome.status !== "completed";
2937
+ }
2938
+ function parentOf(node) {
2939
+ return node.owner !== undefined
2940
+ ? { kind: "task", task: node.owner }
2941
+ : { kind: "conversation", conversation: node.conversationId };
2942
+ }
2943
+ function nodeOf(record) {
2944
+ return {
2945
+ conversationId: record.conversationId,
2946
+ ...(record.owner === undefined ? {} : { owner: record.owner }),
2947
+ background: record.background,
2948
+ };
2949
+ }
2950
+ function overlayOf(tx) {
2951
+ const tasks = new Map(tx.stagedTasks().map((record) => [record.id, record]));
2952
+ const edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null]));
2953
+ return { tasks, edges };
2954
+ }
2955
+ function addTo(map, key, value) {
2956
+ const values = map.get(key);
2957
+ if (values === undefined)
2958
+ map.set(key, new Set([value]));
2959
+ else
2960
+ values.add(value);
2961
+ }
2962
+ function deleteFrom(map, key, value) {
2963
+ const values = map.get(key);
2964
+ if (values === undefined)
2965
+ return;
2966
+ values.delete(value);
2967
+ if (values.size === 0)
2968
+ map.delete(key);
2969
+ }
2970
+ /** Own memo entry only; memo names such as `toString` must not resolve to inherited properties. */
2971
+ function memoOf(record, name) {
2972
+ const memos = record?.memos;
2973
+ return memos !== undefined && Object.hasOwn(memos, name) ? memos[name] : undefined;
2974
+ }
2975
+ /** Overloaded Session method bound for forwarding an argument list unchanged. */
2976
+ function sessionMethod(session, name) {
2977
+ return session[name].bind(session);
2978
+ }
2979
+ function missingMigration(record, definition) {
2980
+ return new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);
2981
+ }
2982
+ function erased(task) {
2983
+ return task.definition;
2984
+ }
2985
+ function endedError(invocation) {
2986
+ return new Error(`Task ${invocation.taskId} invocation has ended`);
2987
+ }
2988
+ /** The record without its restart count, as after a state the task committed. */
2989
+ function progressed(record) {
2990
+ if (record.restarts === undefined)
2991
+ return record;
2992
+ const { restarts: _restarts, ...rest } = record;
2993
+ return rest;
2994
+ }
2995
+ /** Replace a live record's state; memos and the restart count disappear once an outcome is decided. */
2996
+ function withState(record, state) {
2997
+ if (state.status !== "terminal" && state.status !== "completing")
2998
+ return { ...record, state };
2999
+ const { memos: _memos, restarts: _restarts, ...rest } = record;
3000
+ return { ...rest, state };
3001
+ }
3002
+ /** Whether a definition can take the task at reservation: same version, or newer with a migration. */
3003
+ /**
3004
+ * Why a replacement definition cannot take a running task, in `#fit()`'s words: none is registered, it is older than
3005
+ * the task, or it is newer without a `migrate`.
3006
+ */
3007
+ function outdatedReason(task, record) {
3008
+ if (task === undefined)
3009
+ return "missing_task";
3010
+ return task.definition.version < record.version ? "task_too_old" : "migration_failed";
3011
+ }
3012
+ function canReserve(task, record) {
3013
+ const definition = task.definition;
3014
+ return (definition.version === record.version || (definition.version > record.version && definition.migrate !== undefined));
3015
+ }
3016
+ /**
3017
+ * A sleep's `until`, when set, is a time on the Harness clock; it waits for `until` or a non-empty `signals`, none of
3018
+ * whose keys served a wait (`checkSleep()`); an abort handler cannot sleep.
3019
+ */
3020
+ function validateSleep(invocation, current, next) {
3021
+ if (invocation.mode === "abort")
3022
+ throw new Error(`Abort handler of task ${current.id} cannot sleep`);
3023
+ const until = next.until;
3024
+ if (until !== undefined && (typeof until !== "number" || !Number.isFinite(until) || until < 0)) {
3025
+ throw new Error(`Task ${current.id} cannot sleep until ${until}: not a time in milliseconds`);
3026
+ }
3027
+ checkSleep(next, current.memos, current.id);
3028
+ }
3029
+ /** A live task that holds no invocation while it waits: sleeping, waiting, or holding its outcome. */
3030
+ function parked(record) {
3031
+ const status = record.state.status;
3032
+ return status === "sleeping" || status === "waiting" || status === "completing";
3033
+ }
3034
+ /** A sleeping record that cannot wake yet: no abort mark, no listed key with an unused value, `until` not reached. */
3035
+ function asleep(record, now) {
3036
+ const state = record.state;
3037
+ return state.status === "sleeping" && !record.abortRequested && !sleepDue(state, record.memos, now);
3038
+ }
3039
+ /**
3040
+ * The record a reservation writes: `running` at the checkpoint, with the wake that ends its wait or sleep and the signal
3041
+ * memos it marks; a task written back as `pending` keeps the wake it woke with.
3042
+ */
3043
+ function reserved(record, woke) {
3044
+ const state = record.state;
3045
+ if (woke !== undefined) {
3046
+ const woken = { ...record, memos: { ...record.memos, ...woke.memos } };
3047
+ return withState(woken, { status: "running", checkpoint: state.checkpoint, wake: woke.wake });
3048
+ }
3049
+ if (state.status === "pending" || state.status === "running")
3050
+ return withState(record, { ...state, status: "running" });
3051
+ return withState(record, { status: "running", checkpoint: state.checkpoint });
3052
+ }
3053
+ /** The record written back as `pending` (open, close, handover): its checkpoint, and the wake it woke with, if any. */
3054
+ function pendingAgain(record, running) {
3055
+ return withState(record, { ...running, status: "pending" });
3056
+ }
3057
+ /** Structural equality of two JSON values; object key order is ignored. */
3058
+ function jsonEqual(left, right) {
3059
+ if (left === right)
3060
+ return true;
3061
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null)
3062
+ return false;
3063
+ if (Array.isArray(left) || Array.isArray(right)) {
3064
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
3065
+ return false;
3066
+ return left.every((value, index) => jsonEqual(value, right[index]));
3067
+ }
3068
+ const keys = Object.keys(left);
3069
+ if (keys.length !== Object.keys(right).length)
3070
+ return false;
3071
+ return keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));
3072
+ }
3073
+ //# sourceMappingURL=scheduler.js.map