@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/readers.ts ADDED
@@ -0,0 +1,1017 @@
1
+ // What a harness's log says, one line at a time. Each agent CLI (Claude Code,
2
+ // Codex, Grok Build, Gemini CLI, Antigravity CLI) writes one JSON object per
3
+ // line, to a transcript file of its own and to stdout when a managed run is
4
+ // read (@yaks/spawn), and a reader turns one line into the entries it becomes:
5
+ // what a person typed, what the harness put in front of the model, what the
6
+ // model said and thought, and the tool calls the harness ran with what they
7
+ // returned. Code, and only code: which file belongs to which session, and
8
+ // what the graph makes of an entry, is the importer's (./tail.ts).
9
+ //
10
+ // A reader knows a format and nothing about the graph, so what it reports
11
+ // carries no eids. It names each call's tool by name and the call by the
12
+ // harness's own id, and a result names its call by that same id; the importer
13
+ // turns both into entities. The kind of each entry is the transcript's own
14
+ // vocabulary (./native.ts):
15
+ //
16
+ // content what a person typed: prose alone is an input
17
+ // content + notice what the harness put in front of the model
18
+ // content + output what the model said
19
+ // content + reasoning what it thought, marked output as well
20
+ // call{to, id, args} a tool it called, by the tool's name
21
+ // result{call} + content what the tool returned, and `execution{state}`
22
+ // saying whether the call went through
23
+ // stop, usage, cost, refusal the end of a managed turn, and what it cost
24
+ //
25
+ // A tool's arguments and output pass through `scrub()`, since a command's
26
+ // output is where a credential turns up. A person's words and the model's are
27
+ // kept verbatim.
28
+ //
29
+ // The stream shapes are copied from live runs of each CLI, and Claude Code's
30
+ // and Codex's files from the files they keep; Grok's and Antigravity's files
31
+ // follow third-party descriptions until they are read from real ones
32
+ // (T-2761).
33
+
34
+ import { metered } from '@yaks/claude/limits'
35
+ import type { Limit } from 'jsr:@yaks/model@0.2.36'
36
+ import { claudeStops } from './claude-control.js'
37
+ export type { Limit }
38
+ import { type Fixed, instructionParts, toolPart } from './parts.js'
39
+
40
+ /** One parsed line of a harness's log. */
41
+ export type Event = Record<string, unknown>
42
+
43
+ /** The components of one entry, as a reader reports them. */
44
+ export type Comps = Record<string, Record<string, unknown>>
45
+
46
+ /** What one line says. */
47
+ export type Said = {
48
+ /** the entries it becomes, in order */
49
+ entries: Comps[]
50
+ /** what it says about the session itself: the harness's own id for it */
51
+ about?: Comps
52
+ /** when the harness wrote it, where the line says */
53
+ at?: string
54
+ /** what it says about the fixed part every request carries (./parts.ts) */
55
+ fixed?: Fixed[]
56
+ /** what it says about the provider's plan limits */
57
+ limits?: Limit[]
58
+ /** the model it says answers the lines after it, by the model's own name */
59
+ model?: string
60
+ /** a fragment of an entry the lines after it carry on, where a stream
61
+ * prints a reply in pieces: a run of parts of one `key` is one entry, at
62
+ * the line of its first, and any other line ends the run (./tail.ts) */
63
+ part?: { key: string; entry: Comps }
64
+ }
65
+
66
+ /** A harness's line format. */
67
+ export type Reader = (e: Event) => Said
68
+
69
+ /**
70
+ * A reader whose plan limits are one account's: the account that keeps the
71
+ * transcript, or the one a run signs in with. A reading that names no account
72
+ * is a different row from the same plan's reading that names one.
73
+ *
74
+ * ```ts
75
+ * import { accounted, claude } from '@yaks/session'
76
+ * import { assertEquals } from '@std/assert'
77
+ *
78
+ * let week = { utilization: 0.25, resetsAt: 1794913200 }
79
+ * let line = { type: 'rate_limit_event', rate_limit_info: { unifiedWindows: { seven_day: week } } }
80
+ * assertEquals(accounted(claude, 'a')(line).limits?.[0].account, 'a')
81
+ * ```
82
+ */
83
+ export let accounted = (read: Reader, account?: string): Reader =>
84
+ account
85
+ ? (e) => {
86
+ let said = read(e)
87
+ return said.limits
88
+ ? { ...said, limits: said.limits.map((l) => ({ ...l, account })) }
89
+ : said
90
+ }
91
+ : read
92
+
93
+ let str = (v: unknown): string => typeof v == 'string' ? v : ''
94
+ let obj = (v: unknown): Event =>
95
+ v && typeof v == 'object' && !Array.isArray(v) ? v as Event : {}
96
+ let list = (v: unknown): Event[] => Array.isArray(v) ? v.map(obj) : []
97
+ let nothing: Said = { entries: [] }
98
+
99
+ // Readable text out of a content shape: a string, or blocks of which the text
100
+ // ones count.
101
+ let text = (v: unknown): string =>
102
+ typeof v == 'string'
103
+ ? v
104
+ : list(v).filter((b) => b.type == 'text').map((b) => str(b.text))
105
+ .join('\n')
106
+
107
+ /**
108
+ * A credential's shape, redacted: a bearer or basic header, a vendor key, a
109
+ * JWT, an AWS key id, or a `key: value` assignment naming a secret. Ordinary
110
+ * output, code and prose pass through.
111
+ *
112
+ * ```ts
113
+ * import { scrub } from '@yaks/session'
114
+ * import { assertEquals } from '@std/assert'
115
+ *
116
+ * assertEquals(scrub('curl -H "Authorization: Bearer abc.def"'), 'curl -H "Authorization: [redacted]"')
117
+ * assertEquals(scrub('token=ghp_0123456789abcdef'), 'token=[redacted]')
118
+ * assertEquals(scrub('ls -la'), 'ls -la')
119
+ * assertEquals(scrub('value: yak_secret_example'), 'value: [set]')
120
+ * ```
121
+ */
122
+ export let scrub = (s: string): string =>
123
+ s
124
+ .replace(/\byak_secret_[A-Za-z0-9_-]+/g, '[set]')
125
+ .replace(/\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, '[redacted]')
126
+ .replace(
127
+ /\b(?:sk|sk-ant|sess|pk|rk|ghp|gho|ghs|ghu|ghr|xox[baprs])[-_][A-Za-z0-9_-]{8,}/gi,
128
+ '[redacted]',
129
+ )
130
+ .replace(
131
+ /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,
132
+ '[redacted]',
133
+ )
134
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted]')
135
+ .replace(
136
+ /((?:api[_-]?key|secret|password|passwd|token|authorization)["']?\s*[:=]\s*)(?!\[redacted\])(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
137
+ '$1[redacted]',
138
+ )
139
+
140
+ // Every string inside a value, scrubbed: arguments are an object, and a
141
+ // pattern run over its JSON would eat the quotes around what it redacts.
142
+ let scrubbed = (v: unknown): unknown =>
143
+ typeof v == 'string'
144
+ ? scrub(v)
145
+ : Array.isArray(v)
146
+ ? v.map(scrubbed)
147
+ : v && typeof v == 'object'
148
+ ? Object.fromEntries(
149
+ Object.entries(v).map(([k, x]) => [k, scrubbed(x)]),
150
+ )
151
+ : v
152
+
153
+ let said = (body: string, marks: Comps = {}): Comps[] =>
154
+ body.trim() ? [{ content: { body }, ...marks }] : []
155
+
156
+ let call = (to: string, id: unknown, args: unknown): Comps => ({
157
+ call: { to, id: String(id ?? ''), args: obj(scrubbed(args)) },
158
+ })
159
+
160
+ let result = (id: unknown, body: string, failed: boolean): Comps => ({
161
+ result: { call: String(id ?? '') },
162
+ content: { body: scrub(body) },
163
+ execution: {},
164
+ ...(failed ? { refusal: { code: 'is_error' } } : {}),
165
+ })
166
+
167
+ // A count a harness reported, or nothing. Absent beats zero: a tier a vendor
168
+ // never reports must not fold to 0, or a sum cannot tell the two apart.
169
+ let count = (v: unknown): number | undefined => {
170
+ if (v == null) return undefined
171
+ let n = Number(v)
172
+ return Number.isFinite(n) ? n : undefined
173
+ }
174
+
175
+ let put = (k: string, v?: number) => v == null ? {} : { [k]: v }
176
+
177
+ // @yaks/model's `usage`, whose `input_tokens` counts every input token, cached
178
+ // ones included: what Codex reports. Claude reports its cache reads and writes
179
+ // beside an `input_tokens` that counts only the rest, so they are added in.
180
+ let usage = (
181
+ input?: number,
182
+ output?: number,
183
+ cached?: number,
184
+ more: Record<string, number | undefined> = {},
185
+ ): Comps => {
186
+ let told = {
187
+ ...put('input_tokens', input),
188
+ ...put('output_tokens', output),
189
+ ...put('cached_tokens', cached),
190
+ ...Object.assign({}, ...Object.entries(more).map(([k, n]) => put(k, n))),
191
+ }
192
+ return Object.keys(told).length ? { usage: told } : {}
193
+ }
194
+
195
+ let claudeUsage = (raw: unknown): Comps => {
196
+ let u = obj(raw)
197
+ let parts = [
198
+ u.input_tokens,
199
+ u.cache_read_input_tokens,
200
+ u.cache_creation_input_tokens,
201
+ ].map(count)
202
+ return usage(
203
+ parts.every((n) => n == null)
204
+ ? undefined
205
+ : parts.reduce((a: number, n) => a + (n ?? 0), 0),
206
+ count(u.output_tokens),
207
+ count(u.cache_read_input_tokens),
208
+ {
209
+ cache_write_tokens: count(u.cache_creation_input_tokens),
210
+ cache_write_1h_tokens: count(
211
+ obj(u.cache_creation).ephemeral_1h_input_tokens,
212
+ ),
213
+ reasoning_tokens: count(obj(u.output_tokens_details).thinking_tokens),
214
+ },
215
+ )
216
+ }
217
+
218
+ let codexUsage = (raw: unknown): Comps => {
219
+ let u = obj(raw)
220
+ return usage(
221
+ count(u.input_tokens),
222
+ count(u.output_tokens),
223
+ count(u.cached_input_tokens),
224
+ {
225
+ cache_write_tokens: count(u.cache_write_input_tokens),
226
+ reasoning_tokens: count(u.reasoning_output_tokens),
227
+ },
228
+ )
229
+ }
230
+
231
+ // The API request a reply answers. Claude Code writes each block of a reply on
232
+ // a line of its own, every one naming the request and its final usage; the
233
+ // importer keeps the first, and enters it before the blocks it returned
234
+ // (./tail.ts `imported`). It follows them here, so they keep the places, and
235
+ // the names, an import from before requests were read gave them.
236
+ let requested = (e: Event): Comps[] => {
237
+ let m = obj(e.message)
238
+ let model = str(m.model)
239
+ let used = claudeUsage(m.usage)
240
+ let id = str(m.id) || str(e.requestId)
241
+ return id && model != '<synthetic>' && Object.keys(used).length
242
+ ? [{ ask: { id, ...(model ? { to: model } : {}) }, ...used }]
243
+ : []
244
+ }
245
+
246
+ let home = (path: string) => path.replace(/^\/home\/[^/]+(?=\/)/, '~')
247
+
248
+ // What a line sent the model, in characters: what Claude Code rendered.
249
+ let shown = (e: Event, fallback = '') =>
250
+ list(e.rendered).map((r) => str(r.content)).join('').length ||
251
+ fallback.length
252
+
253
+ // What Claude Code says about the fixed part every request carries: its system
254
+ // prompt and tool schemas, the instruction files, and its listings.
255
+ let fixedOf = (e: Event): Fixed[] => {
256
+ let a = obj(e.attachment)
257
+ return e.type != 'attachment' ? [] : a.type == 'prompt_snapshot'
258
+ ? [
259
+ {
260
+ source: 'system',
261
+ parts: (Array.isArray(a.systemPrompt) ? a.systemPrompt : [])
262
+ .flatMap((p) => instructionParts(str(p), 'system')),
263
+ },
264
+ ...list(a.tools).length
265
+ ? [{ source: 'tools', parts: list(a.tools).map(toolPart) }]
266
+ : [],
267
+ ]
268
+ : a.type == 'instructions'
269
+ ? [{
270
+ source: 'instructions',
271
+ parts: list(a.files).flatMap((f) =>
272
+ instructionParts(str(f.content), `instructions ${home(str(f.path))}`)
273
+ ),
274
+ }]
275
+ : a.type == 'skill_listing'
276
+ ? [{
277
+ source: 'skills',
278
+ parts: [['skills', shown(e, str(a.content))]],
279
+ add: !a.isInitial,
280
+ }]
281
+ : a.type == 'deferred_tools_delta'
282
+ ? [{
283
+ source: 'deferred',
284
+ parts: [['deferred tools', shown(e)]],
285
+ add: true,
286
+ }]
287
+ : a.type == 'mcp_instructions_delta'
288
+ ? [{ source: 'mcp', parts: [['mcp instructions', shown(e)]], add: true }]
289
+ : a.type == 'agent_listing_delta'
290
+ ? [{
291
+ source: 'agents',
292
+ parts: [['agent listing', shown(e)]],
293
+ add: !a.isInitial,
294
+ }]
295
+ : []
296
+ }
297
+
298
+ // A slash command is recorded as its wrapper; the person typed the command.
299
+ let typedAs = (text: string): string => {
300
+ let name = text.match(/<command-name>([\s\S]*?)<\/command-name>/)?.[1]
301
+ if (!name) return text
302
+ let args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]
303
+ return args?.trim() ? `${name.trim()} ${args.trim()}` : name.trim()
304
+ }
305
+
306
+ // What the harness says a person typed, and what it put there itself: a task's
307
+ // notification, a message from another session, a note about a command.
308
+ let prompt = (body: string, human: boolean): Comps[] =>
309
+ human
310
+ ? said(typedAs(body))
311
+ : said(body, claudeStops.includes(body) ? { stop: {} } : { notice: {} })
312
+
313
+ let human = (e: Event) => obj(e.origin).kind == 'human'
314
+
315
+ let assistant = (b: Event): Comps[] =>
316
+ b.type == 'text'
317
+ ? said(str(b.text), { output: {} })
318
+ : b.type == 'thinking'
319
+ ? said(str(b.thinking), { reasoning: {}, output: {} })
320
+ : b.type == 'tool_use'
321
+ ? [call(str(b.name), b.id, b.input)]
322
+ : []
323
+
324
+ let user = (b: Event, typed: boolean): Comps[] =>
325
+ b.type == 'text'
326
+ ? prompt(str(b.text), typed)
327
+ : b.type == 'tool_result'
328
+ ? [result(b.tool_use_id, text(b.content), !!b.is_error)]
329
+ : []
330
+
331
+ let blocks = (e: Event): Event[] => {
332
+ let c = obj(e.message).content
333
+ return typeof c == 'string' ? [{ type: 'text', text: c }] : list(c)
334
+ }
335
+
336
+ // One line of Claude Code's, whichever conversation it belongs to.
337
+ let line: Reader = (e) => {
338
+ let at = str(e.timestamp) || undefined
339
+ let a = obj(e.attachment)
340
+ let entries: Comps[] = e.type == 'user' && e.isCompactSummary
341
+ ? said(text(obj(e.message).content), { checkpoint: {}, notice: {} })
342
+ // An answer Claude Code wrote itself for a refused call (its `error`:
343
+ // `rate_limit` for a plan limit, `billing_error`, ...) is a refusal, its
344
+ // text the reason.
345
+ : e.type == 'assistant' && str(e.error)
346
+ ? [{
347
+ refusal: { code: str(e.error) },
348
+ content: { body: text(obj(e.message).content) },
349
+ output: {},
350
+ }]
351
+ : e.type == 'assistant'
352
+ ? [...blocks(e).flatMap(assistant), ...requested(e)]
353
+ : e.type == 'user'
354
+ ? blocks(e).flatMap((b) => user(b, human(e)))
355
+ // A message typed while a turn runs reaches the model as this attachment.
356
+ : e.type == 'attachment' && a.type == 'queued_command'
357
+ ? prompt(text(a.prompt), human(a))
358
+ // A result closes a turn, not the run: a run with background tasks takes
359
+ // another turn when one finishes. Its process exiting is the run's end
360
+ // (@yaks/spawn `ended`). Only a failed turn says something: Claude reports
361
+ // an API refusal as subtype `success` with is_error set, and the result
362
+ // text holds the diagnosis.
363
+ : e.type == 'result' && e.is_error
364
+ ? [{
365
+ refusal: { code: String(e.subtype ?? 'error') },
366
+ // A turn that failed before it began (a resume that finds no
367
+ // conversation) has no result text; its reason is in `errors`.
368
+ content: {
369
+ body: String(
370
+ e.result || (Array.isArray(e.errors) && e.errors.join('; ')) ||
371
+ 'the turn failed',
372
+ ),
373
+ },
374
+ output: {},
375
+ }]
376
+ : []
377
+ let about = e.type == 'system' && e.subtype == 'init' && e.session_id
378
+ ? { session: { id: String(e.session_id) } }
379
+ : undefined
380
+ let model = e.type == 'system' && e.subtype == 'init' && e.model
381
+ ? String(e.model)
382
+ : undefined
383
+ let fixed = fixedOf(e)
384
+ let limits = e.type == 'rate_limit_event'
385
+ ? metered(obj(e.rate_limit_info))
386
+ : []
387
+ return {
388
+ entries,
389
+ ...(about ? { about } : {}),
390
+ ...(at ? { at } : {}),
391
+ ...(fixed.length ? { fixed } : {}),
392
+ ...(limits.length ? { limits } : {}),
393
+ ...(model ? { model } : {}),
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Claude Code: the transcript it keeps of an interactive session
399
+ * (`~/.claude/projects/<project>/<session>.jsonl`), and the stream
400
+ * `claude -p --output-format stream-json` prints. The two share their message
401
+ * lines; the file adds the queue and the harness's own notes, and the stream
402
+ * adds the line that opens a run and the one that closes each turn. A side
403
+ * conversation, which older files keep inline and the stream marks with the
404
+ * call that started it, is a subagent's, read from its own transcript, not
405
+ * this session's. The stream also says how much of the plan's limits is used
406
+ * (`rate_limit_event`), whenever a window's percentage moves; an interactive
407
+ * session's file does not, and its status line is read instead
408
+ * (@yaks/spend). A line written from the graph to open a session in Claude
409
+ * Code names the entry it came from (`yak.entry`, ./resume.ts) and is read as
410
+ * nothing: it is that entry already.
411
+ *
412
+ * ```ts
413
+ * import { claude } from '@yaks/session'
414
+ * import { assertEquals } from '@std/assert'
415
+ *
416
+ * let typed = { type: 'user', origin: { kind: 'human' }, message: { content: 'hi' } }
417
+ * assertEquals(claude(typed).entries, [{ content: { body: 'hi' } }])
418
+ * let aside = { type: 'assistant', parent_tool_use_id: 'toolu_1', message: { content: 'done' } }
419
+ * assertEquals(claude(aside).entries, [])
420
+ * let ours = { ...typed, yak: { entry: 'e' } }
421
+ * assertEquals(claude(ours).entries, [])
422
+ * let week = { utilization: 0.25, resetsAt: 1794913200, status: 'allowed' }
423
+ * let metered = { type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: { seven_day: week } } }
424
+ * assertEquals(claude(metered).limits, [
425
+ * { provider: 'claude', window: 10080, used: 25, resets: '2026-11-17T11:00:00.000Z' },
426
+ * ])
427
+ * ```
428
+ */
429
+ export let claude: Reader = (e) =>
430
+ e.isSidechain || e.parent_tool_use_id || e.yak ? nothing : line(e)
431
+
432
+ /**
433
+ * A Claude Code subagent's own transcript
434
+ * (`<project>/<session>/subagents/agent-<id>.jsonl`), every line of which is
435
+ * a side conversation of the session that started it.
436
+ *
437
+ * ```ts
438
+ * import { subagent } from '@yaks/session'
439
+ * import { assertEquals } from '@std/assert'
440
+ *
441
+ * let said = { type: 'assistant', isSidechain: true, message: { content: 'done' } }
442
+ * assertEquals(subagent(said).entries, [{ content: { body: 'done' }, output: {} }])
443
+ * ```
444
+ */
445
+ export let subagent: Reader = line
446
+
447
+ // What a codex tool item called and what it answered. An MCP call is named the
448
+ // way Claude Code names one; every other item is named by its type.
449
+ let tool = (it: Event): string =>
450
+ it.type == 'mcp_tool_call'
451
+ ? `mcp__${str(it.server)}__${str(it.tool)}`
452
+ : str(it.type)
453
+
454
+ let asked = (it: Event): unknown => {
455
+ if (it.type == 'mcp_tool_call') return it.arguments
456
+ let {
457
+ id: _id,
458
+ type: _type,
459
+ status: _status,
460
+ aggregated_output: _out,
461
+ exit_code: _code,
462
+ result: _result,
463
+ error: _error,
464
+ ...args
465
+ } = it
466
+ return args
467
+ }
468
+
469
+ let answered = (it: Event): string =>
470
+ str(it.aggregated_output) || text(obj(it.result).content) ||
471
+ str(obj(it.error).message) || str(it.status)
472
+
473
+ let failed = (it: Event) =>
474
+ it.status == 'failed' || (it.exit_code != null && it.exit_code != 0)
475
+
476
+ let spoken = (it: Event): Comps[] | undefined =>
477
+ it.type == 'agent_message'
478
+ ? said(str(it.text), { output: {} })
479
+ : it.type == 'reasoning'
480
+ ? said(str(it.text), { reasoning: {}, output: {} })
481
+ : undefined
482
+
483
+ // Why a Codex turn failed. Its event carries only a message, and the one its
484
+ // content filter writes ("This content was flagged for possible cybersecurity
485
+ // risk", "your prompt was flagged as potentially violating our usage policy")
486
+ // is the provider declining the request, `content_policy`.
487
+ let turnFailed = (message: string): string =>
488
+ /\bflagged\b/i.test(message) ? 'content_policy' : 'turn.failed'
489
+
490
+ /**
491
+ * Codex: the stream `codex exec --json` prints.
492
+ *
493
+ * ```ts
494
+ * import { codex } from '@yaks/session'
495
+ * import { assertEquals } from '@std/assert'
496
+ *
497
+ * let done = { type: 'item.completed', item: { type: 'agent_message', text: 'hi' } }
498
+ * assertEquals(codex(done).entries, [{ content: { body: 'hi' }, output: {} }])
499
+ * ```
500
+ */
501
+ export let codex: Reader = (e) => {
502
+ let it = obj(e.item)
503
+ let entries: Comps[] = e.type == 'item.started'
504
+ ? spoken(it) ? [] : [call(tool(it), it.id, asked(it))]
505
+ : e.type == 'item.completed'
506
+ // An item that never said it started is a call and its answer at once.
507
+ ? spoken(it) ?? [
508
+ call(tool(it), it.id, asked(it)),
509
+ result(it.id, answered(it), failed(it)),
510
+ ]
511
+ : e.type == 'turn.completed'
512
+ ? [{ stop: {}, ...codexUsage(e.usage) }]
513
+ : e.type == 'turn.failed'
514
+ ? [{
515
+ refusal: { code: turnFailed(str(obj(e.error).message)) },
516
+ content: { body: str(obj(e.error).message) || 'the turn failed' },
517
+ output: {},
518
+ stop: {},
519
+ }]
520
+ : []
521
+ return e.type == 'thread.started' && e.thread_id
522
+ ? { entries, about: { session: { id: String(e.thread_id) } } }
523
+ : { entries }
524
+ }
525
+
526
+ // Text, given as a string or as its UTF-8 bytes.
527
+ let utf8 = (v: unknown): string | undefined =>
528
+ typeof v == 'string'
529
+ ? v
530
+ : Array.isArray(v) && v.every(Number.isInteger)
531
+ ? new TextDecoder().decode(Uint8Array.from(v))
532
+ : undefined
533
+
534
+ // What a Grok Build tool's result showed the model: its stream answers a call
535
+ // with the tool's own result as JSON, its output in bytes, a shell call's
536
+ // beside `output_for_prompt`, the text the model read, and a search's as
537
+ // `stdout`.
538
+ let prompted = (b: Event): Event => {
539
+ if (b.type != 'tool_result' || typeof b.content != 'string') return b
540
+ let r: Event
541
+ try {
542
+ r = obj(JSON.parse(b.content))
543
+ } catch {
544
+ return b
545
+ }
546
+ let shown = utf8(r.output_for_prompt) ?? utf8(r.stdout)
547
+ return shown == null ? b : { ...b, content: shown }
548
+ }
549
+
550
+ /**
551
+ * Grok Build's stream, `grok -p --output-format streaming-messages-json`:
552
+ * Claude Code's stream-json, read as {@link claude} reads it, except that a
553
+ * tool's result is the tool's own JSON. A shell call's and a search's are
554
+ * read as the text the model was shown (`output_for_prompt`, `stdout`); its
555
+ * history file (`grok`) keeps only that text.
556
+ *
557
+ * ```ts
558
+ * import { grokStream } from '@yaks/session'
559
+ * import { assertEquals } from '@std/assert'
560
+ *
561
+ * let ran = JSON.stringify({ type: 'Bash', output: [104, 105], output_for_prompt: 'exit: 0\nhi' })
562
+ * let answer = { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'c1', content: ran }] } }
563
+ * assertEquals(grokStream(answer).entries, [
564
+ * { result: { call: 'c1' }, content: { body: 'exit: 0\nhi' }, execution: {} },
565
+ * ])
566
+ * let found = JSON.stringify({ type: 'GrepSearch', stdout: [70, 111, 117, 110, 100] })
567
+ * assertEquals(grokStream({ ...answer, message: { content: [{ type: 'tool_result', tool_use_id: 'c2', content: found }] } }).entries, [
568
+ * { result: { call: 'c2' }, content: { body: 'Found' }, execution: {} },
569
+ * ])
570
+ * ```
571
+ */
572
+ export let grokStream: Reader = (e) => {
573
+ let m = obj(e.message)
574
+ return claude(
575
+ e.type == 'user' && Array.isArray(m.content)
576
+ ? { ...e, message: { ...m, content: m.content.map(prompted) } }
577
+ : e,
578
+ )
579
+ }
580
+
581
+ // Why a Google CLI's turn failed: its plan's limit, a quota or a rate limit
582
+ // spent ("You exceeded your current quota", RESOURCE_EXHAUSTED), is
583
+ // `rate_limit`, as Claude's is, so the run ends as one its plan declined and
584
+ // moves to an account with room (@yaks/spawn); anything else is an error.
585
+ let googleFailed = (message: string): Comps => ({
586
+ refusal: {
587
+ code: /\bquota\b|resource.?exhausted|exhausted your capacity|rate.?limit/i
588
+ .test(message)
589
+ ? 'rate_limit'
590
+ : 'error',
591
+ },
592
+ content: { body: message },
593
+ output: {},
594
+ })
595
+
596
+ // A turn's end, with what it used, and why it failed where it did.
597
+ let ended = (error: string, used: Comps): Comps[] => [
598
+ ...error ? [googleFailed(error)] : [],
599
+ { stop: {}, ...used },
600
+ ]
601
+
602
+ // The model that read the conversation in Gemini CLI's `result.stats.models`:
603
+ // when a turn routes across models, the one with the most input tokens
604
+ // answered; the smaller one is Gemini's router.
605
+ let geminiModel = (models: Event): string | undefined =>
606
+ Object.entries(models)
607
+ .filter(([name]) => name)
608
+ .map(([name, raw]) => [name, count(obj(raw).input_tokens) ?? -1] as const)
609
+ .sort((a, b) => b[1] - a[1])[0]?.[0]
610
+
611
+ /**
612
+ * Gemini CLI: the stream `gemini -p --output-format stream-json` prints. Its
613
+ * reply comes in fragments (`message` with `delta`), each a part of the entry
614
+ * the next tool call or the turn's end closes. The prompt it echoes is the
615
+ * session's own request already, and is read as nothing.
616
+ *
617
+ * ```ts
618
+ * import { gemini } from '@yaks/session'
619
+ * import { assertEquals } from '@std/assert'
620
+ *
621
+ * let piece = { type: 'message', role: 'assistant', content: 'Hel', delta: true }
622
+ * assertEquals(gemini(piece).part, { key: 'reply', entry: { content: { body: 'Hel' }, output: {} } })
623
+ * let used = { type: 'tool_use', tool_name: 'read_file', tool_id: 't1', parameters: { file_path: 'a.ts' } }
624
+ * assertEquals(gemini(used).entries, [{ call: { to: 'read_file', id: 't1', args: { file_path: 'a.ts' } } }])
625
+ * let spent = { type: 'result', status: 'error', error: { message: 'You exceeded your current quota' } }
626
+ * assertEquals(gemini(spent).entries[0].refusal, { code: 'rate_limit' })
627
+ * ```
628
+ */
629
+ export let gemini: Reader = (e) => {
630
+ let type = str(e.type)
631
+ let stats = obj(e.stats)
632
+ let entries: Comps[] = type == 'tool_use'
633
+ ? [call(str(e.tool_name), e.tool_id, e.parameters)]
634
+ : type == 'tool_result'
635
+ ? [result(
636
+ e.tool_id,
637
+ str(e.output) || str(obj(e.error).message),
638
+ e.status == 'error',
639
+ )]
640
+ : type == 'error'
641
+ ? e.severity == 'error'
642
+ ? [googleFailed(str(e.message))]
643
+ : said(str(e.message), { notice: {} })
644
+ : type == 'result'
645
+ ? ended(
646
+ e.status == 'success'
647
+ ? ''
648
+ : str(obj(e.error).message) || 'the turn failed',
649
+ usage(
650
+ count(stats.input_tokens),
651
+ count(stats.output_tokens),
652
+ count(stats.cached),
653
+ ),
654
+ )
655
+ : type == 'message' && e.role == 'assistant' && !e.delta
656
+ ? said(str(e.content), { output: {} })
657
+ : []
658
+ let piece = type == 'message' && e.role == 'assistant' && e.delta &&
659
+ str(e.content)
660
+ let model = type == 'init'
661
+ ? (str(e.model) == 'auto' ? '' : str(e.model))
662
+ : type == 'result'
663
+ ? geminiModel(obj(stats.models))
664
+ : undefined
665
+ return {
666
+ entries,
667
+ ...piece
668
+ ? {
669
+ part: { key: 'reply', entry: { content: { body: piece }, output: {} } },
670
+ }
671
+ : {},
672
+ ...type == 'init' && e.session_id
673
+ ? { about: { session: { id: str(e.session_id) } } }
674
+ : {},
675
+ ...model ? { model } : {},
676
+ ...str(e.timestamp) ? { at: str(e.timestamp) } : {},
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Antigravity CLI: the stream `agy --print --output-format stream-json`
682
+ * prints (antigravity.google/docs/cli/headless), an `init`, then a
683
+ * `step_update` per step as it runs and finishes, then the `result`. What
684
+ * the model says arrives as `text_delta` fragments of its `agent_response`
685
+ * step, each a part of that step's entry; a `tool` step finished carries
686
+ * its call and what it answered (`tool_info`). The result repeats the last
687
+ * reply whole (`response`), which its parts already said.
688
+ *
689
+ * ```ts
690
+ * import { antigravityStream } from '@yaks/session'
691
+ * import { assertEquals } from '@std/assert'
692
+ *
693
+ * let ran = { event: 'step_update', step_update: { step_index: 4, state: 'DONE', step_type: 'tool',
694
+ * tool_info: { name: 'run_command', parameters: { CommandLine: 'ls' }, output: 'a.ts' } } }
695
+ * assertEquals(antigravityStream(ran).entries.map((c) => c.call ?? c.result), [
696
+ * { to: 'run_command', id: 'step-4', args: { CommandLine: 'ls' } },
697
+ * { call: 'step-4' },
698
+ * ])
699
+ * ```
700
+ */
701
+ export let antigravityStream: Reader = (e) => {
702
+ let event = str(e.event)
703
+ let s = obj(e.step_update)
704
+ let info = obj(s.tool_info)
705
+ let id = stepCall(Number(s.step_index))
706
+ let r = obj(e.result)
707
+ let u = obj(r.usage)
708
+ let entries: Comps[] = event == 'step_update' && s.step_type == 'tool' &&
709
+ Object.keys(info).length
710
+ ? [
711
+ call(str(info.name) || str(s.tool_name), id, info.parameters),
712
+ ...s.state == 'DONE'
713
+ ? [result(
714
+ id,
715
+ str(info.output) || str(obj(info.error).message),
716
+ !!info.error,
717
+ )]
718
+ : [],
719
+ ]
720
+ : event == 'result'
721
+ ? ended(
722
+ r.status == 'SUCCESS' ? '' : str(r.error) || 'the turn failed',
723
+ // Its `input_tokens` leaves out the cached ones, which `usage` counts.
724
+ usage(
725
+ u.input_tokens == null
726
+ ? undefined
727
+ : (count(u.input_tokens) ?? 0) + (count(u.cache_read_tokens) ?? 0),
728
+ count(u.output_tokens),
729
+ count(u.cache_read_tokens),
730
+ { reasoning_tokens: count(u.thinking_tokens) },
731
+ ),
732
+ )
733
+ : []
734
+ let piece = event == 'step_update' && s.step_type == 'agent_response' &&
735
+ str(s.text_delta)
736
+ let init = obj(e.init)
737
+ return {
738
+ entries,
739
+ ...piece
740
+ ? { part: { key: id, entry: { content: { body: piece }, output: {} } } }
741
+ : {},
742
+ ...event == 'init' && e.conversation_id
743
+ ? { about: { session: { id: str(e.conversation_id) } } }
744
+ : {},
745
+ ...str(init.model) ? { model: str(init.model) } : {},
746
+ }
747
+ }
748
+
749
+ /** The readers this package ships for the stream each harness prints when
750
+ * a run is managed (@yaks/spawn), by the harness's name. */
751
+ export let readers: Record<string, Reader> = {
752
+ claude,
753
+ codex,
754
+ grok: grokStream,
755
+ gemini,
756
+ antigravity: antigravityStream,
757
+ }
758
+
759
+ // Codex rollouts repeat their visible messages in event_msg notifications.
760
+ // Read response_item once; event_msg only supplies turn boundaries and usage.
761
+ let rolloutText = (v: unknown): string =>
762
+ typeof v == 'string' ? v : list(v)
763
+ .filter((b) =>
764
+ ['text', 'input_text', 'output_text', 'summary_text'].includes(
765
+ str(b.type),
766
+ )
767
+ )
768
+ .map((b) => str(b.text)).join('\n')
769
+
770
+ let argumentsOf = (raw: unknown): Event => {
771
+ if (typeof raw != 'string') return obj(raw)
772
+ try {
773
+ return obj(JSON.parse(raw))
774
+ } catch {
775
+ return { input: raw }
776
+ }
777
+ }
778
+
779
+ let rolloutInput = (it: Event): Comps[] => {
780
+ let kinds =
781
+ obj(it.internal_chat_message_metadata_passthrough).content_item_kinds
782
+ let blocks = list(it.content)
783
+ return blocks.flatMap((b, i) => {
784
+ let body = rolloutText([b])
785
+ let kind = Array.isArray(kinds) ? str(kinds[i]) : ''
786
+ let typed = it.role == 'user' &&
787
+ (kind
788
+ ? kind.startsWith('user.')
789
+ : !/^(?:# AGENTS\.md|<environment_context>|<INSTRUCTIONS>)/.test(body))
790
+ return said(body, typed ? {} : { notice: {} })
791
+ })
792
+ }
793
+
794
+ let rolloutItem = (it: Event): Comps[] =>
795
+ it.type == 'message'
796
+ ? it.role == 'assistant'
797
+ ? said(rolloutText(it.content), { output: {} })
798
+ : rolloutInput(it)
799
+ : it.type == 'agent_message'
800
+ ? said(rolloutText(it.content), { notice: {} })
801
+ : it.type == 'reasoning'
802
+ ? said(rolloutText(it.summary), { reasoning: {}, output: {} })
803
+ : it.type == 'function_call' || it.type == 'custom_tool_call'
804
+ ? [
805
+ call(
806
+ [str(it.namespace), str(it.name)].filter(Boolean).join('.'),
807
+ it.call_id,
808
+ it.type == 'custom_tool_call'
809
+ ? { input: it.input }
810
+ : argumentsOf(it.arguments),
811
+ ),
812
+ ]
813
+ : it.type == 'function_call_output' || it.type == 'custom_tool_call_output'
814
+ ? [result(it.call_id, rolloutText(it.output), false)]
815
+ : []
816
+
817
+ /** Codex's on-disk rollout format. Read messages from response_item so the
818
+ * event_msg mirrors never duplicate them. A using names the CLI runner and
819
+ * model; the importer resolves those names into graph identities. */
820
+ export let codexRollout: Reader = (e) => {
821
+ let it = obj(e.payload)
822
+ let entries = e.type == 'response_item'
823
+ ? rolloutItem(it)
824
+ : e.type == 'session_meta'
825
+ ? [{ using: { provider: 'codex' }, notice: {} }]
826
+ : e.type == 'turn_context' && it.model
827
+ ? [{
828
+ using: {
829
+ provider: 'codex',
830
+ model: str(it.model),
831
+ ...(it.effort ? { effort: str(it.effort) } : {}),
832
+ },
833
+ notice: {},
834
+ }]
835
+ : e.type == 'event_msg' && it.type == 'task_complete'
836
+ ? [{ stop: {} }]
837
+ : e.type == 'event_msg' && it.type == 'turn_aborted'
838
+ ? [{ stop: {} }]
839
+ : e.type == 'token_usage_record'
840
+ ? Object.keys(codexUsage(it.usage)).length
841
+ ? [{
842
+ ask: { id: str(it.response_id) || str(it.turn_id) },
843
+ ...codexUsage(it.usage),
844
+ }]
845
+ : []
846
+ : e.type == 'compacted'
847
+ ? said(str(it.message), { checkpoint: {}, notice: {} })
848
+ : []
849
+ let system = str(obj(it.base_instructions).text)
850
+ let limits = e.type == 'event_msg' && it.type == 'token_count'
851
+ ? limited(obj(it.rate_limits))
852
+ : []
853
+ return {
854
+ entries,
855
+ ...(str(e.timestamp) ? { at: str(e.timestamp) } : {}),
856
+ ...(e.type == 'session_meta' && system
857
+ ? { fixed: [{ source: 'system', parts: [['system', system.length]] }] }
858
+ : {}),
859
+ ...(limits.length ? { limits } : {}),
860
+ }
861
+ }
862
+
863
+ // Codex's plan limits, as a token count reports them: a primary window and
864
+ // perhaps a secondary one, each a percentage used and when it resets.
865
+ let limited = (r: Event): Limit[] =>
866
+ [obj(r.primary), obj(r.secondary)].flatMap((w) =>
867
+ w.window_minutes == null || count(w.used_percent) == null ? [] : [{
868
+ provider: 'codex',
869
+ window: Number(w.window_minutes),
870
+ used: Number(w.used_percent),
871
+ ...count(w.resets_at) == null
872
+ ? {}
873
+ : { resets: new Date(Number(w.resets_at) * 1000).toISOString() },
874
+ }]
875
+ )
876
+
877
+ // Readable text out of a row's content: a string, or blocks each carrying its
878
+ // text, whatever the block's type is called.
879
+ let prose = (v: unknown): string =>
880
+ typeof v == 'string'
881
+ ? v
882
+ : list(v).map((b) => str(b.text)).filter(Boolean).join('\n')
883
+
884
+ /**
885
+ * Grok Build: the model's history it keeps of a session,
886
+ * `$GROK_HOME/sessions/<percent-encoded cwd>/<session>/chat_history.jsonl`,
887
+ * one `{type, content}` row per line. An assistant row names its model
888
+ * (`model_id`) and the calls it made (`tool_calls`: `{id, name, arguments}`,
889
+ * the arguments a JSON string), and a `tool_result` names the call it answers
890
+ * (`tool_call_id`). Reasoning that is only `encrypted_content` says nothing
891
+ * readable, and the rows carry no time. The session's `updates.jsonl` streams
892
+ * the same turns as Agent Client Protocol chunks; the history holds each
893
+ * message whole.
894
+ *
895
+ * ```ts
896
+ * import { grok } from '@yaks/session'
897
+ * import { assertEquals } from '@std/assert'
898
+ *
899
+ * let asked = { type: 'assistant', content: 'Looking.', model_id: 'grok-4.6-build',
900
+ * tool_calls: [{ id: 'c1', name: 'read_file', arguments: '{"path":"a.ts"}' }] }
901
+ * assertEquals(grok(asked).entries, [
902
+ * { content: { body: 'Looking.' }, output: {} },
903
+ * { call: { to: 'read_file', id: 'c1', args: { path: 'a.ts' } } },
904
+ * ])
905
+ * assertEquals(grok(asked).model, 'grok-4.6-build')
906
+ * ```
907
+ */
908
+ export let grok: Reader = (e) => {
909
+ let type = str(e.type)
910
+ let body = prose(e.content)
911
+ let entries: Comps[] = type == 'system'
912
+ ? [{ using: { provider: 'grok' }, notice: {} }]
913
+ : type == 'user'
914
+ ? said(body)
915
+ : type == 'assistant'
916
+ ? [
917
+ ...said(body, { output: {} }),
918
+ ...list(e.tool_calls).map((c) =>
919
+ call(str(c.name), c.id, argumentsOf(c.arguments))
920
+ ),
921
+ ]
922
+ : type == 'reasoning'
923
+ ? said(body, { reasoning: {}, output: {} })
924
+ : type == 'tool_result'
925
+ ? [result(e.tool_call_id, body, !!e.is_error)]
926
+ // A call the backend ran itself (its web search) is asked and answered
927
+ // on one row.
928
+ : type == 'backend_tool_call'
929
+ ? [
930
+ call(str(e.name) || 'backend_tool', e.id, argumentsOf(e.arguments)),
931
+ result(e.id, body, false),
932
+ ]
933
+ : type == 'compaction_checkpoint'
934
+ ? said(body, { checkpoint: {}, notice: {} })
935
+ : []
936
+ return {
937
+ entries,
938
+ ...(type == 'system' && body
939
+ ? { fixed: [{ source: 'system', parts: [['system', body.length]] }] }
940
+ : {}),
941
+ ...(type == 'assistant' && str(e.model_id)
942
+ ? { model: str(e.model_id) }
943
+ : {}),
944
+ }
945
+ }
946
+
947
+ // The call an Antigravity step's result answers: a planner response's calls
948
+ // are answered in order by the steps after it, one each, so the `k`th call of
949
+ // step `s` is answered at step `s + 1 + k`, and both name it by that step.
950
+ let stepCall = (step: number) => `step-${step}`
951
+
952
+ /**
953
+ * Antigravity CLI (`agy`): the steps of a conversation,
954
+ * `~/.gemini/antigravity-cli/brain/<conversation>/.system_generated/logs/transcript_full.jsonl`,
955
+ * one `{step_index, source, type, status, created_at, content}` per line. A
956
+ * `PLANNER_RESPONSE` carries what the model said, its `thinking` and the
957
+ * calls it made (`tool_calls`: `{name, args}`, with no id), and each call's
958
+ * outcome is the `GENERIC` step after it, in the order of the calls, its
959
+ * `status` `DONE`, `ERROR`, `INVALID` or `RUNNING`. A call is named by the
960
+ * step that answers it, and that step names its call too, so a call whose
961
+ * planner line was never read still has the call its result answers.
962
+ *
963
+ * ```ts
964
+ * import { antigravity } from '@yaks/session'
965
+ * import { assertEquals } from '@std/assert'
966
+ *
967
+ * let planned = { step_index: 3, type: 'PLANNER_RESPONSE', content: 'Reading it.',
968
+ * tool_calls: [{ name: 'view_file', args: { AbsolutePath: '/w/a.ts' } }] }
969
+ * assertEquals(antigravity(planned).entries, [
970
+ * { content: { body: 'Reading it.' }, output: {} },
971
+ * { call: { to: 'view_file', id: 'step-4', args: { AbsolutePath: '/w/a.ts' } } },
972
+ * ])
973
+ * let done = { step_index: 4, type: 'GENERIC', status: 'DONE', content: 'export {}' }
974
+ * assertEquals(antigravity(done).entries[1].result, { call: 'step-4' })
975
+ * ```
976
+ */
977
+ export let antigravity: Reader = (e) => {
978
+ let type = str(e.type)
979
+ let step = Number(e.step_index)
980
+ let body = prose(e.content)
981
+ let entries: Comps[] = type == 'USER_INPUT'
982
+ ? said(body, e.source == 'USER_EXPLICIT' || !e.source ? {} : { notice: {} })
983
+ : type == 'PLANNER_RESPONSE'
984
+ ? [
985
+ ...said(prose(e.thinking), { reasoning: {}, output: {} }),
986
+ ...said(body, { output: {} }),
987
+ ...list(e.tool_calls).map((c, k) =>
988
+ call(str(c.name), stepCall(step + 1 + k), argumentsOf(c.args))
989
+ ),
990
+ ]
991
+ : type == 'GENERIC' && e.status != 'RUNNING'
992
+ ? [
993
+ { call: { id: stepCall(step) } },
994
+ result(
995
+ stepCall(step),
996
+ body,
997
+ e.status == 'ERROR' || e.status == 'INVALID',
998
+ ),
999
+ ]
1000
+ : type == 'SYSTEM_MESSAGE' || type == 'CONVERSATION_HISTORY'
1001
+ ? said(body, { notice: {} })
1002
+ : type == 'CHECKPOINT'
1003
+ ? said(body, { checkpoint: {}, notice: {} })
1004
+ : type == 'ERROR_MESSAGE'
1005
+ ? [{
1006
+ refusal: { code: 'error' },
1007
+ content: { body: body || 'the step failed' },
1008
+ output: {},
1009
+ }]
1010
+ : []
1011
+ return {
1012
+ entries: step == 0
1013
+ ? [{ using: { provider: 'antigravity' }, notice: {} }, ...entries]
1014
+ : entries,
1015
+ ...(str(e.created_at) ? { at: str(e.created_at) } : {}),
1016
+ }
1017
+ }