@north-light/cli 0.3.530 → 0.3.531

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 (495) hide show
  1. package/dist/clients/attach/session/connection.js +1 -1
  2. package/dist/clients/attach/session/reconnect.js +1 -1
  3. package/dist/clients/attach/viewer.js +3 -3
  4. package/dist/core/async-array.d.ts +7 -0
  5. package/dist/core/async-array.js +1 -0
  6. package/dist/core/audit.d.ts +1 -1
  7. package/dist/core/audit.js +2 -2
  8. package/dist/core/canvas/attention.d.ts +4 -4
  9. package/dist/core/canvas/attention.js +1 -1
  10. package/dist/core/canvas/boot.d.ts +4 -4
  11. package/dist/core/canvas/boot.js +1 -1
  12. package/dist/core/canvas/canvas.d.ts +59 -59
  13. package/dist/core/canvas/canvas.js +19 -19
  14. package/dist/core/canvas/context-strip.js +2 -2
  15. package/dist/core/canvas/crons.d.ts +27 -27
  16. package/dist/core/canvas/crons.js +11 -11
  17. package/dist/core/canvas/daemon-actions.d.ts +10 -10
  18. package/dist/core/canvas/daemon-actions.js +8 -8
  19. package/dist/core/canvas/daemon-owner.d.ts +3 -3
  20. package/dist/core/canvas/daemon-owner.js +2 -2
  21. package/dist/core/canvas/db.d.ts +19 -30
  22. package/dist/core/canvas/db.js +3 -2
  23. package/dist/core/canvas/deliveries.d.ts +16 -16
  24. package/dist/core/canvas/deliveries.js +24 -24
  25. package/dist/core/canvas/executions.d.ts +8 -8
  26. package/dist/core/canvas/executions.js +1 -1
  27. package/dist/core/canvas/focuses.d.ts +8 -8
  28. package/dist/core/canvas/focuses.js +1 -1
  29. package/dist/core/canvas/history.d.ts +3 -3
  30. package/dist/core/canvas/history.js +9 -9
  31. package/dist/core/canvas/install-id.d.ts +1 -1
  32. package/dist/core/canvas/install-id.js +1 -1
  33. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +1 -1
  34. package/dist/core/canvas/managed-worktree-sweep-candidates.js +2 -2
  35. package/dist/core/canvas/memory-reads.d.ts +6 -6
  36. package/dist/core/canvas/memory-reads.js +1 -1
  37. package/dist/core/canvas/nav-model.d.ts +13 -13
  38. package/dist/core/canvas/nav-model.js +1 -1
  39. package/dist/core/canvas/node-agent-paths.d.ts +6 -6
  40. package/dist/core/canvas/node-agent-paths.js +1 -1
  41. package/dist/core/canvas/node-tokens.d.ts +7 -7
  42. package/dist/core/canvas/node-tokens.js +3 -3
  43. package/dist/core/canvas/outcome-actions.d.ts +5 -5
  44. package/dist/core/canvas/outcome-actions.js +3 -3
  45. package/dist/core/canvas/recovery.d.ts +26 -26
  46. package/dist/core/canvas/recovery.js +2 -2
  47. package/dist/core/canvas/render-source.d.ts +1 -1
  48. package/dist/core/canvas/render-source.js +1 -1
  49. package/dist/core/canvas/sessions.d.ts +10 -10
  50. package/dist/core/canvas/sessions.js +4 -4
  51. package/dist/core/canvas/source.js +1 -1
  52. package/dist/core/canvas/structured-requests.d.ts +15 -15
  53. package/dist/core/canvas/structured-requests.js +5 -5
  54. package/dist/core/canvas/tree.d.ts +9 -9
  55. package/dist/core/canvas/tree.js +5 -5
  56. package/dist/core/canvas/waits.d.ts +13 -13
  57. package/dist/core/canvas/waits.js +6 -6
  58. package/dist/core/canvas/worktrees.d.ts +15 -15
  59. package/dist/core/canvas/worktrees.js +1 -1
  60. package/dist/core/command-hooks/transport/exec-lifecycle.js +1 -1
  61. package/dist/core/conversation-store/file-store.d.ts +7 -7
  62. package/dist/core/conversation-store/file-store.js +9 -9
  63. package/dist/core/conversation-store/index.d.ts +16 -14
  64. package/dist/core/conversation-store/index.js +1 -1
  65. package/dist/core/conversation-store/listener.js +5 -5
  66. package/dist/core/conversation-store/patch.d.ts +3 -1
  67. package/dist/core/conversation-store/patch.js +1 -1
  68. package/dist/core/feed/feed.js +3 -3
  69. package/dist/core/feed/inbox.d.ts +2 -2
  70. package/dist/core/feed/inbox.js +1 -1
  71. package/dist/core/feed/messages.d.ts +11 -12
  72. package/dist/core/feed/messages.js +5 -5
  73. package/dist/core/feed/reports.d.ts +4 -4
  74. package/dist/core/feed/reports.js +2 -2
  75. package/dist/core/grants/cover.d.ts +1 -1
  76. package/dist/core/grants/cover.js +1 -1
  77. package/dist/core/grants/local.d.ts +1 -1
  78. package/dist/core/grants/local.js +1 -1
  79. package/dist/core/grants/mirror.d.ts +19 -19
  80. package/dist/core/grants/mirror.js +2 -2
  81. package/dist/core/grants/on-sync.d.ts +1 -1
  82. package/dist/core/grants/on-sync.js +1 -1
  83. package/dist/core/grants/remove.js +1 -1
  84. package/dist/core/grants/sync.js +1 -1
  85. package/dist/core/graph/access.d.ts +17 -17
  86. package/dist/core/graph/access.js +3 -3
  87. package/dist/core/graph/custom.d.ts +16 -16
  88. package/dist/core/graph/custom.js +9 -9
  89. package/dist/core/graph/deletion.d.ts +3 -7
  90. package/dist/core/graph/deletion.js +4 -4
  91. package/dist/core/graph/documents.d.ts +24 -27
  92. package/dist/core/graph/documents.js +7 -7
  93. package/dist/core/graph/edges.d.ts +13 -13
  94. package/dist/core/graph/edges.js +1 -1
  95. package/dist/core/graph/events.d.ts +7 -9
  96. package/dist/core/graph/events.js +8 -8
  97. package/dist/core/graph/exposures.d.ts +6 -6
  98. package/dist/core/graph/exposures.js +4 -4
  99. package/dist/core/graph/jobs.d.ts +6 -8
  100. package/dist/core/graph/jobs.js +2 -2
  101. package/dist/core/graph/kinds/action.js +1 -1
  102. package/dist/core/graph/kinds/custom.js +2 -2
  103. package/dist/core/graph/kinds/document.d.ts +1 -0
  104. package/dist/core/graph/kinds/document.js +4 -4
  105. package/dist/core/graph/kinds/dto.d.ts +2 -2
  106. package/dist/core/graph/kinds/dto.js +1 -1
  107. package/dist/core/graph/kinds/job.js +2 -2
  108. package/dist/core/graph/kinds/kind.d.ts +6 -8
  109. package/dist/core/graph/kinds/kind.js +1 -1
  110. package/dist/core/graph/kinds/node.js +5 -5
  111. package/dist/core/graph/kinds/owner.js +2 -2
  112. package/dist/core/graph/kinds/registry.d.ts +6 -9
  113. package/dist/core/graph/kinds/registry.js +1 -1
  114. package/dist/core/graph/names.d.ts +6 -6
  115. package/dist/core/graph/names.js +3 -3
  116. package/dist/core/graph/object-waits.d.ts +4 -7
  117. package/dist/core/graph/object-waits.js +1 -1
  118. package/dist/core/graph/objects.d.ts +14 -14
  119. package/dist/core/graph/objects.js +9 -9
  120. package/dist/core/graph/package-docs.d.ts +2 -7
  121. package/dist/core/graph/package-docs.js +5 -5
  122. package/dist/core/graph/package-kinds.d.ts +2 -5
  123. package/dist/core/graph/package-kinds.js +1 -1
  124. package/dist/core/graph/package-reconcile.d.ts +2 -5
  125. package/dist/core/graph/package-reconcile.js +1 -1
  126. package/dist/core/graph/reader.d.ts +18 -18
  127. package/dist/core/graph/reader.js +3 -3
  128. package/dist/core/graph/receivers.d.ts +4 -4
  129. package/dist/core/graph/receivers.js +5 -5
  130. package/dist/core/graph/repo-sync/exchange.d.ts +3 -7
  131. package/dist/core/graph/repo-sync/exchange.js +2 -2
  132. package/dist/core/graph/repo-sync/repos.d.ts +7 -5
  133. package/dist/core/graph/repo-sync/repos.js +3 -3
  134. package/dist/core/graph/repo-sync/sync.d.ts +3 -6
  135. package/dist/core/graph/repo-sync/sync.js +2 -2
  136. package/dist/core/graph/rules.d.ts +5 -5
  137. package/dist/core/graph/rules.js +3 -3
  138. package/dist/core/graph/spaces/app.js +1 -1
  139. package/dist/core/graph/spaces/index.d.ts +4 -5
  140. package/dist/core/graph/spaces/index.js +1 -1
  141. package/dist/core/graph/spaces/own-memory.d.ts +4 -4
  142. package/dist/core/graph/spaces/own-memory.js +1 -1
  143. package/dist/core/graph/spaces/person.js +3 -3
  144. package/dist/core/graph/spaces/repo.d.ts +1 -1
  145. package/dist/core/graph/spaces/repo.js +1 -1
  146. package/dist/core/graph/watches.d.ts +15 -15
  147. package/dist/core/graph/watches.js +10 -10
  148. package/dist/core/human/feedback-companion.d.ts +2 -2
  149. package/dist/core/human/feedback-companion.js +1 -1
  150. package/dist/core/human/feedback.d.ts +3 -3
  151. package/dist/core/human/feedback.js +1 -1
  152. package/dist/core/human/requests.d.ts +34 -33
  153. package/dist/core/human/requests.js +20 -20
  154. package/dist/core/human/scan.d.ts +2 -2
  155. package/dist/core/human/scan.js +1 -1
  156. package/dist/core/human/tickets.d.ts +9 -9
  157. package/dist/core/human/tickets.js +1 -1
  158. package/dist/core/llm/app-rungs.d.ts +1 -1
  159. package/dist/core/llm/app-rungs.js +1 -1
  160. package/dist/core/llm/run.js +1 -1
  161. package/dist/core/peer/directory.d.ts +1 -1
  162. package/dist/core/peer/directory.js +1 -1
  163. package/dist/core/peer/envelope.d.ts +3 -3
  164. package/dist/core/peer/envelope.js +1 -1
  165. package/dist/core/peer/home.d.ts +7 -7
  166. package/dist/core/peer/home.js +2 -2
  167. package/dist/core/peer/ingest.d.ts +6 -6
  168. package/dist/core/peer/ingest.js +1 -1
  169. package/dist/core/peer/outbox-store.d.ts +14 -14
  170. package/dist/core/peer/outbox-store.js +5 -5
  171. package/dist/core/peer/receiver.d.ts +2 -2
  172. package/dist/core/peer/receiver.js +1 -1
  173. package/dist/core/peer/stubs.d.ts +10 -10
  174. package/dist/core/peer/stubs.js +1 -1
  175. package/dist/core/providers/approval.d.ts +2 -2
  176. package/dist/core/providers/approval.js +2 -2
  177. package/dist/core/providers/audit.d.ts +3 -3
  178. package/dist/core/providers/audit.js +2 -2
  179. package/dist/core/providers/bundles.js +2 -2
  180. package/dist/core/providers/call.d.ts +2 -2
  181. package/dist/core/providers/call.js +1 -1
  182. package/dist/core/providers/files.d.ts +1 -1
  183. package/dist/core/providers/files.js +1 -1
  184. package/dist/core/providers/mint.js +1 -1
  185. package/dist/core/providers/receipts.d.ts +1 -1
  186. package/dist/core/providers/receipts.js +2 -2
  187. package/dist/core/review/birth.js +1 -1
  188. package/dist/core/review/comments.d.ts +19 -19
  189. package/dist/core/review/comments.js +5 -5
  190. package/dist/core/review/companion.d.ts +1 -1
  191. package/dist/core/review/companion.js +1 -1
  192. package/dist/core/review/document.d.ts +3 -3
  193. package/dist/core/review/document.js +2 -2
  194. package/dist/core/review/fork.js +2 -2
  195. package/dist/core/review/realize.js +1 -1
  196. package/dist/core/review/remap.d.ts +2 -2
  197. package/dist/core/review/remap.js +4 -4
  198. package/dist/core/review/stage.d.ts +1 -1
  199. package/dist/core/review/stage.js +1 -1
  200. package/dist/core/review/store.d.ts +21 -21
  201. package/dist/core/review/store.js +1 -1
  202. package/dist/core/runs/activity.d.ts +1 -1
  203. package/dist/core/runs/activity.js +5 -5
  204. package/dist/core/runs/confinement.d.ts +7 -7
  205. package/dist/core/runs/confinement.js +2 -2
  206. package/dist/core/runs/events.d.ts +12 -12
  207. package/dist/core/runs/events.js +4 -4
  208. package/dist/core/runs/operations.d.ts +11 -11
  209. package/dist/core/runs/operations.js +5 -5
  210. package/dist/core/runs/questions.d.ts +10 -10
  211. package/dist/core/runs/questions.js +3 -3
  212. package/dist/core/runtime/auth-reload.js +1 -1
  213. package/dist/core/runtime/bearings.d.ts +5 -5
  214. package/dist/core/runtime/bearings.js +6 -6
  215. package/dist/core/runtime/broker-inventory.js +1 -1
  216. package/dist/core/runtime/broker-request.js +1 -1
  217. package/dist/core/runtime/broker.js +1 -1
  218. package/dist/core/runtime/close.d.ts +3 -3
  219. package/dist/core/runtime/close.js +1 -1
  220. package/dist/core/runtime/deliver-live.js +1 -1
  221. package/dist/core/runtime/fleet.d.ts +2 -2
  222. package/dist/core/runtime/host.d.ts +3 -3
  223. package/dist/core/runtime/host.js +3 -3
  224. package/dist/core/runtime/kickoff.d.ts +12 -12
  225. package/dist/core/runtime/kickoff.js +17 -17
  226. package/dist/core/runtime/launch-target.d.ts +1 -1
  227. package/dist/core/runtime/launch-target.js +1 -1
  228. package/dist/core/runtime/ledger.d.ts +3 -3
  229. package/dist/core/runtime/ledger.js +3 -3
  230. package/dist/core/runtime/lifecycle.d.ts +1 -1
  231. package/dist/core/runtime/lifecycle.js +2 -2
  232. package/dist/core/runtime/memory-admission.js +1 -1
  233. package/dist/core/runtime/model-swap.d.ts +2 -2
  234. package/dist/core/runtime/model-swap.js +1 -1
  235. package/dist/core/runtime/node-read.d.ts +1 -1
  236. package/dist/core/runtime/node-read.js +2 -2
  237. package/dist/core/runtime/nodes.d.ts +6 -6
  238. package/dist/core/runtime/nodes.js +1 -1
  239. package/dist/core/runtime/outcome-document.d.ts +1 -1
  240. package/dist/core/runtime/outcome-document.js +1 -1
  241. package/dist/core/runtime/persona.d.ts +3 -3
  242. package/dist/core/runtime/persona.js +2 -2
  243. package/dist/core/runtime/placement.d.ts +11 -11
  244. package/dist/core/runtime/placement.js +1 -1
  245. package/dist/core/runtime/promote.d.ts +3 -3
  246. package/dist/core/runtime/promote.js +1 -1
  247. package/dist/core/runtime/recycle.js +1 -1
  248. package/dist/core/runtime/reopen.d.ts +5 -5
  249. package/dist/core/runtime/reopen.js +1 -1
  250. package/dist/core/runtime/reset.d.ts +4 -4
  251. package/dist/core/runtime/reset.js +1 -1
  252. package/dist/core/runtime/revive-all.d.ts +2 -2
  253. package/dist/core/runtime/revive-all.js +1 -1
  254. package/dist/core/runtime/revive.d.ts +4 -4
  255. package/dist/core/runtime/revive.js +2 -2
  256. package/dist/core/runtime/roadmap.d.ts +6 -6
  257. package/dist/core/runtime/roadmap.js +5 -5
  258. package/dist/core/runtime/session-branch.d.ts +1 -1
  259. package/dist/core/runtime/session-branch.js +1 -1
  260. package/dist/core/runtime/session-list-cache.js +1 -1
  261. package/dist/core/runtime/situational-live.js +1 -1
  262. package/dist/core/runtime/spawn.d.ts +2 -2
  263. package/dist/core/runtime/spawn.js +2 -2
  264. package/dist/core/runtime/stop-guard.d.ts +2 -2
  265. package/dist/core/runtime/stop-guard.js +3 -3
  266. package/dist/core/runtime/warm-pool.d.ts +2 -2
  267. package/dist/core/runtime/warm-pool.js +1 -1
  268. package/dist/core/spaces/mounts.d.ts +2 -2
  269. package/dist/core/spaces/mounts.js +1 -1
  270. package/dist/core/spaces/permissions.d.ts +1 -1
  271. package/dist/core/spaces/permissions.js +1 -1
  272. package/dist/core/spaces/process.d.ts +1 -1
  273. package/dist/core/spaces/process.js +1 -1
  274. package/dist/core/spaces/space.js +1 -1
  275. package/dist/core/spaces/stop.d.ts +3 -3
  276. package/dist/core/spaces/stop.js +2 -2
  277. package/dist/core/spaces/users.d.ts +6 -6
  278. package/dist/core/spaces/users.js +1 -1
  279. package/dist/core/storage/attachments.d.ts +2 -2
  280. package/dist/core/storage/attachments.js +1 -1
  281. package/dist/core/storage/shares.d.ts +2 -2
  282. package/dist/core/storage/shares.js +1 -1
  283. package/dist/core/storage/tables.d.ts +21 -21
  284. package/dist/core/storage/tables.js +3 -3
  285. package/dist/core/substrate/delivery/corpus.d.ts +5 -8
  286. package/dist/core/substrate/delivery/corpus.js +3 -3
  287. package/dist/core/substrate/delivery/deliver.d.ts +10 -15
  288. package/dist/core/substrate/delivery/deliver.js +3 -3
  289. package/dist/core/substrate/delivery/plan.d.ts +2 -12
  290. package/dist/core/substrate/delivery/plan.js +3 -3
  291. package/dist/core/substrate/delivery/render-boot.d.ts +4 -4
  292. package/dist/core/substrate/delivery/render-boot.js +18 -18
  293. package/dist/core/substrate/delivery/render-event.d.ts +7 -14
  294. package/dist/core/substrate/delivery/render-event.js +4 -4
  295. package/dist/core/substrate/subject.d.ts +2 -2
  296. package/dist/core/substrate/subject.js +1 -1
  297. package/dist/core/usage/ledger.d.ts +6 -6
  298. package/dist/core/usage/ledger.js +4 -4
  299. package/dist/core/worktree-close.js +4 -4
  300. package/dist/core/worktree-mutation-async.js +7 -7
  301. package/dist/core/worktree-quarantine.js +1 -1
  302. package/dist/core/worktree-sweep.d.ts +1 -1
  303. package/dist/core/worktree-sweep.js +6 -6
  304. package/dist/core/worktree.d.ts +5 -5
  305. package/dist/core/worktree.js +13 -13
  306. package/dist/daemon/analytics/compute.d.ts +2 -2
  307. package/dist/daemon/analytics/compute.js +1 -1
  308. package/dist/daemon/api/app-listener.d.ts +4 -4
  309. package/dist/daemon/api/app-listener.js +13 -13
  310. package/dist/daemon/api/bridge.js +5 -5
  311. package/dist/daemon/api/document-listener.js +6 -6
  312. package/dist/daemon/api/handlers/analytics.js +1 -1
  313. package/dist/daemon/api/handlers/attach.js +1 -1
  314. package/dist/daemon/api/handlers/bash-jobs.js +1 -1
  315. package/dist/daemon/api/handlers/bash.js +1 -1
  316. package/dist/daemon/api/handlers/broker-ops.d.ts +1 -1
  317. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  318. package/dist/daemon/api/handlers/broker-recovery.d.ts +1 -1
  319. package/dist/daemon/api/handlers/broker-recovery.js +1 -1
  320. package/dist/daemon/api/handlers/broker-signals.d.ts +2 -2
  321. package/dist/daemon/api/handlers/broker-signals.js +2 -2
  322. package/dist/daemon/api/handlers/canvas.d.ts +1 -1
  323. package/dist/daemon/api/handlers/canvas.js +4 -4
  324. package/dist/daemon/api/handlers/chat-inventory.js +1 -1
  325. package/dist/daemon/api/handlers/crons.js +1 -1
  326. package/dist/daemon/api/handlers/custom-objects.d.ts +4 -4
  327. package/dist/daemon/api/handlers/custom-objects.js +3 -3
  328. package/dist/daemon/api/handlers/delivery-retry.js +1 -1
  329. package/dist/daemon/api/handlers/delivery.js +1 -1
  330. package/dist/daemon/api/handlers/docs.d.ts +4 -4
  331. package/dist/daemon/api/handlers/docs.js +1 -1
  332. package/dist/daemon/api/handlers/feedback-comments.js +3 -3
  333. package/dist/daemon/api/handlers/files.js +1 -1
  334. package/dist/daemon/api/handlers/focus.js +1 -1
  335. package/dist/daemon/api/handlers/health.js +3 -3
  336. package/dist/daemon/api/handlers/hook-exec.js +1 -1
  337. package/dist/daemon/api/handlers/human-requests.js +1 -1
  338. package/dist/daemon/api/handlers/inbox-page.d.ts +1 -1
  339. package/dist/daemon/api/handlers/inbox-page.js +1 -1
  340. package/dist/daemon/api/handlers/inbox.d.ts +1 -1
  341. package/dist/daemon/api/handlers/inbox.js +1 -1
  342. package/dist/daemon/api/handlers/llm.d.ts +1 -1
  343. package/dist/daemon/api/handlers/llm.js +3 -3
  344. package/dist/daemon/api/handlers/memory-reads.js +1 -1
  345. package/dist/daemon/api/handlers/memory.d.ts +5 -5
  346. package/dist/daemon/api/handlers/memory.js +5 -5
  347. package/dist/daemon/api/handlers/messages.js +2 -2
  348. package/dist/daemon/api/handlers/node-events.d.ts +2 -2
  349. package/dist/daemon/api/handlers/node-events.js +3 -3
  350. package/dist/daemon/api/handlers/node-outcomes.js +1 -1
  351. package/dist/daemon/api/handlers/node-records.js +2 -2
  352. package/dist/daemon/api/handlers/nodes.d.ts +1 -1
  353. package/dist/daemon/api/handlers/nodes.js +1 -1
  354. package/dist/daemon/api/handlers/objects.js +3 -3
  355. package/dist/daemon/api/handlers/package-docs.js +1 -1
  356. package/dist/daemon/api/handlers/plugin-app-token.d.ts +1 -1
  357. package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
  358. package/dist/daemon/api/handlers/profiles.d.ts +3 -3
  359. package/dist/daemon/api/handlers/profiles.js +1 -1
  360. package/dist/daemon/api/handlers/providers.d.ts +1 -1
  361. package/dist/daemon/api/handlers/providers.js +1 -1
  362. package/dist/daemon/api/handlers/questions.js +1 -1
  363. package/dist/daemon/api/handlers/reports.d.ts +1 -1
  364. package/dist/daemon/api/handlers/reports.js +5 -5
  365. package/dist/daemon/api/handlers/review-comments.js +1 -1
  366. package/dist/daemon/api/handlers/reviews.js +1 -1
  367. package/dist/daemon/api/handlers/runs.js +1 -1
  368. package/dist/daemon/api/handlers/structured-requests.js +1 -1
  369. package/dist/daemon/api/handlers/subscriptions.js +1 -1
  370. package/dist/daemon/api/handlers/transfer.js +1 -1
  371. package/dist/daemon/api/map.d.ts +3 -3
  372. package/dist/daemon/api/map.js +1 -1
  373. package/dist/daemon/api/principal.d.ts +1 -1
  374. package/dist/daemon/api/principal.js +1 -1
  375. package/dist/daemon/api/reader.d.ts +5 -5
  376. package/dist/daemon/api/reader.js +1 -1
  377. package/dist/daemon/api/router.d.ts +5 -5
  378. package/dist/daemon/api/router.js +1 -1
  379. package/dist/daemon/api/server.js +1 -1
  380. package/dist/daemon/broker-signals/bus.d.ts +1 -1
  381. package/dist/daemon/broker-signals/bus.js +1 -1
  382. package/dist/daemon/companion-retire.js +1 -1
  383. package/dist/daemon/cron/armed-context.d.ts +2 -2
  384. package/dist/daemon/cron/armed-context.js +1 -1
  385. package/dist/daemon/cron/authority.d.ts +2 -2
  386. package/dist/daemon/cron/authority.js +1 -1
  387. package/dist/daemon/cron/disposition.js +1 -1
  388. package/dist/daemon/cron/ended.d.ts +1 -1
  389. package/dist/daemon/cron/ended.js +2 -2
  390. package/dist/daemon/cron/escalation.js +3 -3
  391. package/dist/daemon/cron/folders.d.ts +1 -1
  392. package/dist/daemon/cron/folders.js +1 -1
  393. package/dist/daemon/cron/held.d.ts +1 -1
  394. package/dist/daemon/cron/held.js +1 -1
  395. package/dist/daemon/cron/lease-recovery.d.ts +1 -1
  396. package/dist/daemon/cron/lease-recovery.js +1 -1
  397. package/dist/daemon/cron/passes.d.ts +2 -2
  398. package/dist/daemon/cron/passes.js +1 -1
  399. package/dist/daemon/cron/run-socket.d.ts +1 -1
  400. package/dist/daemon/cron/run-socket.js +1 -1
  401. package/dist/daemon/cron/settle.js +1 -1
  402. package/dist/daemon/cron/sinks.d.ts +1 -1
  403. package/dist/daemon/cron/sinks.js +2 -2
  404. package/dist/daemon/cron-run.d.ts +12 -3
  405. package/dist/daemon/cron-run.js +2 -2
  406. package/dist/daemon/crtrd.js +6 -6
  407. package/dist/daemon/delivery/run-delivery.js +1 -1
  408. package/dist/daemon/due-sources.d.ts +3 -3
  409. package/dist/daemon/due-sources.js +1 -1
  410. package/dist/daemon/due.d.ts +3 -3
  411. package/dist/daemon/due.js +7 -7
  412. package/dist/daemon/fleet.d.ts +2 -2
  413. package/dist/daemon/fleet.js +11 -11
  414. package/dist/daemon/human/finish.js +3 -3
  415. package/dist/daemon/human/settle.d.ts +1 -1
  416. package/dist/daemon/human/settle.js +1 -1
  417. package/dist/daemon/human/sweep.js +1 -1
  418. package/dist/daemon/joined-owner.d.ts +2 -2
  419. package/dist/daemon/joined-owner.js +1 -1
  420. package/dist/daemon/messaging/node-message.js +1 -1
  421. package/dist/daemon/park-activity.d.ts +2 -2
  422. package/dist/daemon/park-activity.js +1 -1
  423. package/dist/daemon/peer/authority.js +1 -1
  424. package/dist/daemon/peer/forward.d.ts +6 -6
  425. package/dist/daemon/peer/forward.js +1 -1
  426. package/dist/daemon/peer/handlers.js +1 -1
  427. package/dist/daemon/peer/ingress.d.ts +4 -4
  428. package/dist/daemon/peer/ingress.js +1 -1
  429. package/dist/daemon/peer/outbox.d.ts +2 -2
  430. package/dist/daemon/peer/outbox.js +1 -1
  431. package/dist/daemon/peer/relay-service.js +1 -1
  432. package/dist/daemon/plugin-objects/read-leaf.d.ts +2 -2
  433. package/dist/daemon/plugin-objects/read-leaf.js +2 -2
  434. package/dist/daemon/profile-delete.js +1 -1
  435. package/dist/daemon/readiness.d.ts +2 -2
  436. package/dist/daemon/readiness.js +1 -1
  437. package/dist/daemon/reconcilers/action-lane.d.ts +1 -1
  438. package/dist/daemon/reconcilers/action-lane.js +1 -1
  439. package/dist/daemon/reconcilers/bash-deadline.js +2 -2
  440. package/dist/daemon/reconcilers/broker-supervision.d.ts +1 -1
  441. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  442. package/dist/daemon/reconcilers/controller-death.d.ts +1 -1
  443. package/dist/daemon/reconcilers/controller-death.js +1 -1
  444. package/dist/daemon/reconcilers/cron-lane.d.ts +1 -1
  445. package/dist/daemon/reconcilers/cron-lane.js +1 -1
  446. package/dist/daemon/reconcilers/delivery-lane.d.ts +1 -1
  447. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  448. package/dist/daemon/reconcilers/fault-retry-backstop.d.ts +3 -3
  449. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  450. package/dist/daemon/reconcilers/grove-instance-sweep.d.ts +2 -2
  451. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  452. package/dist/daemon/reconcilers/live-obligation.d.ts +6 -6
  453. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  454. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  455. package/dist/daemon/reconcilers/node-deadline.d.ts +1 -1
  456. package/dist/daemon/reconcilers/node-deadline.js +1 -1
  457. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  458. package/dist/daemon/reconcilers/node-lifecycle/respawn-policy.d.ts +3 -3
  459. package/dist/daemon/reconcilers/node-lifecycle/respawn-policy.js +1 -1
  460. package/dist/daemon/reconcilers/node-lifecycle/terminating.js +1 -1
  461. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  462. package/dist/daemon/reconcilers/node-lifecycle/wants-execution.d.ts +1 -1
  463. package/dist/daemon/reconcilers/node-lifecycle/wants-execution.js +1 -1
  464. package/dist/daemon/reconcilers/pending-review-submit.d.ts +1 -1
  465. package/dist/daemon/reconcilers/pending-review-submit.js +1 -1
  466. package/dist/daemon/reconcilers/storage-due-work.js +1 -1
  467. package/dist/daemon/reconcilers/storage-maintenance.d.ts +1 -1
  468. package/dist/daemon/reconcilers/storage-maintenance.js +2 -2
  469. package/dist/daemon/reconcilers/structured-request-lane.d.ts +1 -1
  470. package/dist/daemon/reconcilers/structured-request-lane.js +1 -1
  471. package/dist/daemon/review/comment-notify.js +2 -2
  472. package/dist/daemon/review/companion.d.ts +3 -3
  473. package/dist/daemon/review/companion.js +1 -1
  474. package/dist/daemon/review/finish.js +1 -1
  475. package/dist/daemon/review/sweep.js +1 -1
  476. package/dist/daemon/run-notices.d.ts +4 -4
  477. package/dist/daemon/run-notices.js +1 -1
  478. package/dist/daemon/runs/append-section.d.ts +2 -2
  479. package/dist/daemon/runs/append-section.js +2 -2
  480. package/dist/daemon/runs/observer.d.ts +2 -2
  481. package/dist/daemon/runs/observer.js +2 -2
  482. package/dist/daemon/structured-requests/boot.d.ts +1 -1
  483. package/dist/daemon/structured-requests/boot.js +1 -1
  484. package/dist/daemon/structured-requests/effects.js +1 -1
  485. package/dist/daemon/structured-requests/sidecar.d.ts +1 -1
  486. package/dist/daemon/structured-requests/sidecar.js +1 -1
  487. package/dist/migrations/004-canvas-documents/apply.d.ts +3 -3
  488. package/dist/migrations/004-canvas-documents/apply.js +1 -1
  489. package/dist/migrations/004-canvas-documents/index.d.ts +2 -2
  490. package/dist/migrations/004-canvas-documents/index.js +2 -2
  491. package/dist/migrations/activation.js +2 -2
  492. package/docs/public-api.md +11 -0
  493. package/package.json +3 -2
  494. package/packages/crouter-identity/package.json +1 -1
  495. package/runtime.lock.json +12 -12
@@ -1,4 +1,4 @@
1
- import type { DatabaseSync } from 'node:sqlite';
1
+ import { type CanvasDb } from '../canvas/db.js';
2
2
  /** A node's run and whether that run is isolated (the node's own flag or its root's). */
3
3
  export interface RunPlace {
4
4
  run: string;
@@ -7,19 +7,19 @@ export interface RunPlace {
7
7
  /** The run a node belongs to: its `run_id`, or the node itself when it has none.
8
8
  * A deleted node of an isolated run keeps its run through `deleted_isolated_nodes`,
9
9
  * so what it leaves behind stays confined; any other node without a row is null. */
10
- export declare function runPlace(nodeId: string, db?: DatabaseSync): RunPlace | null;
10
+ export declare function runPlace(nodeId: string, db?: CanvasDb): Promise<RunPlace | null>;
11
11
  /** Record, before a node's row is deleted, the run of a node of an isolated run. */
12
- export declare function rememberDeletedIsolated(nodeId: string, db?: DatabaseSync): void;
12
+ export declare function rememberDeletedIsolated(nodeId: string, db?: CanvasDb): Promise<void>;
13
13
  /** The place of the node that registered a custom object, which is where that object
14
14
  * reads from; null when the person or the app's server registered it. */
15
- export declare function objectPlace(objectRowid: number, db?: DatabaseSync): RunPlace | null;
15
+ export declare function objectPlace(objectRowid: number, db?: CanvasDb): Promise<RunPlace | null>;
16
16
  /** The confinement predicate: two places see each other when they are the same
17
17
  * run, or when neither run is isolated. */
18
18
  export declare function runsSeeEachOther(a: RunPlace, b: RunPlace): boolean;
19
19
  /** Whether a node caller of `app` may reach `target` (a node id) under run confinement.
20
20
  * Confinement applies only within one app; cross-app reach stays with the scope rules. */
21
- export declare function nodeMayReach(callerNode: string, callerApp: string, targetNode: string, targetApp: string | null, db?: DatabaseSync): boolean;
21
+ export declare function nodeMayReach(callerNode: string, callerApp: string, targetNode: string, targetApp: string | null, db?: CanvasDb): Promise<boolean>;
22
22
  /** The same question for a caller that has a place but no node (a cron command: its origin run). */
23
- export declare function placeMayReach(caller: RunPlace, callerApp: string, targetNode: string, targetApp: string | null, db?: DatabaseSync): boolean;
23
+ export declare function placeMayReach(caller: RunPlace, callerApp: string, targetNode: string, targetApp: string | null, db?: CanvasDb): Promise<boolean>;
24
24
  /** The node ids of one run (its root and every node carrying its `run_id`). */
25
- export declare function runNodeIds(run: string, db?: DatabaseSync): string[];
25
+ export declare function runNodeIds(run: string, db?: CanvasDb): Promise<string[]>;
@@ -1,2 +1,2 @@
1
- var a=Object.defineProperty;var n=(e,r)=>a(e,"name",{value:r,configurable:!0});import{openDb as i,prepared as u}from"../canvas/db.js";function l(e,r=i()){const t=u(r,`SELECT n.run_id, n.isolated, r.isolated AS root_isolated FROM nodes n
2
- LEFT JOIN nodes r ON r.node_id = n.run_id WHERE n.node_id = ?`).get(e);if(!t){const o=u(r,"SELECT run_id FROM deleted_isolated_nodes WHERE node_id = ?").get(e);return o?{run:o.run_id,isolated:!0}:null}return{run:t.run_id??e,isolated:t.isolated===1||t.root_isolated===1}}n(l,"runPlace");function R(e,r=i()){const t=l(e,r);t?.isolated&&u(r,"INSERT OR REPLACE INTO deleted_isolated_nodes (node_id, run_id) VALUES (?, ?)").run(e,t.run)}n(R,"rememberDeletedIsolated");function f(e,r=i()){const t=u(r,"SELECT registered_by FROM custom_objects WHERE object = ?").get(e);return t?.registered_by?l(t.registered_by,r)??{run:t.registered_by,isolated:!1}:null}n(f,"objectPlace");function _(e,r){return e.run===r.run||!e.isolated&&!r.isolated}n(_,"runsSeeEachOther");function O(e,r,t,o,s=i()){const d=l(e,s);return d===null?!0:c(d,r,t,o,s)}n(O,"nodeMayReach");function c(e,r,t,o,s=i()){if((o??"app:terminal")!==r)return!0;const d=l(t,s);return d===null?!e.isolated:_(e,d)}n(c,"placeMayReach");function g(e,r=i()){return u(r,"SELECT node_id FROM nodes WHERE run_id = ? OR node_id = ?").all(e,e).map(t=>t.node_id)}n(g,"runNodeIds");export{O as nodeMayReach,f as objectPlace,c as placeMayReach,R as rememberDeletedIsolated,g as runNodeIds,l as runPlace,_ as runsSeeEachOther};
1
+ var d=Object.defineProperty;var n=(t,e)=>d(t,"name",{value:e,configurable:!0});import{openDb as o}from"../canvas/db.js";async function u(t,e){e??=await o();const r=await e.prepare(`SELECT n.run_id, n.isolated, r.isolated AS root_isolated FROM nodes n
2
+ LEFT JOIN nodes r ON r.node_id = n.run_id WHERE n.node_id = ?`).get(t);if(!r){const a=await e.prepare("SELECT run_id FROM deleted_isolated_nodes WHERE node_id = ?").get(t);return a?{run:a.run_id,isolated:!0}:null}return{run:r.run_id??t,isolated:r.isolated===1||r.root_isolated===1}}n(u,"runPlace");async function E(t,e){e??=await o();const r=await u(t,e);r?.isolated&&await e.prepare("INSERT OR REPLACE INTO deleted_isolated_nodes (node_id, run_id) VALUES (?, ?)").run(t,r.run)}n(E,"rememberDeletedIsolated");async function w(t,e){e??=await o();const r=await e.prepare("SELECT registered_by FROM custom_objects WHERE object = ?").get(t);return r?.registered_by?await u(r.registered_by,e)??{run:r.registered_by,isolated:!1}:null}n(w,"objectPlace");function l(t,e){return t.run===e.run||!t.isolated&&!e.isolated}n(l,"runsSeeEachOther");async function R(t,e,r,a,i){i??=await o();const s=await u(t,i);return s===null?!0:await c(s,e,r,a,i)}n(R,"nodeMayReach");async function c(t,e,r,a,i){if(i??=await o(),(a??"app:terminal")!==e)return!0;const s=await u(r,i);return s===null?!t.isolated:l(t,s)}n(c,"placeMayReach");async function f(t,e){return e??=await o(),(await e.prepare("SELECT node_id FROM nodes WHERE run_id = ? OR node_id = ?").all(t,t)).map(r=>r.node_id)}n(f,"runNodeIds");export{R as nodeMayReach,w as objectPlace,c as placeMayReach,E as rememberDeletedIsolated,f as runNodeIds,u as runPlace,l as runsSeeEachOther};
@@ -1,29 +1,29 @@
1
- import type { DatabaseSync } from 'node:sqlite';
1
+ import { type CanvasDb } from '../canvas/db.js';
2
2
  import type { RunEvent, RunEventFields, RunEventOf, RunEventType } from '../../api/dto/run-events.js';
3
3
  /** Every event on a run's stream, declared once in the API contract. */
4
4
  export type { RunEvent, RunEventType, RunEventOf, RunEventFields } from '../../api/dto/run-events.js';
5
5
  /** The run-notice outbox's hook: called (after the appender's commit) for every event appended to a run. */
6
- export declare function onRunEventAppended(hook: ((runId: string) => void) | undefined): void;
6
+ export declare function onRunEventAppended(hook: ((runId: string) => void | Promise<void>) | undefined): void;
7
7
  /** Append one event to a run's log. `type` must be a declared run event and `fields` its fields. */
8
- export declare function appendRunEvent<T extends RunEventType>(db: DatabaseSync, runId: string, nodeId: string, type: T, fields: RunEventFields<T>): RunEventOf<T>;
9
- export declare function emitRunEvent<T extends RunEventType>(runId: string, nodeId: string, type: T, fields: RunEventFields<T>): RunEventOf<T>;
10
- export declare function emitRunSettlement<T extends 'node.settled' | 'child.settled'>(runId: string, nodeId: string, type: T, fields: RunEventFields<T>): void;
11
- export declare function readRunEvents(runId: string, after?: number): {
8
+ export declare function appendRunEvent<T extends RunEventType>(db: CanvasDb, runId: string, nodeId: string, type: T, fields: RunEventFields<T>): Promise<RunEventOf<T>>;
9
+ export declare function emitRunEvent<T extends RunEventType>(runId: string, nodeId: string, type: T, fields: RunEventFields<T>): Promise<RunEventOf<T>>;
10
+ export declare function emitRunSettlement<T extends 'node.settled' | 'child.settled'>(runId: string, nodeId: string, type: T, fields: RunEventFields<T>): Promise<void>;
11
+ export declare function readRunEvents(runId: string, after?: number): Promise<{
12
12
  events: RunEvent[];
13
13
  earliest_sequence: number | null;
14
14
  latest_sequence: number;
15
15
  backlog_count: number;
16
16
  backlog_bytes: number;
17
- };
18
- export declare function subscribeRunEvents(runId: string, wake: () => void): () => void;
17
+ }>;
18
+ export declare function subscribeRunEvents(runId: string, wake: () => void): Promise<() => void>;
19
19
  export declare function notifyRunDeleted(runId: string): void;
20
20
  /** OWN-11 for a joined runtime: the legacy `user:local` grantee is the terminal app. */
21
- export declare function rewriteLocalRunEventGrantee(db: DatabaseSync): number;
21
+ export declare function rewriteLocalRunEventGrantee(db: CanvasDb): Promise<number>;
22
22
  /** A run event cursor stays monotonic. Keep control/settlement/usage history
23
23
  * for the observer's 30-day recovery window, but full payload events for 14
24
24
  * days only; older conversation content is in the transcript store. The stream
25
25
  * already signals a cursor gap when events have expired. Budget one page/tick. */
26
- export declare function expireRunEvents(now: number, limit?: number): number;
26
+ export declare function expireRunEvents(now: number, limit?: number): Promise<number>;
27
27
  /** The conversation store is the canonical full transcript. Keep the full
28
28
  * stream for one day, then redact settled tool calls, prompts and thinking.
29
29
  * This includes older completed events of a still-live run, but tool-call
@@ -31,10 +31,10 @@ export declare function expireRunEvents(now: number, limit?: number): number;
31
31
  * An open turn's deltas and status/settlement markers are never redacted. Cursor scans
32
32
  * avoid re-searching the whole log each tick. Old event payload replay is a
33
33
  * deliberate tradeoff; event identities and 30-day sequence gaps survive. */
34
- export declare function compactRunEvents(now: number, afterRowid?: number, scanLimit?: number, writeLimit?: number): {
34
+ export declare function compactRunEvents(now: number, afterRowid?: number, scanLimit?: number, writeLimit?: number): Promise<{
35
35
  cursor: number;
36
36
  compacted: number;
37
- };
37
+ }>;
38
38
  /** Track an open `run.events` stream an app caller holds under `grant`. */
39
39
  export declare function registerGrantStream(grant: string, close: () => void): () => void;
40
40
  /** Close every open stream held under a grant that is no longer active. */
@@ -1,7 +1,7 @@
1
- var g=Object.defineProperty;var c=(e,t)=>g(e,"name",{value:t,configurable:!0});import{prepared as u}from"../sqlite-statements.js";import{openDb as y,withCanvasWrite as l}from"../canvas/db.js";import{repairRunConversations as O}from"../canvas/sessions.js";const _=new Map;let R;function D(e){R=e}c(D,"onRunEventAppended");function f(e,t,n,r,s){const o=u(e,"SELECT event_cursor, grantee, metadata_json FROM node_rows WHERE node_id = ? AND run_id = ?").get(t,t);if(!o||o.event_cursor===null)throw new Error(`missing run event cursor: ${t}`);const i={type:r,run_id:t,node_id:n,sequence_number:o.event_cursor,ts:new Date().toISOString(),metadata:o.metadata_json?JSON.parse(o.metadata_json):{},...s};return u(e,"INSERT INTO run_events (run_id, sequence_number, node_id, type, ts, body_json, grantee) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t,i.sequence_number,n,r,i.ts,JSON.stringify(i),o.grantee),u(e,"UPDATE nodes SET event_cursor = event_cursor + 1, last_activity_at = ? WHERE node_id = ?").run(i.ts,t),queueMicrotask(()=>{for(const d of _.get(t)??[])d();try{R?.(t)}catch{}}),i}c(f,"appendRunEvent");function M(e,t,n,r){return l(s=>f(s,e,t,n,r))}c(M,"emitRunEvent");function L(e,t,n,r){l(s=>{u(s,"SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = ? AND json_extract(body_json, '$.outcome.revision') = ? LIMIT 1").get(e,t,n,r.outcome.revision)||f(s,e,t,n,r)})}c(L,"emitRunSettlement");function A(e,t=0){O(e);const n=y(),r=u(n,"SELECT event_cursor FROM nodes WHERE node_id = ? AND run_id = ?").get(e,e);if(!r)throw new Error(`run not found: ${e}`);const s=u(n,"SELECT MIN(sequence_number) AS sequence FROM run_events WHERE run_id = ?").get(e),o=u(n,"SELECT COUNT(*) AS count, COALESCE(SUM(LENGTH(body_json)), 0) AS bytes FROM run_events WHERE run_id = ? AND sequence_number > ?").get(e,t);return{events:(o.count>1e3||o.bytes>32*1024*1024?[]:u(n,"SELECT body_json FROM run_events WHERE run_id = ? AND sequence_number > ? ORDER BY sequence_number LIMIT 1000").all(e,t)).map(d=>JSON.parse(d.body_json)),earliest_sequence:s.sequence,latest_sequence:r.event_cursor-1,backlog_count:o.count,backlog_bytes:o.bytes}}c(A,"readRunEvents");function C(e,t){let n=_.get(e);return n||(n=new Set,_.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&_.delete(e)}}c(C,"subscribeRunEvents");function H(e){queueMicrotask(()=>{for(const t of _.get(e)??[])t()})}c(H,"notifyRunDeleted");function x(e){return Number(u(e,"UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}c(x,"rewriteLocalRunEventGrantee");function W(e,t=128){return l(n=>{const r=new Date(e-12096e5).toISOString(),s=new Date(e-720*60*6e4).toISOString(),o=Number(u(n,`DELETE FROM run_events WHERE rowid IN
1
+ var v=Object.defineProperty;var a=(e,t)=>v(e,"name",{value:t,configurable:!0});import{afterCommit as y,withCanvasWrite as _,openDb as S}from"../canvas/db.js";import{emitEvent as g}from"../events/emit.js";import{repairRunConversations as O}from"../canvas/sessions.js";const E=new Map;let w;function L(e){w=e}a(L,"onRunEventAppended");async function f(e,t,n,r,s){const o=await e.prepare("SELECT event_cursor, grantee, metadata_json FROM node_rows WHERE node_id = ? AND run_id = ?").get(t,t);if(!o||o.event_cursor===null)throw new Error(`missing run event cursor: ${t}`);const i={type:r,run_id:t,node_id:n,sequence_number:o.event_cursor,ts:new Date().toISOString(),metadata:o.metadata_json?JSON.parse(o.metadata_json):{},...s};return await e.prepare("INSERT INTO run_events (run_id, sequence_number, node_id, type, ts, body_json, grantee) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t,i.sequence_number,n,r,i.ts,JSON.stringify(i),o.grantee),await e.prepare("UPDATE nodes SET event_cursor = event_cursor + 1, last_activity_at = ? WHERE node_id = ?").run(i.ts,t),y(()=>{for(const d of E.get(t)??[])d();const u=a(d=>{g({level:"error",event:"runs.notice_hook_failed",error:d})},"failed");try{Promise.resolve(w?.(t)).catch(u)}catch(d){u(d)}}),i}a(f,"appendRunEvent");async function M(e,t,n,r){return await _(async s=>await f(s,e,t,n,r))}a(M,"emitRunEvent");async function A(e,t,n,r){await _(async s=>{await s.prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = ? AND json_extract(body_json, '$.outcome.revision') = ? LIMIT 1").get(e,t,n,r.outcome.revision)||await f(s,e,t,n,r)})}a(A,"emitRunSettlement");async function C(e,t=0){await O(e);const n=await S(),r=await n.prepare("SELECT event_cursor FROM nodes WHERE node_id = ? AND run_id = ?").get(e,e);if(!r)throw new Error(`run not found: ${e}`);const s=await n.prepare("SELECT MIN(sequence_number) AS sequence FROM run_events WHERE run_id = ?").get(e),o=await n.prepare("SELECT COUNT(*) AS count, COALESCE(SUM(LENGTH(body_json)), 0) AS bytes FROM run_events WHERE run_id = ? AND sequence_number > ?").get(e,t);return{events:(o.count>1e3||o.bytes>32*1024*1024?[]:await n.prepare("SELECT body_json FROM run_events WHERE run_id = ? AND sequence_number > ? ORDER BY sequence_number LIMIT 1000").all(e,t)).map(u=>JSON.parse(u.body_json)),earliest_sequence:s.sequence,latest_sequence:r.event_cursor-1,backlog_count:o.count,backlog_bytes:o.bytes}}a(C,"readRunEvents");async function H(e,t){let n=E.get(e);return n||(n=new Set,E.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&E.delete(e)}}a(H,"subscribeRunEvents");function x(e){queueMicrotask(()=>{for(const t of E.get(e)??[])t()})}a(x,"notifyRunDeleted");async function W(e){return Number((await e.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run()).changes)}a(W,"rewriteLocalRunEventGrantee");async function h(e,t=128){return await _(async n=>{const r=new Date(e-12096e5).toISOString(),s=new Date(e-720*60*6e4).toISOString(),o=Number((await n.prepare(`DELETE FROM run_events WHERE rowid IN
2
2
  (SELECT rowid FROM run_events WHERE ts < ? AND type IN
3
3
  ('node.tool_call.completed', 'node.tool_call.started', 'node.system_prompt.set',
4
- 'node.thinking.done', 'node.output_text.done') ORDER BY ts LIMIT ?)`).run(r,t).changes),i=Number(u(n,`DELETE FROM run_events WHERE rowid IN
5
- (SELECT rowid FROM run_events WHERE ts < ? ORDER BY ts LIMIT ?)`).run(s,t-o).changes);return o+i})}c(W,"expireRunEvents");function h(e,t=0,n=256,r=8){return l(s=>{const o=u(s,`SELECT e.rowid, e.type, e.ts, length(e.body_json) AS bytes,
4
+ 'node.thinking.done', 'node.output_text.done') ORDER BY ts LIMIT ?)`).run(r,t)).changes),i=Number((await n.prepare(`DELETE FROM run_events WHERE rowid IN
5
+ (SELECT rowid FROM run_events WHERE ts < ? ORDER BY ts LIMIT ?)`).run(s,t-o)).changes);return o+i})}a(h,"expireRunEvents");async function j(e,t=0,n=256,r=8){return await _(async s=>{const o=await s.prepare(`SELECT e.rowid, e.type, e.ts, length(e.body_json) AS bytes,
6
6
  n.finalized_at FROM run_events e LEFT JOIN nodes n ON n.node_id = e.node_id
7
- WHERE e.rowid > ? ORDER BY e.rowid LIMIT ?`).all(t,n);if(!o.length)return{cursor:0,compacted:0};let i=0,d=t;const m=new Date(e-1440*6e4).toISOString(),S=u(s,"SELECT body_json FROM run_events WHERE rowid = ?"),v=u(s,"UPDATE run_events SET body_json = ? WHERE rowid = ?");for(const a of o){if(d=a.rowid,!["node.tool_call.completed","node.tool_call.started","node.system_prompt.set","node.thinking.done"].includes(a.type)||a.ts>=m||a.bytes<1024||a.type==="node.tool_call.started"&&!a.finalized_at)continue;const E=JSON.parse(S.get(a.rowid).body_json);if(E.content_redacted!==!0&&(a.type==="node.tool_call.completed"?delete E.result:a.type==="node.tool_call.started"?delete E.arguments:delete E.text,E.content_redacted=!0,v.run(JSON.stringify(E),a.rowid),++i>=r))break}return{cursor:d,compacted:i}})}c(h,"compactRunEvents");const p=new Map;function j(e,t){let n=p.get(e);return n||(n=new Set,p.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&p.delete(e)}}c(j,"registerGrantStream");function q(e){const t=[...p.get(e)??[]];for(const n of t)n();return t.length}c(q,"closeGrantStreams");export{f as appendRunEvent,q as closeGrantStreams,h as compactRunEvents,M as emitRunEvent,L as emitRunSettlement,W as expireRunEvents,H as notifyRunDeleted,D as onRunEventAppended,A as readRunEvents,j as registerGrantStream,x as rewriteLocalRunEventGrantee,C as subscribeRunEvents};
7
+ WHERE e.rowid > ? ORDER BY e.rowid LIMIT ?`).all(t,n);if(!o.length)return{cursor:0,compacted:0};let i=0,u=t;const d=new Date(e-1440*6e4).toISOString(),R=s.prepare("SELECT body_json FROM run_events WHERE rowid = ?"),m=s.prepare("UPDATE run_events SET body_json = ? WHERE rowid = ?");for(const c of o){if(u=c.rowid,!["node.tool_call.completed","node.tool_call.started","node.system_prompt.set","node.thinking.done"].includes(c.type)||c.ts>=d||c.bytes<1024||c.type==="node.tool_call.started"&&!c.finalized_at)continue;const p=JSON.parse((await R.get(c.rowid)).body_json);if(p.content_redacted!==!0&&(c.type==="node.tool_call.completed"?delete p.result:c.type==="node.tool_call.started"?delete p.arguments:delete p.text,p.content_redacted=!0,await m.run(JSON.stringify(p),c.rowid),++i>=r))break}return{cursor:u,compacted:i}})}a(j,"compactRunEvents");const l=new Map;function F(e,t){let n=l.get(e);return n||(n=new Set,l.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&l.delete(e)}}a(F,"registerGrantStream");function q(e){const t=[...l.get(e)??[]];for(const n of t)n();return t.length}a(q,"closeGrantStreams");export{f as appendRunEvent,q as closeGrantStreams,j as compactRunEvents,M as emitRunEvent,A as emitRunSettlement,h as expireRunEvents,x as notifyRunDeleted,L as onRunEventAppended,C as readRunEvents,F as registerGrantStream,W as rewriteLocalRunEventGrantee,H as subscribeRunEvents};
@@ -1,4 +1,4 @@
1
- import type { DatabaseSync } from 'node:sqlite';
1
+ import { type CanvasDb } from '../canvas/db.js';
2
2
  import type { NodeMeta } from '../canvas/types.js';
3
3
  import type { AppPrincipal } from '../../daemon/api/principal.js';
4
4
  import { type ResolvedAttachments } from '../storage/attachments.js';
@@ -13,7 +13,7 @@ export interface StorageDeps {
13
13
  budgetMs?: number;
14
14
  }
15
15
  /** OWN-11 for a joined runtime: the legacy `user:local` grantee is the terminal app. */
16
- export declare function rewriteLocalIdempotencyGrantee(db: DatabaseSync): number;
16
+ export declare function rewriteLocalIdempotencyGrantee(db: CanvasDb): Promise<number>;
17
17
  export declare class RunError extends Error {
18
18
  readonly status: number;
19
19
  readonly code: string;
@@ -23,17 +23,17 @@ export declare class RunError extends Error {
23
23
  readonly retryable: boolean;
24
24
  constructor(status: number, code: string, message: string, param?: string | undefined, details?: unknown | undefined, scope?: string | undefined, retryable?: boolean);
25
25
  }
26
- export declare function ownedRun(id: string, grantee: string, allowDeleting?: boolean): NodeMeta;
26
+ export declare function ownedRun(id: string, grantee: string, allowDeleting?: boolean): Promise<NodeMeta>;
27
27
  export type RunStatus = 'running' | 'waiting_on_user' | 'idle' | 'settled';
28
28
  /** Whether the run has a turn in flight or work owed to it (the `running` run status). */
29
- export declare function runIsRunning(runId: string): boolean;
30
- export declare function runObject(root: NodeMeta): Record<string, unknown>;
29
+ export declare function runIsRunning(runId: string): Promise<boolean>;
30
+ export declare function runObject(root: NodeMeta): Promise<Record<string, unknown>>;
31
31
  /** How long a kept key replays: a record this old or older reads as absent. The SDK's conformance scenarios hold FakeCloud to it. */
32
32
  export declare const IDEMPOTENCY_WINDOW_MS = 86400000;
33
33
  /** An `Idempotency-Key` header value: absent, or 1–255 characters. */
34
34
  export declare function idempotencyKeyOf(header: unknown): string | undefined;
35
35
  /** Delete keys past their window; returns how many were removed. */
36
- export declare function pruneExpiredIdempotencyKeys(now?: number): number;
36
+ export declare function pruneExpiredIdempotencyKeys(now?: number): Promise<number>;
37
37
  /** Longest `run.start` deadline an app may set: 24 hours. The grammar is `crtr node new --deadline`'s (parts of `<int>[smhd]`, summed). */
38
38
  export declare const RUN_DEADLINE_MAX_MS: number;
39
39
  /** The milliseconds of a `run.start` `deadline` duration; refuses a malformed, zero, or over-24h value as `invalid_request` on `deadline`. */
@@ -54,11 +54,11 @@ export declare function listRuns(grantee: string | null, options: {
54
54
  status?: string;
55
55
  after?: string;
56
56
  limit: number;
57
- visible?: (runId: string) => boolean;
58
- }): {
57
+ visible?: (runId: string) => Promise<boolean>;
58
+ }): Promise<{
59
59
  runs: Record<string, unknown>[];
60
60
  next: string | null;
61
- };
61
+ }>;
62
62
  export declare function waitRun(id: string, grantee: string, seconds: number): Promise<Record<string, unknown>>;
63
63
  export declare function messageRun(root: NodeMeta, original: string, resolveAttachments?: AttachmentResolver, startTurn?: boolean, idempotencyKey?: string): Promise<{
64
64
  run_id: string;
@@ -73,11 +73,11 @@ export declare function cancelRun(root: NodeMeta, _options?: {
73
73
  export declare const RUN_NAME_MAX = 200;
74
74
  /** `run.rename`: set the root node's name — the name `crtr` shows for the node —
75
75
  * through the same path as `PATCH /v1/nodes/:id/config` `name`. */
76
- export declare function renameRun(root: NodeMeta, name: unknown): Record<string, unknown>;
76
+ export declare function renameRun(root: NodeMeta, name: unknown): Promise<Record<string, unknown>>;
77
77
  /** Delete a run. Answers how many of the run's released uploads storage has
78
78
  * not confirmed deleted; the due-work tick retries those. */
79
79
  export declare function deleteRun(root: NodeMeta, storage?: StorageDeps): Promise<{
80
80
  uploads_pending: number;
81
81
  }>;
82
- export declare function traceRun(id: string, grantee: string, format?: string): Record<string, unknown>;
82
+ export declare function traceRun(id: string, grantee: string, format?: string): Promise<Record<string, unknown>>;
83
83
  export declare function requestedScopes(held: readonly string[], value: unknown, grantee: string): string[] | null;
@@ -1,12 +1,12 @@
1
- var ve=Object.defineProperty;var m=(e,t)=>ve(e,"name",{value:t,configurable:!0});import{prepared as w}from"../sqlite-statements.js";import{coveredByAny as be}from"../../shared/env.js";import{createHash as G}from"node:crypto";import{ApiError as Oe}from"../../api/errors.js";import{CrtrError as De}from"../errors.js";import{isAbsolute as X,relative as Ie,resolve as Me,sep as Te,join as Ae}from"node:path";import{SessionManager as Le}from"@earendil-works/pi-coding-agent";import{covers as F}from"@north-light/identity";import{openDb as z,withCanvasWrite as C}from"../canvas/db.js";import{deleteNodeWithOwned as Ce}from"../graph/deletion.js";import{getById as xe}from"../graph/objects.js";import{repairRunConversations as Q}from"../canvas/sessions.js";import{getNode as v,nodeFiles as ke,removeNodeFiles as We,updateNode as Fe}from"../canvas/canvas.js";import{fullName as He}from"../canvas/labels.js";import{renameWindow as qe}from"../runtime/placement.js";import{liveExecutionForNode as V}from"../canvas/executions.js";import{conversationStore as Z,isConversationNotFound as Ue}from"../conversation-store/index.js";import{enqueueNodeMail as Pe}from"../feed/messages.js";import{newestReportBody as Be}from"../feed/reports.js";import{ensureAppProfile as $e,loadExactProfileManifest as je}from"../profiles/manifest.js";import{stopNodeSandboxes as K}from"../spaces/stop.js";import{BrokerUnreachableError as Je}from"../runtime/broker-request.js";import{interruptLive as Ye}from"../runtime/interactive-deliver.js";import{isBrokerLive as ee}from"../runtime/model-swap.js";import{newNodeId as Ge}from"../runtime/nodes.js";import{writeGoal as Xe}from"../runtime/kickoff.js";import{reviveNode as H}from"../runtime/revive.js";import{spawnChildPrepared as ze}from"../runtime/spawn.js";import{isPortableModelToken as Qe}from"../runtime/launch.js";import{parseDurationMs as Ve}from"../wake.js";import{expandModelCandidates as Ze,parseModelSpec as Ke}from"../model-routes.js";import{payerOfGrant as q}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as et}from"../runtime/host.js";import{resolveRunKind as tt}from"../runtime/launch-target.js";import{cycleAwareMessages as nt}from"../runtime/session-cycles.js";import{originFor as te}from"../runtime/stamp/protocol.js";import{readOutputRequest as st,readOutputResult as ne}from"../runtime/structured-output.js";import{admitLegacyStructuredOutput as se}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as rt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as ot}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as it}from"../../daemon/runs/observer.js";import{closeNode as re}from"../runtime/close.js";import{parseScope as dt}from"@north-light/identity";import{appendRunEvent as oe,subscribeRunEvents as at}from"./events.js";import{runActivity as ct}from"./activity.js";import{cancelOpenQuestions as ie,openNoticeIds as ut,openQuestionIds as de}from"./questions.js";import{appSpace as U}from"../layout.js";import{ensureAppSpace as mt}from"../spaces/space.js";import{assertUploadsUsable as ae,resolveStorageUrls as lt}from"../storage/attachments.js";import{storageClient as ft,storageConfig as _t}from"../storage/client.js";import{deleteUploadRow as pt,insertUploadUses as ce,releaseRunUploads as gt}from"../storage/tables.js";import{abortProviderCalls as ue}from"../providers/inflight.js";const me=m((e,t,r)=>lt(t,e,r),"defaultResolver"),Et=3e3;function Rn(e){return Number(w(e,"UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}m(Rn,"rewriteLocalIdempotencyGrantee");class S extends Error{static{m(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,r,n,i,c,d,o=t===503){super(n),this.status=t,this.code=r,this.param=i,this.details=c,this.scope=d,this.retryable=o}}const R=m((e,t)=>new S(400,"invalid_request",e,t),"invalid"),P=m(()=>new S(404,"not_found","run not found"),"missing"),B=m(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),D=m(()=>z(),"db");function x(e,t,r=!1){const n=v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!r&&n.deleting_at)throw P();return n}m(x,"ownedRun");const $=["waiting_on_user","idle","settled"];function T(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=w(D(),`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var Oe=Object.defineProperty;var c=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{coveredByAny as be}from"../../shared/env.js";import{createHash as G}from"node:crypto";import{ApiError as De}from"../../api/errors.js";import{CrtrError as Ie}from"../errors.js";import{isAbsolute as z,relative as Me,resolve as Te,sep as Ae,join as Le}from"node:path";import{SessionManager as Ce}from"@earendil-works/pi-coding-agent";import{covers as U}from"@north-light/identity";import{openDb as P,withCanvasWrite as W}from"../canvas/db.js";import{deleteNodeWithOwned as ke}from"../graph/deletion.js";import{getById as xe}from"../graph/objects.js";import{repairRunConversations as Q}from"../canvas/sessions.js";import{getNode as N,nodeFiles as We,removeNodeFiles as Fe,updateNode as He}from"../canvas/canvas.js";import{fullName as qe}from"../canvas/labels.js";import{renameWindow as Ue}from"../runtime/placement.js";import{liveExecutionForNode as V}from"../canvas/executions.js";import{conversationStore as Z,isConversationNotFound as Pe}from"../conversation-store/index.js";import{enqueueNodeMail as $e}from"../feed/messages.js";import{newestReportBody as Be}from"../feed/reports.js";import{ensureAppProfile as je,loadExactProfileManifest as Je}from"../profiles/manifest.js";import{stopNodeSandboxes as K}from"../spaces/stop.js";import{BrokerUnreachableError as Ye}from"../runtime/broker-request.js";import{interruptLive as Xe}from"../runtime/interactive-deliver.js";import{isBrokerLive as ee}from"../runtime/model-swap.js";import{newNodeId as Ge}from"../runtime/nodes.js";import{reviveNode as $}from"../runtime/revive.js";import{spawnChildPrepared as ze}from"../runtime/spawn.js";import{isPortableModelToken as Qe}from"../runtime/launch.js";import{parseDurationMs as Ve}from"../wake.js";import{expandModelCandidates as Ze,parseModelSpec as Ke}from"../model-routes.js";import{payerOfGrant as B}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as et}from"../runtime/host.js";import{resolveRunKind as tt}from"../runtime/launch-target.js";import{cycleAwareMessages as nt}from"../runtime/session-cycles.js";import{originFor as te}from"../runtime/stamp/protocol.js";import{readOutputRequest as at,readOutputResult as ne}from"../runtime/structured-output.js";import{admitLegacyStructuredOutput as ae}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as st}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as rt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as it}from"../../daemon/runs/observer.js";import{closeNode as se}from"../runtime/close.js";import{parseScope as ot}from"@north-light/identity";import{appendRunEvent as re,subscribeRunEvents as dt}from"./events.js";import{runActivity as ct}from"./activity.js";import{cancelOpenQuestions as ie,openNoticeIds as ut,openQuestionIds as oe}from"./questions.js";import{appSpace as j}from"../layout.js";import{ensureAppSpace as mt}from"../spaces/space.js";import{assertUploadsUsable as de,resolveStorageUrls as lt}from"../storage/attachments.js";import{storageClient as pt,storageConfig as _t}from"../storage/client.js";import{deleteUploadRow as ft,insertUploadUses as ce,releaseRunUploads as wt}from"../storage/tables.js";import{abortProviderCalls as ue}from"../providers/inflight.js";import{filterAsync as me,mapAsync as A}from"../async-array.js";const le=c((e,t,s)=>lt(t,e,s),"defaultResolver"),gt=3e3;async function hn(e){return Number((await e.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run()).changes)}c(hn,"rewriteLocalIdempotencyGrantee");class S extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,s,a,o,m,i,r=t===503){super(a),this.status=t,this.code=s,this.param=o,this.details=m,this.scope=i,this.retryable=r}}const R=c((e,t)=>new S(400,"invalid_request",e,t),"invalid"),J=c(()=>new S(404,"not_found","run not found"),"missing"),Y=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),D=c(async()=>await P(),"db");async function F(e,t,s=!1){const a=await N(e);if(!a||a.parent!==null||a.run_id!==e||a.grantee!==t||!s&&a.deleting_at)throw J();return a}c(F,"ownedRun");const pe=["waiting_on_user","idle","settled"];async function T(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await D()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
2
2
  (n.last_settled_at IS NULL OR EXISTS (
3
3
  SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
4
4
  AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
5
5
  WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
6
- )) LIMIT 1`).get(e.node_id,e.node_id),r=w(D(),"SELECT 1 FROM deliveries WHERE destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?) AND state IN ('armed', 'pending') AND wake = 1 LIMIT 1").get(e.node_id),n=!e.last_settled_at&&e.status!=="done";return t||r||n||rt(e)?"running":de(e.node_id).length?"waiting_on_user":"idle"}m(T,"runStatus");function Sn(e){const t=v(e);return t!==null&&T(t)==="running"}m(Sn,"runIsRunning");function L(e){Q(e.node_id),e=v(e.node_id)??e;const t=T(e),r=t==="settled"?[]:de(e.node_id),n=Be(e.node_id)||void 0,i=t==="settled"?ot(e):null,c=i?.kind==="result"?ne(e.node_id,e.grantee):void 0;return{run_id:e.node_id,name:e.name,status:t,...i?{outcome:i}:{},...c===void 0?{}:{result:c},...n!==void 0?{last_report:n}:{},pending_question_ids:r,open_notice_ids:t==="settled"?[]:ut(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(B())),payer:q(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:ct(e.node_id,t)}}m(L,"runObject");const j=864e5,le=255;function Nn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>le)throw R(`Idempotency-Key must be 1-${le} characters`);return e}}m(Nn,"idempotencyKeyOf");function k(e,t,r,n=z()){const i=w(n,"SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!i||Date.now()-Date.parse(i.created_at)>=j)){if(i.body_hash!==r)throw new S(409,"idempotency_conflict","key used with a different request");return{run_id:i.run_id,response:JSON.parse(i.response_json)}}}m(k,"findIdempotent");function fe(e,t,r,n,i,c,d){w(e,"DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,r,new Date(Date.now()-j).toISOString()),w(e,"INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,r,n,i,JSON.stringify(c),d)}m(fe,"recordIdempotent");function vn(e=Date.now()){return C(t=>Number(w(t,"DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-j).toISOString()).changes))}m(vn,"pruneExpiredIdempotencyKeys");function _e(e,t,r,n,i){const c=n.text;let d=0;return{messageId:Pe(t,{kind:"message",label:c.slice(0,120),senderNodeId:"human",senderName:r,bodyJson:i?{body:c}:{body:c,start_turn:!1},urgency:i?"normal":"deferred",wake:i?1:0,withinEnqueue:m((a,p)=>{n.uses.length&&(ae(r,n.uses,a),ce(n.uses.map(({upload_id:y,path:g})=>({upload_id:y,path:g,run_id:t})),a)),d=oe(a,t,t,"node.message.accepted",{message_id:p,start_turn:i}).sequence_number},"withinEnqueue")}).messageId,sequence:d}}m(_e,"acceptRunMessage");class pe extends Error{static{m(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const wt=1440*60*1e3;function ge(e){const t=typeof e=="string"?Ve(e):null;if(t===null||!Number.isSafeInteger(t))throw R(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw R("deadline must be greater than zero","deadline");if(t>wt)throw R("deadline must be at most 24h","deadline");return t}m(ge,"parseRunDeadlineMs");async function bn(e,t,r,n=me){if(t.isolated&&!et())throw new S(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&ge(t.deadline);const i=G("sha256").update(JSON.stringify(t)).digest("hex");if(r){const s=k(e.grantee,r,i);if(s){const l=x(s.run_id,e.grantee);return!l.pi_pid&&T(l)==="running"&&(t.output_schema!==void 0&&!l.outcome_at&&st(l.node_id).state==="absent"&&ne(l.node_id,l.grantee)===void 0&&se(l.node_id,"terminal",t.output_schema),await H(l.node_id,{resume:!0,capacity:"freeze"})),s.response}}await mt(e.grantee);const c=t.profile===void 0?$e(e.grantee):je(t.profile),d=c.manifest.grantee??"app:terminal";if(d!==e.grantee){const s=`crtr:memory:rw:${d}:profile:${c.profileId}`;if(!e.resolved.some(l=>F(l,s))||t.scopes!==null&&!t.scopes.some(l=>F(l,s)))throw new S(403,"scope_missing",`missing scope ${s}`,"profile",void 0,s)}if(t.model!==void 0){const s=t.model;if(Qe(s)){if(s.includes("/")&&q(e.grant)!=="app"){const l=s.lastIndexOf("/"),h=s.slice(0,l),N=s.slice(l+1);if(["ultra","strong","medium","light"].includes(N)&&Ze({kind:"logical",family:h,strength:N,spec:s},U(e.grantee).files,c.profileId).every(A=>A.family!==h))throw R(`model '${s}' names a model family that is not configured in this daemon`,"model")}}else if(Ke(s)===void 0)throw R(`model '${s}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const o=Ge(),a=Ae(U(e.grantee).nodes,o);if(t.isolated&&t.cwd!==void 0){const s=Ie(a,Me(t.cwd));if(!X(t.cwd)||s===".."||s.startsWith(`..${Te}`)||X(s))throw R("cwd must be inside the isolated root node folder","cwd")}const p=await n(o,e.grantee,t.prompt),y=p.text;let g;try{g=t.message===void 0?void 0:await n(o,e.grantee,t.message)}catch(s){throw p.cleanup(),s}const E=q(e.grant);let u;try{await ze({kind:tt(c),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??a:U(e.grantee).files,profile:c.profileId,prompt:y,nodeId:o,isolated:t.isolated??!1,...t.model===void 0?{}:{model:t.model},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+ge(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:o,event_cursor:1,usage_json:JSON.stringify(B())},withinCreate:m((s,l)=>{if(r){const N=k(e.grantee,r,i,s);if(N)throw new pe(N)}const h=p.uses;if(h.length&&(ae(e.grantee,h,s),ce(h.map(({upload_id:N,path:A})=>({upload_id:N,path:A,run_id:o})),s)),Xe(o,y),u={run_id:o,node_id:o,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:E,status:"running",created_at:l.created,metadata:t.metadata,sequence_number:0},oe(s,o,o,"run.started",{scopes:t.scopes,payer:E,usage:B()}),g){const N=_e(s,o,e.grantee,g,!1);u.message={run_id:o,message_id:N.messageId,sequence_number:N.sequence}}r&&fe(s,e.grantee,r,i,o,u,l.created)},"withinCreate")},t.output_schema===void 0?void 0:s=>{se(s,"terminal",t.output_schema)})}catch(s){if(v(o)||(p.cleanup(),g?.cleanup()),s instanceof pe)return s.winner.response;if(t.model!==void 0&&s instanceof De&&s.code==="usage")throw R(s.message,"model");if(s instanceof Oe&&(s.code==="isolated_run"||s.code==="invalid_request")){const l=s.details&&typeof s.details=="object"&&"param"in s.details&&typeof s.details.param=="string"?s.details.param:void 0;throw new S(s.status,s.code,s.message,l)}throw s}if(!u)throw new Error("run creation did not commit");return u}m(bn,"startRun");function On(e,t){let r;if(t.after)try{const o=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!o||typeof o!="object"||!("activity"in o)||typeof o.activity!="string"||!("id"in o)||typeof o.id!="string")throw new Error("invalid cursor");r={activity:o.activity,id:o.id}}catch{throw R("invalid list cursor","after")}const i=D().prepare(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),s=await(await D()).prepare("SELECT 1 FROM deliveries WHERE destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?) AND state IN ('armed', 'pending') AND wake = 1 LIMIT 1").get(e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||s||a||await st(e)?"running":(await oe(e.node_id)).length?"waiting_on_user":"idle"}c(T,"runStatus");async function Rn(e){const t=await N(e);return t!==null&&await T(t)==="running"}c(Rn,"runIsRunning");async function L(e){await Q(e.node_id),e=await N(e.node_id)??e;const t=await T(e),s=t==="settled"?[]:await oe(e.node_id),a=await Be(e.node_id)||void 0,o=t==="settled"?rt(e):null,m=o?.kind==="result"?ne(e.node_id,e.grantee):void 0;return{run_id:e.node_id,name:e.name,status:t,...o?{outcome:o}:{},...m===void 0?{}:{result:m},...a!==void 0?{last_report:a}:{},pending_question_ids:s,open_notice_ids:t==="settled"?[]:await ut(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(Y())),payer:await B(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await ct(e.node_id,t)}}c(L,"runObject");const X=864e5,_e=255;function Sn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>_e)throw R(`Idempotency-Key must be 1-${_e} characters`);return e}}c(Sn,"idempotencyKeyOf");async function H(e,t,s,a){a??=await P();const o=await a.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!o||Date.now()-Date.parse(o.created_at)>=X)){if(o.body_hash!==s)throw new S(409,"idempotency_conflict","key used with a different request");return{run_id:o.run_id,response:JSON.parse(o.response_json)}}}c(H,"findIdempotent");async function fe(e,t,s,a,o,m,i){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,s,new Date(Date.now()-X).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,s,a,o,JSON.stringify(m),i)}c(fe,"recordIdempotent");async function Nn(e=Date.now()){return Number((await(await P()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-X).toISOString())).changes)}c(Nn,"pruneExpiredIdempotencyKeys");async function we(e,t,s,a,o){const m=a.text;let i=0;return{messageId:(await $e(t,{kind:"message",label:m.slice(0,120),senderNodeId:"human",senderName:s,bodyJson:o?{body:m}:{body:m,start_turn:!1},urgency:o?"normal":"deferred",wake:o?1:0,withinEnqueue:c(async(u,f)=>{a.uses.length&&(await de(s,a.uses,u),await ce(a.uses.map(({upload_id:y,path:g})=>({upload_id:y,path:g,run_id:t})),u)),i=(await re(u,t,t,"node.message.accepted",{message_id:f,start_turn:o})).sequence_number},"withinEnqueue")})).messageId,sequence:i}}c(we,"acceptRunMessage");class ge extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Et=1440*60*1e3;function Ee(e){const t=typeof e=="string"?Ve(e):null;if(t===null||!Number.isSafeInteger(t))throw R(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw R("deadline must be greater than zero","deadline");if(t>Et)throw R("deadline must be at most 24h","deadline");return t}c(Ee,"parseRunDeadlineMs");async function vn(e,t,s,a=le){if(t.isolated&&!et())throw new S(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Ee(t.deadline);const o=G("sha256").update(JSON.stringify(t)).digest("hex");if(s){const n=await H(e.grantee,s,o);if(n){const l=await F(n.run_id,e.grantee);return!l.pi_pid&&await T(l)==="running"&&(t.output_schema!==void 0&&!l.outcome_at&&at(l.node_id).state==="absent"&&ne(l.node_id,l.grantee)===void 0&&await ae(l.node_id,"terminal",t.output_schema),await $(l.node_id,{resume:!0,capacity:"freeze"})),n.response}}await mt(e.grantee);const m=t.profile===void 0?je(e.grantee):Je(t.profile),i=m.manifest.grantee??"app:terminal";if(i!==e.grantee){const n=`crtr:memory:rw:${i}:profile:${m.profileId}`;if(!e.resolved.some(l=>U(l,n))||t.scopes!==null&&!t.scopes.some(l=>U(l,n)))throw new S(403,"scope_missing",`missing scope ${n}`,"profile",void 0,n)}if(t.model!==void 0){const n=t.model;if(Qe(n)){if(n.includes("/")&&await B(e.grant)!=="app"){const l=n.lastIndexOf("/"),E=n.slice(0,l),h=n.slice(l+1);if(["ultra","strong","medium","light"].includes(h)&&Ze({kind:"logical",family:E,strength:h,spec:n},j(e.grantee).files,m.profileId).every(b=>b.family!==E))throw R(`model '${n}' names a model family that is not configured in this daemon`,"model")}}else if(Ke(n)===void 0)throw R(`model '${n}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const r=await Ge(),u=Le(j(e.grantee).nodes,r);if(t.isolated&&t.cwd!==void 0){const n=Me(u,Te(t.cwd));if(!z(t.cwd)||n===".."||n.startsWith(`..${Ae}`)||z(n))throw R("cwd must be inside the isolated root node folder","cwd")}const f=await a(r,e.grantee,t.prompt),y=f.text;let g;try{g=t.message===void 0?void 0:await a(r,e.grantee,t.message)}catch(n){throw f.cleanup(),n}const w=await B(e.grant);let d;try{await ze({kind:tt(m),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??u:j(e.grantee).files,profile:m.profileId,prompt:y,nodeId:r,isolated:t.isolated??!1,...t.model===void 0?{}:{model:t.model},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Ee(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:r,event_cursor:1,usage_json:JSON.stringify(Y())},withinCreate:c(async(n,l)=>{if(s){const h=await H(e.grantee,s,o,n);if(h)throw new ge(h)}const E=f.uses;if(E.length&&(await de(e.grantee,E,n),await ce(E.map(({upload_id:h,path:b})=>({upload_id:h,path:b,run_id:r})),n)),d={run_id:r,node_id:r,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:w,status:"running",created_at:l.created,metadata:t.metadata,sequence_number:0},await re(n,r,r,"run.started",{scopes:t.scopes,payer:w,usage:Y()}),g){const h=await we(n,r,e.grantee,g,!1);d.message={run_id:r,message_id:h.messageId,sequence_number:h.sequence}}s&&await fe(n,e.grantee,s,o,r,d,l.created)},"withinCreate")},t.output_schema===void 0?void 0:async n=>{await ae(n,"terminal",t.output_schema)})}catch(n){if(await N(r)||(f.cleanup(),g?.cleanup()),n instanceof ge)return n.winner.response;if(t.model!==void 0&&n instanceof Ie&&n.code==="usage")throw R(n.message,"model");if(n instanceof De&&(n.code==="isolated_run"||n.code==="invalid_request")){const l=n.details&&typeof n.details=="object"&&"param"in n.details&&typeof n.details.param=="string"?n.details.param:void 0;throw new S(n.status,n.code,n.message,l)}throw n}if(!d)throw new Error("run creation did not commit");return d}c(vn,"startRun");async function On(e,t){let s;if(t.after)try{const r=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!r||typeof r!="object"||!("activity"in r)||typeof r.activity!="string"||!("id"in r)||typeof r.id!="string")throw new Error("invalid cursor");s={activity:r.activity,id:r.id}}catch{throw R("invalid list cursor","after")}const a=await(await D()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
7
7
  WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}
8
- ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e]).filter(({node_id:o})=>!t.visible||t.visible(o)).filter(({activity:o,node_id:a})=>!r||o<r.activity||o===r.activity&&a<r.id).map(o=>({root:v(o.node_id),activity:o.activity})).filter(({root:o})=>!t.status||T(o)===t.status),c=i.slice(0,t.limit),d=c.at(-1);return{runs:c.map(({root:o})=>L(o)),next:i.length>t.limit&&d?Buffer.from(JSON.stringify({activity:d.activity,id:d.root.node_id})).toString("base64url"):null}}m(On,"listRuns");async function Dn(e,t,r){const n=x(e,t),i=m(()=>L(x(e,t)),"read");return!r||$.includes(T(n))?i():new Promise((c,d)=>{const o=m(()=>{clearTimeout(y),clearInterval(p),a();try{c(i())}catch(g){d(g)}},"finish"),a=at(e,()=>{try{$.includes(String(i().status))&&o()}catch(g){clearTimeout(y),clearInterval(p),a(),d(g)}}),p=setInterval(()=>{$.includes(String(i().status))&&o()},250),y=setTimeout(o,r*1e3)})}m(Dn,"waitRun");async function In(e,t,r=me,n=!0,i){const c=e.status==="canceled"||e.outcome_reason==="closed",d=e.grantee??"app:terminal",o=G("sha256").update(JSON.stringify(["run.message",e.node_id,t,n])).digest("hex"),a=m(async E=>{const u=v(e.node_id),s=w(D(),"SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(E.message_id));return u&&!c&&n&&!u.pi_pid&&s&&await H(e.node_id,{resume:!0,capacity:"freeze"}),E},"replay");if(i){const E=k(d,i,o);if(E)return a(E.response)}if(c)throw new S(409,"run_settled","canceled run cannot receive a message");const p=await r(e.node_id,d,t),y=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;let g;try{g=C(E=>{if(i){const l=k(d,i,o,E);if(l)return{replayed:l.response}}y?.(e.node_id);const u=_e(E,e.node_id,d,p,n),s={run_id:e.node_id,message_id:u.messageId,sequence_number:u.sequence};return i&&fe(E,d,i,o,e.node_id,s,new Date().toISOString()),{result:s}})}catch(E){throw p.cleanup(),E}return"replayed"in g?(p.cleanup(),a(g.replayed)):(n&&!e.pi_pid&&await H(e.node_id,{resume:!0,capacity:"freeze"}),g.result)}m(In,"messageRun");async function ht(e){const t=m(()=>new S(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let r=0;r<2;r++){const n=v(e);if(!n)throw P();if(!ee(n)){if(n.streaming)throw t();return}const i=V(e)?.executionId;try{await Ye(e)==="turn"&&ue({nodes:[e]});return}catch(c){if(!(c instanceof Je))throw c;const d=v(e);if(!d)throw P();if(!d.streaming)return;if(r===0&&ee(d)&&V(e)?.executionId!==i)continue;throw t()}}throw t()}m(ht,"interruptNode");async function Mn(e,t="stop"){const r=t==="stop"?w(D(),"SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id).map(({node_id:n})=>n):[e.node_id];return await Promise.all(r.map(n=>ht(n))),L(v(e.node_id)??e)}m(Mn,"interruptRun");async function Tn(e,t={}){const r=w(D(),"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(d=>d.node_id);ue({run:e.node_id});const n=[];if(T(e)!=="settled")n.push(...re(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"}).closed);else for(const d of r){if(d===e.node_id)continue;const o=v(d);o&&o.status!=="done"&&o.status!=="canceled"&&o.status!=="dead"&&n.push(...re(d,{preserveEmpty:!0,stopReason:"run_canceled"}).closed)}if(await ie({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(d=>K(d,"run_canceled")))).some(d=>!d.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const c=v(e.node_id);return L(c??e)}m(Tn,"cancelRun");const Ee=200;function An(e,t){if(typeof t!="string"||!t.trim())throw R("name is required","name");const r=t.trim();if(r.length>Ee)throw R(`name exceeds ${Ee} characters`,"name");const n=Fe(e.node_id,{name:r});return n.window&&qe(n.window,He(n)),L(n)}m(An,"renameRun");async function Ln(e,t={config:_t,client:ft}){await ie({run_id:e.node_id},"the run was deleted");const r=C(a=>(w(a,"UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),w(a,"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(p=>p.node_id)));if((await Promise.all(r.map(a=>K(a,"run_deleted",{deleting:!0})))).some(a=>!a.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const i=r.map(a=>{const p=ke(a);if(p.app===null)throw new Error(`run node missing during deletion: ${a}`);return p}),c=w(D(),"SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:a}of c)try{Z().delete(a)}catch(p){if(!Ue(p))throw p}const d=C(a=>{for(const E of r){const u=xe(a,E);u!==null&&u.deleted_at===null&&Ce(a,u)}const p=gt([e.node_id],a);w(a,"DELETE FROM run_events WHERE run_id = ?").run(e.node_id),w(a,"DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const y=r.map(()=>"?").join(","),g=a.prepare(`SELECT message_id FROM messages WHERE sender_node_id IN (${y}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${y})`).all(...r,...r);a.prepare(`DELETE FROM deliveries WHERE destination_id IN (${y})`).run(...r);for(const{message_id:E}of g)w(a,"DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(E,E);return p});for(const a of i)We(a);const{notifyRunDeleted:o}=await import("./events.js");return o(e.node_id),{uploads_pending:await yt(d,t)}}m(Ln,"deleteRun");async function yt(e,t){if(!e.length||!t.config())return e.length;let r;try{r=t.client()}catch{return e.length}const n=new Set,i=e.map(d=>r.deleteUpload(d).then(()=>{pt(d),n.add(d)},()=>{}));let c;return await Promise.race([Promise.all(i),new Promise(d=>{c=setTimeout(d,t.budgetMs??Et),c.unref?.()})]),clearTimeout(c),e.length-n.size}m(yt,"deleteReleasedUploads");function Cn(e,t,r){x(e,t),Q(e);const n=D();n.exec("BEGIN");try{const c=w(n,"SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e).map(u=>({node_id:u.node_id,parent_node_id:u.parent,conversations:w(n,"SELECT DISTINCT session_id FROM sessions WHERE node_id = ? ORDER BY created_at").all(u.node_id).map(({session_id:s})=>{const{header:l,entries:h}=Z().read(s);if(r==="entries")return{conversation_id:s,header:l,entries:h};const N=Le.inMemory(l.cwd,void 0,[l,...h]),A=nt(N)??[],J=new Map(h.map((_,b)=>[_.id,b])),we=h.filter(_=>_.type==="custom"&&_.customType==="crtr-system-prompt").map(_=>({id:_.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in _?_.data:void 0,timestamp:_.timestamp}})),Y=h.filter(_=>_.type==="custom_message"&&_.customType==="app_message").map(_=>({id:_.id,message:{role:"custom",customType:"app_message",content:"content"in _?_.content:"",timestamp:_.timestamp}})),he=u.node_id===e?h.find(_=>{if(_.type!=="message"||_.message.role!=="user")return!1;const b=te(h,_.message.timestamp);return b?.type==="runtime"&&b.kind==="kickoff"})?.id:void 0,ye=[...A.filter(({id:_})=>!Y.some(b=>b.id===_)),...we,...Y].sort((_,b)=>(J.get(_.id)??Number.MAX_SAFE_INTEGER)-(J.get(b.id)??Number.MAX_SAFE_INTEGER)).map(({id:_,message:b})=>{const f=b,I=f.usage,W=f.role==="user"?te(h,Number(f.timestamp)):null,Re=W?.type==="human"||_===he,M=f.role==="toolResult"?"tool_result":f.role==="bashExecution"?"bash_execution":f.role==="compactionSummary"?"compaction_summary":f.role==="branchSummary"?"branch_summary":f.role==="custom"&&f.customType==="crtr-system-prompt"?"system":f.role==="user"?Re?"user":"custom":f.role,Se=M==="custom"?f.role==="custom"?f.customType:W?.type==="runtime"?W.kind:"unknown":void 0,Ne=M==="system"&&f.customType==="crtr-system-prompt"?[{type:"text",text:f.data?.text??""}]:typeof f.content=="string"?[{type:"text",text:f.content}]:Array.isArray(f.content)?f.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:_,role:M,...M==="custom"?{custom_type:Se}:{},time:typeof f.timestamp=="string"?f.timestamp:new Date(Number(f.timestamp??Date.now())).toISOString(),content:Ne,...M==="assistant"?{model:f.model,provider:f.provider,stop_reason:f.stopReason,...f.errorMessage?{error_message:f.errorMessage}:{},...I?{usage:{input_tokens:I.input??0,output_tokens:I.output??0,cache_read_tokens:I.cacheRead??0,cache_write_tokens:I.cacheWrite??0,cost_usd:I.cost?.total??0}}:{}}:{},...M==="tool_result"?{tool_call_id:f.toolCallId,tool_name:f.toolName,is_error:f.isError}:{}}})??[];return{conversation_id:s,messages:ye}})})),o=w(n,"SELECT event_cursor FROM nodes WHERE node_id = ?").get(e).event_cursor-1,a=new Map(c.map(u=>[u.node_id,it(u.node_id)])),p=w(n,`SELECT node_id, sequence_number FROM run_events
8
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e]),o=await me(await A((await me(a,async({node_id:r})=>!t.visible||await t.visible(r))).filter(({activity:r,node_id:u})=>!s||r<s.activity||r===s.activity&&u<s.id),async r=>({root:await N(r.node_id),activity:r.activity})),async({root:r})=>!t.status||await T(r)===t.status),m=o.slice(0,t.limit),i=m.at(-1);return{runs:await A(m,async({root:r})=>await L(r)),next:o.length>t.limit&&i?Buffer.from(JSON.stringify({activity:i.activity,id:i.root.node_id})).toString("base64url"):null}}c(On,"listRuns");async function bn(e,t,s){const a=await F(e,t),o=c(async()=>await L(await F(e,t)),"read");return!s||pe.includes(await T(a))?await o():new Promise((m,i)=>{let r=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(d),clearInterval(w),r()},"settle"),f=c(async()=>{u();try{m(await o())}catch(n){i(n)}},"finish"),y=c(async()=>{pe.includes(String((await o()).status))&&await f()},"check"),g=c(()=>{y().catch(n=>{u(),i(n)})},"run"),w=setInterval(g,250),d=setTimeout(()=>{f()},s*1e3);dt(e,g).then(n=>{r=n},n=>{u(),i(n)})})}c(bn,"waitRun");async function Dn(e,t,s=le,a=!0,o){const m=e.status==="canceled"||e.outcome_reason==="closed",i=e.grantee??"app:terminal",r=G("sha256").update(JSON.stringify(["run.message",e.node_id,t,a])).digest("hex"),u=c(async w=>{const d=await N(e.node_id),n=await(await D()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(w.message_id));return d&&!m&&a&&!d.pi_pid&&n&&await $(e.node_id,{resume:!0,capacity:"freeze"}),w},"replay");if(o){const w=await H(i,o,r);if(w)return u(w.response)}if(m)throw new S(409,"run_settled","canceled run cannot receive a message");const f=await s(e.node_id,i,t),y=a&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;let g;try{g=await W(async w=>{if(o){const l=await H(i,o,r,w);if(l)return{replayed:l.response}}await y?.(e.node_id);const d=await we(w,e.node_id,i,f,a),n={run_id:e.node_id,message_id:d.messageId,sequence_number:d.sequence};return o&&await fe(w,i,o,r,e.node_id,n,new Date().toISOString()),{result:n}})}catch(w){throw f.cleanup(),w}return"replayed"in g?(f.cleanup(),u(g.replayed)):(a&&!e.pi_pid&&await $(e.node_id,{resume:!0,capacity:"freeze"}),g.result)}c(Dn,"messageRun");async function yt(e){const t=c(()=>new S(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let s=0;s<2;s++){const a=await N(e);if(!a)throw J();if(!ee(a)){if(a.streaming)throw t();return}const o=(await V(e))?.executionId;try{await Xe(e)==="turn"&&ue({nodes:[e]});return}catch(m){if(!(m instanceof Ye))throw m;const i=await N(e);if(!i)throw J();if(!i.streaming)return;if(s===0&&ee(i)&&(await V(e))?.executionId!==o)continue;throw t()}}throw t()}c(yt,"interruptNode");async function In(e,t="stop"){const s=t==="stop"?(await(await D()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:a})=>a):[e.node_id];return await Promise.all(s.map(a=>yt(a))),await L(await N(e.node_id)??e)}c(In,"interruptRun");async function Mn(e,t={}){const s=(await(await D()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(i=>i.node_id);ue({run:e.node_id});const a=[];if(await T(e)!=="settled")a.push(...(await se(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const i of s){if(i===e.node_id)continue;const r=await N(i);r&&r.status!=="done"&&r.status!=="canceled"&&r.status!=="dead"&&a.push(...(await se(i,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await ie({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...a])].map(i=>K(i,"run_canceled")))).some(i=>!i.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const m=await N(e.node_id);return await L(m??e)}c(Mn,"cancelRun");const ye=200;async function Tn(e,t){if(typeof t!="string"||!t.trim())throw R("name is required","name");const s=t.trim();if(s.length>ye)throw R(`name exceeds ${ye} characters`,"name");const a=await He(e.node_id,{name:s});return a.window&&Ue(a.window,qe(a)),await L(a)}c(Tn,"renameRun");async function An(e,t={config:_t,client:pt}){await ie({run_id:e.node_id},"the run was deleted");const s=await W(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(f=>f.node_id)));if((await Promise.all(s.map(u=>K(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const o=await A(s,async u=>{const f=await We(u);if(f.app===null)throw new Error(`run node missing during deletion: ${u}`);return f}),m=await(await D()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of m)try{await Z().delete(u)}catch(f){if(!Pe(f))throw f}const i=await W(async u=>{for(const w of s){const d=await xe(u,w);d!==null&&d.deleted_at===null&&await ke(u,d)}const f=await wt([e.node_id],u);await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const y=s.map(()=>"?").join(","),g=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${y}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${y})`).all(...s,...s);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${y})`).run(...s);for(const{message_id:w}of g)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(w,w);return f});for(const u of o)await Fe(u);const{notifyRunDeleted:r}=await import("./events.js");return r(e.node_id),{uploads_pending:await ht(i,t)}}c(An,"deleteRun");async function ht(e,t){if(!e.length||!t.config())return e.length;let s;try{s=t.client()}catch{return e.length}const a=new Set,o=e.map(i=>s.deleteUpload(i).then(async()=>{await ft(i),a.add(i)},()=>{}));let m;return await Promise.race([Promise.all(o),new Promise(i=>{m=setTimeout(i,t.budgetMs??gt),m.unref?.()})]),clearTimeout(m),e.length-a.size}c(ht,"deleteReleasedUploads");async function Ln(e,t,s){await F(e,t),await Q(e);const a=await W(async d=>{const n=await d.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),l=new Map;for(const k of n)l.set(k.node_id,(await d.prepare("SELECT DISTINCT session_id FROM sessions WHERE node_id = ? ORDER BY created_at").all(k.node_id)).map(x=>x.session_id));const h=(await d.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,b=await d.prepare(`SELECT node_id, sequence_number FROM run_events
9
9
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
10
- ORDER BY sequence_number`).all(e,o);for(const u of p){const s=a.get(u.node_id);s!=null&&u.sequence_number>=s&&a.set(u.node_id,null)}const y=w(n,`SELECT node_id, sequence_number, type, body_json FROM run_events
10
+ ORDER BY sequence_number`).all(e,h),C=await d.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
11
11
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
12
- ORDER BY sequence_number`).all(e,o),g=new Map;for(const u of y){const s=a.get(u.node_id);if(s==null||u.sequence_number<s)continue;const l=JSON.parse(u.body_json),h=g.get(u.node_id)??{thinking:"",text:""};u.type==="node.thinking.delta"?h.thinking+=l.delta:h.text+=l.delta,g.set(u.node_id,h)}const E=c.map(u=>({...u,in_progress_message:a.get(u.node_id)==null?null:g.get(u.node_id)??{thinking:"",text:""}}));return n.exec("COMMIT"),{run_id:e,latest_sequence:o,nodes:E}}catch(i){throw n.exec("ROLLBACK"),i}}m(Cn,"traceRun");function xn(e,t,r){if(t===void 0){if(!e.some(n=>F(n,"crtr:llm")))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw R("scopes must be a list of scope strings","scopes");for(const n of t){try{dt(n)}catch{throw R(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===r.slice(4))throw R(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===r.slice(4))&&!be(e,n))throw new S(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}m(xn,"requestedScopes");export{j as IDEMPOTENCY_WINDOW_MS,wt as RUN_DEADLINE_MAX_MS,Et as RUN_DELETE_STORAGE_BUDGET_MS,Ee as RUN_NAME_MAX,S as RunError,Tn as cancelRun,Ln as deleteRun,Nn as idempotencyKeyOf,Mn as interruptRun,On as listRuns,In as messageRun,x as ownedRun,ge as parseRunDeadlineMs,vn as pruneExpiredIdempotencyKeys,An as renameRun,xn as requestedScopes,Rn as rewriteLocalIdempotencyGrantee,Sn as runIsRunning,L as runObject,bn as startRun,Cn as traceRun,Dn as waitRun};
12
+ ORDER BY sequence_number`).all(e,h);return{nodes:n,sessionIds:l,latestSequence:h,completed:b,deltas:C}}),{nodes:o,sessionIds:m,latestSequence:i,completed:r,deltas:u}=a,f=await A(o,async d=>({node_id:d.node_id,parent_node_id:d.parent,conversations:await A(m.get(d.node_id)??[],async n=>{const{header:l,entries:E}=await Z().read(n);if(s==="entries")return{conversation_id:n,header:l,entries:E};const h=Ce.inMemory(l.cwd,void 0,[l,...E]),b=nt(h)??[],C=new Map(E.map((_,v)=>[_.id,v])),k=E.filter(_=>_.type==="custom"&&_.customType==="crtr-system-prompt").map(_=>({id:_.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in _?_.data:void 0,timestamp:_.timestamp}})),x=E.filter(_=>_.type==="custom_message"&&_.customType==="app_message").map(_=>({id:_.id,message:{role:"custom",customType:"app_message",content:"content"in _?_.content:"",timestamp:_.timestamp}})),he=d.node_id===e?E.find(_=>{if(_.type!=="message"||_.message.role!=="user")return!1;const v=te(E,_.message.timestamp);return v?.type==="runtime"&&v.kind==="kickoff"})?.id:void 0,Re=[...b.filter(({id:_})=>!x.some(v=>v.id===_)),...k,...x].sort((_,v)=>(C.get(_.id)??Number.MAX_SAFE_INTEGER)-(C.get(v.id)??Number.MAX_SAFE_INTEGER)).map(({id:_,message:v})=>{const p=v,I=p.usage,q=p.role==="user"?te(E,Number(p.timestamp)):null,Se=q?.type==="human"||_===he,M=p.role==="toolResult"?"tool_result":p.role==="bashExecution"?"bash_execution":p.role==="compactionSummary"?"compaction_summary":p.role==="branchSummary"?"branch_summary":p.role==="custom"&&p.customType==="crtr-system-prompt"?"system":p.role==="user"?Se?"user":"custom":p.role,Ne=M==="custom"?p.role==="custom"?p.customType:q?.type==="runtime"?q.kind:"unknown":void 0,ve=M==="system"&&p.customType==="crtr-system-prompt"?[{type:"text",text:p.data?.text??""}]:typeof p.content=="string"?[{type:"text",text:p.content}]:Array.isArray(p.content)?p.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:_,role:M,...M==="custom"?{custom_type:Ne}:{},time:typeof p.timestamp=="string"?p.timestamp:new Date(Number(p.timestamp??Date.now())).toISOString(),content:ve,...M==="assistant"?{model:p.model,provider:p.provider,stop_reason:p.stopReason,...p.errorMessage?{error_message:p.errorMessage}:{},...I?{usage:{input_tokens:I.input??0,output_tokens:I.output??0,cache_read_tokens:I.cacheRead??0,cache_write_tokens:I.cacheWrite??0,cost_usd:I.cost?.total??0}}:{}}:{},...M==="tool_result"?{tool_call_id:p.toolCallId,tool_name:p.toolName,is_error:p.isError}:{}}})??[];return{conversation_id:n,messages:Re}})})),y=new Map(f.map(d=>[d.node_id,it(d.node_id)]));for(const d of r){const n=y.get(d.node_id);n!=null&&d.sequence_number>=n&&y.set(d.node_id,null)}const g=new Map;for(const d of u){const n=y.get(d.node_id);if(n==null||d.sequence_number<n)continue;const l=JSON.parse(d.body_json),E=g.get(d.node_id)??{thinking:"",text:""};d.type==="node.thinking.delta"?E.thinking+=l.delta:E.text+=l.delta,g.set(d.node_id,E)}const w=f.map(d=>({...d,in_progress_message:y.get(d.node_id)==null?null:g.get(d.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:i,nodes:w}}c(Ln,"traceRun");function Cn(e,t,s){if(t===void 0){if(!e.some(a=>U(a,"crtr:llm")))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(a=>typeof a!="string"))throw R("scopes must be a list of scope strings","scopes");for(const a of t){try{ot(a)}catch{throw R(`invalid scope ${a}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(a)&&a.split(":")[4]===s.slice(4))throw R(`own-app files cannot narrow a run: ${a}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(a)&&a.split(":")[4]===s.slice(4))&&!be(e,a))throw new S(403,"scope_missing",`missing scope ${a}`,void 0,void 0,a)}if(!t.includes("crtr:llm"))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(Cn,"requestedScopes");export{X as IDEMPOTENCY_WINDOW_MS,Et as RUN_DEADLINE_MAX_MS,gt as RUN_DELETE_STORAGE_BUDGET_MS,ye as RUN_NAME_MAX,S as RunError,Mn as cancelRun,An as deleteRun,Sn as idempotencyKeyOf,In as interruptRun,On as listRuns,Dn as messageRun,F as ownedRun,Ee as parseRunDeadlineMs,Nn as pruneExpiredIdempotencyKeys,Tn as renameRun,Cn as requestedScopes,hn as rewriteLocalIdempotencyGrantee,Rn as runIsRunning,L as runObject,vn as startRun,Ln as traceRun,bn as waitRun};
@@ -1,4 +1,4 @@
1
- import type { DatabaseSync } from 'node:sqlite';
1
+ import { type CanvasDb } from '../canvas/db.js';
2
2
  import { type HumanRequestRecord } from '../human/requests.js';
3
3
  import { type PreparedPage } from '../human/page-authoring.js';
4
4
  /**
@@ -30,30 +30,30 @@ export declare function providerApprovalPage(question: {
30
30
  }>;
31
31
  }): PreparedPage;
32
32
  /** The question's run, asking node, and app, or null when the request is not a question. */
33
- export declare function questionRun(request: HumanRequestRecord, db?: DatabaseSync): AskingNode | null;
33
+ export declare function questionRun(request: HumanRequestRecord, db?: CanvasDb): Promise<AskingNode | null>;
34
34
  export type QuestionKind = 'decision' | 'notice';
35
35
  /** A decision asks for a response; a notice takes none and is acknowledged with empty responses. */
36
36
  export declare function questionKind(request: HumanRequestRecord): QuestionKind;
37
37
  /** Called inside the page request's creating write: carries a new question on its run's stream. */
38
- export declare function appendWaitingOnUser(db: DatabaseSync, request: HumanRequestRecord): void;
38
+ export declare function appendWaitingOnUser(db: CanvasDb, request: HumanRequestRecord): Promise<void>;
39
39
  /** Called inside the settling write: an answered question emits `question.answered`. */
40
- export declare function appendQuestionAnswered(db: DatabaseSync, request: HumanRequestRecord): void;
40
+ export declare function appendQuestionAnswered(db: CanvasDb, request: HumanRequestRecord): Promise<void>;
41
41
  /** Open decisions raised by any node of the run, oldest first; a notice never counts. */
42
- export declare function openQuestionIds(runId: string, db?: DatabaseSync): string[];
42
+ export declare function openQuestionIds(runId: string, db?: CanvasDb): Promise<string[]>;
43
43
  /** Open notices raised by any node of the run, oldest first. */
44
- export declare function openNoticeIds(runId: string, db?: DatabaseSync): string[];
44
+ export declare function openNoticeIds(runId: string, db?: CanvasDb): Promise<string[]>;
45
45
  export type QuestionStatus = 'open' | 'answered' | 'canceled';
46
46
  export declare function questionStatus(request: HumanRequestRecord): QuestionStatus;
47
47
  /** The stored answer or cancellation of a settled question. */
48
48
  export declare function questionResult(request: HumanRequestRecord): unknown;
49
49
  /** The `question.get` shape. */
50
- export declare function questionObject(request: HumanRequestRecord, run: AskingNode | null, approval?: ProviderQuestion | null): Record<string, unknown>;
50
+ export declare function questionObject(request: HumanRequestRecord, run: AskingNode | null, approval?: ProviderQuestion | null): Promise<Record<string, unknown>>;
51
51
  /** A question by id, with its run or an app-owned runless provider approval. */
52
- export declare function getQuestion(questionId: string): {
52
+ export declare function getQuestion(questionId: string): Promise<{
53
53
  request: HumanRequestRecord;
54
54
  run: AskingNode | null;
55
55
  approval: ProviderQuestion | null;
56
- } | null;
56
+ } | null>;
57
57
  /** Open question ids scoped to a run, one asking node, or every run of an app. */
58
58
  export declare function openQuestionIdsFor(target: {
59
59
  run_id: string;
@@ -61,7 +61,7 @@ export declare function openQuestionIdsFor(target: {
61
61
  node_id: string;
62
62
  } | {
63
63
  grantee: string;
64
- }): string[];
64
+ }): Promise<string[]>;
65
65
  /**
66
66
  * Cancel the open questions of a run, of one asking node, or of every run of an
67
67
  * app, through the page mechanism's own cancel (`settleHumanRequest`, first
@@ -1,4 +1,4 @@
1
- var h=Object.defineProperty;var r=(n,e)=>h(n,"name",{value:e,configurable:!0});import{prepared as p}from"../sqlite-statements.js";import{openDb as d}from"../canvas/db.js";import{askingNodeSql as f,getRequest as N}from"../human/requests.js";import{preparePageSource as E}from"../human/page-authoring.js";import{pageAwaitsResponse as a}from"../human/page-schema.js";import{appendRunEvent as _}from"./events.js";function u(n,e){return p(n,"SELECT question_id, grantee, sub, provider, tool, status, option_id FROM provider_approvals WHERE question_id = ?").get(e)??null}r(u,"providerQuestion");function J(n){if(!n.title.trim()||!n.body.trim()||!Array.isArray(n.options)||n.options.length===0)throw new Error("provider approval needs a title, body, and options");const e=new Set(["deny"]);for(const t of n.options){if(!t.option_id||!t.label||e.has(t.option_id))throw new Error("provider approval option ids must be nonempty, unique, and different from deny");e.add(t.option_id)}const o=[...n.options.map(({option_id:t,label:s})=>({id:t,label:s})),{id:"deny",label:"Don't do this"}],i=`export default function Approval() { return <Page title={${JSON.stringify(n.title)}}><UserQuestion id="options" label="Choose an option" body={${JSON.stringify(n.body)}} mode="single" required={true} allowFreetext={false} options={${JSON.stringify(o)}} /></Page>; }`;return E({dialect:"jsx",document:i,delivery:{placement:"inline",inbox:!1,reply:!0}})}r(J,"providerApprovalPage");function v(n,e){return e===null?null:p(n,"SELECT node_id, run_id, grantee FROM node_rows WHERE node_id = ? AND run_id IS NOT NULL").get(e)??null}r(v,"askingNode");function l(n){return JSON.parse(n.specification_json)}r(l,"manifestOf");function c(n,e=d()){if(n.kind!=="page"||!n.settleable)return null;const o=l(n);return v(e,n.requester_node_id??(a(o)?null:o.source?.nodeId??null))}r(c,"questionRun");function m(n){return a(l(n))?"decision":"notice"}r(m,"questionKind");function w(n,e,o=d()){const i=l(n),t=u(o,n.request_id);return{question_id:n.request_id,initiating_app:e,title:n.title,...n.subtitle?{subtitle:n.subtitle}:{},...t?{provider:t.provider,tool:t.tool}:{},steps:i.steps,slots:i.slots.map(s=>({...s.id===void 0?{}:{id:s.id},kind:s.kind,step:s.step,config:s.config}))}}r(w,"questionFields");function T(n,e){const o=c(e,n);o===null||e.state!=="open"||m(e)==="notice"||_(n,o.run_id,o.node_id,"waiting_on_user",w(e,o.grantee,n))}r(T,"appendWaitingOnUser");function L(n,e){const o=e.result_json===null?null:JSON.parse(e.result_json);if(u(n,e.request_id)!==null){const s=o?.responses?.options?.selectedOptionIds?.[0];if(e.outcome==="answered"&&(typeof s!="string"||!s))throw new Error(`provider approval ${e.request_id} has no selected option`);p(n,"UPDATE provider_approvals SET status = ?, option_id = ? WHERE question_id = ? AND status = 'open'").run(e.outcome==="answered"?"answered":"canceled",e.outcome==="answered"?s:null,e.request_id)}if(e.outcome!=="answered"||o===null)return;const t=c(e,n);t!==null&&_(n,t.run_id,t.node_id,"question.answered",{question_id:e.request_id,answer:o.responses??{}})}r(L,"appendQuestionAnswered");function g(n,e,o){return p(o,`SELECT h.request_id, h.specification_json FROM human_requests h JOIN node_rows n ON n.node_id = ${f("h")}
1
+ var g=Object.defineProperty;var r=(n,e)=>g(n,"name",{value:e,configurable:!0});import{openDb as s}from"../canvas/db.js";import{askingNodeSql as c,getRequest as y}from"../human/requests.js";import{preparePageSource as h}from"../human/page-authoring.js";import{pageAwaitsResponse as d}from"../human/page-schema.js";import{appendRunEvent as f}from"./events.js";async function p(n,e){return await n.prepare("SELECT question_id, grantee, sub, provider, tool, status, option_id FROM provider_approvals WHERE question_id = ?").get(e)??null}r(p,"providerQuestion");function j(n){if(!n.title.trim()||!n.body.trim()||!Array.isArray(n.options)||n.options.length===0)throw new Error("provider approval needs a title, body, and options");const e=new Set(["deny"]);for(const o of n.options){if(!o.option_id||!o.label||e.has(o.option_id))throw new Error("provider approval option ids must be nonempty, unique, and different from deny");e.add(o.option_id)}const t=[...n.options.map(({option_id:o,label:a})=>({id:o,label:a})),{id:"deny",label:"Don't do this"}],i=`export default function Approval() { return <Page title={${JSON.stringify(n.title)}}><UserQuestion id="options" label="Choose an option" body={${JSON.stringify(n.body)}} mode="single" required={true} allowFreetext={false} options={${JSON.stringify(t)}} /></Page>; }`;return h({dialect:"jsx",document:i,delivery:{placement:"inline",inbox:!1,reply:!0}})}r(j,"providerApprovalPage");async function N(n,e){return e===null?null:await n.prepare("SELECT node_id, run_id, grantee FROM node_rows WHERE node_id = ? AND run_id IS NOT NULL").get(e)??null}r(N,"askingNode");function u(n){return JSON.parse(n.specification_json)}r(u,"manifestOf");async function l(n,e){if(e??=await s(),n.kind!=="page"||!n.settleable)return null;const t=u(n);return await N(e,n.requester_node_id??(d(t)?null:t.source?.nodeId??null))}r(l,"questionRun");function _(n){return d(u(n))?"decision":"notice"}r(_,"questionKind");async function w(n,e,t){t??=await s();const i=u(n),o=await p(t,n.request_id);return{question_id:n.request_id,initiating_app:e,title:n.title,...n.subtitle?{subtitle:n.subtitle}:{},...o?{provider:o.provider,tool:o.tool}:{},steps:i.steps,slots:i.slots.map(a=>({...a.id===void 0?{}:{id:a.id},kind:a.kind,step:a.step,config:a.config}))}}r(w,"questionFields");async function I(n,e){const t=await l(e,n);t===null||e.state!=="open"||_(e)==="notice"||await f(n,t.run_id,t.node_id,"waiting_on_user",await w(e,t.grantee,n))}r(I,"appendWaitingOnUser");async function J(n,e){const t=e.result_json===null?null:JSON.parse(e.result_json);if(await p(n,e.request_id)!==null){const a=t?.responses?.options?.selectedOptionIds?.[0];if(e.outcome==="answered"&&(typeof a!="string"||!a))throw new Error(`provider approval ${e.request_id} has no selected option`);await n.prepare("UPDATE provider_approvals SET status = ?, option_id = ? WHERE question_id = ? AND status = 'open'").run(e.outcome==="answered"?"answered":"canceled",e.outcome==="answered"?a:null,e.request_id)}if(e.outcome!=="answered"||t===null)return;const o=await l(e,n);o!==null&&await f(n,o.run_id,o.node_id,"question.answered",{question_id:e.request_id,answer:t.responses??{}})}r(J,"appendQuestionAnswered");async function m(n,e,t){return(await t.prepare(`SELECT h.request_id, h.specification_json FROM human_requests h JOIN node_rows n ON n.node_id = ${c("h")}
2
2
  WHERE n.run_id = ? AND h.kind = 'page' AND h.state = 'open' AND h.settleable = 1
3
- ORDER BY h.created_at, h.request_id`).all(n).filter(i=>a(JSON.parse(i.specification_json))===(e==="decision")).map(i=>i.request_id)}r(g,"openIdsOfKind");function F(n,e=d()){return g(n,"decision",e)}r(F,"openQuestionIds");function Q(n,e=d()){return g(n,"notice",e)}r(Q,"openNoticeIds");function O(n){return n.state!=="settled"?"open":n.outcome==="answered"?"answered":"canceled"}r(O,"questionStatus");function S(n){if(n.result_json===null)return null;const e=JSON.parse(n.result_json);return n.outcome==="answered"?e.responses??{}:e}r(S,"questionResult");function $(n,e,o){const i=O(n);return{...w(n,e?.grantee??o.grantee),kind:m(n),...e===null?{}:{run_id:e.run_id,node_id:e.node_id},status:i,...i==="answered"?{answer:S(n)}:{}}}r($,"questionObject");function H(n){const e=N(n);if(e===null||e.kind!=="page"||!e.settleable)return null;const o=d(),i=c(e,o),t=u(o,n);return i===null&&t===null?null:{request:e,run:i,approval:t}}r(H,"getQuestion");function x(n){const[e,o]="run_id"in n?["n.run_id = ?",n.run_id]:"node_id"in n?["n.node_id = ?",n.node_id]:["n.grantee = ?",n.grantee];return d().prepare(`SELECT h.request_id FROM human_requests h JOIN node_rows n ON n.node_id = ${f("h")}
4
- WHERE ${e} AND n.run_id IS NOT NULL AND h.kind = 'page' AND h.state = 'open' AND h.settleable = 1`).all(o).map(i=>i.request_id)}r(x,"openQuestionIdsFor");async function W(n,e){const o=x(n);if(!o.length)return 0;const{cancelHumanTicket:i}=await import("../../daemon/human/finish.js");let t=0;for(const s of o)(await i(s,{reason:e,actor:"crtrd"})).outcome==="settled"&&(t+=1);return t}r(W,"cancelOpenQuestions");export{L as appendQuestionAnswered,T as appendWaitingOnUser,W as cancelOpenQuestions,H as getQuestion,Q as openNoticeIds,F as openQuestionIds,x as openQuestionIdsFor,J as providerApprovalPage,m as questionKind,$ as questionObject,S as questionResult,c as questionRun,O as questionStatus};
3
+ ORDER BY h.created_at, h.request_id`).all(n)).filter(i=>d(JSON.parse(i.specification_json))===(e==="decision")).map(i=>i.request_id)}r(m,"openIdsOfKind");async function T(n,e){return e??=await s(),await m(n,"decision",e)}r(T,"openQuestionIds");async function L(n,e){return e??=await s(),await m(n,"notice",e)}r(L,"openNoticeIds");function E(n){return n.state!=="settled"?"open":n.outcome==="answered"?"answered":"canceled"}r(E,"questionStatus");function v(n){if(n.result_json===null)return null;const e=JSON.parse(n.result_json);return n.outcome==="answered"?e.responses??{}:e}r(v,"questionResult");async function F(n,e,t){const i=E(n);return{...await w(n,e?.grantee??t.grantee),kind:_(n),...e===null?{}:{run_id:e.run_id,node_id:e.node_id},status:i,...i==="answered"?{answer:v(n)}:{}}}r(F,"questionObject");async function Q(n){const e=await y(n);if(e===null||e.kind!=="page"||!e.settleable)return null;const t=await s(),i=await l(e,t),o=await p(t,n);return i===null&&o===null?null:{request:e,run:i,approval:o}}r(Q,"getQuestion");async function O(n){const[e,t]="run_id"in n?["n.run_id = ?",n.run_id]:"node_id"in n?["n.node_id = ?",n.node_id]:["n.grantee = ?",n.grantee];return(await(await s()).prepareUncached(`SELECT h.request_id FROM human_requests h JOIN node_rows n ON n.node_id = ${c("h")}
4
+ WHERE ${e} AND n.run_id IS NOT NULL AND h.kind = 'page' AND h.state = 'open' AND h.settleable = 1`).all(t)).map(i=>i.request_id)}r(O,"openQuestionIdsFor");async function $(n,e){const t=await O(n);if(!t.length)return 0;const{cancelHumanTicket:i}=await import("../../daemon/human/finish.js");let o=0;for(const a of t)(await i(a,{reason:e,actor:"crtrd"})).outcome==="settled"&&(o+=1);return o}r($,"cancelOpenQuestions");export{J as appendQuestionAnswered,I as appendWaitingOnUser,$ as cancelOpenQuestions,Q as getQuestion,L as openNoticeIds,T as openQuestionIds,O as openQuestionIdsFor,j as providerApprovalPage,_ as questionKind,F as questionObject,v as questionResult,l as questionRun,E as questionStatus};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var l=(n,i)=>f(n,"name",{value:i,configurable:!0});import{randomUUID as d}from"node:crypto";import{BrokerClient as h}from"../broker-client/index.js";const a=3e3;function w(n){return new Promise((i,r)=>{const o=new h(n),u=d();let s=!1;const c=setTimeout(()=>t(()=>r(new Error(`timed out after ${a}ms waiting for the broker to ack the auth reload`))),a);typeof c.unref=="function"&&c.unref();function t(e){if(!s){s=!0,clearTimeout(c);try{o.close()}catch{}e()}}l(t,"finish"),o.on("error",e=>t(()=>r(e))),o.on("close",()=>t(()=>r(new Error("broker connection closed before it acked the auth reload")))),o.on("connect",()=>{o.send({type:"hello",role:"observer",client_id:u}),o.send({type:"reload_auth"})}),o.on("frame",e=>{e.type==="ack"&&e.for==="reload_auth"&&e.ok?t(()=>i()):e.type==="error"&&t(()=>r(new Error(e.message)))}),o.connect()})}l(w,"reloadAuthLive");export{w as reloadAuthLive};
1
+ var f=Object.defineProperty;var l=(n,i)=>f(n,"name",{value:i,configurable:!0});import{randomUUID as d}from"node:crypto";import{BrokerClient as h}from"../broker-client/index.js";const a=3e3;function y(n){return new Promise(async(i,r)=>{const o=new h(n),u=d();let s=!1;const c=setTimeout(()=>t(()=>r(new Error(`timed out after ${a}ms waiting for the broker to ack the auth reload`))),a);typeof c.unref=="function"&&c.unref();function t(e){if(!s){s=!0,clearTimeout(c);try{o.close()}catch{}e()}}l(t,"finish"),o.on("error",e=>t(()=>r(e))),o.on("close",()=>t(()=>r(new Error("broker connection closed before it acked the auth reload")))),o.on("connect",()=>{o.send({type:"hello",role:"observer",client_id:u}),o.send({type:"reload_auth"})}),o.on("frame",e=>{e.type==="ack"&&e.for==="reload_auth"&&e.ok?t(()=>i()):e.type==="error"&&t(()=>r(new Error(e.message)))}),o.connect()})}l(y,"reloadAuthLive");export{y as reloadAuthLive};
@@ -13,11 +13,11 @@ export { buildProjectContextBlock, contextDirNote, orchestratorContextNote };
13
13
  * `assembleNodeSubject`'s profile resolution). This absolute-path disclosure
14
14
  * is intentional (spec-approved): the agent must know its full purview, not a
15
15
  * redacted count. */
16
- export declare function profileNote(nodeId: string): string;
16
+ export declare function profileNote(nodeId: string): Promise<string>;
17
17
  /** The graph mini-map: the ancestry trunk (root first), then this node marked
18
18
  * `● you`, then its immediate children. Returns '' for a lone root with no
19
19
  * children (nothing to map). Exported for testing. */
20
- export declare function buildGraphMap(nodeId: string): string;
20
+ export declare function buildGraphMap(nodeId: string): Promise<string>;
21
21
  /** Why a node was born or woken, as carried from the fired cron to the
22
22
  * injection seam. `ownerName` is the armer's resolved display name when it
23
23
  * still exists (a reaped cron's armer renders as a bare id, never crashes). */
@@ -36,7 +36,7 @@ export interface WakeOrigin {
36
36
  }
37
37
  /** Build the provenance a fired cron carries to its injection seam, resolving
38
38
  * the armer's display name if that node still exists. */
39
- export declare function cronWakeOrigin(c: Cron, kind: WakeOrigin['kind']): WakeOrigin;
39
+ export declare function cronWakeOrigin(c: Cron, kind: WakeOrigin['kind']): Promise<WakeOrigin>;
40
40
  /** Render the cron provenance block. The BIRTH variant names the ARMER
41
41
  * explicitly ("armed by node X") so a newborn never reads that id as its own;
42
42
  * the REVIVE variant drops armer attribution — a cron can revive a node it did
@@ -50,7 +50,7 @@ export declare function buildWakeBearings(origin: WakeOrigin): string;
50
50
  /** The bearings on the row-backed delivery engine: the knowledge catalog and
51
51
  * the workspace-open documents render against `ctx`'s ledger; `delivered`
52
52
  * lists what they delivered, for the caller to record. */
53
- export declare function buildContextBearings(nodeId: string, ctx: RenderContext): {
53
+ export declare function buildContextBearings(nodeId: string, ctx: RenderContext): Promise<{
54
54
  content: string;
55
55
  delivered: DeliveredDoc[];
56
- };
56
+ }>;
@@ -1,7 +1,7 @@
1
- var k=Object.defineProperty;var a=(e,n)=>k(e,"name",{value:n,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as y,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as p,orchestratorContextNote as h,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{CONTEXT_INTRO_CUSTOM_TYPE as J}from"../../shared/generated-context.js";function Y(e){const n=s(e);return n===null?"":$(n.cwd,n.profile_id)}a(Y,"profileNote");function E(e){const n=[],r=new Set([e]);let o=s(e)?.parent??null;for(;o!==null&&o!==""&&!r.has(o);){r.add(o);const t=s(o);if(t===null)break;n.unshift(t),o=t.parent??null}return n}a(E,"ancestorTrunk");const X=5;function j(e){return g(e).map(n=>s(n.node_id)).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>l(n.status)-l(r.status))}a(j,"childNodes");function A(e){const n=s(e);if(n===null)return"";const r=E(e),o=j(e);return C(e,n.kind,n.mode,r,o)}a(A,"buildGraphMap");function B(e){const n=s(e),r=n?.fork_from,o=r!=null&&r!==""&&y(r)?s(r):null,t=o!==null?`${r} ("${d(o)}")`:r??"";return S(e,n?.kind??"general",n?.mode??"base",r,t)}a(B,"buildIdentityAssertion");function R(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(R,"armerPhrase");function F(e,n){const r=e.created_by!=null?s(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:d(r)}:{},armedAt:e.created,recur:e.recur}}a(F,"cronWakeOrigin");function I(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
1
+ var b=Object.defineProperty;var a=(e,n)=>b(e,"name",{value:n,configurable:!0});import{getNode as i,fullName as d,isSafeNodeId as k,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as w,contextDirNote as f,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e){const n=await i(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e){const n=[],r=new Set([e]);let t=(await i(e))?.parent??null;for(;t!==null&&t!==""&&!r.has(t);){r.add(t);const o=await i(t);if(o===null)break;n.unshift(o),t=o.parent??null}return n}a(E,"ancestorTrunk");const I=5;async function j(e){return(await Y(await g(e),async n=>await i(n.node_id))).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>l(n.status)-l(r.status))}a(j,"childNodes");async function B(e){const n=await i(e);if(n===null)return"";const r=await E(e),t=await j(e);return C(e,n.kind,n.mode,r,t)}a(B,"buildGraphMap");async function R(e){const n=await i(e),r=n?.fork_from,t=r!=null&&r!==""&&k(r)?await i(r):null,o=t!==null?`${r} ("${d(t)}")`:r??"";return S(e,n?.kind??"general",n?.mode??"base",r,o)}a(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(T,"armerPhrase");async function K(e,n){const r=e.created_by!=null?await i(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:d(r)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
2
  ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const o=R(e);return`<crtr-wake>
4
- ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(I,"buildWakeBearings");function T(e){return O(e?.managed_worktree)}a(T,"managedWorktreeNote");function D(e,n,r){const o=s(e),t=["<crtr-bearings>",B(e)],u=A(e);u!==""&&t.push("","## Your place in the canvas",u),t.push("","## Your documents and context directory",p(e,o?.grantee));const i=Y(e);i!==""&&t.push("",i);const c=T(o);c!==""&&t.push("","## Your managed worktree",c),o?.mode==="orchestrator"&&t.push("",h()),t.push("</crtr-bearings>");const w=_(e)??"",m=o?.cwd!==void 0?f(o.cwd):"";return[t.join(`
6
- `),n,r,w,m].filter(b=>b!=="").join(`
7
- `)}a(D,"bearingsShell");function K(e,n){const r=v(n),o=x(n);return{content:D(e,r.content,o.content),delivered:[...r.delivered,...o.delivered]}}a(K,"buildContextBearings");export{J as CONTEXT_INTRO_CUSTOM_TYPE,K as buildContextBearings,A as buildGraphMap,f as buildProjectContextBlock,I as buildWakeBearings,p as contextDirNote,F as cronWakeOrigin,h as orchestratorContextNote,Y as profileNote};
3
+ </crtr-wake>`;const t=T(e);return`<crtr-wake>
4
+ ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
+ </crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,n,r){const t=await i(e),o=["<crtr-bearings>",await R(e)],s=await B(e);s!==""&&o.push("","## Your place in the canvas",s),o.push("","## Your documents and context directory",f(e,t?.grantee));const u=await A(e);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=_(e)??"",m=t?.cwd!==void 0?w(t.cwd):"";return[o.join(`
6
+ `),n,r,h,m].filter(y=>y!=="").join(`
7
+ `)}a(W,"bearingsShell");async function z(e,n){const r=await v(n),t=await x(n);return{content:await W(e,r.content,t.content),delivered:[...r.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,w as buildProjectContextBlock,q as buildWakeBearings,f as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var n=(o,r)=>_(o,"name",{value:r,configurable:!0});import{randomUUID as y}from"node:crypto";import{getNode as p}from"../canvas/canvas.js";import{BrokerClient as h}from"../broker-client/index.js";import{gatewayCommandRowsFromDetail as k,gatewayMemoryRows as v}from"./chat-inventory-rows.js";import{isBrokerLive as w}from"./model-swap.js";const T=15e3,g=1,C=n(o=>({node_id:o,broker_live:!1,commands:[],memory_refs:[]}),"empty");function S(o){const r=p(o);return r===null||!w(r)?Promise.resolve(C(o)):new Promise(a=>{const e=new h(o),u=y();let f=!1,d=!1,i,s;const l=setTimeout(()=>m(),T);typeof l.unref=="function"&&l.unref();function m(){if(!f){f=!0,clearTimeout(l);try{e.close()}catch{}a({node_id:o,broker_live:d,commands:i??[],memory_refs:s??[]})}}n(m,"finish");function c(){i!==void 0&&s!==void 0&&m()}n(c,"settleWhenComplete"),e.on("error",()=>m()),e.on("close",()=>m()),e.on("connect",()=>{d=!0,e.send({type:"hello",role:"observer",client_id:u,snapshot_tail:g}),e.send({type:"get_commands"}),e.request({type:"list_memory_refs"}).then(t=>{s=t.kind==="list_memory_refs"?v(t.refs):[],c()},()=>{s=[],c()})}),e.on("frame",t=>{if(t.type==="ack"&&t.for==="get_commands"){i=t.ok?k(t.detail):[],c();return}t.type==="error"&&t.id===void 0&&(i??=[],c())}),e.connect()})}n(S,"readChatInventory");export{S as readChatInventory};
1
+ var y=Object.defineProperty;var n=(o,r)=>y(o,"name",{value:r,configurable:!0});import{randomUUID as _}from"node:crypto";import{getNode as p}from"../canvas/canvas.js";import{BrokerClient as h}from"../broker-client/index.js";import{gatewayCommandRowsFromDetail as k,gatewayMemoryRows as w}from"./chat-inventory-rows.js";import{isBrokerLive as v}from"./model-swap.js";const T=15e3,g=1,C=n(o=>({node_id:o,broker_live:!1,commands:[],memory_refs:[]}),"empty");async function S(o){const r=await p(o);return r===null||!v(r)?Promise.resolve(C(o)):new Promise(async d=>{const e=new h(o),u=_();let f=!1,a=!1,i,s;const l=setTimeout(()=>m(),T);typeof l.unref=="function"&&l.unref();function m(){if(!f){f=!0,clearTimeout(l);try{e.close()}catch{}d({node_id:o,broker_live:a,commands:i??[],memory_refs:s??[]})}}n(m,"finish");function c(){i!==void 0&&s!==void 0&&m()}n(c,"settleWhenComplete"),e.on("error",()=>m()),e.on("close",()=>m()),e.on("connect",()=>{a=!0,e.send({type:"hello",role:"observer",client_id:u,snapshot_tail:g}),e.send({type:"get_commands"}),e.request({type:"list_memory_refs"}).then(t=>{s=t.kind==="list_memory_refs"?w(t.refs):[],c()},()=>{s=[],c()})}),e.on("frame",t=>{if(t.type==="ack"&&t.for==="get_commands"){i=t.ok?k(t.detail):[],c();return}t.type==="error"&&t.id===void 0&&(i??=[],c())}),e.connect()})}n(S,"readChatInventory");export{S as readChatInventory};