@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
@@ -0,0 +1,110 @@
1
+ // Find work a resting transcript can do instead of waiting for an unattended
2
+ // dependency. Decisions, explicit outside blockers and a person's queue remain
3
+ // external waits; an agent's queue is work the transcript can take.
4
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
5
+ import { token } from '@yaks/graph/sha256'
6
+ import { dependencies, settled, statusOf } from '@yaks/task'
7
+ import { currentStatus } from './react.js'
8
+
9
+ let comp = (b: Bundle | undefined, name: string) =>
10
+ b?.[name] as Comp | undefined
11
+
12
+ export type Work = {
13
+ tasks: Bundle[]
14
+ claims: Bundle[]
15
+ problems: string[]
16
+ resume: Map<Eid, Bundle[]>
17
+ release: Eid[]
18
+ }
19
+
20
+ let external = async (g: Graph, row: Bundle) => {
21
+ if (row.decision || row.blocked) return true
22
+ let assignee = comp(row, 'filed')?.assignee
23
+ return !!assignee && !!g.vocab.comp('person') &&
24
+ !!(await g.get([String(assignee)], ['person']))[0]?.person
25
+ }
26
+
27
+ /** Follow unfinished dependencies to their runnable leaves. Other active
28
+ * workers keep their work; missing or terminal holders can be replaced. */
29
+ export let unattended = async (
30
+ g: Graph,
31
+ session: Eid,
32
+ roots: Bundle[],
33
+ ): Promise<Work> => {
34
+ let found: Work = {
35
+ tasks: [],
36
+ claims: [],
37
+ problems: [],
38
+ resume: new Map(),
39
+ release: [],
40
+ }
41
+ let seen = new Set<Eid>()
42
+ let visit = async (eid: Eid, path: Eid[]): Promise<void> => {
43
+ if (path.includes(eid)) {
44
+ found.problems.push(`Dependency cycle: ${[...path, eid].join(' -> ')}`)
45
+ return
46
+ }
47
+ if (seen.has(eid)) return
48
+ seen.add(eid)
49
+ let [row] = await g.get([eid])
50
+ if (!row?.task) {
51
+ found.problems.push(`Dependency ${eid} is missing or is not a task`)
52
+ return
53
+ }
54
+ if (settled(statusOf(g.vocab, row)) || await external(g, row)) return
55
+ let holder = comp(row, 'claim')?.session
56
+ let [owner] = holder && holder != session
57
+ ? await g.get([String(holder)], ['session', 'process', 'exit', 'stop'])
58
+ : []
59
+ // Wrapping a managed run marks the session ended before its process exits.
60
+ // Its process remains the authority, including while it is winding down.
61
+ if (owner?.session && owner.process && !owner.exit) return
62
+ let ended = !owner?.process && comp(owner, 'session')?.ended === true ||
63
+ !!owner?.stop
64
+ let status = owner?.session && !owner.process
65
+ ? await currentStatus(g, String(holder))
66
+ : undefined
67
+ let abandoned = !owner?.session || ended ||
68
+ status == 'failed' || status == 'stopped' ||
69
+ !!owner?.exit && comp(owner, 'exit')?.code !== 0
70
+ if (holder && holder != session && abandoned) {
71
+ // Claim release owns this transition. Never overwrite another holder,
72
+ // including one whose terminal entry has not been reconciled yet.
73
+ found.release.push(eid)
74
+ return
75
+ }
76
+ if (holder && holder != session && !abandoned) {
77
+ // A running/queued worker owns its whole dependency chain. A resting
78
+ // worker's leaves are inspected too, so nested parking cannot hide work.
79
+ if (owner?.process ? !owner.exit : status != 'settled') return
80
+ }
81
+ let kids = await dependencies(g, eid)
82
+ let open = []
83
+ for (let kid of kids) {
84
+ let [child] = await g.get([kid])
85
+ if (!child || !settled(statusOf(g.vocab, child))) open.push(kid)
86
+ }
87
+ if (open.length) {
88
+ for (let kid of open) await visit(kid, [...path, eid])
89
+ return
90
+ }
91
+ if (holder && holder != session && !abandoned) {
92
+ let tasks = found.resume.get(String(holder)) ?? []
93
+ tasks.push(row)
94
+ found.resume.set(String(holder), tasks)
95
+ return
96
+ }
97
+ found.tasks.push(row)
98
+ found.claims.push({
99
+ entity: row.entity,
100
+ claim: { session },
101
+ $was: { claim: { session: token(holder) } },
102
+ })
103
+ }
104
+ for (let root of roots) {
105
+ for (let dep of await dependencies(g, root.entity.eid)) {
106
+ await visit(dep, [root.entity.eid])
107
+ }
108
+ }
109
+ return found
110
+ }
package/draining.js ADDED
@@ -0,0 +1,20 @@
1
+ import { system } from "@yaks/fp";
2
+ /** A worker kept its current step through the shutdown grace. The next
3
+ * worker recovers the admitted request from the transcript. */ export class StepHandoff extends Error {
4
+ constructor(){
5
+ super('Worker is handing its session step back');
6
+ }
7
+ }
8
+ /** Stop a step after a short grace for its reply to land. */ export let draining = (stop, step, clock = system)=>{
9
+ let cancel = ()=>{};
10
+ let leave = ()=>cancel = clock.after(10_000, ()=>step.abort(new StepHandoff()));
11
+ stop?.addEventListener('abort', leave, {
12
+ once: true
13
+ });
14
+ if (stop?.aborted) leave();
15
+ return ()=>{
16
+ stop?.removeEventListener('abort', leave);
17
+ cancel();
18
+ };
19
+ };
20
+ //# sourceMappingURL=draining.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"draining.js","sources":["./draining.ts"],"names":[],"mappings":"AAAA,SAAqB,MAAM,wBAA6B;AAExD;6DAC6D,GAC7D,OAAO,MAAM,oBAAoB;EAC/B,aAAc;IACZ,KAAK,CAAC;EACR;AACF;AAEA,2DAA2D,GAC3D,OAAO,IAAI,WAAW,CACpB,MACA,MACA,QAAe,MAAM;EAErB,IAAI,SAAS,KAAO;EACpB,IAAI,QAAQ,IACV,SAAS,MAAM,KAAK,CAAC,QAAQ,IAAM,KAAK,KAAK,CAAC,IAAI;EACpD,MAAM,iBAAiB,SAAS,OAAO;IAAE,MAAM;EAAK;EACpD,IAAI,MAAM,SAAS;EACnB,OAAO;IACL,MAAM,oBAAoB,SAAS;IACnC;EACF;AACF,EAAC"}
package/draining.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { type Clock, system } from '@yaks/fp'
2
+
3
+ /** A worker kept its current step through the shutdown grace. The next
4
+ * worker recovers the admitted request from the transcript. */
5
+ export class StepHandoff extends Error {
6
+ constructor() {
7
+ super('Worker is handing its session step back')
8
+ }
9
+ }
10
+
11
+ /** Stop a step after a short grace for its reply to land. */
12
+ export let draining = (
13
+ stop: AbortSignal | undefined,
14
+ step: AbortController,
15
+ clock: Clock = system,
16
+ ) => {
17
+ let cancel = () => {}
18
+ let leave = () =>
19
+ cancel = clock.after(10_000, () => step.abort(new StepHandoff()))
20
+ stop?.addEventListener('abort', leave, { once: true })
21
+ if (stop?.aborted) leave()
22
+ return () => {
23
+ stop?.removeEventListener('abort', leave)
24
+ cancel()
25
+ }
26
+ }
package/ended.js ADDED
@@ -0,0 +1,210 @@
1
+ // A session is live until it has `session.ended`, so a page of live sessions is
2
+ // a presence test and never reads an entry. An outside harness's session has no
3
+ // entry to say it is over when its process dies: a crash writes no SessionEnd,
4
+ // and a log read again can leave a model request newest, which reads `running`
5
+ // for good. So the mark is written here, from what the computer says runs now.
6
+ // Only what its entries leave unfinished reads `stopped` for it (`statusOf`),
7
+ // and its claims go with it (`session_release`).
8
+ //
9
+ // A session the harness moved on from reads as gone too, since the running
10
+ // process no longer names it; resuming it clears the mark (`session_context`).
11
+ // A subagent also ends once its log has been quiet, while the session it ran
12
+ // under goes on. A managed run is left to its own `exit` (@yaks/process). A
13
+ // session with no transcript file has no process here to ask about, so it is
14
+ // over once it has been quiet, a day if its turn is unfinished. A claim keeps
15
+ // it only mid-turn or while it is parked there (./wake.ts); otherwise the claim
16
+ // goes with the mark. A wake still to fire that reaches it keeps it too
17
+ // (./woken.ts `awaited`): a session that stays on a topic rests a day between
18
+ // turns and is not over. Anything new said to it clears the mark (./reopen.ts).
19
+ import { line } from "@yaks/query";
20
+ import * as fs from "@yaks/file/io";
21
+ import { TOMBSTONE } from "@yaks/graph/bundle";
22
+ import { absolute } from "@yaks/file/local";
23
+ import { runs } from "@yaks/process";
24
+ import { CLAIM, SESSION } from "./comp.js";
25
+ import { versionOf } from "./files.js";
26
+ import { UNFINISHED } from "./state.js";
27
+ import { parked } from "./wake.js";
28
+ import { awaited } from "./woken.js";
29
+ // A log this recent may belong to a process that has yet to list itself.
30
+ let SETTLING = 5 * 60 * 1000;
31
+ // A log with no process to ask about counts as over when this quiet.
32
+ let QUIET = 2 * 60 * 60 * 1000;
33
+ // A turn still owed an answer may be a long tool call, so it waits longer.
34
+ let STALLED = 24 * 60 * 60 * 1000;
35
+ let BATCH = 50;
36
+ let comp = (b, name)=>b?.[name] ?? {};
37
+ /** The session ids Claude's processes run now, from the files in `dir`, one per
38
+ * process. A file outlives a crash, so its pid is asked too. Nothing where
39
+ * there is no such directory, so a computer without one ends nothing. */ export let runningSessions = async (dir, alive = runs)=>{
40
+ let names;
41
+ try {
42
+ names = [
43
+ ...fs.readDirSync(dir)
44
+ ].map((f)=>f.name);
45
+ } catch (e) {
46
+ if (fs.isNotFound(e)) return undefined;
47
+ throw e;
48
+ }
49
+ let ids = new Set();
50
+ for (let name of names.filter((n)=>n.endsWith('.json'))){
51
+ let text;
52
+ try {
53
+ text = fs.readTextFileSync(`${dir}/${name}`);
54
+ } catch (e) {
55
+ if (fs.isNotFound(e)) continue; // it just ended
56
+ throw e;
57
+ }
58
+ let { pid, sessionId } = JSON.parse(text);
59
+ if (!pid || !sessionId) throw new Error(`${name} names no running session`);
60
+ if (await alive(Number(pid))) ids.add(String(sessionId));
61
+ }
62
+ return ids;
63
+ };
64
+ let mtime = (path)=>{
65
+ try {
66
+ return fs.statSync(path).mtime?.getTime();
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ };
71
+ // Quiet since `cutoff`, and every line of it imported. A compressed log's lines
72
+ // can't be counted here: the importer says it reached the end of this version.
73
+ // The second stat closes a race with a harness appending during the read.
74
+ let endedFile = (path, read, cutoff)=>{
75
+ try {
76
+ let before = fs.statSync(path);
77
+ if (!before.isFile || (before.mtime?.getTime() ?? Infinity) > cutoff) {
78
+ return false;
79
+ }
80
+ if (path.endsWith('.zst')) return read.finished == versionOf(before);
81
+ let consumed = Number(read.consumed);
82
+ let bytes = fs.readFileSync(path);
83
+ let after = fs.statSync(path);
84
+ if (before.size != after.size || before.mtime?.getTime() != after.mtime?.getTime() || bytes.at(-1) != 10) return false;
85
+ let lines = 0;
86
+ for (let byte of bytes)if (byte == 10) lines++;
87
+ return lines == consumed;
88
+ } catch {
89
+ return false;
90
+ }
91
+ };
92
+ // Nothing has been written to this session since `cutoff`.
93
+ let quiet = async (g, b, cutoff)=>{
94
+ let [last] = await g.rows(line`.entry.session=${b.entity.eid}&.order=-entry.seq&.limit=1&.fields=created.at`);
95
+ let at = last?.['created.at'] ?? comp(b, 'created').at;
96
+ return Date.parse(String(at)) <= cutoff;
97
+ };
98
+ /** The sessions {@link endGone} would mark, without marking them. */ export let goneSessions = async (g, o = {})=>{
99
+ let now = o.now ?? Date.now();
100
+ let accounts = await Promise.all((o.claude ?? []).map(async (a)=>({
101
+ projects: `${a.projects}/`,
102
+ live: await runningSessions(a.running, o.alive)
103
+ })));
104
+ let open = await g.read(line`.${SESSION} !${SESSION}.ended .fields=entity.eid`);
105
+ let held = await g.read(line`.${CLAIM}.session .fields=${CLAIM}.session`);
106
+ let parts = [
107
+ SESSION,
108
+ 'spawned',
109
+ 'process',
110
+ 'exit',
111
+ 'created'
112
+ ];
113
+ let rows = new Map();
114
+ let read = async (eids)=>{
115
+ let wanted = eids.filter((eid)=>!rows.has(eid));
116
+ if (!wanted.length) return;
117
+ for (let b of (await g.get(wanted, parts))){
118
+ if (b && b[TOMBSTONE] == null) rows.set(b.entity.eid, b);
119
+ }
120
+ };
121
+ let holding = new Set(held.map((b)=>String(comp(b, CLAIM).session)));
122
+ let coming = await awaited(g);
123
+ await read([
124
+ ...new Set([
125
+ ...open.map((b)=>b.entity.eid),
126
+ ...holding
127
+ ])
128
+ ]);
129
+ // A subagent runs in the process of the session at the top of its line.
130
+ let root = async (b)=>{
131
+ let seen = new Set();
132
+ while(true){
133
+ let parent = String(comp(b, 'spawned').parent ?? '');
134
+ if (!parent || seen.has(parent)) return b;
135
+ seen.add(parent);
136
+ await read([
137
+ parent
138
+ ]);
139
+ if (!rows.has(parent)) return b;
140
+ b = rows.get(parent);
141
+ }
142
+ };
143
+ let gone = [];
144
+ for (let b of [
145
+ ...rows.values()
146
+ ]){
147
+ let s = comp(b, SESSION);
148
+ if (!b[SESSION] || s.ended == true) continue;
149
+ let eid = b.entity.eid;
150
+ let owes = UNFINISHED.includes(String(s.status));
151
+ let rests = !owes && !holding.has(eid);
152
+ if (b.process) {
153
+ if (b.exit && (rests || owes && s.transcript)) gone.push(eid);
154
+ continue;
155
+ }
156
+ let [file] = s.transcript ? await g.get([
157
+ String(s.transcript)
158
+ ]) : [];
159
+ let path = file && await absolute(g, file);
160
+ // No log to ask about: quiet says it. A wake coming to it keeps it, and
161
+ // what it holds does only while its turn is unfinished or it is parked
162
+ // there.
163
+ if (!path) {
164
+ let keeps = coming.has(eid) || holding.has(eid) && (owes || await parked(g, eid));
165
+ if (!keeps && await quiet(g, b, now - (owes ? STALLED : QUIET))) {
166
+ gone.push(eid);
167
+ }
168
+ continue;
169
+ }
170
+ let account = accounts.find((a)=>path.startsWith(a.projects));
171
+ if (account) {
172
+ let live = account.live;
173
+ if (!live || (mtime(path) ?? 0) > now - SETTLING) continue;
174
+ let id = String(comp(await root(b), SESSION).id ?? '');
175
+ // A subagent finishes long before the process it ran in.
176
+ let finished = comp(b, 'spawned').parent && !holding.has(eid) && (mtime(path) ?? 0) <= now - QUIET;
177
+ if (!live.has(id) || finished) gone.push(eid);
178
+ } else if (endedFile(path, comp(file, 'transcript'), now - QUIET)) gone.push(eid);
179
+ }
180
+ return gone;
181
+ };
182
+ /**
183
+ * Write `session.ended` on every session whose process is gone or, with no
184
+ * process to ask about, that has come to rest, and answer with their eids.
185
+ * `claude` names each Claude Code account's transcripts and the directory where
186
+ * it lists its processes. It is an observation, not an edit, so `updated` stays as it was.
187
+ *
188
+ * ```ts
189
+ * import { endGone } from '@yaks/session/ended'
190
+ *
191
+ * // await endGone(graph, { claude: [{ projects, running }] })
192
+ * ```
193
+ */ export let endGone = async (g, o = {})=>{
194
+ let gone = await goneSessions(g, o);
195
+ for(let i = 0; i < gone.length; i += BATCH){
196
+ await g.apply(gone.slice(i, i + BATCH).map((eid)=>({
197
+ entity: {
198
+ eid
199
+ },
200
+ [SESSION]: {
201
+ ended: true
202
+ }
203
+ })), {
204
+ trusted: true,
205
+ stamp: false
206
+ });
207
+ }
208
+ return gone;
209
+ };
210
+ //# sourceMappingURL=ended.js.map
package/ended.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ended.js","sources":["./ended.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,gFAAgF;AAChF,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,iDAAiD;AACjD,EAAE;AACF,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,4EAA4E;AAC5E,6EAA6E;AAC7E,8EAA8E;AAC9E,gFAAgF;AAChF,wEAAwE;AACxE,8EAA8E;AAC9E,gFAAgF;AAEhF,SAAS,IAAI,2BAAgC;AAC7C,YAAY,6BAAkC;AAG9C,SAAS,SAAS,kCAAuC;AACzD,SAAS,QAAQ,gCAAqC;AACtD,SAAS,IAAI,6BAAkC;AAC/C,SAAS,KAAK,EAAE,OAAO,oBAAmB;AAC1C,SAAS,SAAS,qBAAoB;AACtC,SAAS,UAAU,qBAAoB;AACvC,SAAS,MAAM,oBAAmB;AAClC,SAAS,OAAO,qBAAoB;AAEpC,yEAAyE;AACzE,IAAI,WAAW,IAAI,KAAK;AACxB,qEAAqE;AACrE,IAAI,QAAQ,IAAI,KAAK,KAAK;AAC1B,2EAA2E;AAC3E,IAAI,UAAU,KAAK,KAAK,KAAK;AAC7B,IAAI,QAAQ;AAEZ,IAAI,OAAO,CAAC,GAAuB,OAAkB,GAAG,CAAC,KAAK,IAAI,CAAC;AAEnE;;uEAEuE,GACvE,OAAO,IAAI,kBAAkB,OAC3B,KACA,QAA2C,IAAI;EAE/C,IAAI;EACJ,IAAI;IACF,QAAQ;SAAI,GAAG,WAAW,CAAC;KAAK,CAAC,GAAG,CAAC,CAAC,IAAM,EAAE,IAAI;EACpD,EAAE,OAAO,GAAG;IACV,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Q,CAAC;QACrC,QAAQ;UAAE;QAAI;QACd,CAAC,QAAQ,EAAE;UAAE,OAAO;QAAK;MAC3B,CAAC,IACD;MAAE,SAAS;MAAM,OAAO;IAAM;EAElC;EACA,OAAO;AACT,EAAC"}
package/ended.ts ADDED
@@ -0,0 +1,225 @@
1
+ // A session is live until it has `session.ended`, so a page of live sessions is
2
+ // a presence test and never reads an entry. An outside harness's session has no
3
+ // entry to say it is over when its process dies: a crash writes no SessionEnd,
4
+ // and a log read again can leave a model request newest, which reads `running`
5
+ // for good. So the mark is written here, from what the computer says runs now.
6
+ // Only what its entries leave unfinished reads `stopped` for it (`statusOf`),
7
+ // and its claims go with it (`session_release`).
8
+ //
9
+ // A session the harness moved on from reads as gone too, since the running
10
+ // process no longer names it; resuming it clears the mark (`session_context`).
11
+ // A subagent also ends once its log has been quiet, while the session it ran
12
+ // under goes on. A managed run is left to its own `exit` (@yaks/process). A
13
+ // session with no transcript file has no process here to ask about, so it is
14
+ // over once it has been quiet, a day if its turn is unfinished. A claim keeps
15
+ // it only mid-turn or while it is parked there (./wake.ts); otherwise the claim
16
+ // goes with the mark. A wake still to fire that reaches it keeps it too
17
+ // (./woken.ts `awaited`): a session that stays on a topic rests a day between
18
+ // turns and is not over. Anything new said to it clears the mark (./reopen.ts).
19
+
20
+ import { line } from '@yaks/query'
21
+ import * as fs from '@yaks/file/io'
22
+
23
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
24
+ import { TOMBSTONE } from '@yaks/graph/bundle'
25
+ import { absolute } from '@yaks/file/local'
26
+ import { runs } from '@yaks/process'
27
+ import { CLAIM, SESSION } from './comp.js'
28
+ import { versionOf } from './files.js'
29
+ import { UNFINISHED } from './state.js'
30
+ import { parked } from './wake.js'
31
+ import { awaited } from './woken.js'
32
+
33
+ // A log this recent may belong to a process that has yet to list itself.
34
+ let SETTLING = 5 * 60 * 1000
35
+ // A log with no process to ask about counts as over when this quiet.
36
+ let QUIET = 2 * 60 * 60 * 1000
37
+ // A turn still owed an answer may be a long tool call, so it waits longer.
38
+ let STALLED = 24 * 60 * 60 * 1000
39
+ let BATCH = 50
40
+
41
+ let comp = (b: Bundle | undefined, name: string) => (b?.[name] ?? {}) as Comp
42
+
43
+ /** The session ids Claude's processes run now, from the files in `dir`, one per
44
+ * process. A file outlives a crash, so its pid is asked too. Nothing where
45
+ * there is no such directory, so a computer without one ends nothing. */
46
+ export let runningSessions = async (
47
+ dir: string,
48
+ alive: (pid: number) => Promise<boolean> = runs,
49
+ ): Promise<Set<string> | undefined> => {
50
+ let names: string[]
51
+ try {
52
+ names = [...fs.readDirSync(dir)].map((f) => f.name)
53
+ } catch (e) {
54
+ if (fs.isNotFound(e)) return undefined
55
+ throw e
56
+ }
57
+ let ids = new Set<string>()
58
+ for (let name of names.filter((n) => n.endsWith('.json'))) {
59
+ let text: string
60
+ try {
61
+ text = fs.readTextFileSync(`${dir}/${name}`)
62
+ } catch (e) {
63
+ if (fs.isNotFound(e)) continue // it just ended
64
+ throw e
65
+ }
66
+ let { pid, sessionId } = JSON.parse(text)
67
+ if (!pid || !sessionId) throw new Error(`${name} names no running session`)
68
+ if (await alive(Number(pid))) ids.add(String(sessionId))
69
+ }
70
+ return ids
71
+ }
72
+
73
+ let mtime = (path: string): number | undefined => {
74
+ try {
75
+ return fs.statSync(path).mtime?.getTime()
76
+ } catch {
77
+ return undefined
78
+ }
79
+ }
80
+
81
+ // Quiet since `cutoff`, and every line of it imported. A compressed log's lines
82
+ // can't be counted here: the importer says it reached the end of this version.
83
+ // The second stat closes a race with a harness appending during the read.
84
+ let endedFile = (path: string, read: Comp, cutoff: number): boolean => {
85
+ try {
86
+ let before = fs.statSync(path)
87
+ if (!before.isFile || (before.mtime?.getTime() ?? Infinity) > cutoff) {
88
+ return false
89
+ }
90
+ if (path.endsWith('.zst')) return read.finished == versionOf(before)
91
+ let consumed = Number(read.consumed)
92
+ let bytes = fs.readFileSync(path)
93
+ let after = fs.statSync(path)
94
+ if (
95
+ before.size != after.size ||
96
+ before.mtime?.getTime() != after.mtime?.getTime() ||
97
+ bytes.at(-1) != 10
98
+ ) return false
99
+ let lines = 0
100
+ for (let byte of bytes) if (byte == 10) lines++
101
+ return lines == consumed
102
+ } catch {
103
+ return false
104
+ }
105
+ }
106
+
107
+ // Nothing has been written to this session since `cutoff`.
108
+ let quiet = async (g: Graph, b: Bundle, cutoff: number): Promise<boolean> => {
109
+ let [last] = await g.rows(
110
+ line`.entry.session=${b.entity.eid}&.order=-entry.seq&.limit=1&.fields=created.at`,
111
+ )
112
+ let at = last?.['created.at'] ?? comp(b, 'created').at
113
+ return Date.parse(String(at)) <= cutoff
114
+ }
115
+
116
+ type Sweep = {
117
+ /** each Claude Code account: where its transcripts are, and where it lists
118
+ * its processes */
119
+ claude?: { projects: string; running: string }[]
120
+ alive?: (pid: number) => Promise<boolean>
121
+ now?: number
122
+ }
123
+
124
+ /** The sessions {@link endGone} would mark, without marking them. */
125
+ export let goneSessions = async (g: Graph, o: Sweep = {}): Promise<Eid[]> => {
126
+ let now = o.now ?? Date.now()
127
+ let accounts = await Promise.all(
128
+ (o.claude ?? []).map(async (a) => ({
129
+ projects: `${a.projects}/`,
130
+ live: await runningSessions(a.running, o.alive),
131
+ })),
132
+ )
133
+ let open = await g.read(
134
+ line`.${SESSION} !${SESSION}.ended .fields=entity.eid`,
135
+ )
136
+ let held = await g.read(line`.${CLAIM}.session .fields=${CLAIM}.session`)
137
+ let parts = [SESSION, 'spawned', 'process', 'exit', 'created']
138
+ let rows = new Map<string, Bundle>()
139
+ let read = async (eids: string[]) => {
140
+ let wanted = eids.filter((eid) => !rows.has(eid))
141
+ if (!wanted.length) return
142
+ for (let b of await g.get(wanted, parts)) {
143
+ if (b && b[TOMBSTONE] == null) rows.set(b.entity.eid, b)
144
+ }
145
+ }
146
+ let holding = new Set(held.map((b) => String(comp(b, CLAIM).session)))
147
+ let coming = await awaited(g)
148
+ await read([...new Set([...open.map((b) => b.entity.eid), ...holding])])
149
+ // A subagent runs in the process of the session at the top of its line.
150
+ let root = async (b: Bundle): Promise<Bundle> => {
151
+ let seen = new Set<string>()
152
+ while (true) {
153
+ let parent = String(comp(b, 'spawned').parent ?? '')
154
+ if (!parent || seen.has(parent)) return b
155
+ seen.add(parent)
156
+ await read([parent])
157
+ if (!rows.has(parent)) return b
158
+ b = rows.get(parent)!
159
+ }
160
+ }
161
+ let gone: Eid[] = []
162
+ for (let b of [...rows.values()]) {
163
+ let s = comp(b, SESSION)
164
+ if (!b[SESSION] || s.ended == true) continue
165
+ let eid = b.entity.eid
166
+ let owes = UNFINISHED.includes(String(s.status))
167
+ let rests = !owes && !holding.has(eid)
168
+ if (b.process) {
169
+ if (b.exit && (rests || (owes && s.transcript))) gone.push(eid)
170
+ continue
171
+ }
172
+ let [file] = s.transcript ? await g.get([String(s.transcript)]) : []
173
+ let path = file && await absolute(g, file)
174
+ // No log to ask about: quiet says it. A wake coming to it keeps it, and
175
+ // what it holds does only while its turn is unfinished or it is parked
176
+ // there.
177
+ if (!path) {
178
+ let keeps = coming.has(eid) ||
179
+ holding.has(eid) && (owes || await parked(g, eid))
180
+ if (!keeps && await quiet(g, b, now - (owes ? STALLED : QUIET))) {
181
+ gone.push(eid)
182
+ }
183
+ continue
184
+ }
185
+ let account = accounts.find((a) => path.startsWith(a.projects))
186
+ if (account) {
187
+ let live = account.live
188
+ if (!live || (mtime(path) ?? 0) > now - SETTLING) continue
189
+ let id = String(comp(await root(b), SESSION).id ?? '')
190
+ // A subagent finishes long before the process it ran in.
191
+ let finished = comp(b, 'spawned').parent && !holding.has(eid) &&
192
+ (mtime(path) ?? 0) <= now - QUIET
193
+ if (!live.has(id) || finished) gone.push(eid)
194
+ } else if (
195
+ endedFile(path, comp(file, 'transcript'), now - QUIET)
196
+ ) gone.push(eid)
197
+ }
198
+ return gone
199
+ }
200
+
201
+ /**
202
+ * Write `session.ended` on every session whose process is gone or, with no
203
+ * process to ask about, that has come to rest, and answer with their eids.
204
+ * `claude` names each Claude Code account's transcripts and the directory where
205
+ * it lists its processes. It is an observation, not an edit, so `updated` stays as it was.
206
+ *
207
+ * ```ts
208
+ * import { endGone } from '@yaks/session/ended'
209
+ *
210
+ * // await endGone(graph, { claude: [{ projects, running }] })
211
+ * ```
212
+ */
213
+ export let endGone = async (g: Graph, o: Sweep = {}): Promise<Eid[]> => {
214
+ let gone = await goneSessions(g, o)
215
+ for (let i = 0; i < gone.length; i += BATCH) {
216
+ await g.apply(
217
+ gone.slice(i, i + BATCH).map((eid) => ({
218
+ entity: { eid },
219
+ [SESSION]: { ended: true },
220
+ })),
221
+ { trusted: true, stamp: false },
222
+ )
223
+ }
224
+ return gone
225
+ }