@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/reach.ts ADDED
@@ -0,0 +1,1107 @@
1
+ // What a step reads of a transcript. A status, a runner step and a tool
2
+ // snapshot each decide from the newest part of a transcript and the few older
3
+ // entries that part names; reading all of it made a step cost more with every
4
+ // line the transcript had ever held (T-128248).
5
+ //
6
+ // `reach` reads newest first, a page at a time, and stops at the oldest seq
7
+ // any of those decisions still looks at: the newest ask and the boundary it
8
+ // was sent from, the turns a retry counts back through, the last stop, and for
9
+ // a model turn the summary a checkpoint left and everything after the line it
10
+ // replaced, the lines after the newest answered ask where its model continues
11
+ // from it (`anchored`), or the lines a finite `sending.window` sends. Beyond
12
+ // that edge it
13
+ // adds only the entries those name (a call a result answers, the ask a line
14
+ // came from, the newest `using` and `sending`, the prompts a checkpoint
15
+ // retains), each by one query. A step running one call reads what its tool
16
+ // reads of the turn (those prompts, `using` and `sending`) and stops where a
17
+ // status does: it sends no window, so it never reads one. Nor does a model
18
+ // turn where none is owed: a transcript running its calls, settled, stopped
19
+ // or failed is sent nothing, so its turn reads what a tool call's does, and
20
+ // only a pending one reads on to its window. What it returns answers every
21
+ // function of ./state.ts and ./compact.ts the step asks as the whole
22
+ // transcript would; ./reach_test.ts holds the two together.
23
+ //
24
+ // Those lookups beyond the edge are remembered, so a step costs the lines
25
+ // appended since the last, not the transcript's length. A line is appended at
26
+ // the next seq (./append.ts), and what each lookup selects changes only by a
27
+ // line appended (a call, the result answering it, a stop, a checkpoint) or by
28
+ // the lines it found: the next reading asks only those and the lines appended
29
+ // since, each by name. A lookup on a transcript whose newest lines were
30
+ // deleted, which may append at those seqs again, or that more lines landed on
31
+ // than a lookup asks for by name, reads it whole. A mark set on an older line
32
+ // (`provisional` on an ask) is read each time.
33
+ //
34
+ // The lines below every one a decision reads (the newest ask, the newest
35
+ // answered one, the turns a retry counts) are what a model is sent and what a
36
+ // status looks over for their shapes: an ask, a call, its result. They are read
37
+ // without their lifecycles, an ask's `attempt` and a call's `execution`, which
38
+ // nothing decides by there and which a store derives again on every read
39
+ // (`attempt.state`, `execution.state`). An open call, a provisional ask and
40
+ // what the newest lines name are read whole by their own lookups, and those
41
+ // readings stand over the line's. The lines a reading reached below its pages
42
+ // are remembered too, as the lookups are: while the newest line it read stands
43
+ // where it was, the next reading asks them again by name, in one get the store
44
+ // answers from memory, and reads them by query again once one is no longer
45
+ // the line it was or holds other components.
46
+ //
47
+ // No page reads a result's `value` either: what a tool answered as data,
48
+ // which can hold a page's screenshot or another search's whole rows, megabytes
49
+ // a result, while a model is sent its words. A turn held every one it reached
50
+ // at once, and a Builder stepping several such transcripts ran out of memory
51
+ // (T-1786). A page reads `result` without it, and a model's view of a result
52
+ // reads its value by name where it needs it (@yaks/context `outputView`).
53
+ //
54
+ // No page reads a line's `sending`. An ask once recorded the instructions it
55
+ // sent as text, tens of kilobytes the same from one ask to the next, and a
56
+ // model turn's reading held one copy an ask: a Builder stepping a handful of
57
+ // long transcripts at once ran out of memory (T-1572). An ask now names them
58
+ // (./told.ts), and an ask written before keeps its text until it is moved. A
59
+ // step reads what was sent of the newest ask, the ask still in flight and each
60
+ // ask an open call came from, and what is in force (`aspect`); those are read
61
+ // by name.
62
+ //
63
+ // A fork reads through its segments (./window.ts): the parent up to the
64
+ // anchor, then its own. A pending transcript with no checkpoint, no anchor and
65
+ // no window is its own context, so its turn reads it all: the model is sent
66
+ // all of it too. Entries without a `seq` belong to the oldest end and are reached when
67
+ // the reading is.
68
+
69
+ import { tablesOf } from '@yaks/archetype/sets'
70
+ import type { Bundle, Comp, Eid, Graph, Row } from 'jsr:@yaks/graph@0.2.36'
71
+ import { type Built, line, sub } from '@yaks/query'
72
+ import { given } from './answer.js'
73
+ import { stoppedNotice } from './claude-control.js'
74
+ import { askingOf, lines } from './compact.js'
75
+ import { checkpointOf } from './pruning.js'
76
+ import { ASK, CALL, CONTENT, ENTRY, OUTPUT, RESULT, USING } from './native.js'
77
+ import {
78
+ attemptState,
79
+ kinded,
80
+ kindOf,
81
+ marksOf,
82
+ newestAsk,
83
+ openCalls,
84
+ ordered,
85
+ outranking,
86
+ RETRIES,
87
+ sendingBefore,
88
+ seqOf,
89
+ statusOf,
90
+ type TranscriptStatus,
91
+ usingBefore,
92
+ } from './state.js'
93
+ import { past, type Segment, transcriptSegments, within } from './window.js'
94
+
95
+ const SENDING = 'sending'
96
+ const PROGRESS = 'tool_progress'
97
+ // What the lines below a decision's are read without.
98
+ const LIFECYCLES = ['attempt', 'execution']
99
+ const FIRST = 64
100
+ // The most lines appended since a lookup that it asks for by name; past them
101
+ // (an import, a run another process wrote) it reads the transcript whole.
102
+ const SINCE = 256
103
+
104
+ let comp = (b: Bundle | undefined, name: string) =>
105
+ b?.[name] as Comp | undefined
106
+
107
+ export type Reach = {
108
+ /** read prose too: the lines a model is sent, their bodies in hand */
109
+ bodies?: boolean
110
+ /** a model turn: its context (checkpoint, prompts, window) is reached too,
111
+ * where the transcript owes one (it is pending); elsewhere what `call`
112
+ * reaches */
113
+ turn?: boolean
114
+ /** a tool call: what a tool reads of the turn it came from (the prompts,
115
+ * the model selection and `sending` in force), but not the window that
116
+ * turn sent */
117
+ call?: boolean
118
+ /** the components to read of each entry; every one but prose by default */
119
+ comps?: string[]
120
+ /** whether the model that answered an ask can continue from it
121
+ * (@yaks/model `Model.anchor`): a model turn after such an ask is sent only
122
+ * what followed it, so its reading stops there */
123
+ anchored?: (ask: Bundle) => boolean | Promise<boolean>
124
+ }
125
+
126
+ // One reading: the chain of segments and what of each entry it brings.
127
+ type Read = {
128
+ g: Graph
129
+ segs: Segment[]
130
+ names?: string[]
131
+ /** read `result` without its `value` */
132
+ valueless?: boolean
133
+ fields: Built
134
+ found: Map<string, Promise<Bundle | undefined>>
135
+ shapes: Map<string, string[]>
136
+ /** the lines of a segment it looked at, by the query naming them */
137
+ lines: Map<string, Promise<Line[]>>
138
+ }
139
+
140
+ type Line = { eid: Eid; seq: number }
141
+
142
+ // What a lookup found in a segment, and the line it was true through.
143
+ type Known = Line & { found: Eid[] }
144
+
145
+ const KEPT = 1024
146
+ let memories = new WeakMap<Graph, Map<string, Known>>()
147
+
148
+ // The components each archetype holds, by its eid, as the graph names them.
149
+ // An archetype is named by the components it holds (@yaks/archetype), so what
150
+ // one says never changes, and every reading of a graph shares what any has
151
+ // read.
152
+ let shaped = new WeakMap<Graph, Map<string, string[]>>()
153
+ let shapesOf = (g: Graph) => {
154
+ let held = shaped.get(g)
155
+ if (!held || held.size > KEPT) shaped.set(g, held = new Map())
156
+ return held
157
+ }
158
+
159
+ // Learn the components of each archetype among `keys` that `shapes` lacks, by
160
+ // name: a descriptor names them by identity (@yaks/archetype `tablesOf`).
161
+ let learn = async (g: Graph, shapes: Map<string, string[]>, keys: Eid[]) => {
162
+ let missing = keys.filter((key) => !shapes.has(key))
163
+ if (!missing.length) return
164
+ for (let b of await g.get(missing, ['archetype'])) {
165
+ let text = comp(b, 'archetype')?.tables
166
+ if (typeof text == 'string') {
167
+ shapes.set(b.entity.eid, tablesOf(text, g.vocab))
168
+ }
169
+ }
170
+ }
171
+
172
+ let chain = async (g: Graph, session: Eid, o: Reach): Promise<Read> => {
173
+ let names = o.bodies
174
+ ? o.comps ? [...new Set([...o.comps, CONTENT])] : undefined
175
+ // A runner needs private execution pins too; `comps` is only the
176
+ // wire-writable component list and omits inference recovery authority.
177
+ : o.comps ?? g.vocab.all.filter((n) => n != CONTENT && n != 'session')
178
+ return {
179
+ g,
180
+ segs: await transcriptSegments(g, session),
181
+ names,
182
+ fields: names
183
+ ? names.reduce<Built>(
184
+ (q, n, i) => i ? line`${sub(q)}&?${n}` : line`?${n}`,
185
+ line``,
186
+ )
187
+ : line`*`,
188
+ found: new Map(),
189
+ shapes: shapesOf(g),
190
+ lines: new Map(),
191
+ }
192
+ }
193
+
194
+ // Select identities separately, then gather the components actually present.
195
+ // Projecting every optional component forces a scalar read for each declared
196
+ // component, even though an entry carries only a handful of them. Several
197
+ // queries' entities are gathered at once; a query asked of named entities
198
+ // alone carries them beside it.
199
+ type Ask = Built | { q: Built; eids: Eid[] }
200
+ let selected = async (r: Read, ...asks: Ask[]): Promise<Bundle[]> => {
201
+ let fields = r.g.vocab.comp('archetype')
202
+ ? line`&.fields=entity.eid,entity.archetype`
203
+ : line`&.fields=entity.eid`
204
+ let owners = []
205
+ for (let a of asks) {
206
+ owners.push(
207
+ ...typeof a == 'string'
208
+ ? await r.g.rows(line`${sub(a)}${sub(fields)}`)
209
+ : await r.g.rows(line`${sub(a.q)}${sub(fields)}`, { eids: a.eids }),
210
+ )
211
+ }
212
+ return await gathered(r, owners)
213
+ }
214
+
215
+ // The entities of `owners`, rows naming each one's eid and archetype, holding
216
+ // the components of `r.names` their archetypes hold.
217
+ // A page's lines (`r.valueless`) hold `result` without its value: read by
218
+ // query, or as a reading before found it (`results`), since a result's call
219
+ // and time are kept as it landed.
220
+ let gathered = async (
221
+ r: Read,
222
+ owners: Row[],
223
+ results?: Map<Eid, Comp>,
224
+ ): Promise<Bundle[]> => {
225
+ let ids = owners.map((b) => String(b['entity.eid']))
226
+ if (!ids.length) return []
227
+ let names = r.names
228
+ if (names && r.g.vocab.comp('archetype')) {
229
+ let keys = [...new Set(owners.map((b) => b['entity.archetype']))]
230
+ if (!keys.includes(undefined)) {
231
+ await learn(r.g, r.shapes, keys.map(String))
232
+ if (keys.every((key) => r.shapes.has(String(key)))) {
233
+ let present = new Set(
234
+ keys.flatMap((key) => r.shapes.get(String(key))!),
235
+ )
236
+ names = names.filter((n) => present.has(n))
237
+ }
238
+ }
239
+ }
240
+ let light = r.valueless && names?.includes(RESULT)
241
+ if (light) names = names!.filter((n) => n != RESULT)
242
+ let rows = new Map((await r.g.get(ids, names)).map((b) => [b.entity.eid, b]))
243
+ if (light) {
244
+ let asked: Eid[] = []
245
+ for (let [id, b] of rows) {
246
+ let held = results?.get(id)
247
+ if (held) b[RESULT] = { ...held }
248
+ else if (
249
+ r.shapes.get(String(b.entity.archetype))?.includes(RESULT) ?? true
250
+ ) asked.push(id)
251
+ }
252
+ for (let b of await valueless(r.g, asked)) {
253
+ let row = rows.get(b.entity.eid)
254
+ if (row) row[RESULT] = b[RESULT]
255
+ }
256
+ }
257
+ return ids.flatMap((id) => rows.get(id) ?? [])
258
+ }
259
+
260
+ // The results among `ids`, each carrying every property of `result` but its
261
+ // value.
262
+ let valueless = async (g: Graph, ids: Eid[]) =>
263
+ !ids.length ? [] : await g.read(
264
+ line`.${RESULT}&.fields=${[
265
+ 'entity.eid',
266
+ ...g.vocab.props(RESULT).filter((p) => p != 'value').map((p) =>
267
+ `${RESULT}.${p}`
268
+ ),
269
+ ]}`,
270
+ { eids: ids },
271
+ )
272
+
273
+ // A segment's lines a reading reached, newest first from the segment's newest,
274
+ // with their shapes, and the seq they were read down to.
275
+ type Shape = Line & { archetype: Eid; result?: Comp }
276
+ type Reached = { from: number; lines: Shape[] }
277
+ const WINDOWS = 64
278
+ let windows = new WeakMap<Graph, Map<string, Reached>>()
279
+
280
+ // The lines of `s` from `at` up and below `under`, as the last reading to reach
281
+ // them found them, asked again by name. While that reading's newest line is
282
+ // where it was, the segment holds its lines and those appended since, which a
283
+ // page has read. Each must still be the line it was, of the same shape; if one
284
+ // is not, or a line appended since lies below the pages, it is undefined.
285
+ let recalled = async (
286
+ r: Read,
287
+ s: Segment,
288
+ at: number,
289
+ under: number,
290
+ ): Promise<Bundle[] | undefined> => {
291
+ let known = windows.get(r.g)?.get(within(s))
292
+ if (!known || at < known.from) return
293
+ let edge = known.lines[0]
294
+ let lines = await tail(r, s, edge.seq)
295
+ let last = lines.at(-1)
296
+ if (last?.eid != edge.eid || last.seq != edge.seq) return
297
+ let range = (l: Line) => l.seq >= at && l.seq < under
298
+ if (lines.slice(0, -1).some(range)) return
299
+ let wanted = known.lines.filter(range)
300
+ let found = await gathered(
301
+ r,
302
+ wanted.map((l) => ({
303
+ 'entity.eid': l.eid,
304
+ 'entity.archetype': l.archetype,
305
+ })),
306
+ new Map(wanted.flatMap((l) => l.result ? [[l.eid, l.result]] : [])),
307
+ )
308
+ let stands = found.length == wanted.length &&
309
+ found.every((b, k) =>
310
+ b.entity.eid == wanted[k].eid &&
311
+ b.entity.archetype == wanted[k].archetype &&
312
+ comp(b, ENTRY)?.session == s.session && seqOf(b) == wanted[k].seq
313
+ )
314
+ return stands ? found : undefined
315
+ }
316
+
317
+ // Older rows of the whole chain, `n` at a time, newest first, without what
318
+ // they sent or a result's value.
319
+ let pages = (r: Read) => {
320
+ let { segs } = r
321
+ let i = segs.length - 1, after = line``
322
+ let without = (...gone: string[]): Read => ({
323
+ ...r,
324
+ names: (r.names ?? r.g.vocab.all).filter((n) => !gone.includes(n)),
325
+ valueless: true,
326
+ })
327
+ let page = without(SENDING)
328
+ let below = without(SENDING, ...LIFECYCLES)
329
+ // What each segment was read down to, and its rows, newest first.
330
+ let reached = segs.map(() => ({ from: Infinity, rows: [] as Bundle[] }))
331
+ let took = (k: number, rows: Bundle[], from: number) => {
332
+ reached[k].rows.push(...rows)
333
+ reached[k].from = Math.min(reached[k].from, from)
334
+ }
335
+ let reaching = false
336
+ return {
337
+ get done() {
338
+ return i < 0
339
+ },
340
+ next: async (n: number): Promise<Bundle[]> => {
341
+ let got: Bundle[] = []
342
+ while (i >= 0 && got.length < n) {
343
+ let want = n - got.length
344
+ let rows = await selected(
345
+ page,
346
+ line`${sub(within(segs[i]))}&.order=-entry.seq&.limit=${want}${
347
+ sub(after)
348
+ }`,
349
+ )
350
+ got.push(...rows)
351
+ if (rows.length < want) {
352
+ took(i, rows, -Infinity)
353
+ i--
354
+ after = line``
355
+ } else {
356
+ took(i, rows, seqOf(rows.at(-1)!))
357
+ after = past(segs[i], rows.at(-1)!.entity.eid)
358
+ }
359
+ }
360
+ return got
361
+ },
362
+ // Every row from `at` up that is still unread, a query for each segment
363
+ // it spans: a segment is read whole when the one before it still holds
364
+ // seqs at or above `at`, since the seqs of a segment all pass those before.
365
+ // They lie below every line a decision reads, so without lifecycles, and
366
+ // the lines a reading reached before are asked again by name.
367
+ until: async (at: number): Promise<Bundle[]> => {
368
+ reaching = true
369
+ let got: Bundle[] = []
370
+ while (i >= 0) {
371
+ let s = segs[i], oldest = reached[i].rows.at(-1)
372
+ let rows =
373
+ await recalled(below, s, at, oldest ? seqOf(oldest) : Infinity) ??
374
+ await selected(
375
+ below,
376
+ line`${sub(within(s))}&.entry.seq>=${at}&.order=-entry.seq${
377
+ sub(after)
378
+ }`,
379
+ )
380
+ got.push(...rows)
381
+ took(i, rows, at)
382
+ if (rows.length) after = line`&.after=${rows.at(-1)!.entity.eid}`
383
+ if (i == 0 || segs[i - 1].through < at) break
384
+ i--
385
+ after = line``
386
+ }
387
+ return got
388
+ },
389
+ // What a reading that reached below its pages read of each segment, for
390
+ // the next to ask again: lines of a seq and a known shape.
391
+ keep: () => {
392
+ if (!reaching || !r.g.vocab.comp('archetype')) return
393
+ let kept = windows.get(r.g) ?? new Map<string, Reached>()
394
+ windows.set(r.g, kept)
395
+ reached.forEach(({ from, rows }, k) => {
396
+ if (from == Infinity) return
397
+ let key = within(segs[k])
398
+ kept.delete(key)
399
+ let lines = rows.map((b) => ({
400
+ eid: b.entity.eid,
401
+ seq: Number(comp(b, ENTRY)?.seq),
402
+ archetype: String(b.entity.archetype ?? ''),
403
+ ...b.result && !('value' in (b.result as Comp))
404
+ ? { result: b.result as Comp }
405
+ : {},
406
+ }))
407
+ if (
408
+ !lines.length ||
409
+ lines.some((l) => !Number.isSafeInteger(l.seq) || !l.archetype)
410
+ ) return
411
+ kept.set(key, { from, lines })
412
+ if (kept.size > WINDOWS) kept.delete(kept.keys().next().value!)
413
+ })
414
+ },
415
+ }
416
+ }
417
+
418
+ // A segment's lines from `seq` up, newest first, as many as SINCE lines
419
+ // appended after it, or its newest line alone: their identities, read once a
420
+ // reading.
421
+ let tail = (r: Read, s: Segment, seq?: number): Promise<Line[]> => {
422
+ let q = seq == null
423
+ ? line`${sub(within(s))}&.limit=1`
424
+ : line`${sub(within(s))}&.entry.seq>=${seq}&.limit=${SINCE + 1}`
425
+ let held = r.lines.get(q)
426
+ if (held) return held
427
+ let read = (async () =>
428
+ (await r.g.rows(
429
+ line`${sub(q)}&.order=-entry.seq&.fields=entity.eid,entry.seq`,
430
+ ))
431
+ .map((row) => ({
432
+ eid: String(row['entity.eid']),
433
+ seq: Number(row['entry.seq']),
434
+ })))()
435
+ r.lines.set(q, read)
436
+ return read
437
+ }
438
+
439
+ // What a lookup in a segment found before, while the line it was true through
440
+ // is still that line, and the segment's newest line now. `ask` is what the
441
+ // lookup asks again: the lines it found and those appended since.
442
+ let recall = async (
443
+ r: Read,
444
+ s: Segment,
445
+ qualifier: Built,
446
+ ): Promise<{ known?: Known; edge?: Line; ask: Eid[] }> => {
447
+ let known = memories.get(r.g)?.get(within(s) + qualifier)
448
+ let lines = await tail(r, s, known?.seq)
449
+ let at = lines.at(-1)
450
+ if (!known || at?.seq != known.seq || at?.eid != known.eid) {
451
+ return { edge: lines[0], ask: [] }
452
+ }
453
+ return {
454
+ known,
455
+ edge: lines[0],
456
+ ask: [...lines.slice(0, -1).map((l) => l.eid), ...known.found],
457
+ }
458
+ }
459
+
460
+ // What a lookup found, true through `edge`, the newest line before it looked.
461
+ let keep = (
462
+ r: Read,
463
+ s: Segment,
464
+ qualifier: Built,
465
+ edge: Line | undefined,
466
+ found: Bundle[],
467
+ ) => {
468
+ let kept = memories.get(r.g) ?? new Map<string, Known>()
469
+ memories.set(r.g, kept)
470
+ let key = within(s) + qualifier
471
+ kept.delete(key)
472
+ if (!edge) return
473
+ kept.set(key, { ...edge, found: found.map((b) => b.entity.eid) })
474
+ if (kept.size > KEPT) kept.delete(kept.keys().next().value!)
475
+ }
476
+
477
+ // The newest entry a qualifier selects, and every one of them.
478
+ let newest = (r: Read, qualifier: Built): Promise<Bundle | undefined> => {
479
+ let seen = r.found.get(qualifier)
480
+ if (seen) return seen
481
+ let found = (async () => {
482
+ for (let s of r.segs.toReversed()) {
483
+ let { known, edge, ask } = await recall(r, s, qualifier)
484
+ let q = line`${sub(within(s))}${
485
+ sub(qualifier)
486
+ }&.order=-entry.seq&.limit=1`
487
+ let page = async (eids?: Eid[]) =>
488
+ (await selected(r, eids ? { q, eids } : q))[0]
489
+ let row = !known ? await page() : ask.length ? await page(ask) : undefined
490
+ // What it found before is gone or no longer one: read it all again.
491
+ if (known?.found.length && !row) row = await page()
492
+ keep(r, s, qualifier, edge, row ? [row] : [])
493
+ if (row) return row
494
+ }
495
+ })()
496
+ r.found.set(qualifier, found)
497
+ return found
498
+ }
499
+ let every = async (
500
+ r: Read,
501
+ qualify: (segment: Segment) => Built | undefined,
502
+ ): Promise<Bundle[]> =>
503
+ (await Promise.all(r.segs.map(async (s) => {
504
+ let qualifier = qualify(s)
505
+ if (!qualifier) return []
506
+ let { known, edge, ask } = await recall(r, s, qualifier)
507
+ let q = line`${sub(within(s))}${sub(qualifier)}`
508
+ let found = !known
509
+ ? await selected(r, q)
510
+ : ask.length
511
+ ? await selected(r, { q, eids: ask })
512
+ : []
513
+ keep(r, s, qualifier, edge, found)
514
+ return found
515
+ }))).flat()
516
+
517
+ // The named entries that are lines of this transcript: an entry another
518
+ // transcript holds, or one a fork left behind, is not among its entries.
519
+ let fetch = async (r: Read, eids: Iterable<Eid>): Promise<Bundle[]> => {
520
+ let ids = [...new Set(eids)]
521
+ if (!ids.length) return []
522
+ let found = await r.g.get(
523
+ ids,
524
+ r.names && !r.names.includes(ENTRY) ? [ENTRY, ...r.names] : r.names,
525
+ )
526
+ return found.filter((b) => {
527
+ let at = comp(b, ENTRY)
528
+ return r.segs.some((s) =>
529
+ s.session == at?.session && Number(at.seq) <= s.through
530
+ )
531
+ })
532
+ }
533
+
534
+ // The entries `aspectBefore` (./state.ts) reads to say what `name` is in force:
535
+ // the newest to carry it, the newest that is not an ask, and the line the
536
+ // newest ask was sent through. `near` is the newest entries already read.
537
+ let aspect = async (
538
+ r: Read,
539
+ name: string,
540
+ near: Bundle[] = [],
541
+ ): Promise<Bundle[]> => {
542
+ if (!r.g.vocab.comp(name)) return []
543
+ let carry = near.filter((b) => name in b)
544
+ let latest = carry.at(-1) ?? await newest(r, line`&.${name}`)
545
+ if (!latest) return []
546
+ let chosen = !latest.ask ? undefined : carry.findLast((b) => !b.ask) ??
547
+ await newest(r, line`&.${name}&!${ASK}`)
548
+ let through = comp(latest, ASK)?.through
549
+ let sent = through == null ? [] : near.filter((b) => b.entity.eid == through)
550
+ return [
551
+ latest,
552
+ ...chosen ? [chosen] : [],
553
+ ...through == null
554
+ ? []
555
+ : sent.length
556
+ ? sent
557
+ : await fetch(r, [String(through)]),
558
+ ]
559
+ }
560
+
561
+ // What `statusOf` reads of an entry.
562
+ const STATUS = [
563
+ ENTRY,
564
+ ASK,
565
+ CALL,
566
+ RESULT,
567
+ PROGRESS,
568
+ 'tool_async',
569
+ OUTPUT,
570
+ USING,
571
+ SENDING,
572
+ 'attempt',
573
+ 'execution',
574
+ 'interrupted',
575
+ 'failed',
576
+ 'provisional',
577
+ 'notice',
578
+ 'stop',
579
+ 'exception',
580
+ 'refusal',
581
+ 'lines',
582
+ ]
583
+
584
+ /** What a transcript is doing, read off the entries a status looks at. The
585
+ * adapter's derived `session.status` is this rule too, but it computes it over
586
+ * every entry each time it is asked, so the cost of asking grows with the
587
+ * transcript; this reads the newest part. Besides entries, only the marks its
588
+ * row wears ({@link Marks}) bear on it: a stop observed from outside
589
+ * (`session.ended`), and a process of its own still running it. */
590
+ export let entryStatus = async (
591
+ g: Graph,
592
+ session: Eid,
593
+ ): Promise<TranscriptStatus> => {
594
+ // The session component itself is never read whole: it wears the status.
595
+ let run = ['process', 'exit'].filter((name) => g.vocab.comp(name))
596
+ let [[row], [ran]] = await Promise.all([
597
+ g.rows(line`.entity.eid=${session}&.fields=session.ended`),
598
+ run.length ? g.get([session], run) : [],
599
+ ])
600
+ return statusOf(
601
+ await reach(g, session, {
602
+ comps: STATUS.filter((name) => g.vocab.comp(name)),
603
+ }),
604
+ { ...marksOf(ran), ended: row?.['session.ended'] === true },
605
+ )
606
+ }
607
+
608
+ /** The model selection in force on a transcript, as the whole of it would say. */
609
+ export let usingOf = async (
610
+ g: Graph,
611
+ session: Eid,
612
+ ): Promise<Comp | undefined> =>
613
+ usingBefore(
614
+ await aspect(
615
+ await chain(g, session, { comps: [ENTRY, USING, ASK] }),
616
+ USING,
617
+ ),
618
+ )
619
+
620
+ /** The newest entry of a transcript, prose and all. */
621
+ export let newestOf = async (
622
+ g: Graph,
623
+ session: Eid,
624
+ ): Promise<Bundle | undefined> =>
625
+ newest(await chain(g, session, { bodies: true }), line``)
626
+
627
+ /** Whether a transcript holds an ask. */
628
+ export let hasAsk = async (g: Graph, session: Eid): Promise<boolean> =>
629
+ !!await newest(await chain(g, session, { comps: [ENTRY] }), line`&.${ASK}`)
630
+
631
+ // The oldest entry a qualifier selects: what was said first never moves, so
632
+ // nothing of it is remembered.
633
+ let oldest = async (
634
+ r: Read,
635
+ qualifier: Built,
636
+ ): Promise<Bundle | undefined> => {
637
+ for (let s of r.segs) {
638
+ let [row] = await selected(
639
+ r,
640
+ line`${sub(within(s))}${sub(qualifier)}&.order=entry.seq&.limit=1`,
641
+ )
642
+ if (row) return row
643
+ }
644
+ }
645
+
646
+ // A qualifier leaving out entries that carry any of `names` the vocabulary
647
+ // declares: an undeclared one is carried by none.
648
+ let without = (g: Graph, ...names: string[]): Built =>
649
+ names.filter((n) => g.vocab.comp(n))
650
+ .reduce<Built>((q, n) => line`${sub(q)}&!${n}`, line``)
651
+
652
+ // A request: an entry choosing the model a run goes on with, not an ask and
653
+ // not a line read from a provider's log.
654
+ let request = (g: Graph) => line`&.${USING}${sub(without(g, ASK, 'lines'))}`
655
+
656
+ /** The first request of a transcript, prose and all: what a run was started
657
+ * with. */
658
+ export let firstRequest = async (
659
+ g: Graph,
660
+ session: Eid,
661
+ ): Promise<Bundle | undefined> =>
662
+ oldest(await chain(g, session, { bodies: true }), request(g))
663
+
664
+ /** The newest request of a transcript: the one a run going on answers. */
665
+ export let latestRequest = async (
666
+ g: Graph,
667
+ session: Eid,
668
+ ): Promise<Bundle | undefined> =>
669
+ newest(await chain(g, session, { comps: [ENTRY, USING] }), request(g))
670
+
671
+ /** The first input of a transcript, prose and all: what it was first told. */
672
+ export let firstInput = async (
673
+ g: Graph,
674
+ session: Eid,
675
+ ): Promise<Bundle | undefined> =>
676
+ oldest(
677
+ await chain(g, session, { bodies: true }),
678
+ line`&.${CONTENT}${sub(without(g, OUTPUT, 'lines', 'notice'))}`,
679
+ )
680
+
681
+ /** The newest receipt of a transcript: the stop that says a run ended, naming
682
+ * the request it answered (`ask.through`), or the one answering `through`. */
683
+ export let receiptOf = async (
684
+ g: Graph,
685
+ session: Eid,
686
+ through?: Eid,
687
+ ): Promise<Bundle | undefined> =>
688
+ newest(
689
+ await chain(g, session, { comps: [ENTRY, ASK, 'stop'] }),
690
+ through == null
691
+ ? line`&.stop${sub(without(g, 'lines'))}&.${ASK}.through`
692
+ : line`&.stop${sub(without(g, 'lines'))}&.${ASK}.through=${through}`,
693
+ )
694
+
695
+ /** What a transcript said last, prose and all: its newest spoken output (not a
696
+ * call, a result, reasoning or an ending), else the newest ending that says
697
+ * why. */
698
+ export let saidOf = async (
699
+ g: Graph,
700
+ session: Eid,
701
+ ): Promise<Bundle | undefined> => {
702
+ let r = await chain(g, session, { bodies: true })
703
+ return await newest(
704
+ r,
705
+ line`&.${OUTPUT}&.${CONTENT}${
706
+ sub(without(g, 'reasoning', CALL, RESULT, 'stop'))
707
+ }`,
708
+ ) ?? await newest(r, line`&.stop&.${CONTENT}`)
709
+ }
710
+
711
+ // What a reading holds besides its newest rows, found by one lookup for all:
712
+ // its own calls (which no result answers), the prompts for a model turn or a
713
+ // tool call, and the checkpoints for a model turn; and for a model turn the
714
+ // asks the runner owes a retry, by a query of their own, since that mark is
715
+ // set on an ask already written. The mark is named first: a query is driven
716
+ // by the first component it names, and the few marked entities are read where
717
+ // every ask of the graph, or every line of the transcript, would be.
718
+ let named = async (r: Read, o: Reach): Promise<Bundle[]> => {
719
+ let has = (name: string) => r.g.vocab.comp(name)
720
+ let turn = !!o.turn
721
+ let parts = [
722
+ ...turn && has('checkpoint') ? [line`.checkpoint`] : [],
723
+ // What a summary's tasks became since (./task-context.ts `admitted`).
724
+ ...turn && has('task_context') ? [line`.task_context`] : [],
725
+ ...(turn || o.call) && has('prompt') ? [line`.prompt`] : [],
726
+ ]
727
+ let own = r.segs.at(-1)
728
+ let calls = has(CALL) && has(RESULT) ? [line`.${CALL} !${RESULT}s`] : []
729
+ return [
730
+ ...await every(r, (s) => {
731
+ let terms = s == own ? [...parts, ...calls] : parts
732
+ if (terms.length) {
733
+ return line`&(${
734
+ sub(terms.reduce((q, p) => line`${sub(q)}|${sub(p)}`))
735
+ })`
736
+ }
737
+ }),
738
+ ...turn && has('provisional')
739
+ ? await selected(
740
+ r,
741
+ ...r.segs.map((s) => line`${sub(within(s))}&.provisional&.${ASK}`),
742
+ )
743
+ : [],
744
+ ]
745
+ }
746
+
747
+ /** The calls of a transcript no result answers. */
748
+ export let openOf = async (g: Graph, session: Eid): Promise<Bundle[]> =>
749
+ (await named(await chain(g, session, { comps: [ENTRY, CALL] }), {}))
750
+ .filter((b) => b.call)
751
+
752
+ // An open call's ask says what it had read. Where the page only has words
753
+ // that landed later, look up the newest words as of `ask.through`, so the
754
+ // call still knows whose turn it was (./answer.ts `askedFor`).
755
+ let callWords = async (
756
+ r: Read,
757
+ entries: Bundle[],
758
+ visible: Bundle[],
759
+ latest: Bundle | undefined,
760
+ input: Built,
761
+ ): Promise<{ words: Bundle[]; through: Bundle[] }> => {
762
+ let byId = new Map(entries.map((b) => [b.entity.eid, b]))
763
+ let ids = new Set(
764
+ openCalls(entries).flatMap((call) => {
765
+ let source = comp(call, CALL)?.source
766
+ let through = comp(byId.get(String(source)), ASK)?.through
767
+ return typeof through == 'string' ? [through] : []
768
+ }),
769
+ )
770
+ let through = await fetch(
771
+ { ...r, names: [ENTRY] },
772
+ [...ids].filter((eid) => !byId.has(eid)),
773
+ )
774
+ for (let b of through) byId.set(b.entity.eid, b)
775
+ let ends = [...ids].flatMap((eid) => byId.get(eid) ?? [])
776
+ let words = await Promise.all(ends.map((end) => {
777
+ let seq = seqOf(end)
778
+ if (latest && seqOf(latest) <= seq) return latest
779
+ return visible.findLast((b) => seqOf(b) <= seq) ??
780
+ newest(r, line`${sub(input)}&.entry.seq<=${seq}`)
781
+ }))
782
+ return { words: words.filter((b) => b != null), through }
783
+ }
784
+
785
+ // Steering reads the words that began the turn, the notices leading up to
786
+ // them, and each `heard` line since. Read below the page by seq only where
787
+ // those words or the start of their notices lie there.
788
+ let hearing = async (
789
+ r: Read,
790
+ rows: Bundle[],
791
+ entries: Bundle[],
792
+ ): Promise<Bundle[]> => {
793
+ let { g } = r
794
+ if (!g.vocab.comp('heard')) return []
795
+ let input = line`&.${CONTENT}${
796
+ sub(without(g, OUTPUT, 'notice', ...kinded()))
797
+ }`
798
+ let page = rows.filter(given)
799
+ let latest = page.at(-1) ?? await newest(r, input)
800
+ let { words, through } = await callWords(r, entries, page, latest, input)
801
+ if (latest) words.push(latest)
802
+ let starts = [...new Set(words)].filter((b) => {
803
+ let start = rows.indexOf(b)
804
+ while (start > 0 && rows[start - 1].notice) start--
805
+ return start <= 0
806
+ })
807
+ if (latest && !starts.length) return through
808
+ let before = await Promise.all(
809
+ starts.map((b) =>
810
+ newest(r, line`&.entry.seq<${seqOf(b)}${sub(without(g, 'notice'))}`)
811
+ ),
812
+ )
813
+ let from = before.length
814
+ ? Math.min(...before.map((b) => b ? seqOf(b) : -Infinity))
815
+ : -Infinity
816
+ let under = rows.length ? seqOf(rows[0]) : Infinity
817
+ let heard = await every(
818
+ r,
819
+ () =>
820
+ line`${sub(Number.isFinite(from) ? line`&.entry.seq>${from}` : line``)}${
821
+ sub(Number.isFinite(under) ? line`&.entry.seq<${under}` : line``)
822
+ }&.heard`,
823
+ )
824
+ return [
825
+ ...through,
826
+ ...starts.filter((b) => seqOf(b) < under),
827
+ ...before.filter((b) => b != null),
828
+ ...heard,
829
+ ]
830
+ }
831
+
832
+ // What a decision still reads, found as the rows come: the oldest seq the rows
833
+ // must reach, undefined while they cannot say.
834
+ type Needs = {
835
+ rows: Bundle[]
836
+ stop: () => Promise<number | undefined>
837
+ seqAt: (eid: Eid) => Promise<number | undefined>
838
+ mark?: number
839
+ /** the seq of the newest summary (`checkpoint`) itself */
840
+ summary?: number
841
+ noAsk?: boolean
842
+ window: (rows: Bundle[]) => Promise<unknown>
843
+ anchored?: (ask: Bundle) => boolean | Promise<boolean>
844
+ }
845
+
846
+ let floor = async (n: Needs, turn: boolean): Promise<number | undefined> => {
847
+ let { rows } = n
848
+ let all = rows.filter((b) => !b.notice || stoppedNotice(b))
849
+ let ask = all.findLast((b) => kindOf(b) == 'ask')
850
+ let turns = all.filter((b) => b.ask || kindOf(b) == 'input')
851
+ if (!ask && !n.noAsk) return undefined
852
+ // A completed request ends the retry streak. With no request at all there
853
+ // is no retry history to find among older notices and stops.
854
+ if (ask && turns.length < RETRIES && attemptState(ask) != 'completed') {
855
+ return undefined
856
+ }
857
+ let seqs = ask ? [seqOf(ask)] : []
858
+ if (turns.length >= RETRIES) seqs.push(seqOf(turns.at(-RETRIES)!))
859
+ // The newest input or stop says whether the transcript is stopped. An
860
+ // imported stop is a notice among the lines, found only by reading them.
861
+ let control = all.findLast((b) => ['input', 'stop'].includes(kindOf(b)!))
862
+ if (rows.some((b) => b.lines)) {
863
+ if (!control) return undefined
864
+ seqs.push(seqOf(control))
865
+ } else if (!control) {
866
+ let stop = await n.stop()
867
+ if (stop != null) seqs.push(stop)
868
+ }
869
+ let sent = async (b: Bundle) => {
870
+ let through = comp(b, ASK)?.through
871
+ let at = through == null ? undefined : await n.seqAt(String(through))
872
+ if (at != null) seqs.push(at)
873
+ }
874
+ if (ask) await sent(ask)
875
+ if (turn) {
876
+ let done = rows.findLast((b) => b.ask && attemptState(b) == 'completed')
877
+ if (!done && !n.noAsk) return undefined
878
+ if (done) {
879
+ seqs.push(seqOf(done))
880
+ await sent(done)
881
+ }
882
+ // The provider holds the conversation through an answered ask after the
883
+ // newest summary, which the turn then follows.
884
+ if (
885
+ done && !(seqOf(done) <= (n.summary ?? -Infinity)) &&
886
+ await n.anchored?.(done)
887
+ ) {
888
+ // `done` and the line it was sent through are read already.
889
+ } else if (n.mark != null) seqs.push(n.mark)
890
+ else {
891
+ let size = Math.floor(Number(await n.window(rows)))
892
+ if (!(size >= 1)) return -Infinity
893
+ let said = lines(rows, askingOf(rows))
894
+ if (said.length < size) return undefined
895
+ let from = said.length - size
896
+ while (from > 0 && kindOf(said[from]) != 'input') from--
897
+ if (from == 0 && kindOf(said[0]) != 'input') return undefined
898
+ seqs.push(seqOf(said[from]))
899
+ }
900
+ }
901
+ return Math.min(...seqs)
902
+ }
903
+
904
+ let read = async (g: Graph, session: Eid, o: Reach): Promise<{
905
+ entries: Bundle[]
906
+ shapes: Map<string, string[]>
907
+ }> => {
908
+ let r = await chain(g, session, o)
909
+ let held = await named(r, o)
910
+ // Archive membership changes without appending a line. Read its metadata
911
+ // afresh, including below checkpoints, without loading the archived prose.
912
+ if (o.turn && g.vocab.comp('archived')) {
913
+ let marks = await selected(
914
+ {
915
+ ...r,
916
+ names: [ENTRY, 'archived', CALL, RESULT, PROGRESS].filter((n) =>
917
+ g.vocab.comp(n)
918
+ ),
919
+ },
920
+ ...r.segs.map((s) => line`${sub(within(s))}&.archived`),
921
+ )
922
+ for (let b of marks) {
923
+ let found = held.find((h) => h.entity.eid == b.entity.eid)
924
+ if (found) Object.assign(found, b)
925
+ else held.push(b)
926
+ }
927
+ }
928
+ let rows: Bundle[] = []
929
+ let find = (eid: Eid) =>
930
+ rows.find((b) => b.entity.eid == eid) ??
931
+ held.find((b) => b.entity.eid == eid)
932
+ let stop: Promise<number | undefined> | undefined
933
+ let n: Needs = {
934
+ rows,
935
+ stop: () =>
936
+ stop ??= (async () => {
937
+ let hit = g.vocab.comp('stop') &&
938
+ await newest({ ...r, fields: line`?entry` }, line`&.stop`)
939
+ return hit ? seqOf(hit) : undefined
940
+ })(),
941
+ seqAt: async (eid) => {
942
+ let b = find(eid) ?? (await fetch({ ...r, names: [ENTRY] }, [eid]))[0]
943
+ return b?.entry ? seqOf(b) : undefined
944
+ },
945
+ window: async (rows) =>
946
+ sendingBefore(await aspect(r, SENDING, rows))?.window,
947
+ anchored: o.anchored,
948
+ }
949
+ let page = pages(r), size = FIRST, started = false
950
+ // Rows, newest first, down to the oldest seq a decision still reads: a
951
+ // status's, or with `turn` a model turn's as well.
952
+ let fill = async (turn: boolean) => {
953
+ while (true) {
954
+ if (started) {
955
+ let at = await floor(n, turn)
956
+ if (page.done || at != null && seqOf(rows[0]) <= at) return
957
+ // What the rows settle is a seq: read down to it at once, not by
958
+ // halves.
959
+ if (at != null && at > -Infinity) {
960
+ let older = await page.until(at)
961
+ if (!o.bodies) older = await withContent(g, older, r.shapes) ?? older
962
+ rows.unshift(...older.reverse())
963
+ let again = await floor(n, turn)
964
+ if (page.done || again != null && seqOf(rows[0]) <= again) return
965
+ }
966
+ size *= 2
967
+ }
968
+ started = true
969
+ let next = await page.next(size)
970
+ if (!o.bodies) next = await withContent(g, next, r.shapes) ?? next
971
+ rows.unshift(...next.reverse())
972
+ if (n.noAsk == null && !rows.some((b) => kindOf(b) == 'ask')) {
973
+ n.noAsk = !await newest(
974
+ { ...r, names: [ENTRY], fields: line`?entry` },
975
+ line`&.${ASK}${sub(without(g, ...outranking('ask')))}`,
976
+ )
977
+ }
978
+ }
979
+ }
980
+ // Older entries the rows name: the call a result answers, the ask a reply
981
+ // or call came from, and what the open calls have reported.
982
+ let reported = new Set<Eid>()
983
+ let missing = (of: (b: Bundle) => unknown) => {
984
+ let seen = new Set([...rows, ...held].map((b) => b.entity.eid))
985
+ return [
986
+ ...new Set(
987
+ [...rows, ...held].flatMap((b) => {
988
+ let eid = of(b)
989
+ return eid == null || seen.has(String(eid)) ? [] : [String(eid)]
990
+ }),
991
+ ),
992
+ ]
993
+ }
994
+ let gather = async () => {
995
+ let open = held.filter((b) => b.call && !reported.has(b.entity.eid))
996
+ .map((b) => b.entity.eid)
997
+ for (let eid of open) reported.add(eid)
998
+ if (open.length && g.vocab.comp(PROGRESS)) {
999
+ held.push(
1000
+ ...await g.read(line`.${PROGRESS}.call=${open}&${sub(r.fields)}`),
1001
+ )
1002
+ }
1003
+ held.push(
1004
+ ...await fetch(r, missing((b) => comp(b, CALL)?.source)),
1005
+ ...await fetch(
1006
+ r,
1007
+ missing((b) => comp(b, RESULT)?.call ?? comp(b, PROGRESS)?.call),
1008
+ ),
1009
+ ...await fetch(r, missing((b) => comp(b, OUTPUT)?.source)),
1010
+ )
1011
+ // What the lookups read of a line stands over the rows' reading of it,
1012
+ // which may lack its lifecycle and what it sent; each lookup adds what it
1013
+ // read, as one may read a line in part that another read whole.
1014
+ let looked = new Map<Eid, Bundle>()
1015
+ for (let b of held) {
1016
+ looked.set(b.entity.eid, { ...looked.get(b.entity.eid), ...b })
1017
+ }
1018
+ let seen = new Set<Eid>()
1019
+ return ordered([...rows, ...held].flatMap((b) => {
1020
+ if (seen.has(b.entity.eid)) return []
1021
+ seen.add(b.entity.eid)
1022
+ return [{ ...b, ...looked.get(b.entity.eid) }]
1023
+ }))
1024
+ }
1025
+ await fill(false)
1026
+ // A model turn's context is read where a turn is owed: a transcript running
1027
+ // its calls, settled, stopped or failed is sent nothing, so its reading is
1028
+ // what a tool call's is.
1029
+ if (o.turn && statusOf(await gather()) == 'pending') {
1030
+ let mark = checkpointOf(ordered(held))
1031
+ if (mark) {
1032
+ // A summary naming no line it replaced through, as a provider's log
1033
+ // imports one (./readers.ts), replaces every line before itself
1034
+ // (./compact.ts `context`).
1035
+ let through = comp(mark, 'checkpoint')?.through
1036
+ let at = through == null ? seqOf(mark) : await n.seqAt(String(through)) ??
1037
+ Number(comp(mark, 'checkpoint')?.seq)
1038
+ n.mark = Number.isSafeInteger(at) && at >= 1 ? at : -Infinity
1039
+ n.summary = seqOf(mark)
1040
+ if (through != null && !find(String(through))) {
1041
+ held.push(...await fetch(r, [String(through)]))
1042
+ }
1043
+ }
1044
+ await fill(true)
1045
+ }
1046
+ page.keep()
1047
+ // And what a model selection and `sending` in force are, and what the asks a
1048
+ // step reads sent.
1049
+ if (o.turn || o.call) {
1050
+ held.push(
1051
+ ...await aspect(r, USING, rows),
1052
+ ...await aspect(r, SENDING, rows),
1053
+ )
1054
+ held.push(...await hearing(r, rows, await gather()))
1055
+ held.push(
1056
+ ...await fetch({ ...r, names: [SENDING] }, unsent(await gather())),
1057
+ )
1058
+ }
1059
+ return { entries: await gather(), shapes: r.shapes }
1060
+ }
1061
+
1062
+ // The asks whose own `sending` a step reads (./react.ts) and a page left out:
1063
+ // the newest, the one in flight and each an open call came from.
1064
+ let unsent = (entries: Bundle[]): Eid[] => {
1065
+ let newest = newestAsk(entries)
1066
+ let sources = new Set(openCalls(entries).map((b) => comp(b, CALL)?.source))
1067
+ return entries.filter((b) =>
1068
+ b.ask && !(SENDING in b) &&
1069
+ (b == newest || attemptState(b) == 'inflight' || sources.has(b.entity.eid))
1070
+ ).map((b) => b.entity.eid)
1071
+ }
1072
+
1073
+ // Re-read every membership/kind fact, including legacy rows and mutable fork
1074
+ // ancestors. Only content presence comes from the immutable archetype; no prose.
1075
+ let withContent = async (
1076
+ g: Graph,
1077
+ entries: Bundle[],
1078
+ known: Map<string, string[]>,
1079
+ ): Promise<Bundle[] | undefined> => {
1080
+ let shapes = [...new Set(entries.map((b) => b.entity.archetype))]
1081
+ if (shapes.includes(undefined)) return undefined
1082
+ await learn(g, known, shapes as Eid[])
1083
+ for (let b of entries) {
1084
+ let tables = known.get(b.entity.archetype!)
1085
+ if (!tables) return undefined
1086
+ if (tables.includes(CONTENT)) b.content = {}
1087
+ }
1088
+ return entries
1089
+ }
1090
+
1091
+ /**
1092
+ * The entries of a transcript a status or a model turn reads, in order: the
1093
+ * newest ones down to where they stop mattering, and the older ones they name.
1094
+ */
1095
+ export let reach = async (
1096
+ g: Graph,
1097
+ session: Eid,
1098
+ o: Reach = {},
1099
+ ): Promise<Bundle[]> => {
1100
+ // Without prose, a line is an input by the `content` its archetype holds.
1101
+ // A graph that keeps no archetypes, or a row without one, is read whole.
1102
+ if (!o.bodies && !g.vocab.comp('archetype')) o = { ...o, bodies: true }
1103
+ let { entries, shapes } = await read(g, session, o)
1104
+ if (o.bodies) return entries
1105
+ return await withContent(g, entries, shapes) ??
1106
+ await reach(g, session, { ...o, bodies: true })
1107
+ }