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