@yaks/session 0.0.0-stage → 0.2.36

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 (393) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1392 -2
  3. package/_dist/admission.d.ts +15 -0
  4. package/_dist/admission.d.ts.map +1 -0
  5. package/_dist/announce.d.ts +17 -0
  6. package/_dist/announce.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +200 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/append.d.ts +10 -0
  10. package/_dist/append.d.ts.map +1 -0
  11. package/_dist/archive.d.ts +6 -0
  12. package/_dist/archive.d.ts.map +1 -0
  13. package/_dist/asks.d.ts +11 -0
  14. package/_dist/asks.d.ts.map +1 -0
  15. package/_dist/audit.d.ts +15 -0
  16. package/_dist/audit.d.ts.map +1 -0
  17. package/_dist/bounce.d.ts +19 -0
  18. package/_dist/bounce.d.ts.map +1 -0
  19. package/_dist/bus.d.ts +8 -0
  20. package/_dist/bus.d.ts.map +1 -0
  21. package/_dist/cache.d.ts +45 -0
  22. package/_dist/cache.d.ts.map +1 -0
  23. package/_dist/child-notice.d.ts +6 -0
  24. package/_dist/child-notice.d.ts.map +1 -0
  25. package/_dist/children.d.ts +59 -0
  26. package/_dist/children.d.ts.map +1 -0
  27. package/_dist/cli.d.ts +8 -0
  28. package/_dist/cli.d.ts.map +1 -0
  29. package/_dist/comp.d.ts +9 -0
  30. package/_dist/comp.d.ts.map +1 -0
  31. package/_dist/compact.d.ts +19 -0
  32. package/_dist/compact.d.ts.map +1 -0
  33. package/_dist/conversation.d.ts +158 -0
  34. package/_dist/conversation.d.ts.map +1 -0
  35. package/_dist/cost.d.ts +13 -0
  36. package/_dist/cost.d.ts.map +1 -0
  37. package/_dist/deferred.d.ts +79 -0
  38. package/_dist/deferred.d.ts.map +1 -0
  39. package/_dist/ended.d.ts +27 -0
  40. package/_dist/ended.d.ts.map +1 -0
  41. package/_dist/files.d.ts +73 -0
  42. package/_dist/files.d.ts.map +1 -0
  43. package/_dist/fork.d.ts +23 -0
  44. package/_dist/fork.d.ts.map +1 -0
  45. package/_dist/graft.d.ts +33 -0
  46. package/_dist/graft.d.ts.map +1 -0
  47. package/_dist/graph.d.ts +14 -0
  48. package/_dist/graph.d.ts.map +1 -0
  49. package/_dist/handoff.d.ts +29 -0
  50. package/_dist/handoff.d.ts.map +1 -0
  51. package/_dist/imported.d.ts +63 -0
  52. package/_dist/imported.d.ts.map +1 -0
  53. package/_dist/intake.d.ts +43 -0
  54. package/_dist/intake.d.ts.map +1 -0
  55. package/_dist/joined.d.ts +35 -0
  56. package/_dist/joined.d.ts.map +1 -0
  57. package/_dist/lease.d.ts +21 -0
  58. package/_dist/lease.d.ts.map +1 -0
  59. package/_dist/lines.d.ts +13 -0
  60. package/_dist/lines.d.ts.map +1 -0
  61. package/_dist/mod.d.ts +107 -0
  62. package/_dist/mod.d.ts.map +1 -0
  63. package/_dist/naming.d.ts +10 -0
  64. package/_dist/naming.d.ts.map +1 -0
  65. package/_dist/native.d.ts +13 -0
  66. package/_dist/native.d.ts.map +1 -0
  67. package/_dist/parts.d.ts +145 -0
  68. package/_dist/parts.d.ts.map +1 -0
  69. package/_dist/plugin.d.ts +33 -0
  70. package/_dist/plugin.d.ts.map +1 -0
  71. package/_dist/project.d.ts +67 -0
  72. package/_dist/project.d.ts.map +1 -0
  73. package/_dist/prose.d.ts +7 -0
  74. package/_dist/prose.d.ts.map +1 -0
  75. package/_dist/providers.d.ts +36 -0
  76. package/_dist/providers.d.ts.map +1 -0
  77. package/_dist/reach.d.ts +39 -0
  78. package/_dist/reach.d.ts.map +1 -0
  79. package/_dist/react.d.ts +236 -0
  80. package/_dist/react.d.ts.map +1 -0
  81. package/_dist/readers.d.ts +221 -0
  82. package/_dist/readers.d.ts.map +1 -0
  83. package/_dist/reap.d.ts +21 -0
  84. package/_dist/reap.d.ts.map +1 -0
  85. package/_dist/recall.d.ts +32 -0
  86. package/_dist/recall.d.ts.map +1 -0
  87. package/_dist/routes.d.ts +15 -0
  88. package/_dist/routes.d.ts.map +1 -0
  89. package/_dist/run.d.ts +81 -0
  90. package/_dist/run.d.ts.map +1 -0
  91. package/_dist/service.d.ts +131 -0
  92. package/_dist/service.d.ts.map +1 -0
  93. package/_dist/source.d.ts +9 -0
  94. package/_dist/source.d.ts.map +1 -0
  95. package/_dist/start.d.ts +29 -0
  96. package/_dist/start.d.ts.map +1 -0
  97. package/_dist/state.d.ts +75 -0
  98. package/_dist/state.d.ts.map +1 -0
  99. package/_dist/status.d.ts +38 -0
  100. package/_dist/status.d.ts.map +1 -0
  101. package/_dist/tail.d.ts +121 -0
  102. package/_dist/tail.d.ts.map +1 -0
  103. package/_dist/timing.d.ts +9 -0
  104. package/_dist/timing.d.ts.map +1 -0
  105. package/_dist/told.d.ts +17 -0
  106. package/_dist/told.d.ts.map +1 -0
  107. package/_dist/tools.d.ts +41 -0
  108. package/_dist/tools.d.ts.map +1 -0
  109. package/_dist/transcript.d.ts +5 -0
  110. package/_dist/transcript.d.ts.map +1 -0
  111. package/_dist/turn.d.ts +49 -0
  112. package/_dist/turn.d.ts.map +1 -0
  113. package/_dist/unknown.d.ts +6 -0
  114. package/_dist/unknown.d.ts.map +1 -0
  115. package/_dist/views.d.ts +9 -0
  116. package/_dist/views.d.ts.map +1 -0
  117. package/_dist/vocab.d.ts +9 -0
  118. package/_dist/vocab.d.ts.map +1 -0
  119. package/_dist/wait.d.ts +15 -0
  120. package/_dist/wait.d.ts.map +1 -0
  121. package/_dist/wake.d.ts +116 -0
  122. package/_dist/wake.d.ts.map +1 -0
  123. package/_dist/watch.d.ts +52 -0
  124. package/_dist/watch.d.ts.map +1 -0
  125. package/_dist/who.d.ts +84 -0
  126. package/_dist/who.d.ts.map +1 -0
  127. package/_dist/window.d.ts +43 -0
  128. package/_dist/window.d.ts.map +1 -0
  129. package/admission.js +137 -0
  130. package/admission.js.map +1 -0
  131. package/admission.ts +164 -0
  132. package/announce.js +123 -0
  133. package/announce.js.map +1 -0
  134. package/announce.ts +126 -0
  135. package/answer.js +372 -0
  136. package/answer.js.map +1 -0
  137. package/answer.ts +426 -0
  138. package/append.js +125 -0
  139. package/append.js.map +1 -0
  140. package/append.ts +205 -0
  141. package/archive.js +62 -0
  142. package/archive.js.map +1 -0
  143. package/archive.ts +62 -0
  144. package/asks.js +80 -0
  145. package/asks.js.map +1 -0
  146. package/asks.ts +106 -0
  147. package/attempt.js +46 -0
  148. package/attempt.js.map +1 -0
  149. package/attempt.ts +60 -0
  150. package/audit.js +57 -0
  151. package/audit.js.map +1 -0
  152. package/audit.ts +65 -0
  153. package/bounce.js +29 -0
  154. package/bounce.js.map +1 -0
  155. package/bounce.ts +34 -0
  156. package/bus.js +568 -0
  157. package/bus.js.map +1 -0
  158. package/bus.ts +683 -0
  159. package/cache.js +169 -0
  160. package/cache.js.map +1 -0
  161. package/cache.ts +230 -0
  162. package/child-notice.js +128 -0
  163. package/child-notice.js.map +1 -0
  164. package/child-notice.ts +136 -0
  165. package/children.js +937 -0
  166. package/children.js.map +1 -0
  167. package/children.ts +925 -0
  168. package/claude-control.js +8 -0
  169. package/claude-control.js.map +1 -0
  170. package/claude-control.ts +12 -0
  171. package/cli.js +23 -0
  172. package/cli.js.map +1 -0
  173. package/cli.ts +28 -0
  174. package/comp.js +76 -0
  175. package/comp.js.map +1 -0
  176. package/comp.ts +78 -0
  177. package/compact.js +157 -0
  178. package/compact.js.map +1 -0
  179. package/compact.ts +209 -0
  180. package/compact_ask.js +280 -0
  181. package/compact_ask.js.map +1 -0
  182. package/compact_ask.ts +199 -0
  183. package/continue.js +131 -0
  184. package/continue.js.map +1 -0
  185. package/continue.ts +143 -0
  186. package/conversation.js +337 -0
  187. package/conversation.js.map +1 -0
  188. package/conversation.ts +593 -0
  189. package/cost.js +111 -0
  190. package/cost.js.map +1 -0
  191. package/cost.ts +93 -0
  192. package/deferred.js +207 -0
  193. package/deferred.js.map +1 -0
  194. package/deferred.ts +219 -0
  195. package/deno.json +1 -0
  196. package/dependencies.js +114 -0
  197. package/dependencies.js.map +1 -0
  198. package/dependencies.ts +110 -0
  199. package/draining.js +20 -0
  200. package/draining.js.map +1 -0
  201. package/draining.ts +26 -0
  202. package/ended.js +210 -0
  203. package/ended.js.map +1 -0
  204. package/ended.ts +225 -0
  205. package/files.js +285 -0
  206. package/files.js.map +1 -0
  207. package/files.ts +318 -0
  208. package/fork.js +96 -0
  209. package/fork.js.map +1 -0
  210. package/fork.ts +124 -0
  211. package/graft.js +97 -0
  212. package/graft.js.map +1 -0
  213. package/graft.ts +88 -0
  214. package/graph.js +49 -0
  215. package/graph.js.map +1 -0
  216. package/graph.ts +61 -0
  217. package/handoff.js +111 -0
  218. package/handoff.js.map +1 -0
  219. package/handoff.ts +147 -0
  220. package/help.js +432 -0
  221. package/help.js.map +1 -0
  222. package/help.ts +431 -0
  223. package/hooks.js +253 -0
  224. package/hooks.js.map +1 -0
  225. package/hooks.ts +333 -0
  226. package/imported.js +259 -0
  227. package/imported.js.map +1 -0
  228. package/imported.ts +201 -0
  229. package/inspect.js +353 -0
  230. package/inspect.js.map +1 -0
  231. package/inspect.ts +378 -0
  232. package/intake.js +115 -0
  233. package/intake.js.map +1 -0
  234. package/intake.ts +124 -0
  235. package/joined.js +67 -0
  236. package/joined.js.map +1 -0
  237. package/joined.ts +69 -0
  238. package/lease.js +146 -0
  239. package/lease.js.map +1 -0
  240. package/lease.ts +151 -0
  241. package/lifecycle.js +49 -0
  242. package/lifecycle.js.map +1 -0
  243. package/lifecycle.ts +46 -0
  244. package/lines.js +171 -0
  245. package/lines.js.map +1 -0
  246. package/lines.ts +177 -0
  247. package/listen.js +604 -0
  248. package/listen.js.map +1 -0
  249. package/listen.ts +976 -0
  250. package/log.js +78 -0
  251. package/log.js.map +1 -0
  252. package/log.ts +88 -0
  253. package/mod.js +107 -0
  254. package/mod.js.map +1 -0
  255. package/mod.ts +113 -0
  256. package/name.js +51 -0
  257. package/name.js.map +1 -0
  258. package/name.ts +84 -0
  259. package/naming.js +96 -0
  260. package/naming.js.map +1 -0
  261. package/naming.ts +102 -0
  262. package/native.js +17 -0
  263. package/native.js.map +1 -0
  264. package/native.ts +17 -0
  265. package/package.json +133 -4
  266. package/parts.js +334 -0
  267. package/parts.js.map +1 -0
  268. package/parts.ts +383 -0
  269. package/plugin.js +77 -0
  270. package/plugin.js.map +1 -0
  271. package/plugin.ts +98 -0
  272. package/project.js +354 -0
  273. package/project.js.map +1 -0
  274. package/project.ts +407 -0
  275. package/prompt.js +57 -0
  276. package/prompt.js.map +1 -0
  277. package/prompt.ts +92 -0
  278. package/prose.js +43 -0
  279. package/prose.js.map +1 -0
  280. package/prose.ts +63 -0
  281. package/providers.js +279 -0
  282. package/providers.js.map +1 -0
  283. package/providers.ts +306 -0
  284. package/pruning.js +80 -0
  285. package/pruning.js.map +1 -0
  286. package/pruning.ts +147 -0
  287. package/reach.js +923 -0
  288. package/reach.js.map +1 -0
  289. package/reach.ts +1107 -0
  290. package/react.js +2259 -0
  291. package/react.js.map +1 -0
  292. package/react.ts +2864 -0
  293. package/readers.js +956 -0
  294. package/readers.js.map +1 -0
  295. package/readers.ts +1017 -0
  296. package/reap.js +60 -0
  297. package/reap.js.map +1 -0
  298. package/reap.ts +65 -0
  299. package/recall.js +67 -0
  300. package/recall.js.map +1 -0
  301. package/recall.ts +114 -0
  302. package/reopen.js +45 -0
  303. package/reopen.js.map +1 -0
  304. package/reopen.ts +44 -0
  305. package/result-entry.js +32 -0
  306. package/result-entry.js.map +1 -0
  307. package/result-entry.ts +34 -0
  308. package/resume.js +266 -0
  309. package/resume.js.map +1 -0
  310. package/resume.ts +283 -0
  311. package/routes.js +129 -0
  312. package/routes.js.map +1 -0
  313. package/routes.ts +147 -0
  314. package/routine.js +179 -0
  315. package/routine.js.map +1 -0
  316. package/routine.ts +191 -0
  317. package/run.js +932 -0
  318. package/run.js.map +1 -0
  319. package/run.ts +999 -0
  320. package/service.js +806 -0
  321. package/service.js.map +1 -0
  322. package/service.ts +911 -0
  323. package/source.js +26 -0
  324. package/source.js.map +1 -0
  325. package/source.ts +40 -0
  326. package/start.js +197 -0
  327. package/start.js.map +1 -0
  328. package/start.ts +214 -0
  329. package/state.js +247 -0
  330. package/state.js.map +1 -0
  331. package/state.ts +404 -0
  332. package/status.js +1222 -0
  333. package/status.js.map +1 -0
  334. package/status.ts +1555 -0
  335. package/status_bench.ts +50 -0
  336. package/statusline.js +187 -0
  337. package/statusline.js.map +1 -0
  338. package/statusline.ts +232 -0
  339. package/tail.js +748 -0
  340. package/tail.js.map +1 -0
  341. package/tail.ts +815 -0
  342. package/talk.js +58 -0
  343. package/talk.js.map +1 -0
  344. package/talk.ts +51 -0
  345. package/task-context.js +41 -0
  346. package/task-context.js.map +1 -0
  347. package/task-context.ts +53 -0
  348. package/texted.js +65 -0
  349. package/texted.js.map +1 -0
  350. package/texted.ts +65 -0
  351. package/timing.js +37 -0
  352. package/timing.js.map +1 -0
  353. package/timing.ts +52 -0
  354. package/told.js +56 -0
  355. package/told.js.map +1 -0
  356. package/told.ts +54 -0
  357. package/tools.js +595 -0
  358. package/tools.js.map +1 -0
  359. package/tools.ts +633 -0
  360. package/transcript.js +34 -0
  361. package/transcript.js.map +1 -0
  362. package/transcript.ts +41 -0
  363. package/turn.js +47 -0
  364. package/turn.js.map +1 -0
  365. package/turn.ts +68 -0
  366. package/unknown.js +8 -0
  367. package/unknown.js.map +1 -0
  368. package/unknown.ts +9 -0
  369. package/views.js +15 -0
  370. package/views.js.map +1 -0
  371. package/views.ts +21 -0
  372. package/vocab.js +24 -0
  373. package/vocab.js.map +1 -0
  374. package/vocab.json +1573 -0
  375. package/vocab.ts +30 -0
  376. package/wait.js +30 -0
  377. package/wait.js.map +1 -0
  378. package/wait.ts +45 -0
  379. package/wake.js +552 -0
  380. package/wake.js.map +1 -0
  381. package/wake.ts +597 -0
  382. package/watch.js +520 -0
  383. package/watch.js.map +1 -0
  384. package/watch.ts +596 -0
  385. package/who.js +309 -0
  386. package/who.js.map +1 -0
  387. package/who.ts +347 -0
  388. package/window.js +179 -0
  389. package/window.js.map +1 -0
  390. package/window.ts +268 -0
  391. package/woken.js +129 -0
  392. package/woken.js.map +1 -0
  393. package/woken.ts +127 -0
package/listen.ts ADDED
@@ -0,0 +1,976 @@
1
+ // What a session hears about its work, one line at a time: a comment on an
2
+ // entity it created or holds a lock on, a knock at it or at that entity, a letter
3
+ // delivered to it, a letter answering one it wrote. `yak session listen` is
4
+ // the command a harness runs under a monitor — Claude Code's Monitor tool reads
5
+ // each line a command prints as one event — so a running agent learns about its
6
+ // work while it works. With `once` it ends once it has said something, for a
7
+ // harness that wakes its agent when a background command ends (Claude Code's
8
+ // background Bash), so an idle agent is woken by what arrives. A wake costs
9
+ // such an agent a read of its whole context, so one wake carries all that is
10
+ // waiting: the command stays up through a quiet window after each line and
11
+ // ends when nothing new came in it, with everything that arrived meanwhile.
12
+ //
13
+ // A line is marked said as it is printed, so the printing is the delivery: the
14
+ // command's output goes to the agent's own harness, never to a file a second
15
+ // loop watches, which can vanish and take every line after it.
16
+ //
17
+ // Person-written comments on records a session created follow it without a
18
+ // claim; once it ends they are held for the project the record is filed under,
19
+ // just like mail. On a record a session holds, an outside session hears every
20
+ // comment but its own, and a native transcript only a person's: its inputs
21
+ // wake it for a model turn.
22
+ //
23
+ // A person's comment on an open task that is not blocked is for the session at
24
+ // work on it, and for nobody else ({@link taken}): the holder hears it, and
25
+ // where no live session holds the task one is started on it with the comment
26
+ // as its first input (./start.ts). It follows neither the session that filed
27
+ // the task nor its project, so the operator is not asked to relay it.
28
+ // A reply is the old session's while it may still hear it, and the project's
29
+ // once it cannot. The session that wrote a letter hears the answer, wherever
30
+ // the far side sent it, until that session is over (its harness ended it, or
31
+ // its transcript stopped or failed). From then on the reply is held for the
32
+ // project it reached (the letter went out from the project's address, so the
33
+ // answer is routed to the project, @yaks/mail's `mail.target`), and the next
34
+ // session of that project hears it. A session's project is the home of the
35
+ // persona it wears (@yaks/persona's `persona.home`, "the project it works
36
+ // for"), with every project filed under that home at any depth, since a
37
+ // sub-project's work is done under its parent's persona (@yaks/project). A
38
+ // session wearing no persona has no project and hears only its own replies.
39
+ //
40
+ // A letter no session wrote to, or whose writer can no longer hear it, is the
41
+ // project's from the start: a new letter to the project's address (a platform
42
+ // alert, a person's feedback), an answer to a tracker's letter (another graph
43
+ // sent it, so this one never kept it), or to a letter that arrived here.
44
+ // Nobody else could ever hear it. An address filed under the project
45
+ // (@yaks/project's `filed.project` on an entity wearing @yaks/mail's `email`)
46
+ // is the project's too, since an entity wears one address: hello@yaks.app,
47
+ // where every platform letter asks to be answered, is filed under the
48
+ // platform's project, which wears hello@bot.yak.sh. A knock at the project is
49
+ // held the same way: the graph's own news for whoever works for it, such as
50
+ // a bug the tracker opened (@yaks/heal knocks with the task it files).
51
+ //
52
+ // What is held for a project a person operates is the operator's alone: a
53
+ // project is operated when a session a person opened (`session.operator`)
54
+ // wears a persona homed at it or at a project it is filed under. TaskMaster is
55
+ // such a session, and the agents it starts wear the same persona, so without
56
+ // this the first of them to call a tool would take the platform's feedback
57
+ // at its hook. While no operator can hear, the item stays held, and the next
58
+ // session a person opens for the project hears it. Only a project nobody has
59
+ // ever operated gives what is held for it to any session that works for it.
60
+ //
61
+ // "The next session" is one at work. A native transcript at rest (settled
62
+ // between turns, however long ago) hears only what is addressed to it, never
63
+ // what is held for its project: a settled transcript is never over, so every
64
+ // one the project ever ran would otherwise stay an heir, and each item would
65
+ // wake one to spend a model turn on news meant for a live line of work.
66
+ //
67
+ // Nothing starts a session for a held reply when none comes: it waits for
68
+ // one. Only a person's comment on an open task does (./start.ts).
69
+ //
70
+ // Where a project wears `helper`, what is addressed to its operator and no
71
+ // person wrote is a helper's to take (./routine.ts marks it `routine` as it is
72
+ // written, ./help.ts starts the helper): no session hears a marked item, so
73
+ // the operator's own is woken only by a person's words and a helper's hand-up.
74
+ //
75
+ // Each item is marked `notified` as it is said, so it is said once, including
76
+ // one that arrived while nothing was listening: a monitor that expired and was
77
+ // armed again hears the gap. A session never hears what it wrote itself, and a
78
+ // knock left at two addresses it hears (itself and its project) is said once.
79
+ //
80
+ // A line carries the item whole, so reading it needs no second command. A
81
+ // managed run's receipt (@yaks/spawn's completion: the run's report as a
82
+ // comment on its task that knocks whoever started it) is said as the knock it
83
+ // is, with where the task stands now.
84
+ //
85
+ // The graph is a file other processes write, so this reads it again every few
86
+ // seconds rather than waiting on commits: @yaks/client's `watch` hears only the
87
+ // commits made in its own process.
88
+
89
+ import type { Actor, Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
90
+ import { signed } from '@yaks/graph/provenance'
91
+ import { Stale } from '@yaks/graph/errors'
92
+ import { token } from '@yaks/graph/sha256'
93
+ import { human } from '@yaks/id'
94
+ import { called } from '@yaks/id/graph'
95
+ import { drawn, eids as mentioned, type Ids } from '@yaks/markdown/structural'
96
+ import { statusOf } from '@yaks/task'
97
+ import {
98
+ absent,
99
+ type And,
100
+ and,
101
+ type Clause,
102
+ eq,
103
+ every,
104
+ fields,
105
+ type Input,
106
+ line,
107
+ list,
108
+ or,
109
+ present,
110
+ walk,
111
+ } from '@yaks/query'
112
+ import { safe } from '@yaks/text'
113
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
114
+ import { CLAIM, SESSION } from './comp.js'
115
+
116
+ let NOTIFIED = 'notified'
117
+ // A helper's to take (./help.ts): no session's listener says it.
118
+ let ROUTINE = 'routine'
119
+
120
+ let str = (v: unknown): string => typeof v == 'string' ? v : ''
121
+ let comp = (b: Bundle | undefined, name: string): Comp =>
122
+ (b?.[name] ?? {}) as Comp
123
+ let fold = (text: string): string => text.replace(/\s+/g, ' ').trim()
124
+ let value = (eids: Eid[]): Input => eids.length == 1 ? eids[0] : list(...eids)
125
+
126
+ /** The queries for what is addressed to one session and not yet said, with
127
+ * every comment on what it holds unless `claimedComments` is false. Each
128
+ * asks about one component the graph declares; a graph without knocks or
129
+ * letters has nothing to hear about them. */
130
+ let addressedTo = (
131
+ vocab: Vocab,
132
+ session: Eid,
133
+ claimedComments = true,
134
+ ): And[] => {
135
+ let has = (name: string) => !!vocab.comp(name)
136
+ let unsaid = (...clauses: Clause[]) => and(...clauses, absent(NOTIFIED))
137
+ return [
138
+ ...has('comment') && claimedComments
139
+ ? [
140
+ unsaid(
141
+ present('comment'),
142
+ eq(`comment.target.${CLAIM}.session`, session),
143
+ ),
144
+ ]
145
+ : [],
146
+ ...has('knock')
147
+ ? [
148
+ unsaid(present('knock'), absent(ROUTINE), eq('knock.target', session)),
149
+ unsaid(
150
+ present('knock'),
151
+ absent(ROUTINE),
152
+ eq(`knock.target.${CLAIM}.session`, session),
153
+ ),
154
+ ]
155
+ : [],
156
+ ...has('deliver')
157
+ ? [unsaid(present('deliver'), eq('deliver.to', session))]
158
+ : [],
159
+ ]
160
+ }
161
+
162
+ /** How each of these sessions that is over came to be: `ended` where its
163
+ * harness ended it, else its transcript's `stopped` or `failed`. Late output
164
+ * cannot hide a stop; a settled turn is still live. A failed transcript is
165
+ * over for what reaches it through what it wrote or holds, but what is said
166
+ * to it by name opens its next turn (./bus.ts). */
167
+ export let ends = async (
168
+ graph: Pick<Graph, 'read'>,
169
+ sessions: Bundle[],
170
+ ): Promise<Map<Eid, 'ended' | 'stopped' | 'failed'>> => {
171
+ let gone = sessions.filter((s) => comp(s, SESSION).ended == true)
172
+ let live = sessions.filter((s) => comp(s, SESSION).ended != true)
173
+ let resting = live.length
174
+ ? await graph.read(and(
175
+ eq('entity.eid', value(live.map((s) => s.entity.eid))),
176
+ eq(`${SESSION}.status`, list('stopped', 'failed')),
177
+ fields('entity.eid', `${SESSION}.status`),
178
+ ))
179
+ : []
180
+ return new Map([
181
+ ...gone.map((s) => [s.entity.eid, 'ended'] as const),
182
+ ...resting.map((s) =>
183
+ [
184
+ s.entity.eid,
185
+ comp(s, SESSION).status == 'failed' ? 'failed' : 'stopped',
186
+ ] as const
187
+ ),
188
+ ])
189
+ }
190
+
191
+ /** The sessions whose harness ended or whose transcript stopped or failed
192
+ * ({@link ends}). */
193
+ export let ended = async (
194
+ graph: Pick<Graph, 'read'>,
195
+ sessions: Bundle[],
196
+ ): Promise<Set<Eid>> => new Set((await ends(graph, sessions)).keys())
197
+
198
+ let eids = (rows: Bundle[]): Eid[] => rows.map((b) => b.entity.eid)
199
+
200
+ /** The native transcripts among the sessions `clauses` pick, read with
201
+ * `props`: no `process` running it outside the graph, no outside harness's
202
+ * `log` read into it, and a `using` entry. The session's own row is asked
203
+ * first, in a read of its own: in one statement SQLite looks for the `using`
204
+ * through every candidate's entries whatever the tests beside it say, an
205
+ * imported transcript's whole log included, on every pass of the bus. */
206
+ export let natives = async (
207
+ graph: Pick<Graph, 'vocab' | 'read'>,
208
+ clauses: Clause[],
209
+ props: string[],
210
+ ): Promise<Bundle[]> => {
211
+ let own = eids(
212
+ await graph.read(and(
213
+ ...clauses,
214
+ present(SESSION),
215
+ ...graph.vocab.comp('process') ? [absent('process')] : [],
216
+ ...graph.vocab.prop(SESSION, 'transcript')
217
+ ? [absent(`${SESSION}.transcript`)]
218
+ : [],
219
+ fields('entity.eid'),
220
+ )),
221
+ )
222
+ return own.length
223
+ ? await graph.read(and(
224
+ eq('entity.eid', value(own)),
225
+ present('entries.using'),
226
+ fields(...props),
227
+ ))
228
+ : []
229
+ }
230
+
231
+ // The transcript statuses of a turn in progress: the model or a tool owes it
232
+ // an answer.
233
+ let WORKING = ['pending', 'running']
234
+
235
+ /** Which of these native transcripts are at work, mid-turn: only such a one
236
+ * hears what is held for its project. A status is read off the transcript's
237
+ * entries, so it is asked of native transcripts alone, never of an outside
238
+ * session's long log. */
239
+ export let atWork = async (
240
+ graph: Pick<Graph, 'read'>,
241
+ sessions: Eid[],
242
+ ): Promise<Eid[]> =>
243
+ sessions.length
244
+ ? eids(
245
+ await graph.read(and(
246
+ eq('entity.eid', value(sessions)),
247
+ eq(`${SESSION}.status`, list(...WORKING)),
248
+ fields(`${SESSION}.persona`),
249
+ )),
250
+ )
251
+ : []
252
+
253
+ /** Every project, by the project it is filed under (@yaks/project's
254
+ * sub-projects, `filed.project`), or '' at the top. */
255
+ export type Projects = Map<Eid, Eid>
256
+
257
+ /** The graph's {@link Projects}: one read of the projects alone. A walk down
258
+ * `filed.project` from a project would pass through every task filed there. */
259
+ export let projects = async (
260
+ graph: Pick<Graph, 'vocab' | 'read'>,
261
+ ): Promise<Projects> =>
262
+ new Map(
263
+ graph.vocab.prop('filed', 'project') && graph.vocab.comp('project')
264
+ ? (await graph.read(and(present('project'), fields('filed.project'))))
265
+ .map((b) => [b.entity.eid, str(comp(b, 'filed').project)])
266
+ : [],
267
+ )
268
+
269
+ /** A project and every project filed under it at any depth. */
270
+ export let below = (tree: Projects, project: Eid): Eid[] => {
271
+ let found = [project], seen = new Set(found)
272
+ for (let i = 0; i < found.length; i++) {
273
+ for (let [p, parent] of tree) {
274
+ if (parent == found[i] && !seen.has(p)) found.push(p), seen.add(p)
275
+ }
276
+ }
277
+ return found
278
+ }
279
+
280
+ /** The projects a session works for: the home of the persona it wears, and
281
+ * every project filed under that home at any depth, from `tree` when the
282
+ * caller keeps one. None when it wears no persona. */
283
+ export let worksFor = async (
284
+ graph: Pick<Graph, 'vocab' | 'read' | 'get'>,
285
+ s: Bundle | undefined,
286
+ tree?: Projects,
287
+ ): Promise<Eid[]> => {
288
+ let persona = str(comp(s, SESSION).persona)
289
+ if (!persona || !graph.vocab.prop('persona', 'home')) return []
290
+ let [worn] = await graph.read(
291
+ and(eq('entity.eid', persona), fields('persona.home')),
292
+ )
293
+ let home = str(comp(worn, 'persona').home)
294
+ return home ? below(tree ?? await projects(graph), home) : []
295
+ }
296
+
297
+ /** The projects among `reach` that no person operates: none of them is the
298
+ * home, or filed under the home, of a persona a session a person opened
299
+ * (`session.operator`) wears, whether or not that session can hear now. What
300
+ * is held for an operated project waits for its operator. */
301
+ let unoperated = async (
302
+ graph: Pick<Graph, 'vocab' | 'read' | 'get'>,
303
+ reach: Eid[],
304
+ tree?: Projects,
305
+ ): Promise<Eid[]> => {
306
+ if (!reach.length || !graph.vocab.prop(SESSION, 'operator')) return reach
307
+ let worn = await graph.read(
308
+ line`.${SESSION}.operator=true&.${SESSION}.persona&.fields=${SESSION}.persona`,
309
+ )
310
+ let personas = [...new Set(worn.map((b) => str(comp(b, SESSION).persona)))]
311
+ let homes = personas.length ? await graph.get(personas, ['persona']) : []
312
+ let run = homes.map((b) => str(comp(b, 'persona').home)).filter(Boolean)
313
+ if (!run.length) return reach
314
+ let known = tree ?? await projects(graph)
315
+ let operated = new Set(run.flatMap((home) => below(known, home)))
316
+ return reach.filter((p) => !operated.has(p))
317
+ }
318
+
319
+ /** The native transcripts at work that may hear these items once they are
320
+ * held: mid-turn, each wearing a persona whose home is a project an item
321
+ * reached, or a project that one is filed under. One settled between turns
322
+ * hears none of it, and an outside session hears it on its own calls, so the
323
+ * feed never reads either. Whether an item is held yet is {@link held}'s to
324
+ * say. */
325
+ export let heirs = async (
326
+ graph: Pick<Graph, 'vocab' | 'read' | 'get'>,
327
+ letters: Bundle[],
328
+ ): Promise<Eid[]> => {
329
+ if (!graph.vocab.prop('persona', 'home')) return []
330
+ // Many unread comments can share a target. Read each target's filing once
331
+ // through this same caller's graph, then retain the items' project order.
332
+ let targets = [
333
+ ...new Set(
334
+ letters.filter((b) => b.comment).map((b) =>
335
+ str(comp(b, 'comment').target)
336
+ ),
337
+ ),
338
+ ]
339
+ let filed = new Map(
340
+ (targets.length ? await graph.get(targets, ['filed']) : []).map((
341
+ b,
342
+ ) => [b.entity.eid, str(comp(b, 'filed').project)]),
343
+ )
344
+ let reached = [
345
+ ...new Set(
346
+ letters.map((b) =>
347
+ b.comment
348
+ ? filed.get(str(comp(b, 'comment').target)) ?? ''
349
+ : str(comp(b, 'mail').target) || str(comp(b, 'knock').target)
350
+ ).filter(Boolean),
351
+ ),
352
+ ]
353
+ if (!reached.length) return []
354
+ let homes = [
355
+ ...new Set(
356
+ [
357
+ ...reached,
358
+ ...graph.vocab.prop('filed', 'project') && graph.vocab.comp('project')
359
+ ? eids(
360
+ await graph.read(and(
361
+ present('project'),
362
+ or(...reached.map((p) => walk('filed.project', '<-', p))),
363
+ fields('entity.eid'),
364
+ )),
365
+ )
366
+ : [],
367
+ ],
368
+ ),
369
+ ]
370
+ // The native transcripts wearing a persona homed there, then those at work.
371
+ // The status is a read of its own: in one statement SQLite reads it off
372
+ // every session the path finds, outside ones included, before the tests
373
+ // beside it.
374
+ let homed = await natives(
375
+ graph,
376
+ [eq(`${SESSION}.persona.persona.home`, value(homes))],
377
+ [`${SESSION}.persona`],
378
+ )
379
+ return atWork(graph, eids(homed))
380
+ }
381
+
382
+ /** The letters that reached these projects (any, left out), unsaid: every
383
+ * arrival (no `deliver`), a new letter or an answer, whether or not this graph
384
+ * kept the letter it answers. */
385
+ export let arrived = (projects?: Eid[]): And =>
386
+ and(
387
+ present('mail'),
388
+ absent('deliver'),
389
+ absent(ROUTINE),
390
+ projects ? eq('mail.target', value(projects)) : present('mail.target'),
391
+ absent(NOTIFIED),
392
+ )
393
+
394
+ /** The knocks at these projects (any project, left out), unsaid, less those a
395
+ * helper takes (./help.ts `routine`). */
396
+ export let knocked = (projects?: Eid[]): And =>
397
+ and(
398
+ present('knock'),
399
+ absent(ROUTINE),
400
+ projects
401
+ ? eq('knock.target', value(projects))
402
+ : present('knock.target.project'),
403
+ absent(NOTIFIED),
404
+ )
405
+
406
+ /** Which of these comments a session at work on their task takes up: a
407
+ * person's, on an open task that is not blocked. The vocabulary's
408
+ * `session_start` owes a start for one whose task no live session holds, by
409
+ * these same tests. None in a graph that knows no person or task. */
410
+ export let taken = async (
411
+ graph: Pick<Graph, 'vocab' | 'read'>,
412
+ comments: Eid[],
413
+ ): Promise<Set<Eid>> => {
414
+ let has = (name: string) => !!graph.vocab.comp(name)
415
+ if (!comments.length || !has('person') || !has('task')) return new Set()
416
+ return new Set(eids(
417
+ await graph.read(and(
418
+ eq('entity.eid', value(comments)),
419
+ present('created.by.person'),
420
+ absent('created.via.session'),
421
+ present('comment.target.task'),
422
+ ...['completed', 'cancelled', 'blocked'].filter(has)
423
+ .map((mark) => absent(`comment.target.${mark}`)),
424
+ fields('entity.eid'),
425
+ )),
426
+ ))
427
+ }
428
+
429
+ /** Unsaid person-written comments on records filed under these projects and
430
+ * created through a session. They are that session's while it can hear, then
431
+ * the project's. */
432
+ export let commented = (projects?: Eid[]): And =>
433
+ and(
434
+ present('comment'),
435
+ present('comment.target.created.via.session'),
436
+ absent('created.via.session'),
437
+ projects
438
+ ? eq('comment.target.filed.project', value(projects))
439
+ : present('comment.target.filed.project'),
440
+ absent(NOTIFIED),
441
+ )
442
+
443
+ /** The addresses filed under these projects: entities wearing `email` that
444
+ * are not projects themselves. A letter to one reached the project. */
445
+ let addresses = async (
446
+ graph: Pick<Graph, 'vocab' | 'read'>,
447
+ projects: Eid[],
448
+ ): Promise<Eid[]> =>
449
+ graph.vocab.comp('email') && graph.vocab.prop('filed', 'project')
450
+ ? (await graph.read(and(
451
+ present('email'),
452
+ absent('project'),
453
+ eq('filed.project', value(projects)),
454
+ ))).map((b) => b.entity.eid)
455
+ : []
456
+
457
+ /** What is held for these projects, unsaid: every knock at one, each letter
458
+ * that answers no letter or one no session wrote, and replies to letters or
459
+ * comments on records created by another session that is over. */
460
+ export let held = async (
461
+ graph: Pick<Graph, 'vocab' | 'read' | 'get'>,
462
+ session: Eid,
463
+ projects: Eid[],
464
+ ): Promise<Bundle[]> => {
465
+ if (!projects.length) return []
466
+ let knocks = graph.vocab.comp('knock')
467
+ ? await graph.read(and(...knocked(projects).clauses, every()))
468
+ : []
469
+ let filed =
470
+ graph.vocab.comp('comment') && graph.vocab.prop('filed', 'project')
471
+ ? await graph.read(and(...commented(projects).clauses, every()))
472
+ : []
473
+ // A comment a session at work takes up is never the project's.
474
+ let working = await taken(graph, eids(filed))
475
+ let comments = filed.filter((b) => !working.has(b.entity.eid))
476
+ let reach = [...projects, ...await addresses(graph, projects)]
477
+ let mail = graph.vocab.comp('mail')
478
+ ? await graph.read(and(...arrived(reach).clauses, every()))
479
+ : []
480
+ let replies = [...mail, ...comments]
481
+ if (!replies.length) return knocks
482
+ let to = (b: Bundle) =>
483
+ str(comp(b, 'comment').target) || str(comp(b, 'mail').reply_to)
484
+ let answered = [...new Set(replies.map(to).filter(Boolean))]
485
+ let writer = new Map(
486
+ (answered.length ? await graph.get(answered, ['created']) : [])
487
+ .map((b) => [b.entity.eid, str(comp(b, 'created').via)]),
488
+ )
489
+ let vias = [...new Set(writer.values())].filter(Boolean)
490
+ let sessions = vias.length
491
+ ? await graph.read(and(
492
+ eq('entity.eid', value(vias)),
493
+ present(SESSION),
494
+ fields('session.ended'),
495
+ ))
496
+ : []
497
+ let gone = await ended(
498
+ graph,
499
+ sessions.filter((s) => s.entity.eid != session),
500
+ )
501
+ let wrote = new Set(sessions.map((s) => s.entity.eid))
502
+ let by = (b: Bundle) => writer.get(to(b)) ?? ''
503
+ return [
504
+ ...knocks,
505
+ ...replies.filter((b) =>
506
+ gone.has(by(b)) || (!b.comment && !wrote.has(by(b)))
507
+ ),
508
+ ]
509
+ }
510
+
511
+ /** Who wrote an item: the run it came through, else the identity. */
512
+ let author = (b: Bundle): string =>
513
+ str(comp(b, 'created').via) || str(comp(b, 'created').by)
514
+
515
+ /** An item's words. A knock's ride in `doc` or, from a session's own notices
516
+ * (wake.ts), in `content{body}`; a letter delivered is said by its subject. */
517
+ export let words = (b: Bundle): string => {
518
+ let doc = comp(b, 'doc')
519
+ return fold(
520
+ b.deliver
521
+ ? str(doc.title)
522
+ : str(doc.body) || str(doc.title) || str(comp(b, 'content').body),
523
+ )
524
+ }
525
+
526
+ /** Who an item is said to be from: the session it came through, else the
527
+ * identity that wrote it. A door that is no session (a web process a person
528
+ * wrote through) is not who it is from. */
529
+ export let writer = (b: Bundle, sessions: Set<Eid>): string => {
530
+ let { by, via } = comp(b, 'created')
531
+ return sessions.has(str(via)) ? str(via) : str(by) || str(via)
532
+ }
533
+
534
+ /** One item as the line a monitor shows. `named` gives the readable id of an
535
+ * entity the item points at, where it could be read, `state` where a task
536
+ * it is about stands, `by` who it is from ({@link writer}), and `ids` what
537
+ * each eid its words hold is called, else it is drawn as its short handle. */
538
+ export let said = (
539
+ vocab: Vocab,
540
+ b: Bundle,
541
+ named: (eid: string) => string,
542
+ state: (eid: string) => string = () => '',
543
+ by = author(b),
544
+ ids?: Ids,
545
+ ): string => {
546
+ let id = human(vocab)(b)
547
+ let from = by ? ` from ${named(by)}` : ''
548
+ let on = str(comp(b, 'comment').target)
549
+ let stands = state(on) ? ` (${state(on)})` : ''
550
+ let line = b.comment && b.knock
551
+ ? `knock ${id} on ${named(on)}${stands}${from}`
552
+ : b.comment
553
+ ? `comment ${id} on ${named(on)}${from}`
554
+ : b.knock
555
+ ? `knock ${id} at ${named(str(comp(b, 'knock').target))}${from}`
556
+ : `mail ${id} from ${str(comp(b, 'mail').from) || named(by)}`
557
+ let text = drawn(words(b), ids)
558
+ return safe(text ? `${line}: ${text}` : line)
559
+ }
560
+
561
+ /** What {@link listen} needs besides the tool's own context. */
562
+ export type Ear = {
563
+ /** where each line goes; the command line prints it */
564
+ out: (line: string) => void
565
+ /** how long to wait between reads, in milliseconds, or what to wait for */
566
+ every: number | (() => Promise<void>)
567
+ /** end once something was said and nothing new came for `quiet` */
568
+ once?: boolean
569
+ /** with `once`, how long nothing new must come before it ends, in
570
+ * milliseconds (default 0: end with the first read that says anything) */
571
+ quiet?: number
572
+ /** the clock the quiet window is read from (default `Date.now`) */
573
+ now?: () => number
574
+ /** stops the loop when it aborts; a command under a monitor stops when its
575
+ * process is killed, so this is for a program that runs it in-process */
576
+ stop?: AbortSignal
577
+ }
578
+
579
+ let pause = (every: Ear['every'], stop?: AbortSignal) =>
580
+ typeof every == 'function' ? every() : new Promise<void>((done) => {
581
+ let finish = () => {
582
+ clearTimeout(timer)
583
+ stop?.removeEventListener('abort', finish)
584
+ done()
585
+ }
586
+ let timer = setTimeout(finish, every)
587
+ stop?.addEventListener('abort', finish, { once: true })
588
+ if (stop?.aborted) finish()
589
+ })
590
+
591
+ /** Select what this listener hears. Addressed items do not wait for a turn;
592
+ * project-held items do, for native transcripts only. Read held items lazily:
593
+ * a native transcript at rest must neither consume nor read its project's news.
594
+ * Author exclusion and deduplication are shared by the native bus and outside
595
+ * listeners. */
596
+ export let pendingItems = async (
597
+ session: Eid,
598
+ native: boolean,
599
+ working: boolean,
600
+ addressed: Bundle[],
601
+ held: () => Bundle[] | Promise<Bundle[]>,
602
+ ): Promise<Bundle[]> => {
603
+ let seen = new Set<Eid>()
604
+ let items: Bundle[] = []
605
+ for (
606
+ let b of [
607
+ ...addressed,
608
+ ...!native || working ? await held() : [],
609
+ ]
610
+ ) {
611
+ if (
612
+ seen.has(b.entity.eid) || author(b) == session
613
+ ) {
614
+ continue
615
+ }
616
+ seen.add(b.entity.eid)
617
+ items.push(b)
618
+ }
619
+ return items
620
+ }
621
+
622
+ /** Unsaid items, and for the record each answers the session that created it
623
+ * and, where asked, the session holding it, with the comments among them only
624
+ * that holder hears ({@link taken}). */
625
+ export type Routes = {
626
+ items: Bundle[]
627
+ creators: Map<Eid, string>
628
+ holders: Map<Eid, string>
629
+ taken: Set<Eid>
630
+ }
631
+
632
+ /** The session an item follows for having created what it answers: none for a
633
+ * comment a session at work takes up. */
634
+ export let creatorOf = (r: Routes, b: Bundle, on: string): string =>
635
+ r.taken.has(b.entity.eid) ? '' : r.creators.get(on) ?? ''
636
+ /** What a caller already read for {@link pending}: the unsaid comments and
637
+ * replies it may route, and the graph's projects when it keeps them. */
638
+ export type News = { comments: Routes; replies: Routes; projects?: Projects }
639
+
640
+ let routed = async (
641
+ graph: Pick<Graph, 'vocab' | 'read'>,
642
+ query: And,
643
+ name: string,
644
+ prop: string,
645
+ ids?: Eid[],
646
+ claimed = false,
647
+ ): Promise<Routes> => {
648
+ let none = new Map<Eid, string>()
649
+ if (ids && !ids.length) {
650
+ return { items: [], creators: none, holders: none, taken: new Set() }
651
+ }
652
+ let items = graph.vocab.comp(name)
653
+ ? await graph.read(
654
+ ids ? and(eq('entity.eid', value(ids)), ...query.clauses) : query,
655
+ )
656
+ : []
657
+ let targets = [...new Set(items.map((b) => str(comp(b, name)[prop])))]
658
+ let rows = targets.length
659
+ ? await graph.read(and(
660
+ eq('entity.eid', value(targets)),
661
+ fields('created.via', ...claimed ? [`${CLAIM}.session`] : []),
662
+ ))
663
+ : []
664
+ let by = (name: string, prop: string) =>
665
+ new Map(rows.map((b) => [b.entity.eid, str(comp(b, name)[prop])]))
666
+ return {
667
+ items,
668
+ creators: by('created', 'via'),
669
+ holders: claimed ? by(CLAIM, 'session') : none,
670
+ taken: claimed ? await taken(graph, eids(items)) : new Set(),
671
+ }
672
+ }
673
+
674
+ /** Unread human comments, their targets' creators and the sessions holding
675
+ * those targets, through the caller's scope: every one, or those among `ids`.
676
+ * A person's are sought from the few people's own writes, so the read grows
677
+ * with what people write, not with every agent's comment never said. */
678
+ export let comments = (
679
+ graph: Pick<Graph, 'vocab' | 'read'>,
680
+ ids?: Eid[],
681
+ ): Promise<Routes> =>
682
+ routed(
683
+ graph,
684
+ and(
685
+ present('comment'),
686
+ absent(NOTIFIED),
687
+ ...graph.vocab.comp('person') ? [present('created.by.person')] : [],
688
+ absent('created.via.session'),
689
+ fields('comment.target'),
690
+ ),
691
+ 'comment',
692
+ 'target',
693
+ ids,
694
+ true,
695
+ )
696
+
697
+ /** Unread replies and the writers they answer, without walking a writer's
698
+ * work: every one, or those among `ids`. */
699
+ export let replies = (
700
+ graph: Pick<Graph, 'vocab' | 'read'>,
701
+ ids?: Eid[],
702
+ ): Promise<Routes> =>
703
+ routed(
704
+ graph,
705
+ and(
706
+ present('mail.reply_to'),
707
+ absent(NOTIFIED),
708
+ absent(ROUTINE),
709
+ fields('mail.reply_to', 'mail.target'),
710
+ ),
711
+ 'mail',
712
+ 'reply_to',
713
+ ids,
714
+ )
715
+
716
+ /** One thing a session has yet to hear: the item, its readable line, and the
717
+ * other knocks that say the same from the same writer, left at another
718
+ * address the session hears (itself and its project, say). They are one
719
+ * knock, said once and marked said together. `starter` is the session that
720
+ * started the one the item was written through (`spawned.parent`), where one
721
+ * did: to that session the item is its worker's report. */
722
+ export type Owed = {
723
+ item: Bundle
724
+ line: string
725
+ same: Bundle[]
726
+ starter?: Eid
727
+ }
728
+
729
+ /** What this session has yet to hear. */
730
+ export let pending = async (
731
+ graph: Pick<Graph, 'vocab' | 'read' | 'get'>,
732
+ session: Eid,
733
+ news?: News,
734
+ ): Promise<Owed[]> => {
735
+ let vocab = graph.vocab
736
+ // A person's comment on a record the session created or holds reaches
737
+ // native and outside sessions alike, and one a session at work takes up
738
+ // only its holder. An agent's comment on a held record reaches an outside
739
+ // session only.
740
+ let [owner] = await graph.read(
741
+ and(
742
+ eq('entity.eid', session),
743
+ fields('session.persona', 'session.operator'),
744
+ ),
745
+ )
746
+ let [process] = vocab.comp('process')
747
+ ? await graph.get([session], ['process'])
748
+ : []
749
+ let native = !process?.process &&
750
+ (await graph.read(
751
+ line`.entity.eid=${session}&.entries.using&.fields=entity.eid&.limit=1`,
752
+ )).length > 0
753
+ let addressed: Bundle[] = []
754
+ // Restrict to unsaid human comments before inspecting the creator of each
755
+ // target. A correlated target join scanned already-delivered history.
756
+ let received = news ??
757
+ { comments: await comments(graph), replies: await replies(graph) }
758
+ let mine = (r: Routes, name: string, prop: string) =>
759
+ r.items.filter((b) => {
760
+ let on = str(comp(b, name)[prop])
761
+ return creatorOf(r, b, on) == session || r.holders.get(on) == session
762
+ }).map((b) => b.entity.eid)
763
+ let ids = [
764
+ ...mine(received.comments, 'comment', 'target'),
765
+ ...mine(received.replies, 'mail', 'reply_to'),
766
+ ]
767
+ if (ids.length) addressed.push(...await graph.get(ids))
768
+ let queries = addressedTo(vocab, session, !native)
769
+ if (queries.length) {
770
+ addressed.push(...await graph.read(and(or(...queries), every())))
771
+ }
772
+ // A session with no project can hear only its addressed items. Deriving
773
+ // its transcript status cannot change that answer and reads its whole log.
774
+ let reach = await worksFor(graph, owner, news?.projects)
775
+ let working = !native ||
776
+ (reach.length > 0 && (await atWork(graph, [session])).length > 0)
777
+ // A session a person opened hears all that is held for its projects; any
778
+ // other only what is held for projects nobody operates. Most passes find
779
+ // nothing held, so the operators are read only when something is.
780
+ let operator = comp(owner, SESSION).operator == true
781
+ let owed = async () => {
782
+ let found = await held(graph, session, reach)
783
+ if (operator || !found.length) return found
784
+ let open = await unoperated(graph, reach, news?.projects)
785
+ return open.length == reach.length ? found : held(graph, session, open)
786
+ }
787
+ return owing(
788
+ graph,
789
+ await pendingItems(session, native, working, addressed, owed),
790
+ )
791
+ }
792
+
793
+ /** These items as what is owed: each with its line, and a knock that says
794
+ * the same as an earlier one from the same writer folded into that one. */
795
+ export let owing = async (
796
+ graph: Pick<Graph, 'vocab' | 'get' | 'read'>,
797
+ items: Bundle[],
798
+ ): Promise<Owed[]> => {
799
+ if (!items.length) return []
800
+ let vocab = graph.vocab
801
+ let pointed = [
802
+ ...new Set(
803
+ items.flatMap((b) => [
804
+ str(comp(b, 'comment').target),
805
+ str(comp(b, 'knock').target),
806
+ str(comp(b, 'created').via),
807
+ str(comp(b, 'created').by),
808
+ ]).filter(Boolean),
809
+ ),
810
+ ]
811
+ let names = new Map<string, string>(), states = new Map<string, string>()
812
+ let sessions = new Set<Eid>(), starters = new Map<string, Eid>()
813
+ for (let b of await graph.get(pointed)) {
814
+ names.set(b.entity.eid, human(vocab)(b))
815
+ if (b.task) states.set(b.entity.eid, statusOf(vocab, b) ?? '')
816
+ if (b[SESSION]) sessions.add(b.entity.eid)
817
+ let parent = str(comp(b, 'spawned').parent)
818
+ if (parent) starters.set(b.entity.eid, parent as Eid)
819
+ }
820
+ let named = (eid: string) => names.get(eid) ?? eid
821
+ let state = (eid: string) => states.get(eid) ?? ''
822
+ // The words say the id a person wrote, which the store keeps as its eid.
823
+ let ids = await called(graph, items.flatMap((b) => mentioned(words(b))))
824
+ let calls: Ids = (eid) => ids.get(eid)
825
+ let out: Owed[] = [], knocks = new Map<string, Owed>()
826
+ for (let item of items) {
827
+ let key = item.knock && !item.comment && words(item)
828
+ ? `${author(item)} ${words(item)}`
829
+ : ''
830
+ let first = knocks.get(key)
831
+ if (first) {
832
+ first.same.push(item)
833
+ continue
834
+ }
835
+ let line = said(vocab, item, named, state, writer(item, sessions), calls)
836
+ let starter = starters.get(str(comp(item, 'created').via))
837
+ let owed: Owed = { item, line, same: [], ...starter ? { starter } : {} }
838
+ if (key) knocks.set(key, owed)
839
+ out.push(owed)
840
+ }
841
+ return out
842
+ }
843
+
844
+ /** An item to mark said: with it the knocks that say the `same`
845
+ * ({@link Owed}), and what lands `together` with its mark or not at all (a
846
+ * native session's input, and for a session started on the item, the session
847
+ * and its claim, ./start.ts). */
848
+ export type Said = { item: Bundle; same?: Bundle[]; together?: Bundle[] }
849
+
850
+ let marking = ({ item, same = [], together = [] }: Said): Bundle[] => [
851
+ ...together,
852
+ {
853
+ entity: { eid: item.entity.eid },
854
+ [NOTIFIED]: {},
855
+ $was: { [NOTIFIED]: { at: token(null) } },
856
+ },
857
+ ...same.map((b) => ({ entity: { eid: b.entity.eid }, [NOTIFIED]: {} })),
858
+ ]
859
+
860
+ /** Mark these items said in one committed batch, each only if nobody has
861
+ * delivered it meanwhile. One somebody has, or whose guard `together` no
862
+ * longer holds, is left out with all that rode with it, and the rest land.
863
+ * Answers the ones that landed. */
864
+ export let deliverAll = async (
865
+ graph: Pick<Graph, 'apply'>,
866
+ actor: Actor | null,
867
+ said: Said[],
868
+ ): Promise<Said[]> => {
869
+ while (said.length) {
870
+ try {
871
+ await graph.apply(signed(said.flatMap(marking), actor))
872
+ break
873
+ } catch (error) {
874
+ if (!(error instanceof Stale)) throw error
875
+ let { eid } = error
876
+ let rest = said.filter((s) =>
877
+ !marking(s).some((b) => b.entity.eid == eid)
878
+ )
879
+ said = rest.length < said.length ? rest : []
880
+ }
881
+ }
882
+ return said
883
+ }
884
+
885
+ /** Mark one item said ({@link deliverAll}); whether it landed. */
886
+ export let deliver = async (
887
+ graph: Pick<Graph, 'apply'>,
888
+ actor: Actor | null,
889
+ item: Bundle,
890
+ together: Bundle[] = [],
891
+ same: Bundle[] = [],
892
+ ): Promise<boolean> =>
893
+ (await deliverAll(graph, actor, [{ item, together, same }])).length > 0
894
+
895
+ /** Take back the mark {@link deliver} set on items whose lines never reached
896
+ * the session, so they are owed again. */
897
+ export let undeliver = async (
898
+ graph: Pick<Graph, 'apply'>,
899
+ actor: Actor | null,
900
+ items: Bundle[],
901
+ ): Promise<void> => {
902
+ if (items.length) {
903
+ await graph.apply(signed(
904
+ items.map((b) => ({ entity: { eid: b.entity.eid }, [NOTIFIED]: null })),
905
+ actor,
906
+ ))
907
+ }
908
+ }
909
+
910
+ /** One pass: say what is addressed to the session and mark each line said. */
911
+ export let hear = async (
912
+ graph: Pick<Graph, 'vocab' | 'read' | 'get' | 'apply'>,
913
+ actor: Actor | null,
914
+ session: Eid,
915
+ out: (line: string) => void,
916
+ ): Promise<number> => {
917
+ let count = 0
918
+ for (let { item, line, same } of await pending(graph, session)) {
919
+ out(line)
920
+ if (!await deliver(graph, actor, item, [], same)) continue
921
+ count++
922
+ }
923
+ return count
924
+ }
925
+
926
+ /** How long what a session is owed waits for more before it wakes the
927
+ * session, in milliseconds: a wake costs a read of its whole context, so one
928
+ * wake carries all that is waiting. */
929
+ export let QUIET = 5000
930
+
931
+ /** How many quiet windows the first thing owed waits at most. Knocks that
932
+ * keep coming inside each window would otherwise hold it from the agent for
933
+ * as long as they came. */
934
+ export let HOLD = 6
935
+
936
+ /** Say everything addressed to the session as it arrives, until `stop`
937
+ * aborts or, when `once`, until something was said and nothing new came for
938
+ * `quiet`. */
939
+ export let listen = async (
940
+ graph:
941
+ & Pick<Graph, 'vocab' | 'read' | 'get' | 'apply'>
942
+ & Partial<Pick<Graph, 'storage'>>,
943
+ actor: Actor | null,
944
+ session: Eid,
945
+ ear: Ear,
946
+ ): Promise<void> => {
947
+ if (!graph.vocab.comp(NOTIFIED)) {
948
+ throw new Error(
949
+ 'session listen marks what it said with `notified`, which @yaks/mail ' +
950
+ 'declares — compose that plugin',
951
+ )
952
+ }
953
+ let first = true, prior: unknown
954
+ let now = ear.now ?? Date.now, quiet = ear.quiet ?? 0
955
+ let began: number | undefined, last = 0
956
+ while (!ear.stop?.aborted) {
957
+ // Sample before reading: a commit during hear must be read next beat.
958
+ // SQLite revisions include other processes' commits; watch does not.
959
+ let revision = await graph.storage?.revision?.()
960
+ if (first || revision === undefined || revision !== prior) {
961
+ first = false
962
+ prior = revision
963
+ let lines = 0
964
+ await hear(graph, actor, session, (line) => (lines++, ear.out(line)))
965
+ if (lines) {
966
+ last = now()
967
+ began ??= last
968
+ }
969
+ }
970
+ if (
971
+ ear.once && began !== undefined &&
972
+ (now() - last >= quiet || now() - began >= quiet * HOLD)
973
+ ) return
974
+ await pause(ear.every, ear.stop)
975
+ }
976
+ }