@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/state.js ADDED
@@ -0,0 +1,247 @@
1
+ // Transcript state from entry bundles alone. Rendering and in-memory readers
2
+ // share this pure logic without loading SQL derivations or tool execution.
3
+ import { line } from "@yaks/query";
4
+ import { cachedPrefixExpires } from "@yaks/model";
5
+ import { stoppedNotice } from "./claude-control.js";
6
+ import { ASK, CALL, CONTENT, EXCEPTION, OUTPUT, REFUSAL, RESULT, STOP_ENTRY, USING } from "./native.js";
7
+ /** A request is in flight while a holder owns its attempt. */ export let attemptState = (ask)=>ask.interrupted ? 'interrupted' : ask.attempt?.by != null ? 'inflight' : 'completed';
8
+ /** How many consecutive interrupted requests the runner retries through before it leaves a
9
+ * transcript `failed`. */ export let RETRIES = 3;
10
+ /** The error code of a request refused at a ceiling (a spending allowance, a
11
+ * quota): final rather than retried, since the next ask meets the same
12
+ * ceiling. The transcript is `failed` until something new is said to it. */ export let LIMIT = 'limit';
13
+ // A result is a result even when it carries the refusal that answered its
14
+ // call.
15
+ let KINDS = [
16
+ [
17
+ STOP_ENTRY,
18
+ 'stop'
19
+ ],
20
+ [
21
+ RESULT,
22
+ 'result'
23
+ ],
24
+ [
25
+ 'tool_progress',
26
+ 'result'
27
+ ],
28
+ [
29
+ EXCEPTION,
30
+ 'exception'
31
+ ],
32
+ [
33
+ REFUSAL,
34
+ 'refusal'
35
+ ],
36
+ [
37
+ ASK,
38
+ 'ask'
39
+ ],
40
+ [
41
+ CALL,
42
+ 'call'
43
+ ],
44
+ [
45
+ 'interrupted',
46
+ 'interrupted'
47
+ ],
48
+ [
49
+ 'reasoning',
50
+ 'reasoning'
51
+ ]
52
+ ];
53
+ /** The components that make an entry a kind ({@link kindOf}): a line
54
+ * carrying none of them, with prose and no `output`, is an input. */ export let kinded = ()=>KINDS.map(([c])=>c);
55
+ /** The components that make an entry a kind ranked before `kind`
56
+ * ({@link kindOf}), whatever else it carries: a stop naming the request it
57
+ * answers (`ask.through`) is a stop, not an ask. */ export let outranking = (kind)=>KINDS.slice(0, KINDS.findIndex(([, k])=>k == kind)).map(([c])=>c);
58
+ let content = (b)=>b[CONTENT];
59
+ /** The ask an entry's prose came from, when a model returned it. */ export let sourceOf = (b)=>{
60
+ let s = b[OUTPUT]?.source;
61
+ return s == null ? undefined : String(s);
62
+ };
63
+ /** Which kind of entry a bundle is, or `undefined` for one carrying none of
64
+ * the kind components and no prose. */ export let kindOf = (b)=>stoppedNotice(b) ? 'stop' : KINDS.find(([comp])=>comp in b)?.[1] ?? (OUTPUT in b ? 'output' : content(b) ? 'input' : undefined);
65
+ /** The seq of an entry bundle. */ export let seqOf = (b)=>Number(b.entry?.seq ?? 0);
66
+ /** The prose of an entry: its `content.body`, or nothing. */ export let textOf = (b)=>String(content(b)?.body ?? '');
67
+ /** Entries in transcript order. */ export let ordered = (entries)=>entries.toSorted((a, b)=>seqOf(a) - seqOf(b));
68
+ /** The newest `ask` of a transcript: the model turn in force. */ export let newestAsk = (entries)=>ordered(entries).findLast((b)=>kindOf(b) == 'ask');
69
+ // When the prefix a session's newest ask cached leaves its provider's prompt
70
+ // cache (its provider component's `cache_expires_at`, @yaks/model
71
+ // `cachedPrefixExpires`). Unknown for an ask of another transcript, one not
72
+ // answered, or one whose provider records no expiry.
73
+ let expiry = (entries, session)=>{
74
+ let ask = newestAsk(entries);
75
+ if (!ask || ask.entry?.session != session) return;
76
+ let expires = cachedPrefixExpires(ask);
77
+ return expires ? Date.parse(expires) : undefined;
78
+ };
79
+ /** What a session's newest ask sent (its `sending`, which names its
80
+ * instructions), while the prefix it cached is still in the provider's prompt
81
+ * cache. An ask whose expiry is unknown keeps none. */ export let cachedSending = (entries, session, now = Date.now())=>(expiry(entries, session) ?? -Infinity) > now ? newestAsk(entries)?.sending : undefined;
82
+ /** Whether the prefix a session's newest ask cached is known to have expired,
83
+ * so the next request pays for its whole context whatever it sends. An
84
+ * unknown expiry is not cold: nothing says the cache is gone. */ export let cold = (entries, session, now = Date.now())=>(expiry(entries, session) ?? Infinity) <= now;
85
+ // Give provider clocks and retention estimates one extra minute before
86
+ // rewriting a prompt. The recorded expiry is specific to the dispatched ask.
87
+ export let pastCache = (entries, session, now = Date.now())=>cold(entries, session, now - 60_000);
88
+ let sessionOf = (b)=>b?.entry?.session;
89
+ // A fork inherits the prefix as history. A call there can still be open at
90
+ // the fork point and finish later in its own transcript.
91
+ let ownCalls = (all)=>{
92
+ let session = sessionOf(all.at(-1));
93
+ return all.filter((b)=>kindOf(b) == 'call' && sessionOf(b) == session);
94
+ };
95
+ let callsIn = (all)=>{
96
+ let answered = new Set(all.filter((b)=>RESULT in b).map((b)=>String(b[RESULT]?.call)));
97
+ return ownCalls(all).filter((b)=>!answered.has(b.entity.eid));
98
+ };
99
+ /** The calls that no result answers — what the runner runs next, and what
100
+ * keeps a transcript running past the prose the model returned beside them. */ export let openCalls = (entries)=>callsIn(ordered(entries));
101
+ /** Whether something new has arrived beyond the newest request's context
102
+ * boundary for the model to take a turn on. An input asks at once. A result,
103
+ * or the Pending entry a call of the newest reply is given when it outlasts
104
+ * its patience (./react.ts `PATIENCE`), asks once each background call of that
105
+ * reply has answered or outlasted it: the model asked for them together. A
106
+ * background call alone asks nothing more of the model, and the Pending of an
107
+ * older reply's call never asks again: a later request already sent it as
108
+ * pending. This says the model owes work independently of tools running. */ export let modelReady = (entries)=>{
109
+ let all = ordered(entries).filter((b)=>!b.notice);
110
+ let ask = newestAsk(all);
111
+ let through = all.find((b)=>b.entity.eid == ask?.ask?.through);
112
+ let boundary = through ? seqOf(through) : ask ? seqOf(ask) : 0;
113
+ let reply = all.filter((b)=>!!ask && !!b.tool_async && b.call?.source == ask.entity.eid);
114
+ let calls = new Set(reply.map((b)=>b.entity.eid));
115
+ let heard = new Set(all.flatMap((b)=>{
116
+ let call = b.result?.call ?? b.tool_progress?.call;
117
+ return call == null ? [] : [
118
+ String(call)
119
+ ];
120
+ }));
121
+ let together = reply.every((b)=>heard.has(b.entity.eid));
122
+ return all.some((b)=>seqOf(b) > boundary && (kindOf(b) == 'input' || together && (!!b.result || !!b.tool_progress && calls.has(String(b.tool_progress.call)))));
123
+ };
124
+ // An anonymous claim belongs to the process that made it. If that process
125
+ // vanished before answering, the session runner recovers it without replay.
126
+ let abandoned = (calls)=>calls.some((b)=>{
127
+ let execution = b.execution;
128
+ return !!execution && execution.by == null && !b.interrupted;
129
+ });
130
+ /** A transcript the runner answers: one that asked it, by a request or a turn
131
+ * it took. A turn read from a harness's file (`lines`) is that harness's, which
132
+ * answers its own transcript. */ export let served = (entries)=>entries.some((b)=>USING in b || ASK in b && !('lines' in b));
133
+ /** The transcripts a runner is working on: the ones the session cap counts
134
+ * and a restart wakes. That is a transcript the runner answers ({@link served})
135
+ * with something outstanding. An empty session has nothing to run, and one run
136
+ * outside the graph reads `running` while its own runner owes the answer; a
137
+ * graph holds thousands of both (every session a harness's hooks recorded).
138
+ * Unlike `served`, a model chosen by a notice counts as asking. */ export let live = line`.session.status=pending,running,queued (.entries.using|.entries.ask)`;
139
+ /** What the entries leave owing. `session.ended` turns only these into `stopped`:
140
+ * a transcript that settled, failed or never began keeps reading that way. */ export let UNFINISHED = [
141
+ 'pending',
142
+ 'running',
143
+ 'queued'
144
+ ];
145
+ /** The {@link Marks} a session row wears. */ export let marksOf = (row)=>({
146
+ ended: row?.session?.ended == true,
147
+ process: !!row?.process && row.exit == null
148
+ });
149
+ /** The status of a transcript, from its entries in any order and the marks
150
+ * its row wears. A process of its own owes whatever the entries leave owing,
151
+ * so it reads `running` where they say `pending`, never the runner's to
152
+ * answer; once it exits, its ending (@yaks/spawn) is an entry like any. */ export let statusOf = (entries, { ended = false, process = false } = {})=>{
153
+ let status = entriesSay(entries);
154
+ if (ended && UNFINISHED.includes(status)) return 'stopped';
155
+ return process && status == 'pending' ? 'running' : status;
156
+ };
157
+ let entriesSay = (entries)=>{
158
+ // A thought says nothing of where the work stands.
159
+ let all = ordered(entries).filter((b)=>(!b.notice || stoppedNotice(b)) && !b.reasoning);
160
+ let newest = all.at(-1);
161
+ if (!newest) return 'empty';
162
+ let kind = kindOf(newest);
163
+ // Finishing a step already admitted before a stop does not resume work.
164
+ // Only fresh input can reopen the transcript.
165
+ let control = all.findLast((b)=>[
166
+ 'input',
167
+ 'stop'
168
+ ].includes(kindOf(b) ?? ''));
169
+ if (kindOf(control ?? newest) == 'stop') return 'stopped';
170
+ let asked = all.findLast((b)=>kindOf(b) == 'ask');
171
+ let turn = all.filter((b)=>!asked || seqOf(b) >= seqOf(asked));
172
+ // A background call's Pending answers the provider protocol, but only its
173
+ // result answers the work. Unlike legacy synchronous calls, background calls
174
+ // can outlive many asks, and asks while they run only for something new.
175
+ let calls = callsIn(turn).filter((b)=>!b.tool_async);
176
+ let pending = callsIn(all).some((b)=>b.tool_async);
177
+ let background = ownCalls(all).some((b)=>b.tool_async);
178
+ if (abandoned(calls)) return 'running';
179
+ if (kind == 'exception') return 'failed';
180
+ if (kind == 'interrupted' && newest.failed && !newest.ask && !newest.call) {
181
+ return 'failed';
182
+ }
183
+ if (turn.some((b)=>attemptState(b) == 'inflight')) {
184
+ return 'running';
185
+ }
186
+ let afterAsk = (ask = asked)=>{
187
+ return ask && all.some((b)=>seqOf(b) > seqOf(ask) && kindOf(b) == 'input') ? 'pending' : 'failed';
188
+ };
189
+ if (kind == 'refusal') {
190
+ let source = newest.output?.source;
191
+ let ask = all.find((b)=>b.entity.eid == source && kindOf(b) == 'ask');
192
+ return ask ? afterAsk(ask) : 'failed';
193
+ }
194
+ let interrupted = asked;
195
+ if (interrupted?.interrupted) {
196
+ if (interrupted.failed && !all.some((b)=>kindOf(b) == 'input' && seqOf(b) > seqOf(interrupted))) return 'failed';
197
+ if (all.some((b)=>kindOf(b) == 'input' && seqOf(b) > seqOf(interrupted))) {
198
+ return 'pending';
199
+ }
200
+ if (interrupted.provisional) return 'pending';
201
+ let turns = all.filter((b)=>b.ask || kindOf(b) == 'input').slice(-RETRIES);
202
+ return turns.length == RETRIES && turns.every((b)=>b.ask && b.interrupted) ? 'failed' : 'pending';
203
+ }
204
+ if (calls.length) return 'running';
205
+ if (background && modelReady(all)) return 'pending';
206
+ if (pending) return 'running';
207
+ // An ask with no attempt is a line a harness wrote before the rest of its
208
+ // reply: the turn runs on.
209
+ if (kind == 'ask' && newest.attempt && attemptState(newest) == 'completed') return 'settled';
210
+ if (kind == 'ask' || kind == 'call') return 'running';
211
+ // Inputs can be admitted while a provider request is in flight. Its reply
212
+ // does not acknowledge messages after that request's recorded boundary.
213
+ if (kind == 'output') {
214
+ let ask = asked;
215
+ let through = all.find((b)=>b.entity.eid == ask?.ask?.through);
216
+ if (through && all.some((b)=>seqOf(b) > seqOf(through) && kindOf(b) == 'input')) return 'pending';
217
+ return 'settled';
218
+ }
219
+ return served(all) ? 'pending' : 'running';
220
+ };
221
+ /** `session.status` for an in-memory store (@yaks/ram's `computed`): the rule
222
+ * above over the session's entries, as @yaks/sqlite derives it (./status.ts),
223
+ * so a query filtering on it answers alike in both. */ export let statusComputed = {
224
+ 'session.status': (s, among)=>statusOf(among.list.filter((b)=>b.entry?.session == s.entity.eid), marksOf(s))
225
+ };
226
+ /** A selected aspect at an entry, with late ask records bounded by their prefix. */ let aspectBefore = (entries, name, seq = Infinity)=>{
227
+ let all = ordered(entries).filter((b)=>seqOf(b) <= seq && name in b);
228
+ let latest = all.at(-1);
229
+ let ask = latest?.ask;
230
+ // An ask records what was served, not a choice: a selection made after that
231
+ // ask's context boundary outlives a reply recorded late.
232
+ let chosen = ask ? all.filter((b)=>!b.ask).at(-1) : undefined;
233
+ let through = chosen && entries.find((b)=>b.entity.eid == ask.through);
234
+ return (chosen && (!through || seqOf(chosen) > seqOf(through)) ? chosen : latest)?.[name];
235
+ };
236
+ /** What a transcript's lines selected to send, apart from what its asks
237
+ * recorded as sent: the `sending` of its newest line that is no ask. */ export let sendingSelected = (entries)=>ordered(entries).findLast((b)=>'sending' in b && !b.ask)?.sending;
238
+ /** The model selection in force at an entry: provider, model and effort. Why
239
+ * a router chose it (`using.why`) stays on the input it answered, so no ask,
240
+ * later input or child repeats a reason the plans have since outgrown. */ export let usingBefore = (entries, seq = Infinity)=>{
241
+ let using = aspectBefore(entries, USING, seq);
242
+ if (!using) return undefined;
243
+ let { why: _, ...selection } = using;
244
+ return selection;
245
+ };
246
+ /** What is sent, selected independently of who answers. */ export let sendingBefore = (entries, seq = Infinity)=>aspectBefore(entries, 'sending', seq);
247
+ //# sourceMappingURL=state.js.map
package/state.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","sources":["./state.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,2EAA2E;AAC3E,SAAqB,IAAI,2BAAgC;AAGzD,SAAS,mBAAmB,2BAAgC;AAC5D,SAAS,aAAa,8BAA6B;AACnD,SACE,GAAG,EACH,IAAI,EACJ,OAAO,EACP,SAAS,EACT,MAAM,EACN,OAAO,EACP,MAAM,EACN,UAAU,EACV,KAAK,sBACa;AAEpB,4DAA4D,GAC5D,OAAO,IAAI,eAAe,CACxB,MAEA,IAAI,WAAW,GACX,gBACA,AAAC,IAAI,OAAO,EAAuB,MAAM,OACzC,aACA,YAAW;AA2BjB;wBACwB,GACxB,OAAO,IAAI,UAAU,EAAC;AAEtB;;0EAE0E,GAC1E,OAAO,IAAI,QAAQ,QAAO;AAE1B,0EAA0E;AAC1E,QAAQ;AACR,IAAI,QAA0B;EAC5B;IAAC;IAAY;GAAO;EACpB;IAAC;IAAQ;GAAS;EAClB;IAAC;IAAiB;GAAS;EAC3B;IAAC;IAAW;GAAY;EACxB;IAAC;IAAS;GAAU;EACpB;IAAC;IAAK;GAAM;EACZ;IAAC;IAAM;GAAO;EACd;IAAC;IAAe;GAAc;EAC9B;IAAC;IAAa;GAAY;CAC3B;AAED;mEACmE,GACnE,OAAO,IAAI,SAAS,IAAgB,MAAM,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,IAAI,kBAAkB,CAAC,UAC5B,QAAQ,SAAS,QAAQ,CAAC,CAAC,IAAM,aAAa,KAAK,CAAC,EAAE,GAAG,GAAG,QAE/C;AAEf;;wEAEwE,GACxE,OAAO,IAAI,cAAc,CACvB,SACA,MAAM,QAAQ;EAEd,IAAI,QAAQ,aAAa,SAAS,OAAO;EACzC,IAAI,CAAC,OAAO,OAAO;EACnB,IAAI,EAAE,KAAK,CAAC,EAAE,GAAG,WAAW,GAAG;EAC/B,OAAO;AACT,EAAC;AAED,yDAAyD,GACzD,OAAO,IAAI,gBAAgB,CACzB,SACA,MAAM,QAAQ,GACO,aAAa,SAAS,WAAW,KAAI"}
package/state.ts ADDED
@@ -0,0 +1,404 @@
1
+ // Transcript state from entry bundles alone. Rendering and in-memory readers
2
+ // share this pure logic without loading SQL derivations or tool execution.
3
+ import { type Built, line } from '@yaks/query'
4
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
5
+ import type { Computed } from 'jsr:@yaks/match@0.2.36'
6
+ import { cachedPrefixExpires } from '@yaks/model'
7
+ import { stoppedNotice } from './claude-control.js'
8
+ import {
9
+ ASK,
10
+ CALL,
11
+ CONTENT,
12
+ EXCEPTION,
13
+ OUTPUT,
14
+ REFUSAL,
15
+ RESULT,
16
+ STOP_ENTRY,
17
+ USING,
18
+ } from './native.js'
19
+
20
+ /** A request is in flight while a holder owns its attempt. */
21
+ export let attemptState = (
22
+ ask: Bundle,
23
+ ): 'interrupted' | 'inflight' | 'completed' =>
24
+ ask.interrupted
25
+ ? 'interrupted'
26
+ : (ask.attempt as Comp | undefined)?.by != null
27
+ ? 'inflight'
28
+ : 'completed'
29
+
30
+ /** The kinds of entry: the component stored beside `entry`, or for prose,
31
+ * `output` when an `output` is stored beside it and `input` when none is.
32
+ * `reasoning` is what a model said of its reasoning beside a reply: neither
33
+ * the reply nor anyone's words. */
34
+ export type Kind =
35
+ | 'input'
36
+ | 'reasoning'
37
+ | 'ask'
38
+ | 'call'
39
+ | 'output'
40
+ | 'result'
41
+ | 'stop'
42
+ | 'refusal'
43
+ | 'interrupted'
44
+ | 'exception'
45
+
46
+ /** What a transcript is doing. */
47
+ export type TranscriptStatus =
48
+ | 'empty'
49
+ | 'pending'
50
+ | 'running'
51
+ | 'settled'
52
+ | 'stopped'
53
+ | 'failed'
54
+
55
+ /** How many consecutive interrupted requests the runner retries through before it leaves a
56
+ * transcript `failed`. */
57
+ export let RETRIES = 3
58
+
59
+ /** The error code of a request refused at a ceiling (a spending allowance, a
60
+ * quota): final rather than retried, since the next ask meets the same
61
+ * ceiling. The transcript is `failed` until something new is said to it. */
62
+ export let LIMIT = 'limit'
63
+
64
+ // A result is a result even when it carries the refusal that answered its
65
+ // call.
66
+ let KINDS: [string, Kind][] = [
67
+ [STOP_ENTRY, 'stop'],
68
+ [RESULT, 'result'],
69
+ ['tool_progress', 'result'],
70
+ [EXCEPTION, 'exception'],
71
+ [REFUSAL, 'refusal'],
72
+ [ASK, 'ask'],
73
+ [CALL, 'call'],
74
+ ['interrupted', 'interrupted'],
75
+ ['reasoning', 'reasoning'],
76
+ ]
77
+
78
+ /** The components that make an entry a kind ({@link kindOf}): a line
79
+ * carrying none of them, with prose and no `output`, is an input. */
80
+ export let kinded = (): string[] => KINDS.map(([c]) => c)
81
+
82
+ /** The components that make an entry a kind ranked before `kind`
83
+ * ({@link kindOf}), whatever else it carries: a stop naming the request it
84
+ * answers (`ask.through`) is a stop, not an ask. */
85
+ export let outranking = (kind: Kind): string[] =>
86
+ KINDS.slice(0, KINDS.findIndex(([, k]) => k == kind)).map(([c]) => c)
87
+
88
+ let content = (b: Bundle) => b[CONTENT] as Comp | undefined
89
+
90
+ /** The ask an entry's prose came from, when a model returned it. */
91
+ export let sourceOf = (b: Bundle): string | undefined => {
92
+ let s = (b[OUTPUT] as Comp | undefined)?.source
93
+ return s == null ? undefined : String(s)
94
+ }
95
+
96
+ /** Which kind of entry a bundle is, or `undefined` for one carrying none of
97
+ * the kind components and no prose. */
98
+ export let kindOf = (b: Bundle): Kind | undefined =>
99
+ stoppedNotice(b) ? 'stop' : KINDS.find(([comp]) => comp in b)?.[1] ??
100
+ (OUTPUT in b ? 'output' : content(b) ? 'input' : undefined)
101
+
102
+ /** The seq of an entry bundle. */
103
+ export let seqOf = (b: Bundle): number => Number((b.entry as Comp)?.seq ?? 0)
104
+
105
+ /** The prose of an entry: its `content.body`, or nothing. */
106
+ export let textOf = (b: Bundle): string => String(content(b)?.body ?? '')
107
+
108
+ /** Entries in transcript order. */
109
+ export let ordered = (entries: Bundle[]): Bundle[] =>
110
+ entries.toSorted((a, b) => seqOf(a) - seqOf(b))
111
+
112
+ /** The newest `ask` of a transcript: the model turn in force. */
113
+ export let newestAsk = (entries: Bundle[]): Bundle | undefined =>
114
+ ordered(entries).findLast((b) => kindOf(b) == 'ask')
115
+
116
+ // When the prefix a session's newest ask cached leaves its provider's prompt
117
+ // cache (its provider component's `cache_expires_at`, @yaks/model
118
+ // `cachedPrefixExpires`). Unknown for an ask of another transcript, one not
119
+ // answered, or one whose provider records no expiry.
120
+ let expiry = (entries: Bundle[], session: string): number | undefined => {
121
+ let ask = newestAsk(entries)
122
+ if (!ask || (ask.entry as Comp | undefined)?.session != session) return
123
+ let expires = cachedPrefixExpires(ask)
124
+ return expires ? Date.parse(expires) : undefined
125
+ }
126
+
127
+ /** What a session's newest ask sent (its `sending`, which names its
128
+ * instructions), while the prefix it cached is still in the provider's prompt
129
+ * cache. An ask whose expiry is unknown keeps none. */
130
+ export let cachedSending = (
131
+ entries: Bundle[],
132
+ session: string,
133
+ now: number = Date.now(),
134
+ ): Comp | undefined =>
135
+ (expiry(entries, session) ?? -Infinity) > now
136
+ ? newestAsk(entries)?.sending as Comp | undefined
137
+ : undefined
138
+
139
+ /** Whether the prefix a session's newest ask cached is known to have expired,
140
+ * so the next request pays for its whole context whatever it sends. An
141
+ * unknown expiry is not cold: nothing says the cache is gone. */
142
+ export let cold = (
143
+ entries: Bundle[],
144
+ session: string,
145
+ now: number = Date.now(),
146
+ ): boolean => (expiry(entries, session) ?? Infinity) <= now
147
+
148
+ // Give provider clocks and retention estimates one extra minute before
149
+ // rewriting a prompt. The recorded expiry is specific to the dispatched ask.
150
+ export let pastCache = (
151
+ entries: Bundle[],
152
+ session: string,
153
+ now: number = Date.now(),
154
+ ): boolean => cold(entries, session, now - 60_000)
155
+
156
+ let sessionOf = (b: Bundle | undefined) =>
157
+ (b?.entry as Comp | undefined)?.session
158
+
159
+ // A fork inherits the prefix as history. A call there can still be open at
160
+ // the fork point and finish later in its own transcript.
161
+ let ownCalls = (all: Bundle[]) => {
162
+ let session = sessionOf(all.at(-1))
163
+ return all.filter((b) => kindOf(b) == 'call' && sessionOf(b) == session)
164
+ }
165
+
166
+ let callsIn = (all: Bundle[]): Bundle[] => {
167
+ let answered = new Set(
168
+ all.filter((b) => RESULT in b)
169
+ .map((b) => String((b[RESULT] as Comp)?.call)),
170
+ )
171
+ return ownCalls(all).filter((b) => !answered.has(b.entity.eid))
172
+ }
173
+
174
+ /** The calls that no result answers — what the runner runs next, and what
175
+ * keeps a transcript running past the prose the model returned beside them. */
176
+ export let openCalls = (entries: Bundle[]): Bundle[] =>
177
+ callsIn(ordered(entries))
178
+
179
+ /** Whether something new has arrived beyond the newest request's context
180
+ * boundary for the model to take a turn on. An input asks at once. A result,
181
+ * or the Pending entry a call of the newest reply is given when it outlasts
182
+ * its patience (./react.ts `PATIENCE`), asks once each background call of that
183
+ * reply has answered or outlasted it: the model asked for them together. A
184
+ * background call alone asks nothing more of the model, and the Pending of an
185
+ * older reply's call never asks again: a later request already sent it as
186
+ * pending. This says the model owes work independently of tools running. */
187
+ export let modelReady = (entries: Bundle[]): boolean => {
188
+ let all = ordered(entries).filter((b) => !b.notice)
189
+ let ask = newestAsk(all)
190
+ let through = all.find((b) =>
191
+ b.entity.eid == (ask?.ask as Comp | undefined)?.through
192
+ )
193
+ let boundary = through ? seqOf(through) : ask ? seqOf(ask) : 0
194
+ let reply = all.filter((b) =>
195
+ !!ask && !!b.tool_async &&
196
+ (b.call as Comp | undefined)?.source == ask.entity.eid
197
+ )
198
+ let calls = new Set(reply.map((b) => b.entity.eid))
199
+ let heard = new Set(all.flatMap((b) => {
200
+ let call = (b.result as Comp | undefined)?.call ??
201
+ (b.tool_progress as Comp | undefined)?.call
202
+ return call == null ? [] : [String(call)]
203
+ }))
204
+ let together = reply.every((b) => heard.has(b.entity.eid))
205
+ return all.some((b) =>
206
+ seqOf(b) > boundary && (
207
+ kindOf(b) == 'input' || together && (
208
+ !!b.result ||
209
+ !!b.tool_progress && calls.has(String((b.tool_progress as Comp).call))
210
+ )
211
+ )
212
+ )
213
+ }
214
+
215
+ // An anonymous claim belongs to the process that made it. If that process
216
+ // vanished before answering, the session runner recovers it without replay.
217
+ let abandoned = (calls: Bundle[]): boolean =>
218
+ calls.some((b) => {
219
+ let execution = b.execution as Comp | undefined
220
+ return !!execution && execution.by == null && !b.interrupted
221
+ })
222
+
223
+ /** A transcript the runner answers: one that asked it, by a request or a turn
224
+ * it took. A turn read from a harness's file (`lines`) is that harness's, which
225
+ * answers its own transcript. */
226
+ export let served = (entries: Bundle[]): boolean =>
227
+ entries.some((b) => USING in b || (ASK in b && !('lines' in b)))
228
+
229
+ /** The transcripts a runner is working on: the ones the session cap counts
230
+ * and a restart wakes. That is a transcript the runner answers ({@link served})
231
+ * with something outstanding. An empty session has nothing to run, and one run
232
+ * outside the graph reads `running` while its own runner owes the answer; a
233
+ * graph holds thousands of both (every session a harness's hooks recorded).
234
+ * Unlike `served`, a model chosen by a notice counts as asking. */
235
+ export let live: Built =
236
+ line`.session.status=pending,running,queued (.entries.using|.entries.ask)`
237
+
238
+ /** What the entries leave owing. `session.ended` turns only these into `stopped`:
239
+ * a transcript that settled, failed or never began keeps reading that way. */
240
+ export let UNFINISHED = ['pending', 'running', 'queued']
241
+
242
+ /** What a session's own row says beside its entries: `ended`, its
243
+ * `session.ended` mark, and `process`, a process of its own running it (a
244
+ * @yaks/process `process` with no `exit` yet, as a spawned CLI run wears). */
245
+ export type Marks = { ended?: boolean; process?: boolean }
246
+
247
+ /** The {@link Marks} a session row wears. */
248
+ export let marksOf = (row: Bundle | undefined): Marks => ({
249
+ ended: (row?.session as Comp | undefined)?.ended == true,
250
+ process: !!row?.process && row.exit == null,
251
+ })
252
+
253
+ /** The status of a transcript, from its entries in any order and the marks
254
+ * its row wears. A process of its own owes whatever the entries leave owing,
255
+ * so it reads `running` where they say `pending`, never the runner's to
256
+ * answer; once it exits, its ending (@yaks/spawn) is an entry like any. */
257
+ export let statusOf = (
258
+ entries: Bundle[],
259
+ { ended = false, process = false }: Marks = {},
260
+ ): TranscriptStatus => {
261
+ let status = entriesSay(entries)
262
+ if (ended && UNFINISHED.includes(status)) return 'stopped'
263
+ return process && status == 'pending' ? 'running' : status
264
+ }
265
+
266
+ let entriesSay = (entries: Bundle[]): TranscriptStatus => {
267
+ // A thought says nothing of where the work stands.
268
+ let all = ordered(entries).filter((b) =>
269
+ (!b.notice || stoppedNotice(b)) && !b.reasoning
270
+ )
271
+ let newest = all.at(-1)
272
+ if (!newest) return 'empty'
273
+ let kind = kindOf(newest)
274
+ // Finishing a step already admitted before a stop does not resume work.
275
+ // Only fresh input can reopen the transcript.
276
+ let control = all.findLast((b) => ['input', 'stop'].includes(kindOf(b) ?? ''))
277
+ if (kindOf(control ?? newest) == 'stop') return 'stopped'
278
+ let asked = all.findLast((b) => kindOf(b) == 'ask')
279
+ let turn = all.filter((b) => !asked || seqOf(b) >= seqOf(asked))
280
+ // A background call's Pending answers the provider protocol, but only its
281
+ // result answers the work. Unlike legacy synchronous calls, background calls
282
+ // can outlive many asks, and asks while they run only for something new.
283
+ let calls = callsIn(turn).filter((b) => !b.tool_async)
284
+ let pending = callsIn(all).some((b) => b.tool_async)
285
+ let background = ownCalls(all).some((b) => b.tool_async)
286
+ if (abandoned(calls)) return 'running'
287
+ if (kind == 'exception') return 'failed'
288
+ if (kind == 'interrupted' && newest.failed && !newest.ask && !newest.call) {
289
+ return 'failed'
290
+ }
291
+ if (turn.some((b) => attemptState(b) == 'inflight')) {
292
+ return 'running'
293
+ }
294
+ let afterAsk = (ask = asked) => {
295
+ return ask && all.some((b) => seqOf(b) > seqOf(ask) && kindOf(b) == 'input')
296
+ ? 'pending'
297
+ : 'failed'
298
+ }
299
+ if (kind == 'refusal') {
300
+ let source = (newest.output as Comp | undefined)?.source
301
+ let ask = all.find((b) => b.entity.eid == source && kindOf(b) == 'ask')
302
+ return ask ? afterAsk(ask) : 'failed'
303
+ }
304
+ let interrupted = asked
305
+ if (interrupted?.interrupted) {
306
+ if (
307
+ interrupted.failed &&
308
+ !all.some((b) => kindOf(b) == 'input' && seqOf(b) > seqOf(interrupted))
309
+ ) return 'failed'
310
+ if (
311
+ all.some((b) => kindOf(b) == 'input' && seqOf(b) > seqOf(interrupted))
312
+ ) {
313
+ return 'pending'
314
+ }
315
+ if (interrupted.provisional) return 'pending'
316
+ let turns = all.filter((b) => b.ask || kindOf(b) == 'input').slice(
317
+ -RETRIES,
318
+ )
319
+ return turns.length == RETRIES && turns.every((b) => b.ask && b.interrupted)
320
+ ? 'failed'
321
+ : 'pending'
322
+ }
323
+ if (calls.length) return 'running'
324
+ if (background && modelReady(all)) return 'pending'
325
+ if (pending) return 'running'
326
+ // An ask with no attempt is a line a harness wrote before the rest of its
327
+ // reply: the turn runs on.
328
+ if (
329
+ kind == 'ask' && newest.attempt && attemptState(newest) == 'completed'
330
+ ) return 'settled'
331
+ if (kind == 'ask' || kind == 'call') return 'running'
332
+ // Inputs can be admitted while a provider request is in flight. Its reply
333
+ // does not acknowledge messages after that request's recorded boundary.
334
+ if (kind == 'output') {
335
+ let ask = asked
336
+ let through = all.find((b) => b.entity.eid == (ask?.ask as Comp)?.through)
337
+ if (
338
+ through && all.some((b) =>
339
+ seqOf(b) > seqOf(through) &&
340
+ kindOf(b) == 'input'
341
+ )
342
+ ) return 'pending'
343
+ return 'settled'
344
+ }
345
+ return served(all) ? 'pending' : 'running'
346
+ }
347
+
348
+ /** `session.status` for an in-memory store (@yaks/ram's `computed`): the rule
349
+ * above over the session's entries, as @yaks/sqlite derives it (./status.ts),
350
+ * so a query filtering on it answers alike in both. */
351
+ export let statusComputed: Computed = {
352
+ 'session.status': (s, among) =>
353
+ statusOf(
354
+ among.list.filter((b) =>
355
+ (b.entry as Comp | undefined)?.session == s.entity.eid
356
+ ),
357
+ marksOf(s),
358
+ ),
359
+ }
360
+
361
+ /** A selected aspect at an entry, with late ask records bounded by their prefix. */
362
+ let aspectBefore = (
363
+ entries: Bundle[],
364
+ name: string,
365
+ seq = Infinity,
366
+ ): Comp | undefined => {
367
+ let all = ordered(entries).filter((b) => seqOf(b) <= seq && name in b)
368
+ let latest = all.at(-1)
369
+ let ask = latest?.ask as Comp | undefined
370
+ // An ask records what was served, not a choice: a selection made after that
371
+ // ask's context boundary outlives a reply recorded late.
372
+ let chosen = ask ? all.filter((b) => !b.ask).at(-1) : undefined
373
+ let through = chosen &&
374
+ entries.find((b) => b.entity.eid == ask!.through)
375
+ return (chosen && (!through || seqOf(chosen) > seqOf(through))
376
+ ? chosen
377
+ : latest)?.[name] as Comp | undefined
378
+ }
379
+
380
+ /** What a transcript's lines selected to send, apart from what its asks
381
+ * recorded as sent: the `sending` of its newest line that is no ask. */
382
+ export let sendingSelected = (entries: Bundle[]): Comp | undefined =>
383
+ ordered(entries).findLast((b) => 'sending' in b && !b.ask)?.sending as
384
+ | Comp
385
+ | undefined
386
+
387
+ /** The model selection in force at an entry: provider, model and effort. Why
388
+ * a router chose it (`using.why`) stays on the input it answered, so no ask,
389
+ * later input or child repeats a reason the plans have since outgrown. */
390
+ export let usingBefore = (
391
+ entries: Bundle[],
392
+ seq = Infinity,
393
+ ): Comp | undefined => {
394
+ let using = aspectBefore(entries, USING, seq)
395
+ if (!using) return undefined
396
+ let { why: _, ...selection } = using
397
+ return selection
398
+ }
399
+
400
+ /** What is sent, selected independently of who answers. */
401
+ export let sendingBefore = (
402
+ entries: Bundle[],
403
+ seq = Infinity,
404
+ ): Comp | undefined => aspectBefore(entries, 'sending', seq)