@diffra-ai/durable 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/CHANGELOG.md +440 -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 @@
1
+ {"version":3,"file":"writer.js","sourceRoot":"","sources":["../../src/session/writer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAwC7C,MAAM,cAAc,GAA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QACf,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClB,CAAC;IAED,6FAA6F;IAC7F,WAAW,CAAC,IAAc;QACzB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI;YAAE,IAAI,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;gBAAE,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACrG,CAAC;IAED,kGAAkG;IAClG,KAAK,CAAC,IAAc;QACnB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QACpB,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI;YAAE,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IACrD,CAAC;CACD;AAED;;;GAGG;AACH,SAAS,GAAG;IACX,IAAI,OAAO,YAAY,KAAK,UAAU;QAAE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/F,MAAM,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;IACrC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC9B,OAAO,CAAC,KAAK,CAAC,SAAS,GAAG,GAAG,EAAE;YAC9B,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO,EAAE,CAAC;QACX,CAAC,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// The Session's writer: commits the mutation line admitted, stored in batches off the line and published in line order.\nimport type { Context } from \"@diffra-ai/chord/context\";\nimport { withoutAbortSignal } from \"@diffra-ai/chord/context\";\nimport { SessionFailed } from \"../errors.ts\";\nimport type { CommitResult, Seq, StorageWrite } from \"../types.ts\";\n\n/** A part's own failure at publication: memory could not adopt it, or one of the Session's own observers threw. */\nexport type PublishFailure = { readonly kind: \"adoption\" | \"listener\"; readonly error: unknown };\n\n/** One logical commit the line admitted: stored (`writes`, never empty), or held in memory only (no `writes`). */\nexport type PartSpec = {\n\t/** Line index of the job that admitted it: a failure it causes makes only later jobs' outcomes `SessionFailed`. */\n\treadonly index: number;\n\treadonly writes: readonly StorageWrite[] | undefined;\n\t/** Keys it writes: a read of one waits for its publication. */\n\treadonly keys: readonly string[];\n\treadonly context: Context;\n\t/** Publish it in memory, in line order, once it is durable (with its seq) or, held, once the parts before it are. */\n\treadonly publish: (seq: Seq | undefined) => PublishFailure | undefined;\n\t/** It will never be published: abort what it prepared. */\n\treadonly discard: () => void;\n};\n\n/** An admitted part and its outcome. */\nexport type Part = PartSpec & {\n\t/**\n\t * Resolves once it is published; rejects once it never will be, and also after publication when its storage call\n\t * rejected or the Session failed meanwhile. Always handled, so a part nobody awaits rejects silently.\n\t */\n\treadonly outcome: Promise<void>;\n};\n\ntype Admitted = Part & {\n\treadonly settle: { resolve(): void; reject(error: unknown): void };\n\t/** Set once its outcome is settled. */\n\tdone: boolean;\n\t/** Opens once it is published or never will be; never rejects. */\n\treadonly gate: PromiseWithResolvers<void>;\n};\n\n/** How a part that will not resolve settles: with an error of its own, which may be any value, or `SessionFailed`. */\ntype FailedOutcome = { readonly kind: \"own\"; readonly error: unknown } | { readonly kind: \"failed\" };\n\nconst SESSION_FAILED: FailedOutcome = { kind: \"failed\" };\n\n/** What the writer needs of its Session. */\nexport type WriterHost = {\n\tcommit(\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t\treceive: (index: number, seq: Seq) => void,\n\t\tcontext: Context,\n\t): Promise<CommitResult>;\n\t/** Apply a stored batch to the Session's read caches, right before it is published. */\n\tstored(writes: readonly StorageWrite[]): void;\n\t/**\n\t * Run one part's publication inside the Storage's own scope (`Storage.publishing`); `undefined` when it ran at once,\n\t * else settles once it ran.\n\t */\n\tpublishing(publish: () => void, context: Context): Promise<void> | undefined;\n\t/** The Session's failure, if it failed. */\n\tfailure(): { readonly error: unknown } | undefined;\n\t/**\n\t * Fail the Session; `at` is the line index of the first job whose outcome the failure is, and `own` the jobs after it\n\t * whose outcome is still their own error (the other parts of a call that rejected), not `SessionFailed`.\n\t */\n\tfail(error: unknown, at: number, own: readonly number[]): void;\n\t/** Report an own observer's throw that cannot fail the Session, as it fails with a storage error. */\n\treport(error: unknown, context: Context): void;\n};\n\n/**\n * The writer of one Session. The line admits each commit as a part once its callback and settlement succeeded; the\n * writer sends every part admitted while no call is in flight as one `commit()` call, off the line, and publishes\n * the parts of a call one by one, in line order, with a macrotask between two, so the continuations of the waits one\n * resolves start before the next is published. Held commits are parts without writes, published when the parts before\n * them are.\n *\n * Each part registers the keys it writes; until it is published, it is the newest unpublished writer of each, and a\n * job that touches one waits for its gate. A key leaves when its newest writer is published, so the map holds one entry\n * per key with an unpublished writer.\n */\nexport class Writer {\n\treadonly #host: WriterHost;\n\t/** Admitted parts not yet sent, in line order. */\n\t#queue: Admitted[] = [];\n\t#flight = false;\n\t/** Per key, the newest unpublished part that writes it. */\n\treadonly #unpublished = new Map<string, Admitted>();\n\t/** The newest admitted part that is not yet published, whose gate opens after every earlier one's. */\n\t#newest: Admitted | undefined;\n\n\tconstructor(host: WriterHost) {\n\t\tthis.#host = host;\n\t}\n\n\t/** Admit a part: register its keys, queue it, and send it at once unless a call is in flight. */\n\tadmit(spec: PartSpec): Part {\n\t\tconst outcome = Promise.withResolvers<void>();\n\t\toutcome.promise.catch(() => {});\n\t\tconst part: Admitted = {\n\t\t\t...spec,\n\t\t\toutcome: outcome.promise,\n\t\t\tsettle: {\n\t\t\t\tresolve: () => {\n\t\t\t\t\tpart.done = true;\n\t\t\t\t\toutcome.resolve();\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tpart.done = true;\n\t\t\t\t\toutcome.reject(error);\n\t\t\t\t},\n\t\t\t},\n\t\t\tdone: false,\n\t\t\tgate: Promise.withResolvers<void>(),\n\t\t};\n\t\tfor (const key of spec.keys) this.#unpublished.set(key, part);\n\t\tthis.#newest = part;\n\t\tthis.#queue.push(part);\n\t\tthis.#pump();\n\t\treturn part;\n\t}\n\n\t/** The gate of the newest unpublished writer of `key`, or `undefined` when it has none. */\n\tgate(key: string): Promise<void> | undefined {\n\t\treturn this.#unpublished.get(key)?.gate.promise;\n\t}\n\n\t/** Opens once every part admitted so far is published or never will be. */\n\tdrained(): Promise<void> | undefined {\n\t\treturn this.#newest?.gate.promise;\n\t}\n\n\t/** Keys with an unpublished writer, for tests that bound memory. */\n\tget unpublished(): number {\n\t\treturn this.#unpublished.size;\n\t}\n\n\t#pump(): void {\n\t\tif (this.#flight || this.#queue.length === 0) return;\n\t\tthis.#flight = true;\n\t\tconst parts = this.#queue;\n\t\tthis.#queue = [];\n\t\tvoid this.#flush(parts);\n\t}\n\n\t/**\n\t * Send and publish `parts`, then what was admitted meanwhile. Never rejects: a throw the writer did not expect fails\n\t * the Session and settles the parts (`#abandon()`), so no outcome or gate is stranded.\n\t */\n\tasync #flush(parts: readonly Admitted[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#send(parts);\n\t\t} catch (error) {\n\t\t\tthis.#abandon(parts, error);\n\t\t}\n\t\tthis.#flight = false;\n\t\tthis.#pump();\n\t}\n\n\t/** Store `parts` in one call, then publish them in order; settles every one of them. */\n\tasync #send(parts: readonly Admitted[]): Promise<void> {\n\t\tconst stored = parts.filter((part) => part.writes !== undefined);\n\t\tconst seqs: (Seq | undefined)[] = [];\n\t\tlet result: CommitResult | undefined;\n\t\tlet rejected: { readonly error: unknown } | undefined;\n\t\tconst failed = this.#host.failure();\n\t\tif (failed !== undefined) {\n\t\t\tfor (const part of parts) this.#unpublish(part, new SessionFailed(failed.error));\n\t\t\treturn;\n\t\t}\n\t\tif (stored.length > 0) {\n\t\t\ttry {\n\t\t\t\tresult = await this.#host.commit(\n\t\t\t\t\tstored.map((part) => part.writes!),\n\t\t\t\t\t(index, seq) => {\n\t\t\t\t\t\tseqs[index] = seq;\n\t\t\t\t\t},\n\t\t\t\t\twithoutAbortSignal(stored[0]!.context),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\trejected = { error };\n\t\t\t}\n\t\t}\n\t\t// A call that settles once another failure failed the Session reports `SessionFailed` with that first error,\n\t\t// whatever it returned (spec §10.1), and publishes nothing.\n\t\tconst failedMeanwhile = this.#host.failure();\n\t\tif (failedMeanwhile !== undefined) {\n\t\t\tfor (const part of parts) this.#unpublish(part, new SessionFailed(failedMeanwhile.error));\n\t\t\treturn;\n\t\t}\n\t\tawait this.#publish(parts, seqs, result, rejected);\n\t}\n\n\t/**\n\t * Publish the received parts and held ones in order, a macrotask apart, and settle every part (group commit §3.4). A\n\t * refusal, a rejection, or a part whose adoption or own observer throws fails the Session once the parts before it\n\t * are published and the host observers got the last one; the parts after it are not published, and reject with\n\t * `SessionFailed`. What the failure decides (the outcomes, and the gates of the parts it concerns) is settled only\n\t * once the Session failed, so no job waiting at such a gate, and no later outcome, goes on as if it had not.\n\t */\n\tasync #publish(\n\t\tparts: readonly Admitted[],\n\t\tseqs: readonly (Seq | undefined)[],\n\t\tresult: CommitResult | undefined,\n\t\trejected: { readonly error: unknown } | undefined,\n\t): Promise<void> {\n\t\tlet stop: { readonly error: unknown; readonly at: number; readonly external?: true } | undefined;\n\t\t/**\n\t\t * Settled once the Session failed: each part, whether it was published, and its outcome: an error of its own (any\n\t\t * value, `undefined` included), or `SessionFailed`.\n\t\t */\n\t\tconst failing: { readonly part: Admitted; readonly outcome: FailedOutcome; readonly published: boolean }[] = [];\n\t\tlet storedIndex = 0;\n\t\tlet published = 0;\n\t\tfor (const part of parts) {\n\t\t\tconst index = part.writes === undefined ? undefined : storedIndex++;\n\t\t\tif (stop !== undefined) {\n\t\t\t\t// A part after a rejected call's last receipt has the call's error; any other part after a stop was not sent,\n\t\t\t\t// nor any part once something else failed the Session.\n\t\t\t\tconst outcome: FailedOutcome =\n\t\t\t\t\trejected !== undefined && index !== undefined && stop.external !== true\n\t\t\t\t\t\t? { kind: \"own\", error: rejected.error }\n\t\t\t\t\t\t: SESSION_FAILED;\n\t\t\t\tfailing.push({ part, outcome, published: false });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst seq = index === undefined ? undefined : seqs[index];\n\t\t\tif (index !== undefined && seq === undefined) {\n\t\t\t\tconst error =\n\t\t\t\t\trejected !== undefined\n\t\t\t\t\t\t? rejected.error\n\t\t\t\t\t\t: index === result?.stored && result.kind === \"refused\"\n\t\t\t\t\t\t\t? result.refused\n\t\t\t\t\t\t\t: new Error(\"Storage committed without adopting the batch\");\n\t\t\t\tfailing.push({ part, outcome: { kind: \"own\", error }, published: false });\n\t\t\t\tstop = { error, at: part.index };\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// A macrotask between two parts: what the first resolves runs before the second is published.\n\t\t\tif (published++ > 0) await hop();\n\t\t\tlet failure: PublishFailure | undefined;\n\t\t\t// Failed by something else meanwhile, during the hop or before a storage's scope runs the publication: nothing\n\t\t\t// more of the call is published. Checked right before it would be, after every wait.\n\t\t\tlet external: { readonly error: unknown } | undefined;\n\t\t\tconst publication = this.#host.publishing(() => {\n\t\t\t\texternal = this.#host.failure();\n\t\t\t\tif (external !== undefined) return;\n\t\t\t\t// Its keys leave first, so what its publication schedules sees it published; its waiters wake after it.\n\t\t\t\tthis.#unregister(part);\n\t\t\t\t// A throw anywhere in it, the read caches included, leaves memory behind what is stored: like an adoption's.\n\t\t\t\ttry {\n\t\t\t\t\tif (part.writes !== undefined) this.#host.stored(part.writes);\n\t\t\t\t\tfailure = part.publish(seq);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure = { kind: \"adoption\", error };\n\t\t\t\t}\n\t\t\t}, part.context);\n\t\t\tif (publication !== undefined) await publication;\n\t\t\tif (external !== undefined) {\n\t\t\t\tstop = { error: external.error, at: part.index, external: true };\n\t\t\t\tfailing.push({ part, outcome: SESSION_FAILED, published: false });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (failure?.kind === \"adoption\") {\n\t\t\t\tfailing.push({ part, outcome: { kind: \"own\", error: failure.error }, published: true });\n\t\t\t\tstop = { error: failure.error, at: part.index };\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// A part published while its call rejected is durable but rejects (spec §10.1); an own observer's throw is then\n\t\t\t// reported, as the Session fails with the storage error.\n\t\t\tif (rejected !== undefined) {\n\t\t\t\tif (failure !== undefined) this.#host.report(failure.error, part.context);\n\t\t\t\tfailing.push({ part, outcome: { kind: \"own\", error: rejected.error }, published: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// An own observer's throw: the commit stands; the Session fails after it.\n\t\t\tif (failure !== undefined) stop = { error: failure.error, at: part.index };\n\t\t\tconst failedMeanwhile = this.#host.failure();\n\t\t\tif (failedMeanwhile !== undefined && failure === undefined) {\n\t\t\t\tpart.settle.reject(new SessionFailed(failedMeanwhile.error));\n\t\t\t} else part.settle.resolve();\n\t\t\tthis.#open(part);\n\t\t}\n\t\tif (rejected !== undefined || stop !== undefined) {\n\t\t\t// After the host dispatch of the last part published, which is one microtask away.\n\t\t\tawait Promise.resolve();\n\t\t\t// Every part of the call that rejected keeps the storage error; the first of them is the failure's boundary.\n\t\t\tconst own = failing.flatMap(({ part, outcome }) => (outcome.kind === \"own\" ? [part.index] : []));\n\t\t\tif (rejected !== undefined) this.#host.fail(rejected.error, own[0]!, own);\n\t\t\telse this.#host.fail(stop!.error, stop!.at, own);\n\t\t}\n\t\tfor (const { part, outcome, published: stored } of failing) {\n\t\t\tconst error = outcome.kind === \"own\" ? outcome.error : this.#failed(stop!.error);\n\t\t\tif (stored) {\n\t\t\t\tpart.settle.reject(error);\n\t\t\t\tthis.#open(part);\n\t\t\t} else this.#unpublish(part, error);\n\t\t}\n\t\t// Admitted while this call ran, after the failure: never sent.\n\t\tconst failure = this.#host.failure();\n\t\tif (failure !== undefined) {\n\t\t\tconst queued = this.#queue;\n\t\t\tthis.#queue = [];\n\t\t\tfor (const part of queued) this.#unpublish(part, new SessionFailed(failure.error));\n\t\t}\n\t}\n\n\t/**\n\t * A throw the writer itself did not expect while sending or publishing `parts` (a bug): fail the Session at the first\n\t * of them and settle every one not settled yet, so no outcome, gate, or close waits on it forever.\n\t */\n\t#abandon(parts: readonly Admitted[], error: unknown): void {\n\t\tthis.#host.fail(error, parts[0]!.index, []);\n\t\tfor (const part of parts) {\n\t\t\tif (!part.done) this.#unpublish(part, this.#failed(error));\n\t\t\tthis.#unregister(part);\n\t\t\tthis.#open(part);\n\t\t}\n\t}\n\n\t/** `SessionFailed` with the Session's failure, or with `error` until the Session records it. */\n\t#failed(error: unknown): SessionFailed {\n\t\tconst failure = this.#host.failure();\n\t\treturn new SessionFailed(failure !== undefined ? failure.error : error);\n\t}\n\n\t/** Settle a part that will never be published: discard it, reject it with `error`, and open its gate. */\n\t#unpublish(part: Admitted, error: unknown): void {\n\t\tpart.discard();\n\t\tpart.settle.reject(error);\n\t\tthis.#unregister(part);\n\t\tthis.#open(part);\n\t}\n\n\t/** Drop the keys a part is still the newest writer of: it is published, or never will be. */\n\t#unregister(part: Admitted): void {\n\t\tfor (const key of part.keys) if (this.#unpublished.get(key) === part) this.#unpublished.delete(key);\n\t}\n\n\t/** Open a part's gate: the jobs waiting for it go on. The newest part's opens `drained()` too. */\n\t#open(part: Admitted): void {\n\t\tpart.gate.resolve();\n\t\tif (this.#newest === part) this.#newest = undefined;\n\t}\n}\n\n/**\n * Yield to the event loop once: `setImmediate` where there is one, otherwise a `MessageChannel` message (Workers,\n * browsers). Microtasks queued before it, such as wait continuations, run first.\n */\nfunction hop(): Promise<void> {\n\tif (typeof setImmediate === \"function\") return new Promise((resolve) => setImmediate(resolve));\n\tconst channel = new MessageChannel();\n\treturn new Promise((resolve) => {\n\t\tchannel.port1.onmessage = () => {\n\t\t\tchannel.port1.close();\n\t\t\tresolve();\n\t\t};\n\t\tchannel.port2.postMessage(undefined);\n\t});\n}\n"]}
@@ -0,0 +1,180 @@
1
+ import { type JsonValue } from "@diffra-ai/chord/json";
2
+ import { type Static } from "@diffra-ai/schema";
3
+ import type { SettledSubmissionRecord } from "./harness/types.ts";
4
+ import type { SubmissionRecord, TaskRecord, TaskState, WakeReason } from "./types.ts";
5
+ /** The key of one wait for a signal: JSON, used in sleeps and parks. `T` is a phantom type. */
6
+ export type SignalKey<T> = {
7
+ readonly signal: string;
8
+ readonly key: string;
9
+ readonly "~value"?: T;
10
+ };
11
+ /** A signal kind, built by `defineSignal()`: values of type `T` delivered under keys. */
12
+ export interface SignalToken<T> {
13
+ readonly name: string;
14
+ readonly version: number;
15
+ /** The key of one wait; throws for an empty key. */
16
+ key(key: string): SignalKey<T>;
17
+ }
18
+ /** What `defineSignal()` takes. */
19
+ export type SignalDefinition<S extends object> = {
20
+ /** Unique like a task or document kind; must not contain "/". */
21
+ readonly name: string;
22
+ /** Positive integer version of the value shape. */
23
+ readonly version: number;
24
+ /** A diffra-schema schema of a JSON value; the value type is `Static<S>`. */
25
+ readonly schema: S;
26
+ /** A value stored by an older version, to the current shape. */
27
+ readonly migrate?: (value: JsonValue, fromVersion: number) => Static<S>;
28
+ };
29
+ /** A key's state: the value delivered under it, or expired because its sleep's deadline came first. */
30
+ export type SignalState<T> = {
31
+ readonly kind: "value";
32
+ readonly value: T;
33
+ } | {
34
+ readonly kind: "expired";
35
+ };
36
+ /**
37
+ * What a delivery did: `delivered` (durably accepted, not necessarily consumed), `duplicate` (the key holds a value),
38
+ * `invalid` (not JSON, or not matching the schema), `closed` (the task ended, holds its outcome, is abort-marked, or the
39
+ * key expired), `not_found` (no such task).
40
+ */
41
+ export type SignalResult = "delivered" | "duplicate" | "invalid" | "closed" | "not_found";
42
+ type AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;
43
+ type Memos = Readonly<Record<string, JsonValue>>;
44
+ type Sleeping = Extract<TaskState<JsonValue, JsonValue>, {
45
+ readonly status: "sleeping";
46
+ }>;
47
+ /** Define a signal kind. Throws for a name with "/", a version that is not a positive integer, or a non-JSON schema. */
48
+ export declare function defineSignal<S extends object>(definition: SignalDefinition<S>): SignalToken<Static<S>>;
49
+ /**
50
+ * Built in: delivered to `SubmissionDraft.notify` when the submission settles, in the settling commit. Its value is the
51
+ * settled record, what `Submission.wait()` resolves to; its schema checks each variant's required fields, so another
52
+ * delivery cannot take the key with something else.
53
+ */
54
+ export declare const SubmissionSettled: SignalToken<({
55
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
56
+ readonly id: import("./types.ts").SubmissionId;
57
+ readonly conversationId: import("./types.ts").ConversationId;
58
+ readonly requestId?: string;
59
+ readonly notify?: import("./types.ts").SubmissionNotify;
60
+ } & {
61
+ readonly type: "input";
62
+ } & {
63
+ readonly status: "done";
64
+ readonly entry: import("./types.ts").EntryId;
65
+ readonly answer: import("./types.ts").EntryId;
66
+ readonly reason?: never;
67
+ readonly detail?: never;
68
+ } & {
69
+ readonly status: "done" | "unanswered";
70
+ }) | ({
71
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
72
+ readonly id: import("./types.ts").SubmissionId;
73
+ readonly conversationId: import("./types.ts").ConversationId;
74
+ readonly requestId?: string;
75
+ readonly notify?: import("./types.ts").SubmissionNotify;
76
+ } & {
77
+ readonly type: "input";
78
+ } & {
79
+ readonly status: "unanswered";
80
+ readonly entry?: import("./types.ts").EntryId;
81
+ readonly answer?: never;
82
+ readonly reason: string;
83
+ readonly detail?: JsonValue;
84
+ } & {
85
+ readonly status: "done" | "unanswered";
86
+ }) | ({
87
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
88
+ readonly id: import("./types.ts").SubmissionId;
89
+ readonly conversationId: import("./types.ts").ConversationId;
90
+ readonly requestId?: string;
91
+ readonly notify?: import("./types.ts").SubmissionNotify;
92
+ } & {
93
+ readonly type: "write";
94
+ } & {
95
+ readonly status: "done";
96
+ readonly entry: import("./types.ts").EntryId;
97
+ readonly answer?: never;
98
+ readonly reason?: never;
99
+ readonly detail?: never;
100
+ } & {
101
+ readonly status: "done" | "unanswered";
102
+ }) | ({
103
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
104
+ readonly id: import("./types.ts").SubmissionId;
105
+ readonly conversationId: import("./types.ts").ConversationId;
106
+ readonly requestId?: string;
107
+ readonly notify?: import("./types.ts").SubmissionNotify;
108
+ } & {
109
+ readonly type: "write";
110
+ } & {
111
+ readonly status: "unanswered";
112
+ readonly entry?: never;
113
+ readonly answer?: never;
114
+ readonly reason: string;
115
+ readonly detail?: JsonValue;
116
+ } & {
117
+ readonly status: "done" | "unanswered";
118
+ }) | ({
119
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
120
+ readonly id: import("./types.ts").SubmissionId;
121
+ readonly conversationId: import("./types.ts").ConversationId;
122
+ readonly requestId?: string;
123
+ readonly notify?: import("./types.ts").SubmissionNotify;
124
+ } & {
125
+ readonly type: "continue";
126
+ } & {
127
+ readonly status: "done";
128
+ readonly entry?: never;
129
+ readonly answer: import("./types.ts").EntryId;
130
+ readonly reason?: never;
131
+ readonly detail?: never;
132
+ } & {
133
+ readonly status: "done" | "unanswered";
134
+ }) | ({
135
+ readonly trace?: import("@diffra-ai/telemetry").TelemetryCarrier;
136
+ readonly id: import("./types.ts").SubmissionId;
137
+ readonly conversationId: import("./types.ts").ConversationId;
138
+ readonly requestId?: string;
139
+ readonly notify?: import("./types.ts").SubmissionNotify;
140
+ } & {
141
+ readonly type: "continue";
142
+ } & {
143
+ readonly status: "unanswered";
144
+ readonly entry?: never;
145
+ readonly answer?: never;
146
+ readonly reason: string;
147
+ readonly detail?: JsonValue;
148
+ } & {
149
+ readonly status: "done" | "unanswered";
150
+ })>;
151
+ /** Whether a submission settled: answered (`done`) or not (`unanswered`). */
152
+ export declare function isSettled(record: SubmissionRecord): record is SettledSubmissionRecord;
153
+ /**
154
+ * Decide a delivery to `record` (spec suspendable §3.2): the result, and the record to write when it changes, with the
155
+ * value stored, or the key marked expired when the task sleeps on it past its deadline.
156
+ */
157
+ export declare function deliverSignal<T>(record: AnyTaskRecord | undefined, token: SignalToken<T>, key: string, value: T, now: number): {
158
+ readonly result: SignalResult;
159
+ readonly record?: AnyTaskRecord;
160
+ };
161
+ /**
162
+ * A key's state in `memos`, the value migrated to the token's version; undefined while nothing came. Throws for a stored
163
+ * version newer than the token's, a missing or throwing `migrate`, or a migrated value the schema rejects.
164
+ */
165
+ export declare function readSignal<T>(memos: Memos | undefined, token: SignalToken<T>, key: string): SignalState<T> | undefined;
166
+ /** Throws unless a sleep waits for something (`until` or a non-empty `signals`) and none of its keys served a wait. */
167
+ export declare function checkSleep(state: Sleeping, memos: Memos | undefined, task: number): void;
168
+ /** Whether a sleep can wake now: a listed key holds a value no wake used, or its deadline came. */
169
+ export declare function sleepDue(state: Sleeping, memos: Memos | undefined, now: number): boolean;
170
+ /**
171
+ * The wake of a sleep that can wake now, and the memos the waking reservation writes: the first listed key holding a
172
+ * value no wake used, marked consumed; otherwise the deadline, with every listed key that holds nothing marked expired.
173
+ * Undefined when the sleep cannot wake yet.
174
+ */
175
+ export declare function sleepWake(state: Sleeping, memos: Memos | undefined, now: number): {
176
+ readonly wake: WakeReason;
177
+ readonly memos: Memos;
178
+ } | undefined;
179
+ export {};
180
+ //# sourceMappingURL=signals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAON,KAAK,MAAM,EAKX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAA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KAAK,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAaxF;AAED,mGAAmG;AACnG,wBAAgB,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAExF;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACxB,KAAK,EAAE,QAAQ,EACf,KAAK,EAAE,KAAK,GAAG,SAAS,EACxB,GAAG,EAAE,MAAM,GACT;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;CAAE,GAAG,SAAS,CAgBlE"}
@@ -0,0 +1,236 @@
1
+ // Signals: typed JSON values delivered to a live task from outside, kept in its memos until a wake uses them.
2
+ import { isJsonValue } from "@diffra-ai/chord/json";
3
+ import { compile, int, lit, obj, opt, str, union, unsafe, } from "@diffra-ai/schema";
4
+ /** What only Durable reads of a token: its compiled schema and migration. */
5
+ const internals = new WeakMap();
6
+ /** Define a signal kind. Throws for a name with "/", a version that is not a positive integer, or a non-JSON schema. */
7
+ export function defineSignal(definition) {
8
+ const { name, version, schema } = definition;
9
+ if (name === "" || name.includes("/"))
10
+ throw new TypeError(`Signal name ${JSON.stringify(name)} must be non-empty, without "/"`);
11
+ if (!Number.isInteger(version) || version < 1)
12
+ throw new TypeError(`Signal ${name} version must be a positive integer`);
13
+ const nonJson = nonJsonType(schema);
14
+ if (nonJson !== undefined)
15
+ throw new TypeError(`Signal ${name} schema admits non-JSON values (${nonJson})`);
16
+ const token = {
17
+ name,
18
+ version,
19
+ key: (key) => {
20
+ if (key === "")
21
+ throw new TypeError(`Signal ${name} key must be non-empty`);
22
+ return { signal: name, key };
23
+ },
24
+ };
25
+ internals.set(token, { validator: compile(schema), migrate: definition.migrate });
26
+ return token;
27
+ }
28
+ /** Keywords whose value is a schema or an array of schemas. Annotations (`examples`, `default`) are not walked. */
29
+ const SCHEMA_KEYWORDS = [
30
+ "items",
31
+ "prefixItems",
32
+ "additionalItems",
33
+ "unevaluatedItems",
34
+ "contains",
35
+ "anyOf",
36
+ "oneOf",
37
+ "allOf",
38
+ "not",
39
+ "if",
40
+ "then",
41
+ "else",
42
+ "additionalProperties",
43
+ "unevaluatedProperties",
44
+ "propertyNames",
45
+ ];
46
+ /** Keywords whose value maps names to schemas; draft 7's `dependencies` may also map to name arrays, which hold none. */
47
+ const SCHEMA_MAP_KEYWORDS = [
48
+ "properties",
49
+ "patternProperties",
50
+ "dependentSchemas",
51
+ "dependencies",
52
+ "$defs",
53
+ "definitions",
54
+ ];
55
+ /** A non-JSON type a schema accepts anywhere (diffra-schema's `bytes`, `bigint`, TypeBox's `undefined`), if any. */
56
+ function nonJsonType(schema) {
57
+ if (typeof schema !== "object" || schema === null)
58
+ return undefined;
59
+ const node = schema;
60
+ const types = Array.isArray(node.type) ? node.type : [node.type];
61
+ const found = types.find((type) => type === "bytes" || type === "bigint" || type === "undefined");
62
+ if (found !== undefined)
63
+ return found;
64
+ const children = [];
65
+ for (const keyword of SCHEMA_KEYWORDS) {
66
+ const value = node[keyword];
67
+ if (Array.isArray(value))
68
+ children.push(...value);
69
+ else
70
+ children.push(value);
71
+ }
72
+ for (const keyword of SCHEMA_MAP_KEYWORDS) {
73
+ const value = node[keyword];
74
+ if (typeof value === "object" && value !== null)
75
+ children.push(...Object.values(value));
76
+ }
77
+ for (const child of children) {
78
+ const nested = nonJsonType(child);
79
+ if (nested !== undefined)
80
+ return nested;
81
+ }
82
+ return undefined;
83
+ }
84
+ function internalsOf(token) {
85
+ const found = internals.get(token);
86
+ if (found === undefined)
87
+ throw new TypeError(`Signal ${token.name} was not built by defineSignal()`);
88
+ return found;
89
+ }
90
+ /** A settled record of `type` and `status` with `fields` besides the common ones; other fields are allowed. */
91
+ function settled(type, status, fields = {}) {
92
+ const common = {
93
+ id: int(),
94
+ conversationId: int(),
95
+ requestId: opt(str()),
96
+ notify: opt(obj({ taskId: int(), key: str() })),
97
+ };
98
+ return obj({ ...common, type: lit(type), status: lit(status), ...fields }, { open: true });
99
+ }
100
+ /**
101
+ * Built in: delivered to `SubmissionDraft.notify` when the submission settles, in the settling commit. Its value is the
102
+ * settled record, what `Submission.wait()` resolves to; its schema checks each variant's required fields, so another
103
+ * delivery cannot take the key with something else.
104
+ */
105
+ export const SubmissionSettled = defineSignal({
106
+ name: "diffra.submission-settled",
107
+ version: 1,
108
+ schema: unsafe(union([
109
+ settled("input", "done", { entry: int(), answer: int() }),
110
+ settled("write", "done", { entry: int() }),
111
+ settled("continue", "done", { answer: int() }),
112
+ settled("input", "unanswered", { entry: opt(int()), reason: str() }),
113
+ settled("write", "unanswered", { reason: str() }),
114
+ settled("continue", "unanswered", { reason: str() }),
115
+ ])),
116
+ });
117
+ /** Whether a submission settled: answered (`done`) or not (`unanswered`). */
118
+ export function isSettled(record) {
119
+ return record.status === "done" || record.status === "unanswered";
120
+ }
121
+ /** The memo holding a key's state. Signal names contain no "/", so names never collide. */
122
+ function signalMemoName(signal, key) {
123
+ return `diffra.signal.${signal}/${key}`;
124
+ }
125
+ /**
126
+ * Decide a delivery to `record` (spec suspendable §3.2): the result, and the record to write when it changes, with the
127
+ * value stored, or the key marked expired when the task sleeps on it past its deadline.
128
+ */
129
+ export function deliverSignal(record, token, key, value, now) {
130
+ if (record === undefined)
131
+ return { result: "not_found" };
132
+ const state = record.state;
133
+ if (state.status === "terminal" || state.status === "completing" || record.abortRequested)
134
+ return { result: "closed" };
135
+ // Values come from outside: the trust boundary of the signal's schema.
136
+ if (key === "" || !isJsonValue(value) || !internalsOf(token).validator.check(value))
137
+ return { result: "invalid" };
138
+ const name = signalMemoName(token.name, key);
139
+ const stored = memoOf(record.memos, name);
140
+ if (stored !== undefined)
141
+ return { result: stored.expired === true ? "closed" : "duplicate" };
142
+ if (state.status === "sleeping" &&
143
+ state.until !== undefined &&
144
+ state.until <= now &&
145
+ state.signals?.some((listed) => listed.signal === token.name && listed.key === key) === true) {
146
+ return { result: "closed", record: withMemos(record, { [name]: { expired: true } }) };
147
+ }
148
+ // `setTask()` copies the record, the value with it.
149
+ const memo = { version: token.version, value };
150
+ return { result: "delivered", record: withMemos(record, { [name]: memo }) };
151
+ }
152
+ /**
153
+ * A key's state in `memos`, the value migrated to the token's version; undefined while nothing came. Throws for a stored
154
+ * version newer than the token's, a missing or throwing `migrate`, or a migrated value the schema rejects.
155
+ */
156
+ export function readSignal(memos, token, key) {
157
+ const stored = memoOf(memos, signalMemoName(token.name, key));
158
+ if (stored === undefined)
159
+ return undefined;
160
+ if (stored.expired === true)
161
+ return { kind: "expired" };
162
+ if (stored.version === token.version)
163
+ return { kind: "value", value: stored.value };
164
+ if (stored.version > token.version) {
165
+ throw new Error(`Signal ${token.name} value has version ${stored.version}, newer than ${token.version}`);
166
+ }
167
+ const { validator, migrate } = internalsOf(token);
168
+ if (migrate === undefined)
169
+ throw new Error(`Signal ${token.name} has no migration from version ${stored.version}`);
170
+ const migrated = migrate(stored.value, stored.version);
171
+ if (!isJsonValue(migrated) || !validator.check(migrated)) {
172
+ throw new Error(`Signal ${token.name} migration from version ${stored.version} returned an invalid value`);
173
+ }
174
+ return { kind: "value", value: migrated };
175
+ }
176
+ /** Throws unless a sleep waits for something (`until` or a non-empty `signals`) and none of its keys served a wait. */
177
+ export function checkSleep(state, memos, task) {
178
+ if (state.until === undefined && (state.signals === undefined || state.signals.length === 0)) {
179
+ throw new Error(`Task ${task} cannot sleep without until or signals`);
180
+ }
181
+ for (const { signal, key } of state.signals ?? []) {
182
+ const stored = memoOf(memos, signalMemoName(signal, key));
183
+ if (stored === undefined)
184
+ continue;
185
+ if (stored.expired === true)
186
+ throw new Error(`Task ${task} cannot sleep on signal ${signal} key ${key}: it expired`);
187
+ if (stored.consumed === true) {
188
+ throw new Error(`Task ${task} cannot sleep on signal ${signal} key ${key}: it already woke a wait`);
189
+ }
190
+ }
191
+ }
192
+ /** Whether a sleep can wake now: a listed key holds a value no wake used, or its deadline came. */
193
+ export function sleepDue(state, memos, now) {
194
+ return readyKey(state, memos) !== undefined || (state.until !== undefined && state.until <= now);
195
+ }
196
+ /**
197
+ * The wake of a sleep that can wake now, and the memos the waking reservation writes: the first listed key holding a
198
+ * value no wake used, marked consumed; otherwise the deadline, with every listed key that holds nothing marked expired.
199
+ * Undefined when the sleep cannot wake yet.
200
+ */
201
+ export function sleepWake(state, memos, now) {
202
+ const ready = readyKey(state, memos);
203
+ if (ready !== undefined) {
204
+ const name = signalMemoName(ready.signal, ready.key);
205
+ // `readyKey()` found a value there.
206
+ const consumed = { ...memoOf(memos, name), consumed: true };
207
+ return { wake: { reason: "signal", signal: ready.signal, key: ready.key }, memos: { [name]: consumed } };
208
+ }
209
+ if (state.until === undefined || state.until > now)
210
+ return undefined;
211
+ if (state.signals === undefined || state.signals.length === 0)
212
+ return { wake: { reason: "time" }, memos: {} };
213
+ const expired = {};
214
+ for (const { signal, key } of state.signals) {
215
+ const name = signalMemoName(signal, key);
216
+ if (memoOf(memos, name) === undefined)
217
+ expired[name] = { expired: true };
218
+ }
219
+ return { wake: { reason: "expired" }, memos: expired };
220
+ }
221
+ /** The first listed key, in `signals` order, holding a value no wake used. */
222
+ function readyKey(state, memos) {
223
+ return state.signals?.find(({ signal, key }) => {
224
+ const stored = memoOf(memos, signalMemoName(signal, key));
225
+ return stored !== undefined && stored.expired !== true && stored.consumed !== true;
226
+ });
227
+ }
228
+ /** `record` with `memos` added; signal memos are written only to live records. */
229
+ function withMemos(record, memos) {
230
+ return { ...record, memos: { ...record.memos, ...memos } };
231
+ }
232
+ /** Own memo entries only; a name such as `toString` must not resolve to an inherited property. */
233
+ function memoOf(memos, name) {
234
+ return memos !== undefined && Object.hasOwn(memos, name) ? memos[name] : undefined;
235
+ }
236
+ //# sourceMappingURL=signals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.js","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,OAAO,EAAE,W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AAC;QACzC,IAAI,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,SAAS;YAAE,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1E,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACxD,CAAC;AAED,8EAA8E;AAC9E,SAAS,QAAQ,CAChB,KAAe,EACf,KAAwB;IAExB,OAAO,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE;QAC9C,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,EAAE,cAAc,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;QAC1D,OAAO,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI,CAAC;IACpF,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,SAAS,SAAS,CAAC,MAAqB,EAAE,KAAY;IACrD,OAAO,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,GAAG,KAAK,EAAE,EAAmB,CAAC;AAC7E,CAAC;AAED,kGAAkG;AAClG,SAAS,MAAM,CAAC,KAAwB,EAAE,IAAY;IACrD,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAE,KAAK,CAAC,IAAI,CAAgB,CAAC,CAAC,CAAC,SAAS,CAAC;AACpG,CAAC","sourcesContent":["// Signals: typed JSON values delivered to a live task from outside, kept in its memos until a wake uses them.\nimport { isJsonValue, type JsonValue } from \"@diffra-ai/chord/json\";\nimport {\n\tcompile,\n\tint,\n\tlit,\n\tobj,\n\topt,\n\ttype Properties,\n\ttype Static,\n\tstr,\n\tunion,\n\tunsafe,\n\ttype Validator,\n} from \"@diffra-ai/schema\";\nimport type { SettledSubmissionRecord } from \"./harness/types.ts\";\nimport type { SubmissionRecord, TaskRecord, TaskState, WakeReason } from \"./types.ts\";\n\n/** The key of one wait for a signal: JSON, used in sleeps and parks. `T` is a phantom type. */\nexport type SignalKey<T> = { readonly signal: string; readonly key: string; readonly \"~value\"?: T };\n\n/** A signal kind, built by `defineSignal()`: values of type `T` delivered under keys. */\nexport interface SignalToken<T> {\n\treadonly name: string;\n\treadonly version: number;\n\t/** The key of one wait; throws for an empty key. */\n\tkey(key: string): SignalKey<T>;\n}\n\n/** What `defineSignal()` takes. */\nexport type SignalDefinition<S extends object> = {\n\t/** Unique like a task or document kind; must not contain \"/\". */\n\treadonly name: string;\n\t/** Positive integer version of the value shape. */\n\treadonly version: number;\n\t/** A diffra-schema schema of a JSON value; the value type is `Static<S>`. */\n\treadonly schema: S;\n\t/** A value stored by an older version, to the current shape. */\n\treadonly migrate?: (value: JsonValue, fromVersion: number) => Static<S>;\n};\n\n/** A key's state: the value delivered under it, or expired because its sleep's deadline came first. */\nexport type SignalState<T> = { readonly kind: \"value\"; readonly value: T } | { readonly kind: \"expired\" };\n\n/**\n * What a delivery did: `delivered` (durably accepted, not necessarily consumed), `duplicate` (the key holds a value),\n * `invalid` (not JSON, or not matching the schema), `closed` (the task ended, holds its outcome, is abort-marked, or the\n * key expired), `not_found` (no such task).\n */\nexport type SignalResult = \"delivered\" | \"duplicate\" | \"invalid\" | \"closed\" | \"not_found\";\n\n/**\n * Stored state of one key, in the task's memo `diffra.signal.<name>/<key>`, told apart by `expired`: the stored shape stays\n * as records already hold it.\n */\ntype SignalMemo = (ValueMemo & { readonly expired?: never }) | { readonly expired: true };\n\n/** A stored key that holds a value: its version, and whether a wake used it. */\ntype ValueMemo = { readonly version: number; readonly value: JsonValue; readonly consumed?: true };\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype Memos = Readonly<Record<string, JsonValue>>;\ntype Sleeping = Extract<TaskState<JsonValue, JsonValue>, { readonly status: \"sleeping\" }>;\n\ntype SignalInternals = {\n\treadonly validator: Validator<unknown>;\n\treadonly migrate: ((value: JsonValue, fromVersion: number) => unknown) | undefined;\n};\n\n/** What only Durable reads of a token: its compiled schema and migration. */\nconst internals = new WeakMap<SignalToken<unknown>, SignalInternals>();\n\n/** Define a signal kind. Throws for a name with \"/\", a version that is not a positive integer, or a non-JSON schema. */\nexport function defineSignal<S extends object>(definition: SignalDefinition<S>): SignalToken<Static<S>> {\n\tconst { name, version, schema } = definition;\n\tif (name === \"\" || name.includes(\"/\"))\n\t\tthrow new TypeError(`Signal name ${JSON.stringify(name)} must be non-empty, without \"/\"`);\n\tif (!Number.isInteger(version) || version < 1)\n\t\tthrow new TypeError(`Signal ${name} version must be a positive integer`);\n\tconst nonJson = nonJsonType(schema);\n\tif (nonJson !== undefined) throw new TypeError(`Signal ${name} schema admits non-JSON values (${nonJson})`);\n\tconst token: SignalToken<Static<S>> = {\n\t\tname,\n\t\tversion,\n\t\tkey: (key) => {\n\t\t\tif (key === \"\") throw new TypeError(`Signal ${name} key must be non-empty`);\n\t\t\treturn { signal: name, key };\n\t\t},\n\t};\n\tinternals.set(token, { validator: compile(schema), migrate: definition.migrate });\n\treturn token;\n}\n\n/** Keywords whose value is a schema or an array of schemas. Annotations (`examples`, `default`) are not walked. */\nconst SCHEMA_KEYWORDS = [\n\t\"items\",\n\t\"prefixItems\",\n\t\"additionalItems\",\n\t\"unevaluatedItems\",\n\t\"contains\",\n\t\"anyOf\",\n\t\"oneOf\",\n\t\"allOf\",\n\t\"not\",\n\t\"if\",\n\t\"then\",\n\t\"else\",\n\t\"additionalProperties\",\n\t\"unevaluatedProperties\",\n\t\"propertyNames\",\n] as const;\n\n/** Keywords whose value maps names to schemas; draft 7's `dependencies` may also map to name arrays, which hold none. */\nconst SCHEMA_MAP_KEYWORDS = [\n\t\"properties\",\n\t\"patternProperties\",\n\t\"dependentSchemas\",\n\t\"dependencies\",\n\t\"$defs\",\n\t\"definitions\",\n] as const;\n\n/** A non-JSON type a schema accepts anywhere (diffra-schema's `bytes`, `bigint`, TypeBox's `undefined`), if any. */\nfunction nonJsonType(schema: unknown): string | undefined {\n\tif (typeof schema !== \"object\" || schema === null) return undefined;\n\tconst node = schema as Readonly<Record<string, unknown>>;\n\tconst types = Array.isArray(node.type) ? node.type : [node.type];\n\tconst found = types.find((type) => type === \"bytes\" || type === \"bigint\" || type === \"undefined\");\n\tif (found !== undefined) return found as string;\n\tconst children: unknown[] = [];\n\tfor (const keyword of SCHEMA_KEYWORDS) {\n\t\tconst value = node[keyword];\n\t\tif (Array.isArray(value)) children.push(...value);\n\t\telse children.push(value);\n\t}\n\tfor (const keyword of SCHEMA_MAP_KEYWORDS) {\n\t\tconst value = node[keyword];\n\t\tif (typeof value === \"object\" && value !== null) children.push(...Object.values(value));\n\t}\n\tfor (const child of children) {\n\t\tconst nested = nonJsonType(child);\n\t\tif (nested !== undefined) return nested;\n\t}\n\treturn undefined;\n}\n\nfunction internalsOf(token: SignalToken<unknown>): SignalInternals {\n\tconst found = internals.get(token);\n\tif (found === undefined) throw new TypeError(`Signal ${token.name} was not built by defineSignal()`);\n\treturn found;\n}\n\n/** A settled record of `type` and `status` with `fields` besides the common ones; other fields are allowed. */\nfunction settled(type: \"input\" | \"write\" | \"continue\", status: \"done\" | \"unanswered\", fields: Properties = {}) {\n\tconst common = {\n\t\tid: int(),\n\t\tconversationId: int(),\n\t\trequestId: opt(str()),\n\t\tnotify: opt(obj({ taskId: int(), key: str() })),\n\t};\n\treturn obj({ ...common, type: lit(type), status: lit(status), ...fields }, { open: true });\n}\n\n/**\n * Built in: delivered to `SubmissionDraft.notify` when the submission settles, in the settling commit. Its value is the\n * settled record, what `Submission.wait()` resolves to; its schema checks each variant's required fields, so another\n * delivery cannot take the key with something else.\n */\nexport const SubmissionSettled = defineSignal({\n\tname: \"diffra.submission-settled\",\n\tversion: 1,\n\tschema: unsafe<SettledSubmissionRecord>(\n\t\tunion([\n\t\t\tsettled(\"input\", \"done\", { entry: int(), answer: int() }),\n\t\t\tsettled(\"write\", \"done\", { entry: int() }),\n\t\t\tsettled(\"continue\", \"done\", { answer: int() }),\n\t\t\tsettled(\"input\", \"unanswered\", { entry: opt(int()), reason: str() }),\n\t\t\tsettled(\"write\", \"unanswered\", { reason: str() }),\n\t\t\tsettled(\"continue\", \"unanswered\", { reason: str() }),\n\t\t]),\n\t),\n});\n\n/** Whether a submission settled: answered (`done`) or not (`unanswered`). */\nexport function isSettled(record: SubmissionRecord): record is SettledSubmissionRecord {\n\treturn record.status === \"done\" || record.status === \"unanswered\";\n}\n\n/** The memo holding a key's state. Signal names contain no \"/\", so names never collide. */\nfunction signalMemoName(signal: string, key: string): string {\n\treturn `diffra.signal.${signal}/${key}`;\n}\n\n/**\n * Decide a delivery to `record` (spec suspendable §3.2): the result, and the record to write when it changes, with the\n * value stored, or the key marked expired when the task sleeps on it past its deadline.\n */\nexport function deliverSignal<T>(\n\trecord: AnyTaskRecord | undefined,\n\ttoken: SignalToken<T>,\n\tkey: string,\n\tvalue: T,\n\tnow: number,\n): { readonly result: SignalResult; readonly record?: AnyTaskRecord } {\n\tif (record === undefined) return { result: \"not_found\" };\n\tconst state = record.state;\n\tif (state.status === \"terminal\" || state.status === \"completing\" || record.abortRequested)\n\t\treturn { result: \"closed\" };\n\t// Values come from outside: the trust boundary of the signal's schema.\n\tif (key === \"\" || !isJsonValue(value) || !internalsOf(token).validator.check(value)) return { result: \"invalid\" };\n\tconst name = signalMemoName(token.name, key);\n\tconst stored = memoOf(record.memos, name);\n\tif (stored !== undefined) return { result: stored.expired === true ? \"closed\" : \"duplicate\" };\n\tif (\n\t\tstate.status === \"sleeping\" &&\n\t\tstate.until !== undefined &&\n\t\tstate.until <= now &&\n\t\tstate.signals?.some((listed) => listed.signal === token.name && listed.key === key) === true\n\t) {\n\t\treturn { result: \"closed\", record: withMemos(record, { [name]: { expired: true } }) };\n\t}\n\t// `setTask()` copies the record, the value with it.\n\tconst memo: ValueMemo = { version: token.version, value };\n\treturn { result: \"delivered\", record: withMemos(record, { [name]: memo }) };\n}\n\n/**\n * A key's state in `memos`, the value migrated to the token's version; undefined while nothing came. Throws for a stored\n * version newer than the token's, a missing or throwing `migrate`, or a migrated value the schema rejects.\n */\nexport function readSignal<T>(\n\tmemos: Memos | undefined,\n\ttoken: SignalToken<T>,\n\tkey: string,\n): SignalState<T> | undefined {\n\tconst stored = memoOf(memos, signalMemoName(token.name, key));\n\tif (stored === undefined) return undefined;\n\tif (stored.expired === true) return { kind: \"expired\" };\n\tif (stored.version === token.version) return { kind: \"value\", value: stored.value as T };\n\tif (stored.version > token.version) {\n\t\tthrow new Error(`Signal ${token.name} value has version ${stored.version}, newer than ${token.version}`);\n\t}\n\tconst { validator, migrate } = internalsOf(token);\n\tif (migrate === undefined) throw new Error(`Signal ${token.name} has no migration from version ${stored.version}`);\n\tconst migrated = migrate(stored.value, stored.version);\n\tif (!isJsonValue(migrated) || !validator.check(migrated)) {\n\t\tthrow new Error(`Signal ${token.name} migration from version ${stored.version} returned an invalid value`);\n\t}\n\treturn { kind: \"value\", value: migrated as T };\n}\n\n/** Throws unless a sleep waits for something (`until` or a non-empty `signals`) and none of its keys served a wait. */\nexport function checkSleep(state: Sleeping, memos: Memos | undefined, task: number): void {\n\tif (state.until === undefined && (state.signals === undefined || state.signals.length === 0)) {\n\t\tthrow new Error(`Task ${task} cannot sleep without until or signals`);\n\t}\n\tfor (const { signal, key } of state.signals ?? []) {\n\t\tconst stored = memoOf(memos, signalMemoName(signal, key));\n\t\tif (stored === undefined) continue;\n\t\tif (stored.expired === true)\n\t\t\tthrow new Error(`Task ${task} cannot sleep on signal ${signal} key ${key}: it expired`);\n\t\tif (stored.consumed === true) {\n\t\t\tthrow new Error(`Task ${task} cannot sleep on signal ${signal} key ${key}: it already woke a wait`);\n\t\t}\n\t}\n}\n\n/** Whether a sleep can wake now: a listed key holds a value no wake used, or its deadline came. */\nexport function sleepDue(state: Sleeping, memos: Memos | undefined, now: number): boolean {\n\treturn readyKey(state, memos) !== undefined || (state.until !== undefined && state.until <= now);\n}\n\n/**\n * The wake of a sleep that can wake now, and the memos the waking reservation writes: the first listed key holding a\n * value no wake used, marked consumed; otherwise the deadline, with every listed key that holds nothing marked expired.\n * Undefined when the sleep cannot wake yet.\n */\nexport function sleepWake(\n\tstate: Sleeping,\n\tmemos: Memos | undefined,\n\tnow: number,\n): { readonly wake: WakeReason; readonly memos: Memos } | undefined {\n\tconst ready = readyKey(state, memos);\n\tif (ready !== undefined) {\n\t\tconst name = signalMemoName(ready.signal, ready.key);\n\t\t// `readyKey()` found a value there.\n\t\tconst consumed: ValueMemo = { ...(memoOf(memos, name) as ValueMemo), consumed: true };\n\t\treturn { wake: { reason: \"signal\", signal: ready.signal, key: ready.key }, memos: { [name]: consumed } };\n\t}\n\tif (state.until === undefined || state.until > now) return undefined;\n\tif (state.signals === undefined || state.signals.length === 0) return { wake: { reason: \"time\" }, memos: {} };\n\tconst expired: Record<string, JsonValue> = {};\n\tfor (const { signal, key } of state.signals) {\n\t\tconst name = signalMemoName(signal, key);\n\t\tif (memoOf(memos, name) === undefined) expired[name] = { expired: true };\n\t}\n\treturn { wake: { reason: \"expired\" }, memos: expired };\n}\n\n/** The first listed key, in `signals` order, holding a value no wake used. */\nfunction readyKey(\n\tstate: Sleeping,\n\tmemos: Memos | undefined,\n): { readonly signal: string; readonly key: string } | undefined {\n\treturn state.signals?.find(({ signal, key }) => {\n\t\tconst stored = memoOf(memos, signalMemoName(signal, key));\n\t\treturn stored !== undefined && stored.expired !== true && stored.consumed !== true;\n\t});\n}\n\n/** `record` with `memos` added; signal memos are written only to live records. */\nfunction withMemos(record: AnyTaskRecord, memos: Memos): AnyTaskRecord {\n\treturn { ...record, memos: { ...record.memos, ...memos } } as AnyTaskRecord;\n}\n\n/** Own memo entries only; a name such as `toString` must not resolve to an inherited property. */\nfunction memoOf(memos: Memos | undefined, name: string): SignalMemo | undefined {\n\treturn memos !== undefined && Object.hasOwn(memos, name) ? (memos[name] as SignalMemo) : undefined;\n}\n"]}
@@ -0,0 +1,69 @@
1
+ import type { Context } from "@diffra-ai/chord/context";
2
+ import type { JsonValue } from "@diffra-ai/chord/json";
3
+ import type { CommitResult, ConversationId, ConversationQuery, ConversationRecord, Cursor, DocumentAddress, DocumentId, DocumentPoint, DocumentQuery, DocumentRecord, EntryId, EntryQuery, EntryRecord, Id, Page, Seq, Storage, StorageWrite, StoredDocument, SubmissionId, SubmissionQuery, SubmissionRecord, TaskId, TaskQuery, TaskRecord } from "../types.ts";
4
+ type StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;
5
+ type IndexedDbStorageOptions = {
6
+ readonly indexedDB?: IDBFactory;
7
+ };
8
+ /** Browser IndexedDB implementation of the durable storage contract. One owner must serialize access to each database. */
9
+ export declare class IndexedDbStorage implements Storage {
10
+ private readonly database;
11
+ private closed;
12
+ private closing;
13
+ private activeOperations;
14
+ private operationsDrained;
15
+ private constructor();
16
+ /** Open or create a browser-only IndexedDB database. */
17
+ static open(name: string, options?: IndexedDbStorageOptions): Promise<IndexedDbStorage>;
18
+ /** Delete a closed database. Open connections in this or another owner can block deletion. */
19
+ static delete(name: string, options?: IndexedDbStorageOptions): Promise<void>;
20
+ /**
21
+ * Commit `batches` in one IndexedDB transaction, each with its own seq. Each batch does every read and check, copy
22
+ * resolution included, against the state the earlier ones left before it issues its first write; the first one
23
+ * refused ends the call, and the transaction commits the ones before it. An error of IndexedDB itself aborts the
24
+ * transaction: the call rejects with nothing stored.
25
+ */
26
+ commit(batches: readonly (readonly StorageWrite[])[], receive: (index: number, seq: Seq) => void, _context: Context): Promise<CommitResult>;
27
+ mintId<I extends Id<string>>(): Promise<I>;
28
+ conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined>;
29
+ scanConversations(query: ConversationQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<ConversationRecord, Cursor>>;
30
+ entry(id: EntryId, context: Context): Promise<{
31
+ readonly entry: EntryRecord;
32
+ readonly commitSeq: Seq;
33
+ } | undefined>;
34
+ entry(conversationId: ConversationId, id: EntryId, context: Context): Promise<{
35
+ readonly entry: EntryRecord;
36
+ readonly commitSeq: Seq;
37
+ } | undefined>;
38
+ findLatestHeadMarker(conversationId: ConversationId, atOrBeforeEntryId: EntryId | undefined, _context: Context): Promise<(EntryRecord & {
39
+ readonly head: EntryId;
40
+ }) | undefined>;
41
+ scanEntries(query: EntryQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<EntryRecord, Cursor>>;
42
+ task(id: TaskId, _context: Context): Promise<StoredTask | undefined>;
43
+ scanTasks(query: TaskQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<StoredTask, Cursor>>;
44
+ submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined>;
45
+ scanSubmissions(query: SubmissionQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<SubmissionRecord, Cursor>>;
46
+ submissionByRequest(conversationId: ConversationId, requestId: string, _context: Context): Promise<SubmissionRecord | undefined>;
47
+ findDocument(address: DocumentAddress, at: DocumentPoint, _context: Context): Promise<DocumentRecord | undefined>;
48
+ document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined>;
49
+ scanDocuments(query: DocumentQuery, limit: number, cursor: Cursor | undefined, _context: Context): Promise<Page<DocumentRecord, Cursor>>;
50
+ close(_context: Context): Promise<void>;
51
+ private closeDatabase;
52
+ private transaction;
53
+ private readConversation;
54
+ private readEntriesDescending;
55
+ private readEntriesAscending;
56
+ private materializeDocument;
57
+ private checkGlobalIds;
58
+ private prepareDocumentActions;
59
+ private checkDocumentActions;
60
+ private currentDocumentId;
61
+ private claimId;
62
+ private applyTableWrite;
63
+ /** Resolve each copy to a base of its source's state before this batch, which may not change the source. */
64
+ private resolveCopies;
65
+ private applyDocumentActions;
66
+ private assertOpen;
67
+ }
68
+ export type { IndexedDbStorageOptions };
69
+ //# sourceMappingURL=indexeddb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb.d.ts","sourceRoot":"","sources":["../../src/storage/indexeddb.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGvD,OAAO,KAAK,EACX,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,MAAM,EACN,eAAe,EAGf,UAAU,EACV,aAAa,EACb,aAAa,EACb,cAAc,EACd,OAAO,EACP,UAAU,EACV,WAAW,EACX,EAAE,EAEF,IAAI,EAEJ,GAAG,EACH,OAAO,EACP,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,MAAM,EACN,SAAS,EACT,UAAU,EACV,MAAM,aAAa,CAAC;AAuCrB,KAAK,UAAU,GAAG,UAAU,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;AA8D9D,KAAK,uBAAuB,GAAG;IAC9B,QAAQ,CAAC,SAAS,CAAC,EAAE,UAAU,CAAC;CAChC,CAAC;AA2QF,0HAA0H;AAC1H,qBAAa,gBAAiB,YAAW,OAAO;IAC/C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAc;IACvC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,iBAAiB,CAA2B;IAEpD,OAAO,eAEN;IAED,wDAAwD;IACxD,OAAa,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAqBhG;IAED,8FAA8F;IAC9F,OAAa,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC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