@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/bus.ts ADDED
@@ -0,0 +1,683 @@
1
+ // Delivery of the session bus. Words given a session from outside it, a
2
+ // person's by a page, a channel or a conversation tool, are taken in once
3
+ // each (./intake.ts); what is addressed to a session in the graph is
4
+ // delivered to it as below. A native transcript gets an input in the same
5
+ // batch that marks the item said; a caller using a tool sees owed lines in
6
+ // that tool's reply, or, when its harness reports to the hook door, the
7
+ // context that harness adds after a call of its own (./routes.ts). The
8
+ // listener for an outside harness uses listen.ts.
9
+ //
10
+ // A native transcript answers its inputs with a model turn that reads its
11
+ // whole context, so all that is waiting for one is written in one batch and
12
+ // taken in one turn: an item waits through a quiet window for more
13
+ // ({@link ripe}), as it does for `yak session listen --once`.
14
+ //
15
+ // The native side follows the graph's commits ({@link follow}): its own
16
+ // graph's, and through the host's feed every other process's. A pass looks at
17
+ // what was written since the last one, so its cost follows what can be said,
18
+ // not the unsaid history (thousands of agents' comments and letters nobody
19
+ // hears), and a quiet graph reads nothing. A written item is asked about
20
+ // alone. A transcript entry asks again about its own session, which may have
21
+ // come to work and so hear what is held for its project. Any other way an
22
+ // item reaches a session (a claim, a session's persona, where a record is
23
+ // filed) changes rarely, and the pass after it asks about everything, as the
24
+ // first pass does.
25
+
26
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
27
+ import type { Feed } from 'jsr:@yaks/host@0.2.36'
28
+ import { type Clock, groupBy, resolvers, sleep, system } from '@yaks/fp'
29
+ import { derivedEid } from '@yaks/graph/identity'
30
+ import { who } from '@yaks/graph/call'
31
+ import {
32
+ absent,
33
+ and,
34
+ type Clause,
35
+ eq,
36
+ fields,
37
+ list,
38
+ or,
39
+ present,
40
+ } from '@yaks/query'
41
+ import { CLAIM, SESSION } from './comp.js'
42
+ import {
43
+ arrived,
44
+ comments,
45
+ creatorOf,
46
+ deliver,
47
+ deliverAll,
48
+ ends,
49
+ heirs,
50
+ HOLD,
51
+ knocked,
52
+ natives,
53
+ type News,
54
+ type Owed,
55
+ pending,
56
+ type Projects,
57
+ projects,
58
+ QUIET,
59
+ replies as replyRoutes,
60
+ type Routes,
61
+ undeliver,
62
+ } from './listen.js'
63
+ import { type Beside, recall, type Recalling } from './recall.js'
64
+ import { sessionFor } from './who.js'
65
+
66
+ let comp = (b: Bundle, name: string): Comp => (b[name] ?? {}) as Comp
67
+
68
+ /** What a pass looks at: every unsaid item, or the items written and the
69
+ * sessions whose transcripts moved since the last pass. */
70
+ export type Scope = { all: boolean; items: Set<Eid>; sessions: Set<Eid> }
71
+
72
+ /** A scope with nothing in it, or with everything. */
73
+ export let scope = (all = false): Scope => ({
74
+ all,
75
+ items: new Set(),
76
+ sessions: new Set(),
77
+ })
78
+
79
+ let idle = (s: Scope) => !s.all && !s.items.size && !s.sessions.size
80
+
81
+ // The components an item is, and those that route one to a session.
82
+ let ITEMS = ['comment', 'knock', 'deliver', 'mail', 'notified']
83
+ let ROUTES = [
84
+ CLAIM,
85
+ SESSION,
86
+ 'process',
87
+ 'persona',
88
+ 'filed',
89
+ 'project',
90
+ 'using',
91
+ 'email',
92
+ ]
93
+
94
+ let item = (b: Bundle) => ITEMS.some((c) => c in b)
95
+
96
+ /** Add to `into` what these committed bundles give a pass to look at. */
97
+ export let noted = (into: Scope, bundles: Bundle[]): Scope => {
98
+ for (let b of bundles) {
99
+ if (ROUTES.some((c) => c in b)) into.all = true
100
+ else if (item(b)) into.items.add(b.entity.eid)
101
+ let session = comp(b, 'entry').session
102
+ if (typeof session == 'string') into.sessions.add(session)
103
+ }
104
+ return into
105
+ }
106
+
107
+ /** Hand `hear` every commit: this graph's own through its `effect` phase,
108
+ * and every other process's through the host's feed. Without a feed the
109
+ * others' commits cannot be heard, so nothing is heard, and the caller asks
110
+ * about everything instead. Returns what unsubscribes the feed. */
111
+ let heed = (
112
+ host: { graph: Graph; feed?: Feed },
113
+ name: string,
114
+ hear: (bundles: Bundle[], missed: boolean) => void,
115
+ ): (() => void) | undefined => {
116
+ let stop = host.feed?.((news) => hear(news.applied.flat(), news.missed))
117
+ if (stop) {
118
+ host.graph.use({
119
+ name,
120
+ hooks: { effect: (bundles) => (hear(bundles, false), bundles) },
121
+ })
122
+ }
123
+ return stop
124
+ }
125
+
126
+ let merge = (into: Scope, from: Scope): Scope => {
127
+ into.all ||= from.all
128
+ for (let id of from.items) into.items.add(id)
129
+ for (let id of from.sessions) into.sessions.add(id)
130
+ return into
131
+ }
132
+
133
+ let among = (ids?: Eid[]): Clause[] =>
134
+ ids ? [eq('entity.eid', ids.length == 1 ? ids[0] : list(...ids))] : []
135
+
136
+ // Find pending items first. Most sessions have no bus work, so a timer never
137
+ // needs to scan their transcripts. `ids` keeps to those items.
138
+ let candidates = async (
139
+ g: Graph,
140
+ news: News,
141
+ ids?: Eid[],
142
+ ): Promise<Eid[]> => {
143
+ let route = (...props: string[]) =>
144
+ fields(...props.filter((p) => {
145
+ let [c, key] = p.split('.')
146
+ return g.vocab.prop(c, key)
147
+ }))
148
+ let unsaid = (component: string, ...clauses: Clause[]) =>
149
+ and(present(component), ...among(ids), ...clauses, absent('notified'))
150
+ let queries = [
151
+ ...g.vocab.comp('knock')
152
+ ? [
153
+ unsaid(
154
+ 'knock',
155
+ present('knock.target.session'),
156
+ ),
157
+ unsaid('knock', present('knock.target.claim.session')),
158
+ ]
159
+ : [],
160
+ ...g.vocab.comp('deliver')
161
+ ? [unsaid(
162
+ 'deliver',
163
+ present('deliver.to.session'),
164
+ )]
165
+ : [],
166
+ ]
167
+ // A reply is for the session that wrote the letter or record it answers, and once
168
+ // that session is over, for a session of the project it reached; any other
169
+ // letter that reached a project, and a knock at one, is that project's from
170
+ // the start.
171
+ let reached = g.vocab.comp('mail')
172
+ ? await g.read(
173
+ and(
174
+ ...among(ids),
175
+ ...arrived().clauses,
176
+ route('mail.target', 'mail.reply_to'),
177
+ ),
178
+ )
179
+ : []
180
+ let projects = g.vocab.comp('knock') && g.vocab.comp('project')
181
+ ? await g.read(
182
+ and(...among(ids), ...knocked().clauses, route('knock.target')),
183
+ )
184
+ : []
185
+ // First select unsaid human comments, then inspect only their targets.
186
+ // Following target.created.via.session inside the global comment scan made
187
+ // SQLite repeat the target chain over every historical comment each tick.
188
+ let creators = [
189
+ ...new Set([
190
+ ...news.comments.creators.values(),
191
+ ...news.replies.creators.values(),
192
+ ]),
193
+ ].filter(Boolean)
194
+ let sessions = new Set(
195
+ creators.length
196
+ ? (await g.read(and(
197
+ eq('entity.eid', list(...creators)),
198
+ present('session'),
199
+ fields('entity.eid'),
200
+ ))).map((b) => b.entity.eid)
201
+ : [],
202
+ )
203
+ let replies = news.replies.items.filter((b) =>
204
+ sessions.has(
205
+ news.replies.creators.get(String(comp(b, 'mail').reply_to)) ?? '',
206
+ )
207
+ )
208
+ let items = [
209
+ ...news.comments.items.filter((b) => {
210
+ let on = String(comp(b, 'comment').target)
211
+ return sessions.has(creatorOf(news.comments, b, on)) ||
212
+ !!news.comments.holders.get(on)
213
+ }),
214
+ ...queries.length
215
+ ? await g.read(and(
216
+ or(...queries),
217
+ route('knock.target', 'deliver.to'),
218
+ ))
219
+ : [],
220
+ ]
221
+ // A comment a session at work takes up is never held for a project.
222
+ let comments = g.vocab.prop('filed', 'project')
223
+ ? items.filter((b) => b.comment && !news.comments.taken.has(b.entity.eid))
224
+ : []
225
+ let targets = [
226
+ ...new Set(
227
+ [
228
+ ...items.map((b) =>
229
+ comp(b, 'comment').target ?? comp(b, 'knock').target ??
230
+ comp(b, 'deliver').to
231
+ ),
232
+ ...replies.map((b) =>
233
+ news.replies.creators.get(String(comp(b, 'mail').reply_to))
234
+ ),
235
+ ].filter((id): id is Eid => typeof id == 'string'),
236
+ ),
237
+ ]
238
+ // A target is a session itself, or names the session that created or
239
+ // claimed it; only those two references are read, never the whole record.
240
+ let rows = targets.length
241
+ ? await g.read(and(
242
+ eq('entity.eid', list(...targets)),
243
+ fields('created.via', `${CLAIM}.session`),
244
+ ))
245
+ : []
246
+ return [
247
+ ...new Set([
248
+ ...targets,
249
+ ...rows.flatMap((b) =>
250
+ [comp(b, 'created').via, comp(b, CLAIM).session].filter((
251
+ id,
252
+ ): id is Eid => typeof id == 'string')
253
+ ),
254
+ ...await heirs(g, [...replies, ...reached, ...projects, ...comments]),
255
+ ]),
256
+ ]
257
+ }
258
+
259
+ // The native transcripts among these entities which can hear, each with
260
+ // whether its last turn failed. A failed one is over for what reaches it
261
+ // through what it wrote or holds, which its project hears instead
262
+ // (./listen.ts `held`), but what is said to it by name, a knock at it or a
263
+ // letter delivered to it, opens its next turn, as it reopens one that ended
264
+ // (./reopen.ts). An outside session's long log is never loaded to tell.
265
+ let hearing = async (
266
+ g: Graph,
267
+ ids: Eid[],
268
+ ): Promise<Map<Eid, boolean>> => {
269
+ let found = ids.length
270
+ ? await natives(g, [eq('entity.eid', list(...ids))], [`${SESSION}.ended`])
271
+ : []
272
+ let gone = await ends(g, found)
273
+ return new Map(
274
+ found.map((s) => s.entity.eid)
275
+ .filter((id) => (gone.get(id) ?? 'failed') == 'failed')
276
+ .map((id) => [id, gone.has(id)]),
277
+ )
278
+ }
279
+
280
+ // What a failed transcript hears of the news: only what is said to it by
281
+ // name, which {@link pending} reads for itself.
282
+ let byName = (news: News): News => {
283
+ let none = { items: [], creators: new Map(), holders: new Map() }
284
+ return {
285
+ ...news,
286
+ comments: { ...none, taken: news.comments.taken },
287
+ replies: { ...none, taken: news.replies.taken },
288
+ }
289
+ }
290
+
291
+ /** A line a native transcript is owed: the item, what is said of it, and the
292
+ * session it is said to. */
293
+ export type Due = { session: Eid } & Owed
294
+
295
+ /** What one pass over native sessions owes them, read and not yet said: the
296
+ * lines {@link feed} appends. A scope keeps the pass to the items it names and
297
+ * the sessions it names, each asked about all it is owed. */
298
+ export let due = async (g: Graph, at: Scope = scope(true)): Promise<Due[]> => {
299
+ if (!g.vocab.comp('notified')) return []
300
+ let out: Due[] = []
301
+ let ids = at.all ? undefined : [...at.items]
302
+ let news: News = {
303
+ comments: await comments(g, ids),
304
+ replies: await replyRoutes(g, ids),
305
+ }
306
+ let found = !ids || ids.length ? await candidates(g, news, ids) : []
307
+ let listening = await hearing(g, [...new Set([...found, ...at.sessions])])
308
+ if (listening.size) news.projects = await projects(g)
309
+ for (let [id, failed] of listening) {
310
+ for (let said of await pending(g, id, failed ? byName(news) : news)) {
311
+ out.push({ session: id, ...said })
312
+ }
313
+ }
314
+ return out
315
+ }
316
+
317
+ /** The input entry that says an item to a native session: one entry per
318
+ * session and item, so saying it again writes nothing new. */
319
+ export let input = (session: Eid, item: Eid, body: string): Bundle => ({
320
+ entity: { eid: derivedEid(`session bus ${session} ${item}`) },
321
+ entry: { session },
322
+ intake: { item },
323
+ content: { body },
324
+ })
325
+
326
+ // When a line's item was written; one that says no time was never not there.
327
+ let writtenAt = (d: Due): number => {
328
+ let at = Date.parse(String(comp(d.item, 'created').at))
329
+ return isNaN(at) ? -Infinity : at
330
+ }
331
+
332
+ /** The lines ready to be said at `now`, and those `held` for more with when
333
+ * the first of them is ready (`at`). A session's lines are said together,
334
+ * once nothing new was written for it in `quiet` ms, and no later than
335
+ * {@link HOLD} such windows after the oldest of them. An item that says no
336
+ * time is not waited on. */
337
+ export let ripe = (
338
+ due: Due[],
339
+ now: number,
340
+ quiet: number,
341
+ ): { ready: Due[]; held: Due[]; at: number } => {
342
+ let ready: Due[] = [], held: Due[] = [], at = Infinity
343
+ for (let lines of groupBy(due, (d) => d.session).values()) {
344
+ let times = lines.map(writtenAt)
345
+ let when = Math.min(
346
+ Math.max(...times) + quiet,
347
+ Math.min(...times) + quiet * HOLD,
348
+ )
349
+ if (when <= now) ready.push(...lines)
350
+ else {
351
+ held.push(...lines)
352
+ at = Math.min(at, when)
353
+ }
354
+ }
355
+ return { ready, held, at }
356
+ }
357
+
358
+ /** Append these lines as inputs, each session's in one committed batch and
359
+ * in the order their items were written, so the session wakes once and one
360
+ * turn takes them all. A line a session's own worker wrote names that worker
361
+ * (`attention{worker}`): its report, which a session that drops leaves out
362
+ * once it has replied (./pruning.ts). A batch that fails leaves its items unmarked, so the
363
+ * next pass can retry them, and an item another session was given first is
364
+ * left out of it and not said twice. `attention` wakes the effects role's
365
+ * runner. Answers how many were said. */
366
+ export let give = async (g: Graph, due: Due[]): Promise<number> => {
367
+ let count = 0
368
+ for (let [session, lines] of groupBy(due, (d) => d.session)) {
369
+ let said = lines
370
+ .toSorted((a, b) => (writtenAt(a) - writtenAt(b)) || 0)
371
+ .map(({ item, line, same, starter }) => ({
372
+ item,
373
+ same,
374
+ together: [{
375
+ ...input(session, item.entity.eid, line),
376
+ attention: starter == session
377
+ ? { worker: comp(item, 'created').via }
378
+ : {},
379
+ }],
380
+ }))
381
+ count += (await deliverAll(g, null, said)).length
382
+ }
383
+ return count
384
+ }
385
+
386
+ /** One pass over native sessions: each line {@link due} is given as an
387
+ * input ({@link give}), with what `beside` sets under it (./recall.ts). */
388
+ export let feed = async (
389
+ g: Graph,
390
+ at?: Scope,
391
+ beside: Beside = (owed) => Promise.resolve(owed),
392
+ ): Promise<number> => give(g, await beside(await due(g, at)))
393
+
394
+ /** Feed native sessions until `signal` aborts: a first pass over everything,
395
+ * then a pass each time a commit gives one something to look at, at once. A
396
+ * session's lines wait for more through a `quiet` window ({@link ripe}), and
397
+ * the pass that says them comes when it closes. A host with no feed cannot
398
+ * hear other processes' commits, so it asks about everything every `every`
399
+ * ms. A pass that fails is reported and its scope asked about again after
400
+ * `every` ms; `clock` is the time it keeps, and `wait` what waits on it. */
401
+ export let follow = async (
402
+ host: Recalling & { feed?: Feed },
403
+ signal: AbortSignal,
404
+ options: {
405
+ every?: number
406
+ quiet?: number
407
+ clock?: Clock
408
+ wait?: (ms: number, signal: AbortSignal) => Promise<unknown>
409
+ } = {},
410
+ ): Promise<void> => {
411
+ let { every = 1000, quiet = QUIET, clock = system } = options
412
+ let wait = options.wait ?? ((ms, signal) => sleep(ms, signal, clock))
413
+ let { beside } = recall(host)
414
+ // What a commit gave the next pass to look at, and the lines the last one
415
+ // held, with when the first of them is ready.
416
+ let next = scope(true), held = scope(), opens = Infinity
417
+ let bell = resolvers<void>()
418
+ let ring = () => bell.resolve()
419
+ signal.addEventListener('abort', ring, { once: true })
420
+ let stop = signal.aborted
421
+ ? undefined
422
+ : heed(host, '@yaks/session/bus', (bundles, missed) => {
423
+ if (signal.aborted) return
424
+ noted(next, bundles).all ||= missed
425
+ if (!idle(next)) ring()
426
+ })
427
+ // Until a commit rings, or the window on what is held closes.
428
+ let rest = async () => {
429
+ if (opens == Infinity) return await bell.promise
430
+ let woken = new AbortController()
431
+ await Promise.race([
432
+ bell.promise,
433
+ wait(opens - clock.now(), AbortSignal.any([signal, woken.signal])),
434
+ ])
435
+ woken.abort()
436
+ }
437
+ try {
438
+ while (true) {
439
+ let now = stop ? merge(next, held) : scope(true)
440
+ next = scope(), held = scope(), opens = Infinity
441
+ try {
442
+ if (!idle(now)) {
443
+ let found = ripe(await due(host.graph, now), clock.now(), quiet)
444
+ await give(host.graph, await beside(found.ready))
445
+ for (let { session, item } of found.held) {
446
+ held.sessions.add(session)
447
+ held.items.add(item.entity.eid)
448
+ }
449
+ opens = found.at
450
+ }
451
+ } catch (error) {
452
+ await (host.report?.(error) ?? console.error('session bus —', error))
453
+ merge(next, now)
454
+ await wait(every, signal)
455
+ }
456
+ if (signal.aborted) return
457
+ if (!stop) await wait(every, signal)
458
+ else if (idle(next)) await rest()
459
+ bell = resolvers()
460
+ }
461
+ } finally {
462
+ stop?.()
463
+ signal.removeEventListener('abort', ring)
464
+ }
465
+ }
466
+
467
+ /** A process's book of the unsaid person-written comments and replies, by
468
+ * the creator of what each answers, and of the graph's projects: what
469
+ * {@link pending} reads for one outside session at its doors instead of every
470
+ * unsaid item in the graph and the walk to its projects. */
471
+ export type Ledger = {
472
+ /** The comments and replies owed to this session, read again by id. */
473
+ owed: (session: Eid) => Promise<News>
474
+ }
475
+
476
+ /** What a door over this host's graph needs to hear for one session, and to
477
+ * set beside its person's words what they said before (./recall.ts). */
478
+ export type Door = Recalling & {
479
+ feed?: Feed
480
+ stopping?: AbortSignal
481
+ }
482
+
483
+ let ledgers = new WeakMap<Graph, Ledger>()
484
+
485
+ // How many written items a ledger keeps to read again before it reads
486
+ // everything instead: a door unused for long costs one full read, not memory
487
+ // that grows with every commit meanwhile.
488
+ let BACKLOG = 5000
489
+
490
+ /** The graph's ledger, kept from its commits, as {@link follow} keeps the
491
+ * native bus: the first use reads every unsaid comment and reply once, and
492
+ * each later use reads again only the items written since, so a door's read
493
+ * costs what its session is owed and what was written meanwhile. What routes
494
+ * an item here, the creator of what it answers, is written before it and
495
+ * never changes. A said item is dropped when its mark is heard. The projects
496
+ * are read again only after a commit writes a project. Undefined for a host
497
+ * with no feed, whose doors read everything each time; a missed commit reads
498
+ * everything again. */
499
+ export let ledger = (host: Door): Ledger | undefined => {
500
+ let kept = ledgers.get(host.graph)
501
+ if (kept || !host.feed) return kept
502
+ let g = host.graph
503
+ let by = new Map<Eid, Set<Eid>>(), whose = new Map<Eid, Eid>()
504
+ let written = new Set<Eid>(), stale = true
505
+ // The projects as last read, and how many commits have written one: a read
506
+ // that a write overtook is used once and not kept.
507
+ let tree: Projects | undefined, moved = 0
508
+ let stop = heed(host, '@yaks/session/ledger', (bundles, missed) => {
509
+ stale ||= missed
510
+ let filed = missed
511
+ for (let b of bundles) {
512
+ if (item(b)) written.add(b.entity.eid)
513
+ filed ||= 'project' in b || !!tree?.has(b.entity.eid)
514
+ }
515
+ if (filed) tree = undefined, moved++
516
+ if (written.size > BACKLOG) stale = true
517
+ if (stale) written.clear()
518
+ })
519
+ let known = async () => {
520
+ if (tree) return tree
521
+ let at = moved, read = await projects(g)
522
+ if (at == moved) tree = read
523
+ return read
524
+ }
525
+ host.stopping?.addEventListener('abort', () => stop?.(), { once: true })
526
+ let enter = (r: Routes, name: string, prop: string) => {
527
+ for (let b of r.items) {
528
+ let creator = creatorOf(r, b, String(comp(b, name)[prop]))
529
+ if (!creator) continue
530
+ by.set(creator, (by.get(creator) ?? new Set()).add(b.entity.eid))
531
+ whose.set(b.entity.eid, creator)
532
+ }
533
+ }
534
+ let drop = (id: Eid) => {
535
+ by.get(whose.get(id) ?? '')?.delete(id)
536
+ whose.delete(id)
537
+ }
538
+ let read = async (ids?: Eid[]) => {
539
+ let news = {
540
+ comments: await comments(g, ids),
541
+ replies: await replyRoutes(g, ids),
542
+ }
543
+ enter(news.comments, 'comment', 'target')
544
+ enter(news.replies, 'mail', 'reply_to')
545
+ return news
546
+ }
547
+ let update = async () => {
548
+ let ids = stale ? undefined : [...written]
549
+ if (ids && !ids.length) return
550
+ stale = false
551
+ written.clear()
552
+ if (ids) ids.forEach(drop)
553
+ else {
554
+ by.clear()
555
+ whose.clear()
556
+ }
557
+ try {
558
+ await read(ids)
559
+ } catch (error) {
560
+ stale = true
561
+ throw error
562
+ }
563
+ }
564
+ // One use at a time, so two doors at once never index a read twice.
565
+ let turn: Promise<unknown> = Promise.resolve()
566
+ let made: Ledger = {
567
+ owed: (session) => {
568
+ let done = turn.then(async () => {
569
+ await update()
570
+ let ids = [...by.get(session) ?? []]
571
+ ids.forEach(drop)
572
+ let news = await read(ids)
573
+ return { ...news, projects: await known() }
574
+ })
575
+ turn = done.catch(() => {})
576
+ return done
577
+ },
578
+ }
579
+ ledgers.set(g, made)
580
+ return made
581
+ }
582
+
583
+ // Every line owed to an outside session, each marked said as it is taken,
584
+ // and under a line the host's person wrote, what they said before.
585
+ // The mark names the session it was said to as what carried it, as
586
+ // `yak session listen` does, not the process whose door said it.
587
+ let owed = async (host: Door, id: Eid): Promise<Owed[]> => {
588
+ let g = host.graph
589
+ let out: Owed[] = []
590
+ for (let said of await pending(g, id, await ledger(host)?.owed(id))) {
591
+ if (await deliver(g, { via: id }, said.item, [], said.same)) {
592
+ out.push(said)
593
+ }
594
+ }
595
+ return recall(host).beside(out)
596
+ }
597
+
598
+ // Whether a session's harness reports to the hook door. Both doors below run
599
+ // on every tool call, so they read `hooked` and the session's id, never the
600
+ // session whole: that derives its status and cost from its log, tens of
601
+ // milliseconds of the web's one thread for a long transcript.
602
+ let hooked = async (g: Graph, id: Eid): Promise<boolean> =>
603
+ !!(await g.get([id], ['hooked']))[0]?.hooked
604
+
605
+ /** Lines owed to an outside caller, appended to a direct tool reply. A
606
+ * session whose harness reports to the hook door ({@link heard}) hears there
607
+ * instead: its forks and subagents call tools under its id too, and the first
608
+ * of them to call would take what its own line of work is owed. */
609
+ export let reply = async (host: Door, call: Bundle): Promise<Bundle[]> => {
610
+ let g = host.graph
611
+ if (!g.vocab.comp('notified')) return []
612
+ let id = who(call)?.via
613
+ if (!id) return []
614
+ let [session] = await g.read(
615
+ and(eq('entity.eid', id), fields(`${SESSION}.id`)),
616
+ )
617
+ if (
618
+ !session?.session || await hooked(g, id) ||
619
+ (await hearing(g, [id])).size
620
+ ) return []
621
+ return (await owed(host, id)).map(({ item, line }) => ({
622
+ entity: {
623
+ eid: derivedEid(`session reply ${call.entity.eid} ${item.entity.eid}`),
624
+ },
625
+ content: { body: line },
626
+ }))
627
+ }
628
+
629
+ /** What a harness hook reports: the harness's id for its session, and the
630
+ * subagent the event came from, when it came from one (Claude Code's
631
+ * `session_id` and `agent_id`). */
632
+ export type Hook = {
633
+ session_id?: unknown
634
+ agent_id?: unknown
635
+ hook_event_name?: unknown
636
+ }
637
+
638
+ /**
639
+ * The hook door's answer to one event: the lines owed to the session, when
640
+ * the event came from the session's own line of work, as the context the
641
+ * harness adds to it, or at the end of a turn (`Stop`) as the reason the stop
642
+ * is blocked, so the agent takes them up before its run ends. An event from a subagent hears nothing, so what the
643
+ * session is owed waits for the session. The first event, a subagent's too,
644
+ * marks the session `hooked`, and from then on the bus says nothing in a tool
645
+ * reply to it, which cannot tell the session from its subagents.
646
+ *
647
+ * The lines are marked said as they are taken, and `reaches` then asks the
648
+ * door whether its answer can still reach the harness. A harness that gave up
649
+ * on the hook while the lines were read and marked gets none of them, and
650
+ * they stay owed for its next hook or `yak session listen`: a line said twice
651
+ * beats a line lost.
652
+ */
653
+ export let heard = async (
654
+ host: Door,
655
+ hook: Hook,
656
+ reaches: () => Promise<boolean> = () => Promise.resolve(true),
657
+ ): Promise<object> => {
658
+ let g = host.graph
659
+ if (!g.vocab.comp('notified')) return {}
660
+ let said = typeof hook.session_id == 'string' ? hook.session_id : ''
661
+ let session = said ? await sessionFor(g, said, [`${SESSION}.id`]) : undefined
662
+ if (!session?.session) return {}
663
+ let id = session.entity.eid
664
+ if (!await hooked(g, id)) await g.apply([{ entity: { eid: id }, hooked: {} }])
665
+ if (hook.agent_id) return {}
666
+ let taken = await owed(host, id)
667
+ if (!taken.length) return {}
668
+ if (!await reaches()) {
669
+ await undeliver(
670
+ g,
671
+ null,
672
+ taken.flatMap(({ item, same }) => [item, ...same]),
673
+ )
674
+ return {}
675
+ }
676
+ let text = taken.map(({ line }) => line).join('\n')
677
+ let event = String(hook.hook_event_name ?? 'PostToolUse')
678
+ // A turn's end takes no added context: what is owed blocks the stop, and
679
+ // the harness hands its reason to the agent as the next turn.
680
+ return event == 'Stop'
681
+ ? { decision: 'block', reason: text }
682
+ : { hookSpecificOutput: { hookEventName: event, additionalContext: text } }
683
+ }