@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.js ADDED
@@ -0,0 +1,923 @@
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
+ import { tablesOf } from "@yaks/archetype/sets";
69
+ import { line, sub } from "@yaks/query";
70
+ import { given } from "./answer.js";
71
+ import { stoppedNotice } from "./claude-control.js";
72
+ import { askingOf, lines } from "./compact.js";
73
+ import { checkpointOf } from "./pruning.js";
74
+ import { ASK, CALL, CONTENT, ENTRY, OUTPUT, RESULT, USING } from "./native.js";
75
+ import { attemptState, kinded, kindOf, marksOf, newestAsk, openCalls, ordered, outranking, RETRIES, sendingBefore, seqOf, statusOf, usingBefore } from "./state.js";
76
+ import { past, transcriptSegments, within } from "./window.js";
77
+ const SENDING = 'sending';
78
+ const PROGRESS = 'tool_progress';
79
+ // What the lines below a decision's are read without.
80
+ const LIFECYCLES = [
81
+ 'attempt',
82
+ 'execution'
83
+ ];
84
+ const FIRST = 64;
85
+ // The most lines appended since a lookup that it asks for by name; past them
86
+ // (an import, a run another process wrote) it reads the transcript whole.
87
+ const SINCE = 256;
88
+ let comp = (b, name)=>b?.[name];
89
+ const KEPT = 1024;
90
+ let memories = new WeakMap();
91
+ // The components each archetype holds, by its eid, as the graph names them.
92
+ // An archetype is named by the components it holds (@yaks/archetype), so what
93
+ // one says never changes, and every reading of a graph shares what any has
94
+ // read.
95
+ let shaped = new WeakMap();
96
+ let shapesOf = (g)=>{
97
+ let held = shaped.get(g);
98
+ if (!held || held.size > KEPT) shaped.set(g, held = new Map());
99
+ return held;
100
+ };
101
+ // Learn the components of each archetype among `keys` that `shapes` lacks, by
102
+ // name: a descriptor names them by identity (@yaks/archetype `tablesOf`).
103
+ let learn = async (g, shapes, keys)=>{
104
+ let missing = keys.filter((key)=>!shapes.has(key));
105
+ if (!missing.length) return;
106
+ for (let b of (await g.get(missing, [
107
+ 'archetype'
108
+ ]))){
109
+ let text = comp(b, 'archetype')?.tables;
110
+ if (typeof text == 'string') {
111
+ shapes.set(b.entity.eid, tablesOf(text, g.vocab));
112
+ }
113
+ }
114
+ };
115
+ let chain = async (g, session, o)=>{
116
+ let names = o.bodies ? o.comps ? [
117
+ ...new Set([
118
+ ...o.comps,
119
+ CONTENT
120
+ ])
121
+ ] : undefined : o.comps ?? g.vocab.all.filter((n)=>n != CONTENT && n != 'session');
122
+ return {
123
+ g,
124
+ segs: await transcriptSegments(g, session),
125
+ names,
126
+ fields: names ? names.reduce((q, n, i)=>i ? line`${sub(q)}&?${n}` : line`?${n}`, line``) : line`*`,
127
+ found: new Map(),
128
+ shapes: shapesOf(g),
129
+ lines: new Map()
130
+ };
131
+ };
132
+ let selected = async (r, ...asks)=>{
133
+ let fields = r.g.vocab.comp('archetype') ? line`&.fields=entity.eid,entity.archetype` : line`&.fields=entity.eid`;
134
+ let owners = [];
135
+ for (let a of asks){
136
+ owners.push(...typeof a == 'string' ? await r.g.rows(line`${sub(a)}${sub(fields)}`) : await r.g.rows(line`${sub(a.q)}${sub(fields)}`, {
137
+ eids: a.eids
138
+ }));
139
+ }
140
+ return await gathered(r, owners);
141
+ };
142
+ // The entities of `owners`, rows naming each one's eid and archetype, holding
143
+ // the components of `r.names` their archetypes hold.
144
+ // A page's lines (`r.valueless`) hold `result` without its value: read by
145
+ // query, or as a reading before found it (`results`), since a result's call
146
+ // and time are kept as it landed.
147
+ let gathered = async (r, owners, results)=>{
148
+ let ids = owners.map((b)=>String(b['entity.eid']));
149
+ if (!ids.length) return [];
150
+ let names = r.names;
151
+ if (names && r.g.vocab.comp('archetype')) {
152
+ let keys = [
153
+ ...new Set(owners.map((b)=>b['entity.archetype']))
154
+ ];
155
+ if (!keys.includes(undefined)) {
156
+ await learn(r.g, r.shapes, keys.map(String));
157
+ if (keys.every((key)=>r.shapes.has(String(key)))) {
158
+ let present = new Set(keys.flatMap((key)=>r.shapes.get(String(key))));
159
+ names = names.filter((n)=>present.has(n));
160
+ }
161
+ }
162
+ }
163
+ let light = r.valueless && names?.includes(RESULT);
164
+ if (light) names = names.filter((n)=>n != RESULT);
165
+ let rows = new Map((await r.g.get(ids, names)).map((b)=>[
166
+ b.entity.eid,
167
+ b
168
+ ]));
169
+ if (light) {
170
+ let asked = [];
171
+ for (let [id, b] of rows){
172
+ let held = results?.get(id);
173
+ if (held) b[RESULT] = {
174
+ ...held
175
+ };
176
+ else if (r.shapes.get(String(b.entity.archetype))?.includes(RESULT) ?? true) asked.push(id);
177
+ }
178
+ for (let b of (await valueless(r.g, asked))){
179
+ let row = rows.get(b.entity.eid);
180
+ if (row) row[RESULT] = b[RESULT];
181
+ }
182
+ }
183
+ return ids.flatMap((id)=>rows.get(id) ?? []);
184
+ };
185
+ // The results among `ids`, each carrying every property of `result` but its
186
+ // value.
187
+ let valueless = async (g, ids)=>!ids.length ? [] : await g.read(line`.${RESULT}&.fields=${[
188
+ 'entity.eid',
189
+ ...g.vocab.props(RESULT).filter((p)=>p != 'value').map((p)=>`${RESULT}.${p}`)
190
+ ]}`, {
191
+ eids: ids
192
+ });
193
+ const WINDOWS = 64;
194
+ let windows = new WeakMap();
195
+ // The lines of `s` from `at` up and below `under`, as the last reading to reach
196
+ // them found them, asked again by name. While that reading's newest line is
197
+ // where it was, the segment holds its lines and those appended since, which a
198
+ // page has read. Each must still be the line it was, of the same shape; if one
199
+ // is not, or a line appended since lies below the pages, it is undefined.
200
+ let recalled = async (r, s, at, under)=>{
201
+ let known = windows.get(r.g)?.get(within(s));
202
+ if (!known || at < known.from) return;
203
+ let edge = known.lines[0];
204
+ let lines = await tail(r, s, edge.seq);
205
+ let last = lines.at(-1);
206
+ if (last?.eid != edge.eid || last.seq != edge.seq) return;
207
+ let range = (l)=>l.seq >= at && l.seq < under;
208
+ if (lines.slice(0, -1).some(range)) return;
209
+ let wanted = known.lines.filter(range);
210
+ let found = await gathered(r, wanted.map((l)=>({
211
+ 'entity.eid': l.eid,
212
+ 'entity.archetype': l.archetype
213
+ })), new Map(wanted.flatMap((l)=>l.result ? [
214
+ [
215
+ l.eid,
216
+ l.result
217
+ ]
218
+ ] : [])));
219
+ let stands = found.length == wanted.length && found.every((b, k)=>b.entity.eid == wanted[k].eid && b.entity.archetype == wanted[k].archetype && comp(b, ENTRY)?.session == s.session && seqOf(b) == wanted[k].seq);
220
+ return stands ? found : undefined;
221
+ };
222
+ // Older rows of the whole chain, `n` at a time, newest first, without what
223
+ // they sent or a result's value.
224
+ let pages = (r)=>{
225
+ let { segs } = r;
226
+ let i = segs.length - 1, after = line``;
227
+ let without = (...gone)=>({
228
+ ...r,
229
+ names: (r.names ?? r.g.vocab.all).filter((n)=>!gone.includes(n)),
230
+ valueless: true
231
+ });
232
+ let page = without(SENDING);
233
+ let below = without(SENDING, ...LIFECYCLES);
234
+ // What each segment was read down to, and its rows, newest first.
235
+ let reached = segs.map(()=>({
236
+ from: Infinity,
237
+ rows: []
238
+ }));
239
+ let took = (k, rows, from)=>{
240
+ reached[k].rows.push(...rows);
241
+ reached[k].from = Math.min(reached[k].from, from);
242
+ };
243
+ let reaching = false;
244
+ return {
245
+ get done () {
246
+ return i < 0;
247
+ },
248
+ next: async (n)=>{
249
+ let got = [];
250
+ while(i >= 0 && got.length < n){
251
+ let want = n - got.length;
252
+ let rows = await selected(page, line`${sub(within(segs[i]))}&.order=-entry.seq&.limit=${want}${sub(after)}`);
253
+ got.push(...rows);
254
+ if (rows.length < want) {
255
+ took(i, rows, -Infinity);
256
+ i--;
257
+ after = line``;
258
+ } else {
259
+ took(i, rows, seqOf(rows.at(-1)));
260
+ after = past(segs[i], rows.at(-1).entity.eid);
261
+ }
262
+ }
263
+ return got;
264
+ },
265
+ // Every row from `at` up that is still unread, a query for each segment
266
+ // it spans: a segment is read whole when the one before it still holds
267
+ // seqs at or above `at`, since the seqs of a segment all pass those before.
268
+ // They lie below every line a decision reads, so without lifecycles, and
269
+ // the lines a reading reached before are asked again by name.
270
+ until: async (at)=>{
271
+ reaching = true;
272
+ let got = [];
273
+ while(i >= 0){
274
+ let s = segs[i], oldest = reached[i].rows.at(-1);
275
+ let rows = await recalled(below, s, at, oldest ? seqOf(oldest) : Infinity) ?? await selected(below, line`${sub(within(s))}&.entry.seq>=${at}&.order=-entry.seq${sub(after)}`);
276
+ got.push(...rows);
277
+ took(i, rows, at);
278
+ if (rows.length) after = line`&.after=${rows.at(-1).entity.eid}`;
279
+ if (i == 0 || segs[i - 1].through < at) break;
280
+ i--;
281
+ after = line``;
282
+ }
283
+ return got;
284
+ },
285
+ // What a reading that reached below its pages read of each segment, for
286
+ // the next to ask again: lines of a seq and a known shape.
287
+ keep: ()=>{
288
+ if (!reaching || !r.g.vocab.comp('archetype')) return;
289
+ let kept = windows.get(r.g) ?? new Map();
290
+ windows.set(r.g, kept);
291
+ reached.forEach(({ from, rows }, k)=>{
292
+ if (from == Infinity) return;
293
+ let key = within(segs[k]);
294
+ kept.delete(key);
295
+ let lines = rows.map((b)=>({
296
+ eid: b.entity.eid,
297
+ seq: Number(comp(b, ENTRY)?.seq),
298
+ archetype: String(b.entity.archetype ?? ''),
299
+ ...b.result && !('value' in b.result) ? {
300
+ result: b.result
301
+ } : {}
302
+ }));
303
+ if (!lines.length || lines.some((l)=>!Number.isSafeInteger(l.seq) || !l.archetype)) return;
304
+ kept.set(key, {
305
+ from,
306
+ lines
307
+ });
308
+ if (kept.size > WINDOWS) kept.delete(kept.keys().next().value);
309
+ });
310
+ }
311
+ };
312
+ };
313
+ // A segment's lines from `seq` up, newest first, as many as SINCE lines
314
+ // appended after it, or its newest line alone: their identities, read once a
315
+ // reading.
316
+ let tail = (r, s, seq)=>{
317
+ let q = seq == null ? line`${sub(within(s))}&.limit=1` : line`${sub(within(s))}&.entry.seq>=${seq}&.limit=${SINCE + 1}`;
318
+ let held = r.lines.get(q);
319
+ if (held) return held;
320
+ let read = (async ()=>(await r.g.rows(line`${sub(q)}&.order=-entry.seq&.fields=entity.eid,entry.seq`)).map((row)=>({
321
+ eid: String(row['entity.eid']),
322
+ seq: Number(row['entry.seq'])
323
+ })))();
324
+ r.lines.set(q, read);
325
+ return read;
326
+ };
327
+ // What a lookup in a segment found before, while the line it was true through
328
+ // is still that line, and the segment's newest line now. `ask` is what the
329
+ // lookup asks again: the lines it found and those appended since.
330
+ let recall = async (r, s, qualifier)=>{
331
+ let known = memories.get(r.g)?.get(within(s) + qualifier);
332
+ let lines = await tail(r, s, known?.seq);
333
+ let at = lines.at(-1);
334
+ if (!known || at?.seq != known.seq || at?.eid != known.eid) {
335
+ return {
336
+ edge: lines[0],
337
+ ask: []
338
+ };
339
+ }
340
+ return {
341
+ known,
342
+ edge: lines[0],
343
+ ask: [
344
+ ...lines.slice(0, -1).map((l)=>l.eid),
345
+ ...known.found
346
+ ]
347
+ };
348
+ };
349
+ // What a lookup found, true through `edge`, the newest line before it looked.
350
+ let keep = (r, s, qualifier, edge, found)=>{
351
+ let kept = memories.get(r.g) ?? new Map();
352
+ memories.set(r.g, kept);
353
+ let key = within(s) + qualifier;
354
+ kept.delete(key);
355
+ if (!edge) return;
356
+ kept.set(key, {
357
+ ...edge,
358
+ found: found.map((b)=>b.entity.eid)
359
+ });
360
+ if (kept.size > KEPT) kept.delete(kept.keys().next().value);
361
+ };
362
+ // The newest entry a qualifier selects, and every one of them.
363
+ let newest = (r, qualifier)=>{
364
+ let seen = r.found.get(qualifier);
365
+ if (seen) return seen;
366
+ let found = (async ()=>{
367
+ for (let s of r.segs.toReversed()){
368
+ let { known, edge, ask } = await recall(r, s, qualifier);
369
+ let q = line`${sub(within(s))}${sub(qualifier)}&.order=-entry.seq&.limit=1`;
370
+ let page = async (eids)=>(await selected(r, eids ? {
371
+ q,
372
+ eids
373
+ } : q))[0];
374
+ let row = !known ? await page() : ask.length ? await page(ask) : undefined;
375
+ // What it found before is gone or no longer one: read it all again.
376
+ if (known?.found.length && !row) row = await page();
377
+ keep(r, s, qualifier, edge, row ? [
378
+ row
379
+ ] : []);
380
+ if (row) return row;
381
+ }
382
+ })();
383
+ r.found.set(qualifier, found);
384
+ return found;
385
+ };
386
+ let every = async (r, qualify)=>(await Promise.all(r.segs.map(async (s)=>{
387
+ let qualifier = qualify(s);
388
+ if (!qualifier) return [];
389
+ let { known, edge, ask } = await recall(r, s, qualifier);
390
+ let q = line`${sub(within(s))}${sub(qualifier)}`;
391
+ let found = !known ? await selected(r, q) : ask.length ? await selected(r, {
392
+ q,
393
+ eids: ask
394
+ }) : [];
395
+ keep(r, s, qualifier, edge, found);
396
+ return found;
397
+ }))).flat();
398
+ // The named entries that are lines of this transcript: an entry another
399
+ // transcript holds, or one a fork left behind, is not among its entries.
400
+ let fetch = async (r, eids)=>{
401
+ let ids = [
402
+ ...new Set(eids)
403
+ ];
404
+ if (!ids.length) return [];
405
+ let found = await r.g.get(ids, r.names && !r.names.includes(ENTRY) ? [
406
+ ENTRY,
407
+ ...r.names
408
+ ] : r.names);
409
+ return found.filter((b)=>{
410
+ let at = comp(b, ENTRY);
411
+ return r.segs.some((s)=>s.session == at?.session && Number(at.seq) <= s.through);
412
+ });
413
+ };
414
+ // The entries `aspectBefore` (./state.ts) reads to say what `name` is in force:
415
+ // the newest to carry it, the newest that is not an ask, and the line the
416
+ // newest ask was sent through. `near` is the newest entries already read.
417
+ let aspect = async (r, name, near = [])=>{
418
+ if (!r.g.vocab.comp(name)) return [];
419
+ let carry = near.filter((b)=>name in b);
420
+ let latest = carry.at(-1) ?? await newest(r, line`&.${name}`);
421
+ if (!latest) return [];
422
+ let chosen = !latest.ask ? undefined : carry.findLast((b)=>!b.ask) ?? await newest(r, line`&.${name}&!${ASK}`);
423
+ let through = comp(latest, ASK)?.through;
424
+ let sent = through == null ? [] : near.filter((b)=>b.entity.eid == through);
425
+ return [
426
+ latest,
427
+ ...chosen ? [
428
+ chosen
429
+ ] : [],
430
+ ...through == null ? [] : sent.length ? sent : await fetch(r, [
431
+ String(through)
432
+ ])
433
+ ];
434
+ };
435
+ // What `statusOf` reads of an entry.
436
+ const STATUS = [
437
+ ENTRY,
438
+ ASK,
439
+ CALL,
440
+ RESULT,
441
+ PROGRESS,
442
+ 'tool_async',
443
+ OUTPUT,
444
+ USING,
445
+ SENDING,
446
+ 'attempt',
447
+ 'execution',
448
+ 'interrupted',
449
+ 'failed',
450
+ 'provisional',
451
+ 'notice',
452
+ 'stop',
453
+ 'exception',
454
+ 'refusal',
455
+ 'lines'
456
+ ];
457
+ /** What a transcript is doing, read off the entries a status looks at. The
458
+ * adapter's derived `session.status` is this rule too, but it computes it over
459
+ * every entry each time it is asked, so the cost of asking grows with the
460
+ * transcript; this reads the newest part. Besides entries, only the marks its
461
+ * row wears ({@link Marks}) bear on it: a stop observed from outside
462
+ * (`session.ended`), and a process of its own still running it. */ export let entryStatus = async (g, session)=>{
463
+ // The session component itself is never read whole: it wears the status.
464
+ let run = [
465
+ 'process',
466
+ 'exit'
467
+ ].filter((name)=>g.vocab.comp(name));
468
+ let [[row], [ran]] = await Promise.all([
469
+ g.rows(line`.entity.eid=${session}&.fields=session.ended`),
470
+ run.length ? g.get([
471
+ session
472
+ ], run) : []
473
+ ]);
474
+ return statusOf(await reach(g, session, {
475
+ comps: STATUS.filter((name)=>g.vocab.comp(name))
476
+ }), {
477
+ ...marksOf(ran),
478
+ ended: row?.['session.ended'] === true
479
+ });
480
+ };
481
+ /** The model selection in force on a transcript, as the whole of it would say. */ export let usingOf = async (g, session)=>usingBefore(await aspect(await chain(g, session, {
482
+ comps: [
483
+ ENTRY,
484
+ USING,
485
+ ASK
486
+ ]
487
+ }), USING));
488
+ /** The newest entry of a transcript, prose and all. */ export let newestOf = async (g, session)=>newest(await chain(g, session, {
489
+ bodies: true
490
+ }), line``);
491
+ /** Whether a transcript holds an ask. */ export let hasAsk = async (g, session)=>!!await newest(await chain(g, session, {
492
+ comps: [
493
+ ENTRY
494
+ ]
495
+ }), line`&.${ASK}`);
496
+ // The oldest entry a qualifier selects: what was said first never moves, so
497
+ // nothing of it is remembered.
498
+ let oldest = async (r, qualifier)=>{
499
+ for (let s of r.segs){
500
+ let [row] = await selected(r, line`${sub(within(s))}${sub(qualifier)}&.order=entry.seq&.limit=1`);
501
+ if (row) return row;
502
+ }
503
+ };
504
+ // A qualifier leaving out entries that carry any of `names` the vocabulary
505
+ // declares: an undeclared one is carried by none.
506
+ let without = (g, ...names)=>names.filter((n)=>g.vocab.comp(n)).reduce((q, n)=>line`${sub(q)}&!${n}`, line``);
507
+ // A request: an entry choosing the model a run goes on with, not an ask and
508
+ // not a line read from a provider's log.
509
+ let request = (g)=>line`&.${USING}${sub(without(g, ASK, 'lines'))}`;
510
+ /** The first request of a transcript, prose and all: what a run was started
511
+ * with. */ export let firstRequest = async (g, session)=>oldest(await chain(g, session, {
512
+ bodies: true
513
+ }), request(g));
514
+ /** The newest request of a transcript: the one a run going on answers. */ export let latestRequest = async (g, session)=>newest(await chain(g, session, {
515
+ comps: [
516
+ ENTRY,
517
+ USING
518
+ ]
519
+ }), request(g));
520
+ /** The first input of a transcript, prose and all: what it was first told. */ export let firstInput = async (g, session)=>oldest(await chain(g, session, {
521
+ bodies: true
522
+ }), line`&.${CONTENT}${sub(without(g, OUTPUT, 'lines', 'notice'))}`);
523
+ /** The newest receipt of a transcript: the stop that says a run ended, naming
524
+ * the request it answered (`ask.through`), or the one answering `through`. */ export let receiptOf = async (g, session, through)=>newest(await chain(g, session, {
525
+ comps: [
526
+ ENTRY,
527
+ ASK,
528
+ 'stop'
529
+ ]
530
+ }), through == null ? line`&.stop${sub(without(g, 'lines'))}&.${ASK}.through` : line`&.stop${sub(without(g, 'lines'))}&.${ASK}.through=${through}`);
531
+ /** What a transcript said last, prose and all: its newest spoken output (not a
532
+ * call, a result, reasoning or an ending), else the newest ending that says
533
+ * why. */ export let saidOf = async (g, session)=>{
534
+ let r = await chain(g, session, {
535
+ bodies: true
536
+ });
537
+ return await newest(r, line`&.${OUTPUT}&.${CONTENT}${sub(without(g, 'reasoning', CALL, RESULT, 'stop'))}`) ?? await newest(r, line`&.stop&.${CONTENT}`);
538
+ };
539
+ // What a reading holds besides its newest rows, found by one lookup for all:
540
+ // its own calls (which no result answers), the prompts for a model turn or a
541
+ // tool call, and the checkpoints for a model turn; and for a model turn the
542
+ // asks the runner owes a retry, by a query of their own, since that mark is
543
+ // set on an ask already written. The mark is named first: a query is driven
544
+ // by the first component it names, and the few marked entities are read where
545
+ // every ask of the graph, or every line of the transcript, would be.
546
+ let named = async (r, o)=>{
547
+ let has = (name)=>r.g.vocab.comp(name);
548
+ let turn = !!o.turn;
549
+ let parts = [
550
+ ...turn && has('checkpoint') ? [
551
+ line`.checkpoint`
552
+ ] : [],
553
+ // What a summary's tasks became since (./task-context.ts `admitted`).
554
+ ...turn && has('task_context') ? [
555
+ line`.task_context`
556
+ ] : [],
557
+ ...(turn || o.call) && has('prompt') ? [
558
+ line`.prompt`
559
+ ] : []
560
+ ];
561
+ let own = r.segs.at(-1);
562
+ let calls = has(CALL) && has(RESULT) ? [
563
+ line`.${CALL} !${RESULT}s`
564
+ ] : [];
565
+ return [
566
+ ...await every(r, (s)=>{
567
+ let terms = s == own ? [
568
+ ...parts,
569
+ ...calls
570
+ ] : parts;
571
+ if (terms.length) {
572
+ return line`&(${sub(terms.reduce((q, p)=>line`${sub(q)}|${sub(p)}`))})`;
573
+ }
574
+ }),
575
+ ...turn && has('provisional') ? await selected(r, ...r.segs.map((s)=>line`${sub(within(s))}&.provisional&.${ASK}`)) : []
576
+ ];
577
+ };
578
+ /** The calls of a transcript no result answers. */ export let openOf = async (g, session)=>(await named(await chain(g, session, {
579
+ comps: [
580
+ ENTRY,
581
+ CALL
582
+ ]
583
+ }), {})).filter((b)=>b.call);
584
+ // An open call's ask says what it had read. Where the page only has words
585
+ // that landed later, look up the newest words as of `ask.through`, so the
586
+ // call still knows whose turn it was (./answer.ts `askedFor`).
587
+ let callWords = async (r, entries, visible, latest, input)=>{
588
+ let byId = new Map(entries.map((b)=>[
589
+ b.entity.eid,
590
+ b
591
+ ]));
592
+ let ids = new Set(openCalls(entries).flatMap((call)=>{
593
+ let source = comp(call, CALL)?.source;
594
+ let through = comp(byId.get(String(source)), ASK)?.through;
595
+ return typeof through == 'string' ? [
596
+ through
597
+ ] : [];
598
+ }));
599
+ let through = await fetch({
600
+ ...r,
601
+ names: [
602
+ ENTRY
603
+ ]
604
+ }, [
605
+ ...ids
606
+ ].filter((eid)=>!byId.has(eid)));
607
+ for (let b of through)byId.set(b.entity.eid, b);
608
+ let ends = [
609
+ ...ids
610
+ ].flatMap((eid)=>byId.get(eid) ?? []);
611
+ let words = await Promise.all(ends.map((end)=>{
612
+ let seq = seqOf(end);
613
+ if (latest && seqOf(latest) <= seq) return latest;
614
+ return visible.findLast((b)=>seqOf(b) <= seq) ?? newest(r, line`${sub(input)}&.entry.seq<=${seq}`);
615
+ }));
616
+ return {
617
+ words: words.filter((b)=>b != null),
618
+ through
619
+ };
620
+ };
621
+ // Steering reads the words that began the turn, the notices leading up to
622
+ // them, and each `heard` line since. Read below the page by seq only where
623
+ // those words or the start of their notices lie there.
624
+ let hearing = async (r, rows, entries)=>{
625
+ let { g } = r;
626
+ if (!g.vocab.comp('heard')) return [];
627
+ let input = line`&.${CONTENT}${sub(without(g, OUTPUT, 'notice', ...kinded()))}`;
628
+ let page = rows.filter(given);
629
+ let latest = page.at(-1) ?? await newest(r, input);
630
+ let { words, through } = await callWords(r, entries, page, latest, input);
631
+ if (latest) words.push(latest);
632
+ let starts = [
633
+ ...new Set(words)
634
+ ].filter((b)=>{
635
+ let start = rows.indexOf(b);
636
+ while(start > 0 && rows[start - 1].notice)start--;
637
+ return start <= 0;
638
+ });
639
+ if (latest && !starts.length) return through;
640
+ let before = await Promise.all(starts.map((b)=>newest(r, line`&.entry.seq<${seqOf(b)}${sub(without(g, 'notice'))}`)));
641
+ let from = before.length ? Math.min(...before.map((b)=>b ? seqOf(b) : -Infinity)) : -Infinity;
642
+ let under = rows.length ? seqOf(rows[0]) : Infinity;
643
+ let heard = await every(r, ()=>line`${sub(Number.isFinite(from) ? line`&.entry.seq>${from}` : line``)}${sub(Number.isFinite(under) ? line`&.entry.seq<${under}` : line``)}&.heard`);
644
+ return [
645
+ ...through,
646
+ ...starts.filter((b)=>seqOf(b) < under),
647
+ ...before.filter((b)=>b != null),
648
+ ...heard
649
+ ];
650
+ };
651
+ let floor = async (n, turn)=>{
652
+ let { rows } = n;
653
+ let all = rows.filter((b)=>!b.notice || stoppedNotice(b));
654
+ let ask = all.findLast((b)=>kindOf(b) == 'ask');
655
+ let turns = all.filter((b)=>b.ask || kindOf(b) == 'input');
656
+ if (!ask && !n.noAsk) return undefined;
657
+ // A completed request ends the retry streak. With no request at all there
658
+ // is no retry history to find among older notices and stops.
659
+ if (ask && turns.length < RETRIES && attemptState(ask) != 'completed') {
660
+ return undefined;
661
+ }
662
+ let seqs = ask ? [
663
+ seqOf(ask)
664
+ ] : [];
665
+ if (turns.length >= RETRIES) seqs.push(seqOf(turns.at(-RETRIES)));
666
+ // The newest input or stop says whether the transcript is stopped. An
667
+ // imported stop is a notice among the lines, found only by reading them.
668
+ let control = all.findLast((b)=>[
669
+ 'input',
670
+ 'stop'
671
+ ].includes(kindOf(b)));
672
+ if (rows.some((b)=>b.lines)) {
673
+ if (!control) return undefined;
674
+ seqs.push(seqOf(control));
675
+ } else if (!control) {
676
+ let stop = await n.stop();
677
+ if (stop != null) seqs.push(stop);
678
+ }
679
+ let sent = async (b)=>{
680
+ let through = comp(b, ASK)?.through;
681
+ let at = through == null ? undefined : await n.seqAt(String(through));
682
+ if (at != null) seqs.push(at);
683
+ };
684
+ if (ask) await sent(ask);
685
+ if (turn) {
686
+ let done = rows.findLast((b)=>b.ask && attemptState(b) == 'completed');
687
+ if (!done && !n.noAsk) return undefined;
688
+ if (done) {
689
+ seqs.push(seqOf(done));
690
+ await sent(done);
691
+ }
692
+ // The provider holds the conversation through an answered ask after the
693
+ // newest summary, which the turn then follows.
694
+ if (done && !(seqOf(done) <= (n.summary ?? -Infinity)) && await n.anchored?.(done)) {
695
+ // `done` and the line it was sent through are read already.
696
+ } else if (n.mark != null) seqs.push(n.mark);
697
+ else {
698
+ let size = Math.floor(Number(await n.window(rows)));
699
+ if (!(size >= 1)) return -Infinity;
700
+ let said = lines(rows, askingOf(rows));
701
+ if (said.length < size) return undefined;
702
+ let from = said.length - size;
703
+ while(from > 0 && kindOf(said[from]) != 'input')from--;
704
+ if (from == 0 && kindOf(said[0]) != 'input') return undefined;
705
+ seqs.push(seqOf(said[from]));
706
+ }
707
+ }
708
+ return Math.min(...seqs);
709
+ };
710
+ let read = async (g, session, o)=>{
711
+ let r = await chain(g, session, o);
712
+ let held = await named(r, o);
713
+ // Archive membership changes without appending a line. Read its metadata
714
+ // afresh, including below checkpoints, without loading the archived prose.
715
+ if (o.turn && g.vocab.comp('archived')) {
716
+ let marks = await selected({
717
+ ...r,
718
+ names: [
719
+ ENTRY,
720
+ 'archived',
721
+ CALL,
722
+ RESULT,
723
+ PROGRESS
724
+ ].filter((n)=>g.vocab.comp(n))
725
+ }, ...r.segs.map((s)=>line`${sub(within(s))}&.archived`));
726
+ for (let b of marks){
727
+ let found = held.find((h)=>h.entity.eid == b.entity.eid);
728
+ if (found) Object.assign(found, b);
729
+ else held.push(b);
730
+ }
731
+ }
732
+ let rows = [];
733
+ let find = (eid)=>rows.find((b)=>b.entity.eid == eid) ?? held.find((b)=>b.entity.eid == eid);
734
+ let stop;
735
+ let n = {
736
+ rows,
737
+ stop: ()=>stop ??= (async ()=>{
738
+ let hit = g.vocab.comp('stop') && await newest({
739
+ ...r,
740
+ fields: line`?entry`
741
+ }, line`&.stop`);
742
+ return hit ? seqOf(hit) : undefined;
743
+ })(),
744
+ seqAt: async (eid)=>{
745
+ let b = find(eid) ?? (await fetch({
746
+ ...r,
747
+ names: [
748
+ ENTRY
749
+ ]
750
+ }, [
751
+ eid
752
+ ]))[0];
753
+ return b?.entry ? seqOf(b) : undefined;
754
+ },
755
+ window: async (rows)=>sendingBefore(await aspect(r, SENDING, rows))?.window,
756
+ anchored: o.anchored
757
+ };
758
+ let page = pages(r), size = FIRST, started = false;
759
+ // Rows, newest first, down to the oldest seq a decision still reads: a
760
+ // status's, or with `turn` a model turn's as well.
761
+ let fill = async (turn)=>{
762
+ while(true){
763
+ if (started) {
764
+ let at = await floor(n, turn);
765
+ if (page.done || at != null && seqOf(rows[0]) <= at) return;
766
+ // What the rows settle is a seq: read down to it at once, not by
767
+ // halves.
768
+ if (at != null && at > -Infinity) {
769
+ let older = await page.until(at);
770
+ if (!o.bodies) older = await withContent(g, older, r.shapes) ?? older;
771
+ rows.unshift(...older.reverse());
772
+ let again = await floor(n, turn);
773
+ if (page.done || again != null && seqOf(rows[0]) <= again) return;
774
+ }
775
+ size *= 2;
776
+ }
777
+ started = true;
778
+ let next = await page.next(size);
779
+ if (!o.bodies) next = await withContent(g, next, r.shapes) ?? next;
780
+ rows.unshift(...next.reverse());
781
+ if (n.noAsk == null && !rows.some((b)=>kindOf(b) == 'ask')) {
782
+ n.noAsk = !await newest({
783
+ ...r,
784
+ names: [
785
+ ENTRY
786
+ ],
787
+ fields: line`?entry`
788
+ }, line`&.${ASK}${sub(without(g, ...outranking('ask')))}`);
789
+ }
790
+ }
791
+ };
792
+ // Older entries the rows name: the call a result answers, the ask a reply
793
+ // or call came from, and what the open calls have reported.
794
+ let reported = new Set();
795
+ let missing = (of)=>{
796
+ let seen = new Set([
797
+ ...rows,
798
+ ...held
799
+ ].map((b)=>b.entity.eid));
800
+ return [
801
+ ...new Set([
802
+ ...rows,
803
+ ...held
804
+ ].flatMap((b)=>{
805
+ let eid = of(b);
806
+ return eid == null || seen.has(String(eid)) ? [] : [
807
+ String(eid)
808
+ ];
809
+ }))
810
+ ];
811
+ };
812
+ let gather = async ()=>{
813
+ let open = held.filter((b)=>b.call && !reported.has(b.entity.eid)).map((b)=>b.entity.eid);
814
+ for (let eid of open)reported.add(eid);
815
+ if (open.length && g.vocab.comp(PROGRESS)) {
816
+ held.push(...await g.read(line`.${PROGRESS}.call=${open}&${sub(r.fields)}`));
817
+ }
818
+ held.push(...await fetch(r, missing((b)=>comp(b, CALL)?.source)), ...await fetch(r, missing((b)=>comp(b, RESULT)?.call ?? comp(b, PROGRESS)?.call)), ...await fetch(r, missing((b)=>comp(b, OUTPUT)?.source)));
819
+ // What the lookups read of a line stands over the rows' reading of it,
820
+ // which may lack its lifecycle and what it sent; each lookup adds what it
821
+ // read, as one may read a line in part that another read whole.
822
+ let looked = new Map();
823
+ for (let b of held){
824
+ looked.set(b.entity.eid, {
825
+ ...looked.get(b.entity.eid),
826
+ ...b
827
+ });
828
+ }
829
+ let seen = new Set();
830
+ return ordered([
831
+ ...rows,
832
+ ...held
833
+ ].flatMap((b)=>{
834
+ if (seen.has(b.entity.eid)) return [];
835
+ seen.add(b.entity.eid);
836
+ return [
837
+ {
838
+ ...b,
839
+ ...looked.get(b.entity.eid)
840
+ }
841
+ ];
842
+ }));
843
+ };
844
+ await fill(false);
845
+ // A model turn's context is read where a turn is owed: a transcript running
846
+ // its calls, settled, stopped or failed is sent nothing, so its reading is
847
+ // what a tool call's is.
848
+ if (o.turn && statusOf(await gather()) == 'pending') {
849
+ let mark = checkpointOf(ordered(held));
850
+ if (mark) {
851
+ // A summary naming no line it replaced through, as a provider's log
852
+ // imports one (./readers.ts), replaces every line before itself
853
+ // (./compact.ts `context`).
854
+ let through = comp(mark, 'checkpoint')?.through;
855
+ let at = through == null ? seqOf(mark) : await n.seqAt(String(through)) ?? Number(comp(mark, 'checkpoint')?.seq);
856
+ n.mark = Number.isSafeInteger(at) && at >= 1 ? at : -Infinity;
857
+ n.summary = seqOf(mark);
858
+ if (through != null && !find(String(through))) {
859
+ held.push(...await fetch(r, [
860
+ String(through)
861
+ ]));
862
+ }
863
+ }
864
+ await fill(true);
865
+ }
866
+ page.keep();
867
+ // And what a model selection and `sending` in force are, and what the asks a
868
+ // step reads sent.
869
+ if (o.turn || o.call) {
870
+ held.push(...await aspect(r, USING, rows), ...await aspect(r, SENDING, rows));
871
+ held.push(...await hearing(r, rows, await gather()));
872
+ held.push(...await fetch({
873
+ ...r,
874
+ names: [
875
+ SENDING
876
+ ]
877
+ }, unsent(await gather())));
878
+ }
879
+ return {
880
+ entries: await gather(),
881
+ shapes: r.shapes
882
+ };
883
+ };
884
+ // The asks whose own `sending` a step reads (./react.ts) and a page left out:
885
+ // the newest, the one in flight and each an open call came from.
886
+ let unsent = (entries)=>{
887
+ let newest = newestAsk(entries);
888
+ let sources = new Set(openCalls(entries).map((b)=>comp(b, CALL)?.source));
889
+ return entries.filter((b)=>b.ask && !(SENDING in b) && (b == newest || attemptState(b) == 'inflight' || sources.has(b.entity.eid))).map((b)=>b.entity.eid);
890
+ };
891
+ // Re-read every membership/kind fact, including legacy rows and mutable fork
892
+ // ancestors. Only content presence comes from the immutable archetype; no prose.
893
+ let withContent = async (g, entries, known)=>{
894
+ let shapes = [
895
+ ...new Set(entries.map((b)=>b.entity.archetype))
896
+ ];
897
+ if (shapes.includes(undefined)) return undefined;
898
+ await learn(g, known, shapes);
899
+ for (let b of entries){
900
+ let tables = known.get(b.entity.archetype);
901
+ if (!tables) return undefined;
902
+ if (tables.includes(CONTENT)) b.content = {};
903
+ }
904
+ return entries;
905
+ };
906
+ /**
907
+ * The entries of a transcript a status or a model turn reads, in order: the
908
+ * newest ones down to where they stop mattering, and the older ones they name.
909
+ */ export let reach = async (g, session, o = {})=>{
910
+ // Without prose, a line is an input by the `content` its archetype holds.
911
+ // A graph that keeps no archetypes, or a row without one, is read whole.
912
+ if (!o.bodies && !g.vocab.comp('archetype')) o = {
913
+ ...o,
914
+ bodies: true
915
+ };
916
+ let { entries, shapes } = await read(g, session, o);
917
+ if (o.bodies) return entries;
918
+ return await withContent(g, entries, shapes) ?? await reach(g, session, {
919
+ ...o,
920
+ bodies: true
921
+ });
922
+ };
923
+ //# sourceMappingURL=reach.js.map