@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/tail.ts ADDED
@@ -0,0 +1,815 @@
1
+ // The importer: a harness's own log, read into a session's transcript. One
2
+ // importer serves every session run outside the graph's own daemon, whatever
3
+ // started it: @yaks/spawn follows a managed run's stdout with it, and the
4
+ // package's duty (./service.ts) follows the transcript file an interactive
5
+ // harness keeps for itself. A reader (./readers.ts) says what each line means;
6
+ // this decides which entities it becomes, and writes them.
7
+ //
8
+ // The log is the durable record, and the graph holds the transcript read out
9
+ // of it. The log is a file (@yaks/file's `file{path, root}`, on the volume that
10
+ // holds it), and each entry wears the line it came from, `lines{file, start}`.
11
+ // The file carries `transcript{session, consumed, version, finished}`: how many
12
+ // of its lines have been read, written in the transaction that writes each
13
+ // line's entries, and on its own once lines that make none are read past. A
14
+ // resume begins there, whatever has become of the entries since: a line that
15
+ // made none, or one whose entries a strip deleted, is never read again.
16
+ //
17
+ // Codex compresses a finished rollout from `X.jsonl` to `X.jsonl.zst`. That is
18
+ // another file holding the same lines, so its reading moves with it: the
19
+ // transcript, and the session's `session.transcript` where it named the old
20
+ // file.
21
+ //
22
+ // Each entry's eid is derived from its session, its line and its place in the
23
+ // line, and a call's from the harness's own id for it, which is what its result
24
+ // names. Reading a line twice writes the same entities twice, which changes
25
+ // nothing, and a result finds its call without a lookup. A harness can write
26
+ // one session's id into two files (two processes under one id), and their
27
+ // lines would collide: the session's first file (`session.transcript`) names
28
+ // its entries by session and line alone, and an entry of any other file names
29
+ // that file's path too.
30
+ //
31
+ // A call arrives already running, held by the session itself
32
+ // (`execution{state, by}`): the harness ran it in its own process, and a tool
33
+ // runner (@yaks/tools) leaves a call somebody else holds alone. Its result
34
+ // says whether it went through.
35
+ //
36
+ // This module reads files; it is reached through `@yaks/session/tail`, never
37
+ // the main module, which a browser loads.
38
+
39
+ import { line as query } from '@yaks/query'
40
+ import { after, batches, records } from './log.js'
41
+
42
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
43
+ import { derivedEid, identityEid } from '@yaks/graph/identity'
44
+ import { onDisk } from '@yaks/file/local'
45
+ import { status } from '@yaks/graph/errors'
46
+ import { TOMBSTONE } from '@yaks/graph/bundle'
47
+ import { who } from '@yaks/graph/call'
48
+ import { metering } from '@yaks/model'
49
+ import type { Reader, Said } from './readers.ts'
50
+ import { humanCaller } from './who.js'
51
+ import type { Chunks } from './archive.ts'
52
+ import { fix, step, type Walk, walker } from './parts.js'
53
+ import {
54
+ imported,
55
+ merge,
56
+ type Open,
57
+ pieced,
58
+ retained,
59
+ typed,
60
+ } from './imported.js'
61
+
62
+ export { askOf, callOf, imported, pieced, prose } from './imported.js'
63
+
64
+ /** A log being read, and the session it is read into. */
65
+ export type Tail = {
66
+ /** the file */
67
+ path: string
68
+ /** an immutable source read in bounded asynchronous chunks */
69
+ stream?: Chunks
70
+ version?: string
71
+ skip?: number
72
+ /** the session; a transcript file can name one the graph has not met yet,
73
+ * and it is created with the first line that says something, or once the
74
+ * lines read say nothing */
75
+ session?: Eid
76
+ /** the harness's own id for the session, which a created one carries */
77
+ id?: string
78
+ /** the file, as the bundle that makes it one; its entity keeps how far it
79
+ * has been read */
80
+ file: Bundle
81
+ /** whether this is the file the session was first read from, whose entries
82
+ * are named by session and line alone */
83
+ own: boolean
84
+ /** whether the file's transcript is written yet: its first write says whose
85
+ * transcript it is */
86
+ known: boolean
87
+ /** whether a person drives it; false preserves an automatic opening */
88
+ operator?: boolean
89
+ /** the operator mark already stored on the session */
90
+ operatorStored?: boolean
91
+ /** the lines read so far */
92
+ line: number
93
+ /** the line the file's `consumed` stands at */
94
+ marked: number
95
+ /** the byte the next read starts at */
96
+ at: number
97
+ /** when the newest line that says so was written */
98
+ time?: string
99
+ /** the model the newest line that says so named as answering */
100
+ model?: string
101
+ rest: string
102
+ dec: TextDecoder
103
+ /** what the requests read so far carried (./parts.ts), followed from the
104
+ * log's first line */
105
+ walk?: Walk
106
+ /** a resumed walk, followed in slices before any new entries are read */
107
+ replay?: { line: number; lines: AsyncGenerator<string>; part?: Open }
108
+ /** the run of parts read so far and not yet ended (./readers.ts
109
+ * `Said.part`), which no `consumed` passes */
110
+ part?: Open
111
+ }
112
+
113
+ /** How a line is read in. */
114
+ export type Pull = {
115
+ /** who a prompt typed into this transcript is signed by */
116
+ person?: Eid
117
+ /** whether the line is of the session's first file; an entry of any other
118
+ * file names its path in its eid too (default true) */
119
+ own?: boolean
120
+ /** keep only the prose: what was typed and what the model said */
121
+ prose?: boolean
122
+ /** flush a last line the harness never ended with a newline */
123
+ final?: boolean
124
+ /** where a line the graph refuses is reported (default the console) */
125
+ report?: (err: unknown) => void
126
+ /** stop between lines once this aborts: what is left stays with the tail,
127
+ * for the next pull, and the session's `consumed` says where the read
128
+ * stood */
129
+ signal?: AbortSignal
130
+ /** stop between lines past this moment (`performance.now()`), the way an
131
+ * abort stops it, once a line is read: a long log is read over several
132
+ * pulls */
133
+ until?: number
134
+ }
135
+
136
+ /** Whether a tail is behind its file: a pull stopped before its end, and
137
+ * holds lines it has not read into the graph yet. */
138
+ export let behind = (t: Tail): boolean => t.rest.includes('\n')
139
+
140
+ let comp = (b: Bundle | undefined, name: string) =>
141
+ b?.[name] as Comp | undefined
142
+
143
+ // One line's rows, and when the harness wrote it.
144
+ type Line = { bundles: Bundle[]; at?: string }
145
+
146
+ // What a line says, its plan-limit readings timed and placed: a line that
147
+ // reports limits and says no time of its own (Claude's `rate_limit_event`)
148
+ // was written after the newest line that said one, and a limit on one model
149
+ // is on the model the log last said answers it. `last` keeps both.
150
+ let timed = (said: Said, last: { time?: string; model?: string }): Said => {
151
+ last.time = said.at ?? last.time
152
+ last.model = said.model ?? last.model
153
+ if (!said.limits) return said
154
+ let model = last.model && identityEid('model', [last.model])
155
+ return {
156
+ ...said,
157
+ ...!said.at && last.time ? { at: last.time } : {},
158
+ limits: metering(said.limits, model),
159
+ }
160
+ }
161
+
162
+ // How many lines one transaction writes at most, and how much text: a line
163
+ // to a transaction rewrites the same index pages once per line, which is
164
+ // most of what reading a long log in costs.
165
+ let RUN = 500
166
+ let RUN_TEXT = 4 * 1024 * 1024
167
+
168
+ // Each line of a run, without the rows it only touches where the graph or a
169
+ // line before it in the run has settled them: a tool's row is written where it
170
+ // is missing, since writing it again moves its stamp for nothing, and so is a
171
+ // request, which every line of its reply names again; an answer's state only
172
+ // where its call is there, or the patch alone would make an entity; a
173
+ // plan-limit reading only over an older one. A line `worth` refuses is left
174
+ // out of what the lines after it see. Answers the eids the graph held too.
175
+ let settled = async (
176
+ g: Graph,
177
+ run: Line[],
178
+ worth: (bundles: Bundle[], i: number) => boolean = () => true,
179
+ ): Promise<{ lines: Bundle[][]; held: Set<Eid> }> => {
180
+ let eids = new Set(run.flatMap((l) => l.bundles.map((b) => b.entity.eid)))
181
+ let read = new Map<Eid, string>()
182
+ let held = new Set<Eid>()
183
+ for (let r of eids.size ? await g.get([...eids], ['rate_limit']) : []) {
184
+ if (!r || r[TOMBSTONE] != null) continue
185
+ held.add(r.entity.eid)
186
+ read.set(r.entity.eid, String(comp(r, 'rate_limit')?.at ?? ''))
187
+ }
188
+ let there = new Set(held)
189
+ let lines = run.map(({ bundles }, i) => {
190
+ let kept = bundles.filter((b) => {
191
+ let eid = b.entity.eid
192
+ if (b.rate_limit) {
193
+ return String(comp(b, 'rate_limit')?.at ?? '') >= (read.get(eid) ?? '')
194
+ }
195
+ if (b.entry ? b.ask : b.tool || b.provider || b.model) {
196
+ return !there.has(eid)
197
+ }
198
+ return b.entry || !b.execution || there.has(eid)
199
+ })
200
+ if (!worth(kept, i)) return []
201
+ for (let b of kept) {
202
+ there.add(b.entity.eid)
203
+ if (b.rate_limit) {
204
+ read.set(b.entity.eid, String(comp(b, 'rate_limit')?.at ?? ''))
205
+ }
206
+ }
207
+ return kept
208
+ })
209
+ return { lines, held }
210
+ }
211
+
212
+ // A run's lines as one batch, each entity dated as a transaction per line
213
+ // would date it (@yaks/graph `$at`): one the graph held, when the last line
214
+ // that writes it was written; a new one, when the first was.
215
+ let joined = (run: Line[], held: Set<Eid>): Bundle[] => {
216
+ let at = new Map<Eid, string>()
217
+ for (let { bundles, at: when } of run) {
218
+ if (!when) continue
219
+ for (let { entity: { eid } } of bundles) {
220
+ if (held.has(eid) || !at.has(eid)) at.set(eid, when)
221
+ }
222
+ }
223
+ return fold([], run.flatMap((l) => l.bundles)).map((b) =>
224
+ at.has(b.entity.eid) ? { ...b, $at: at.get(b.entity.eid) } : b
225
+ )
226
+ }
227
+
228
+ let live = (b: Bundle | undefined) => b && b[TOMBSTONE] == null ? b : undefined
229
+
230
+ /** How far the file at `path` has been read, and into which session: its
231
+ * `transcript`, if it has one. */
232
+ export let transcriptOf = async (
233
+ g: Graph,
234
+ path: string,
235
+ ): Promise<Comp | undefined> => {
236
+ let [file] = await onDisk(g, path)
237
+ let [row] = await g.get([file.entity.eid], ['transcript'])
238
+ return comp(live(row), 'transcript')
239
+ }
240
+
241
+ // Whether a file is its session's first: the one the session names, or any
242
+ // file of a session that names none yet.
243
+ let owns = async (g: Graph, session: Eid | undefined, file: Eid) => {
244
+ if (!session) return true
245
+ // Ownership needs one stored reference, not the derived transcript status.
246
+ let [s] = await g.read(
247
+ query`.entity.eid=${session} .fields=session.transcript`,
248
+ )
249
+ let first = comp(s, 'session')?.transcript
250
+ return !first || first == file
251
+ }
252
+
253
+ // Codex compresses a finished rollout from `X.jsonl` to `X.jsonl.zst`: another
254
+ // file, holding the same lines. A compressed file not read yet takes over the
255
+ // reading of the one it was compressed from, and the session's first file
256
+ // moves with it.
257
+ let compressed = async (
258
+ g: Graph,
259
+ file: Bundle,
260
+ path: string,
261
+ ): Promise<Comp | undefined> => {
262
+ if (!path.endsWith('.zst')) return undefined
263
+ let [was] = await onDisk(g, path.slice(0, -'.zst'.length))
264
+ let from = was.entity.eid
265
+ let [row] = await g.get([from], ['transcript'])
266
+ let held = comp(live(row), 'transcript')
267
+ if (!held) return undefined
268
+ let session = held.session as Eid | undefined
269
+ let [s] = session
270
+ ? await g.read(
271
+ query`.entity.eid=${session} .fields=session.transcript`,
272
+ )
273
+ : []
274
+ // Compressing a log is no edit to its session, so `updated` stays. The session
275
+ // moves first: stopped between the two, the next read moves the file.
276
+ if (comp(s, 'session')?.transcript == from) {
277
+ await g.apply([{
278
+ entity: { eid: session! },
279
+ session: { transcript: file.entity.eid },
280
+ }], { trusted: true, stamp: false })
281
+ }
282
+ await g.apply([
283
+ { ...file, transcript: held },
284
+ { entity: { eid: from }, transcript: null },
285
+ ], { trusted: true })
286
+ return held
287
+ }
288
+
289
+ /**
290
+ * A tail on `path`, placed after the lines its transcript says were read.
291
+ *
292
+ * ```ts
293
+ * import { tail } from '@yaks/session/tail'
294
+ *
295
+ * // let t = await tail(graph, '/logs/run.out', { session })
296
+ * ```
297
+ */
298
+ export let tail = async (
299
+ g: Graph,
300
+ path: string,
301
+ o: {
302
+ session?: Eid
303
+ id?: string
304
+ stream?: Chunks
305
+ prefix?: string
306
+ version?: string
307
+ } = {},
308
+ ): Promise<Tail> => {
309
+ let [file] = await onDisk(g, path)
310
+ let [row] = await g.get([file.entity.eid], ['transcript'])
311
+ let held = comp(live(row), 'transcript') ??
312
+ await compressed(g, file, path)
313
+ let previous = held?.version ?? held?.finished
314
+ let changed = o.version && previous && previous != o.version
315
+ let line = changed ? 0 : Number(held?.consumed ?? 0)
316
+ if (changed) {
317
+ await g.apply([{
318
+ entity: { eid: file.entity.eid },
319
+ transcript: { consumed: 0, finished: null, version: o.version },
320
+ }], { trusted: true })
321
+ }
322
+ let fields = [
323
+ 'session.operator',
324
+ 'session.source',
325
+ 'spawned.parent',
326
+ 'created.by',
327
+ 'created.via',
328
+ ]
329
+ .filter((name) => {
330
+ let [c, p] = name.split('.')
331
+ return g.vocab.props(c).includes(p)
332
+ })
333
+ let [session] = o.session
334
+ ? await g.read(
335
+ fields.length
336
+ ? query`.entity.eid=${o.session} .fields=${fields}`
337
+ : query`.entity.eid=${o.session} .fields=`,
338
+ )
339
+ : []
340
+ let operatorStored = comp(session, 'session')?.operator as
341
+ | boolean
342
+ | undefined
343
+ let automatic = session && (
344
+ comp(session, 'session')?.source || comp(session, 'spawned')?.parent ||
345
+ !await humanCaller(g, who(session), session.entity.eid)
346
+ )
347
+ return {
348
+ path,
349
+ ...o,
350
+ operator: automatic ? false : operatorStored,
351
+ operatorStored,
352
+ file,
353
+ own: await owns(g, o.session, file.entity.eid),
354
+ known: !!held,
355
+ line,
356
+ marked: line,
357
+ at: o.stream ? 0 : await after(path, line),
358
+ ...(o.stream ? { skip: line } : {}),
359
+ rest: o.prefix ?? '',
360
+ dec: new TextDecoder(),
361
+ }
362
+ }
363
+
364
+ let parsed = (text: string): Record<string, unknown> | undefined => {
365
+ try {
366
+ let e = JSON.parse(text)
367
+ return e && typeof e == 'object' ? e : undefined
368
+ } catch {
369
+ return undefined // not JSON: diagnostics, not transcript
370
+ }
371
+ }
372
+
373
+ // What reading to `line` writes beside the line's own entities: how far the
374
+ // file is read, and, the first time, the file itself and whose transcript it
375
+ // holds; the session learns its first file, and that a person typed into it.
376
+ let marks = (t: Tail, line: number, typed = false): Bundle[] => {
377
+ let operator = typed && t.operator == null ? true : t.operator
378
+ return [
379
+ {
380
+ ...(t.known ? { entity: t.file.entity } : t.file),
381
+ transcript: {
382
+ consumed: line,
383
+ ...(t.version ? { version: t.version } : {}),
384
+ ...(t.known ? {} : { session: t.session }),
385
+ },
386
+ },
387
+ ...(t.own && !t.known || operator != t.operatorStored
388
+ ? [{
389
+ entity: { eid: t.session! },
390
+ session: {
391
+ ...(t.own && !t.known ? { transcript: t.file.entity.eid } : {}),
392
+ ...(operator != t.operatorStored ? { operator } : {}),
393
+ },
394
+ }]
395
+ : []),
396
+ ]
397
+ }
398
+
399
+ // Bundles for entities a list already names folded into those.
400
+ let fold = (list: Bundle[], more: Bundle[]): Bundle[] => {
401
+ let out = new Map(list.map((b) => [b.entity.eid, b]))
402
+ for (let b of more) {
403
+ let was = out.get(b.entity.eid)
404
+ out.set(b.entity.eid, was ? merge(was, b) : b)
405
+ }
406
+ return [...out.values()]
407
+ }
408
+
409
+ // A file's first write learns again whether it is its session's first:
410
+ // another file of the session may have been written first since the tail was
411
+ // opened.
412
+ let settle = async (g: Graph, t: Tail) => {
413
+ if (!t.known) t.own = await owns(g, t.session, t.file.entity.eid)
414
+ }
415
+
416
+ // The session a file names, created now that it has said something, as the
417
+ // entity the harness's id for it names (./who.ts `sessionEid`).
418
+ let created = async (g: Graph, t: Tail): Promise<Eid> => {
419
+ let made = await g.apply([{
420
+ entity: { eid: '$session' },
421
+ session: { id: t.id },
422
+ }])
423
+ return made.find((b) => b.session)!.entity.eid
424
+ }
425
+
426
+ // What a line's entries owe the requests they carry (./parts.ts).
427
+ let walked = (w: Walk, made: Bundle[]): Bundle[] =>
428
+ made.filter((b) => b.entry || b.tool).flatMap((b) => step(w, b))
429
+
430
+ // The walk a tail keeps, begun before it reads a line: a log read from its
431
+ // start begins one empty, and one taken up partway first follows the lines
432
+ // already read, writing nothing, so its next request knows what came before.
433
+ let follow = async (t: Tail, read: Reader, o: Pull): Promise<boolean> => {
434
+ if (!t.walk) {
435
+ t.walk = walker()
436
+ if (t.line && !t.stream && t.session) {
437
+ t.replay = { line: 0, lines: records(t.path) }
438
+ }
439
+ }
440
+ let replay = t.replay
441
+ if (!replay) return true
442
+ let breath = performance.now(), from = replay.line
443
+ while (replay.line < t.line) {
444
+ if (
445
+ o.signal?.aborted ||
446
+ replay.line > from && performance.now() > (o.until ?? Infinity)
447
+ ) return false
448
+ if (performance.now() - breath > 50) {
449
+ await new Promise((go) => setTimeout(go, 0))
450
+ breath = performance.now()
451
+ }
452
+ let raw = await replay.lines.next()
453
+ if (raw.done) break
454
+ let line = ++replay.line
455
+ let event = parsed(raw.value)
456
+ if (!event) continue
457
+ let said = read(event)
458
+ for (let f of said.fixed ?? []) fix(t.walk, f)
459
+ for (let [one, at] of pieced(replay, said, line)) {
460
+ walked(
461
+ t.walk,
462
+ imported(one, {
463
+ ...o,
464
+ session: t.session!,
465
+ file: t.file.entity.eid,
466
+ path: t.path,
467
+ line: at,
468
+ own: t.own,
469
+ }),
470
+ )
471
+ }
472
+ }
473
+ await replay.lines.return(undefined)
474
+ t.replay = undefined
475
+ return true
476
+ }
477
+
478
+ /**
479
+ * Read what the log holds past the tail into its session, a run of lines to a
480
+ * transaction, each entity dated when the harness wrote the line that wrote it
481
+ * where the line says. A line the reader does not recognize, or one that is not
482
+ * JSON at all, becomes nothing: the file keeps it. Answers how many lines were
483
+ * read.
484
+ *
485
+ * ```ts
486
+ * import { claude } from '@yaks/session'
487
+ * import { pull, tail } from '@yaks/session/tail'
488
+ *
489
+ * // let t = await tail(graph, path, { id })
490
+ * // await pull(graph, t, claude, { person })
491
+ * ```
492
+ */
493
+ export let pull = async (
494
+ g: Graph,
495
+ t: Tail,
496
+ read: Reader,
497
+ o: Pull = {},
498
+ ): Promise<number> => {
499
+ let from = t.line
500
+ let breath = performance.now()
501
+ let run: (Line & { line: number; person: boolean })[] = []
502
+ let text = 0
503
+ // What a run of lines writes, in one transaction. Trusted: `transcript` is
504
+ // server-owned, and this is the server reading a file on its own machine. A
505
+ // run the graph refuses is written again a line at a time, so only the line
506
+ // it refuses is left out: reported, and left in the file, since it would be
507
+ // refused again. Any other failure ends the read, past lines this tail has
508
+ // already taken, so the caller opens a new tail where the transcript stands.
509
+ let write = async (lines: typeof run) => {
510
+ let { lines: kept, held } = await settled(g, lines)
511
+ let last = lines.at(-1)!
512
+ let person = lines.some((l) => l.person)
513
+ await g.apply(
514
+ fold(
515
+ joined(lines.map((l, i) => ({ ...l, bundles: kept[i] })), held),
516
+ marks(t, last.line, person),
517
+ ),
518
+ { trusted: true },
519
+ )
520
+ t.marked = last.line
521
+ t.known = true
522
+ if (person && t.operator == null) t.operator = true
523
+ t.operatorStored = t.operator
524
+ }
525
+ // A run written, or, when the graph refuses it, each of its lines alone.
526
+ let land = async (lines: typeof run): Promise<void> => {
527
+ try {
528
+ await write(lines)
529
+ } catch (e) {
530
+ if (status(e) >= 500) throw e
531
+ if (lines.length == 1) return void (o.report ?? console.error)(e)
532
+ for (let l of lines) await land([l])
533
+ }
534
+ }
535
+ let flush = async () => {
536
+ let lines = run
537
+ run = []
538
+ text = 0
539
+ if (lines.length) await land(lines)
540
+ }
541
+ // What a line says, its entries sitting at line `at`, into the run that
542
+ // reading `line` writes: a run of parts is placed at its first line, and
543
+ // read once the line that ends it is.
544
+ let take = async (said: Said, at: number, line: number) => {
545
+ let kept = o.prose ? said.entries.filter(retained) : said.entries
546
+ if (!kept.length && !said.about && !said.limits?.length) return
547
+ t.session ??= await created(g, t)
548
+ // A run is one write, so one reading of `own` holds for all its lines.
549
+ if (!run.length) await settle(g, t)
550
+ let made = imported(said, {
551
+ ...o,
552
+ session: t.session,
553
+ file: t.file.entity.eid,
554
+ path: t.path,
555
+ line: at,
556
+ own: t.own,
557
+ })
558
+ let signed = made.some((b) => b.$actor)
559
+ // A line a person signed is a transaction of its own: in a batch, an
560
+ // entity nobody signs is written by the first writer the batch names
561
+ // (@yaks/graph `writers`), and nothing else in the run is theirs.
562
+ if (signed) await flush()
563
+ run.push({
564
+ bundles: fold(made, t.walk ? walked(t.walk, made) : []),
565
+ at: said.at,
566
+ line,
567
+ person: kept.some(typed),
568
+ })
569
+ if (signed || run.length >= RUN || text >= RUN_TEXT) await flush()
570
+ }
571
+ reading: for await (let all of batches(t, o.final)) {
572
+ if (!o.prose && !await follow(t, read, o)) {
573
+ t.rest = [...all, t.rest].join('\n')
574
+ break
575
+ }
576
+ for (let [i, raw] of all.entries()) {
577
+ if (
578
+ o.signal?.aborted ||
579
+ t.line > from && performance.now() > (o.until ?? Infinity)
580
+ ) {
581
+ t.rest = [...all.slice(i), t.rest].join('\n')
582
+ break reading
583
+ }
584
+ // A long read hands the event loop back every so often: the lease its duty
585
+ // holds and every other duty in the process renew and fire on timers.
586
+ if (performance.now() - breath > 50) {
587
+ await new Promise((go) => setTimeout(go, 0))
588
+ breath = performance.now()
589
+ }
590
+ let line = ++t.line
591
+ let event = parsed(raw)
592
+ if (!event) continue
593
+ let said = timed(read(event), t)
594
+ if (t.walk) { for (let f of said.fixed ?? []) fix(t.walk, f) }
595
+ for (let [one, at] of pieced(t, said, line)) await take(one, at, line)
596
+ text += raw.length
597
+ }
598
+ }
599
+ // A run of parts the log ends on is all it will say.
600
+ if (t.part && (o.final || o.prose || t.stream?.done)) {
601
+ let open = t.part
602
+ t.part = undefined
603
+ await take({ entries: [open.entry] }, open.line, t.line)
604
+ }
605
+ await flush()
606
+ // Lines past the last that made an entry, or refused ones, are marked read
607
+ // where the file is done or not yet known; a file still being written has
608
+ // its next entry carry the mark, or `rest` write it once the file is quiet.
609
+ if (o.final || o.prose || t.stream?.done || !t.known) await rest(g, t)
610
+ if (t.stream?.done && !behind(t) && !t.skip && t.version) {
611
+ await g.apply([{
612
+ entity: t.file.entity,
613
+ transcript: { finished: t.version },
614
+ }], { trusted: true })
615
+ }
616
+ return t.line - from
617
+ }
618
+
619
+ /**
620
+ * Mark a tail's file read to the line the tail stands at, so a resume starts
621
+ * after it and a quiet file reads as imported to its end: what lines that made
622
+ * no entry leave unwritten while the file is still being written (`pull`).
623
+ *
624
+ * ```ts
625
+ * import { rest } from '@yaks/session/tail'
626
+ *
627
+ * // await rest(graph, t) // once its file has gone quiet
628
+ * ```
629
+ */
630
+ export let rest = async (g: Graph, t: Tail): Promise<void> => {
631
+ // A run of parts not yet ended is read again from its first line.
632
+ let read = t.part ? t.part.line - 1 : t.line
633
+ if (read <= t.marked) return
634
+ t.session ??= await created(g, t)
635
+ await settle(g, t)
636
+ await g.apply(marks(t, read), { trusted: true })
637
+ t.known = true
638
+ t.marked = read
639
+ }
640
+
641
+ // What an earlier reading of a line put on an entry that a request now
642
+ // carries on its own entry: a run's whole usage on its ending, Codex's usage
643
+ // on an entry of its own. The usage comes off, with the cost, request and
644
+ // context beside it, and an entry left with nothing of its own goes. `rows`
645
+ // holds what the graph holds at the line's entries (`placesOf`).
646
+ let unspent = (
647
+ rows: Map<Eid, Bundle>,
648
+ key: string,
649
+ line: number,
650
+ said: Said,
651
+ made: Bundle[],
652
+ ): Bundle[] => {
653
+ let now = new Map(made.map((b) => [b.entity.eid, b]))
654
+ let plumbing = [
655
+ 'entry',
656
+ 'lines',
657
+ 'usage',
658
+ 'cost',
659
+ 'ask',
660
+ 'context_parts',
661
+ 'created',
662
+ 'updated',
663
+ ]
664
+ return placesOf(key, line, said).flatMap((eid): Bundle[] => {
665
+ let r = rows.get(eid)
666
+ if (!r || r[TOMBSTONE] != null || !r.usage) return []
667
+ if (now.get(eid)?.usage) return []
668
+ let own = Object.keys(r).some((k) =>
669
+ k != 'entity' && !k.startsWith('$') && !plumbing.includes(k)
670
+ )
671
+ return [
672
+ own
673
+ ? {
674
+ entity: { eid },
675
+ usage: null,
676
+ cost: null,
677
+ ask: null,
678
+ context_parts: null,
679
+ }
680
+ : { entity: { eid }, $delete: true },
681
+ ]
682
+ })
683
+ }
684
+
685
+ // The entries a line's place in the file names.
686
+ let placesOf = (key: string, line: number, said: Said): Eid[] =>
687
+ said.entries.map((_, i) => derivedEid(`${key} ${line} ${i}`))
688
+
689
+ /**
690
+ * Read a log already imported again from its start, for its model requests
691
+ * alone: each request's entry (`ask`, `usage`, `context_parts`) where the
692
+ * session lacks it, the session's `fixed`, and plan limits, each dated when
693
+ * the line was written. What an earlier reading counted elsewhere (on the
694
+ * line's other entries, or as the whole run's usage on its ending) comes off,
695
+ * so each request is counted once. The log can be a copy of the session's
696
+ * own, such as the transcript a provider keeps of a managed run. The
697
+ * transcript's other entries are followed, never written. A run of lines is
698
+ * read and written at once. Answers how many requests it wrote.
699
+ *
700
+ * ```ts
701
+ * import { claude } from '@yaks/session'
702
+ * import { recount } from '@yaks/session/tail'
703
+ *
704
+ * // await recount(graph, path, claude, { session })
705
+ * ```
706
+ */
707
+ export let recount = async (
708
+ g: Graph,
709
+ path: string,
710
+ read: Reader,
711
+ o: { session: Eid; signal?: AbortSignal },
712
+ ): Promise<number> => {
713
+ let [file] = await onDisk(g, path)
714
+ let own = await owns(g, o.session, file.entity.eid)
715
+ let key = own ? o.session : `${o.session} ${path}`
716
+ let w = walker()
717
+ let line = 0, wrote = 0, placed = false
718
+ let last: { time?: string; model?: string } = {}
719
+ let run: (Line & { line: number; said: Said; made: Bundle[] })[] = []
720
+ let size = 0
721
+ let flush = async () => {
722
+ let lines = run
723
+ run = []
724
+ size = 0
725
+ if (!lines.length) return
726
+ let places = lines.flatMap((l) => placesOf(key, l.line, l.said))
727
+ // Which places hold usage is read alone; a whole entry, with all it
728
+ // says, only where the usage is one this reading does not make.
729
+ let rows = new Map<Eid, Bundle>()
730
+ for (let r of places.length ? await g.get(places, ['usage']) : []) {
731
+ if (r) rows.set(r.entity.eid, r)
732
+ }
733
+ let made = new Set(
734
+ lines.flatMap((l) => l.made.filter((b) => b.usage)).map((b) =>
735
+ b.entity.eid
736
+ ),
737
+ )
738
+ let stale = [...rows.values()].filter((r) =>
739
+ r.usage && !made.has(r.entity.eid)
740
+ ).map((r) => r.entity.eid)
741
+ for (let r of stale.length ? await g.get(stale) : []) {
742
+ if (r) rows.set(r.entity.eid, r)
743
+ }
744
+ let gone = lines.map((l) => unspent(rows, key, l.line, l.said, l.made))
745
+ let { lines: kept, held } = await settled(
746
+ g,
747
+ lines,
748
+ // A line with nothing of its own to write is not written.
749
+ (bundles, i) =>
750
+ !!gone[i].length ||
751
+ bundles.some((b) => b.entry || b.rate_limit || b.fixed),
752
+ )
753
+ let all = joined(
754
+ lines.map((l, i) => ({ ...l, bundles: [...kept[i], ...gone[i]] })),
755
+ new Set([...held, ...rows.keys()]),
756
+ )
757
+ if (!all.length) return
758
+ // The entries it writes sit at lines of the file: the first write makes
759
+ // the file an entity too.
760
+ await g.apply([...placed ? [] : [file], ...all], { trusted: true })
761
+ placed = true
762
+ wrote += kept.flat().filter((b) => b.entry).length
763
+ }
764
+ let breath = performance.now()
765
+ for await (let raw of records(path)) {
766
+ if (o.signal?.aborted) break
767
+ if (performance.now() - breath > 50) {
768
+ await new Promise((go) => setTimeout(go, 0))
769
+ breath = performance.now()
770
+ }
771
+ line++
772
+ let event = parsed(raw)
773
+ if (!event) continue
774
+ let said = timed(read(event), last)
775
+ for (let f of said.fixed ?? []) fix(w, f)
776
+ let made = imported(said, {
777
+ session: o.session,
778
+ file: file.entity.eid,
779
+ path,
780
+ line,
781
+ own,
782
+ })
783
+ let owed = walked(w, made)
784
+ let asked = made.filter((b) =>
785
+ b.entry ? b.ask && b.usage : b.provider || b.model || b.rate_limit
786
+ )
787
+ run.push({ bundles: fold(asked, owed), at: said.at, line, said, made })
788
+ size += raw.length
789
+ if (run.length >= RUN || size >= RUN_TEXT) await flush()
790
+ }
791
+ await flush()
792
+ let over = await ended(g, o.session)
793
+ if (over.length) await g.apply(over, { trusted: true })
794
+ return wrote
795
+ }
796
+
797
+ // A run's ending that an earlier reading gave the whole run's usage, where
798
+ // the session's requests now carry their own: the usage comes off it, with
799
+ // the cost, request and context beside it, as `unspent` takes it off a line
800
+ // read again. A provider that reports usage only per run keeps it there.
801
+ let ended = async (g: Graph, session: Eid): Promise<Bundle[]> => {
802
+ let [counted] = await g.read(
803
+ query`.entry.session=${session} .ask .usage !stop .limit=1`,
804
+ )
805
+ if (!counted) return []
806
+ return (await g.read(query`.entry.session=${session} .stop .usage`)).map((
807
+ b,
808
+ ) => ({
809
+ entity: { eid: b.entity.eid },
810
+ usage: null,
811
+ cost: null,
812
+ ask: null,
813
+ context_parts: null,
814
+ }))
815
+ }