@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/children.ts ADDED
@@ -0,0 +1,925 @@
1
+ import { line, sub } from '@yaks/query'
2
+ import { derivedEid } from '@yaks/graph/identity'
3
+ import { appendEntry } from './append.js'
4
+ import { workedOn } from './lease.js'
5
+ // Delegation is transcript structure, not a process handle. A spawned session
6
+ // names its parent and originating call; a fork additionally names a prefix.
7
+ // Submission is serialized per graph (across parents and tool tables). The
8
+ // durable queue order and fork prefix commit with the child. Replays find
9
+ // that same child; preparation is deferred until the runner admits it
10
+ // (./run.ts).
11
+ import { aside, dispatchStatus, tail } from './admission.js'
12
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
13
+ import { identityEid } from '@yaks/graph/identity'
14
+ import { Stale } from '@yaks/graph/errors'
15
+ import { token } from '@yaks/graph/sha256'
16
+ import { link } from '@yaks/edge'
17
+ import { human, parse } from '@yaks/id'
18
+ import { done, statusComps, statusOf as taskStatus } from '@yaks/task'
19
+ import {
20
+ type Tool,
21
+ type ToolContext,
22
+ ToolError,
23
+ transcript,
24
+ wordsOf,
25
+ } from './react.js'
26
+ import { entryStatus, newestOf, openOf, usingOf } from './reach.js'
27
+ import { live, newestAsk, seqOf, textOf, usingBefore } from './state.js'
28
+ import { type Clock, system } from '@yaks/fp'
29
+ import { changes } from './wait.js'
30
+ import { calledIn, childNotice, overheard } from './child-notice.js'
31
+ import { askedFor, steered } from './answer.js'
32
+ import { coldFork, forkRequest } from './fork.js'
33
+
34
+ export type ChildLimits = {
35
+ /** Defaults for user-created tasks, resolved before durable queue admission. */
36
+ taskDefaults?: (parent: Eid, child: Eid) => Promise<Record<string, unknown>>
37
+ maxChildren?: number
38
+ maxSessions?: number
39
+ /** Fork the current request with a harness-written instruction. */
40
+ forkLatest?: boolean
41
+ /** Return a historical recap for a cold fork, scoped to its request. */
42
+ forkRecap?: (
43
+ request: Bundle,
44
+ visible: ReadonlySet<Eid>,
45
+ ) => Promise<string | undefined>
46
+ /** Application-owned optional spawn parameters and preparation, applied when
47
+ * the child is admitted. */
48
+ childProperties?: Record<string, unknown>
49
+ prepareChild?: (
50
+ input: { parent: Eid; child: Eid; args: Record<string, unknown> },
51
+ ) => Promise<Omit<Bundle, 'entity'>>
52
+ /** The clock a wait keeps time by (default the system's). */
53
+ clock?: Clock
54
+ /** The model a child asks (`using{provider, model, effort}`, each by eid
55
+ * or by name), given the one it would take: its parent's in force, with the
56
+ * model and effort its spawn named. Without this, that one. */
57
+ using?: (using: Comp, parent: Comp) => Comp | Promise<Comp>
58
+ }
59
+ let locks = new WeakMap<Graph, Promise<unknown>>()
60
+ let comp = (b: Bundle | undefined, name: string) =>
61
+ b?.[name] as Comp | undefined
62
+ let row = async (g: Graph, eid: Eid, comps?: string[]) =>
63
+ (await g.get([eid], comps))[0]
64
+ let spawnedOf = async (g: Graph, session: Eid) =>
65
+ comp(await row(g, session, ['spawned']), 'spawned')
66
+
67
+ /** The session that directly started this helper or fork. */
68
+ export let parentOf = async (
69
+ g: Graph,
70
+ session: Eid,
71
+ ): Promise<Eid | undefined> => {
72
+ let parent = (await spawnedOf(g, session))?.parent
73
+ return typeof parent == 'string' ? parent : undefined
74
+ }
75
+
76
+ // Waiting needs only the child's place, not its computed transcript status/cost.
77
+ export let childPlace = async (
78
+ g: Graph,
79
+ eid: Eid,
80
+ ): Promise<Bundle | undefined> =>
81
+ (await g.get(
82
+ [eid],
83
+ ['dispatch', 'admitted', 'waiting'].filter((name) => g.vocab.comp(name)),
84
+ ))[0]
85
+
86
+ let taskRow = async (
87
+ g: Graph,
88
+ id: string,
89
+ comps?: string[],
90
+ ): Promise<Bundle> => {
91
+ let b = await row(g, id, comps)
92
+ if (!b && parse(id)) [b] = await g.read(line`.task .entity.eid=${id} *`)
93
+ if (!b?.task) throw new ToolError('task', `not a task: ${id}`)
94
+ return b
95
+ }
96
+
97
+ /** The child a call starts ({@link spawnChild}'s `source`): the same each
98
+ * time it is asked, so a replay finds it, and so does a caller that names
99
+ * its own sources. */
100
+ export let childOf = (call: Eid): Eid => derivedEid(`child:${call}`)
101
+
102
+ /** Direct children, including forks created by the session tools. */
103
+ export let children = (g: Graph, session: Eid): Promise<Bundle[]> =>
104
+ Promise.resolve(g.read(line`.spawned.parent=${session}&*`))
105
+
106
+ // How many sessions the cap counts: their number, never their rows.
107
+ let running = async (g: Graph): Promise<number> =>
108
+ Number((await g.rows(line`${sub(live)} .count`))[0]?.n ?? 0)
109
+
110
+ /** The admission path the harness calls, shared by root starts and delegated
111
+ * starts. */
112
+ export let admit = <T>(
113
+ g: Graph,
114
+ parent: Eid | undefined,
115
+ limits: ChildLimits,
116
+ create: () => Promise<T>,
117
+ ): Promise<T> => {
118
+ let go = (locks.get(g) ?? Promise.resolve()).catch(() => {}).then(
119
+ async () => {
120
+ let maxChildren = limits.maxChildren ?? 32
121
+ let maxSessions = limits.maxSessions ?? 64
122
+ for (let n of [maxChildren, maxSessions]) {
123
+ if (!Number.isInteger(n) || n < 0) {
124
+ throw new Error('invalid session cap')
125
+ }
126
+ }
127
+ if (!parent && await running(g) >= maxSessions) {
128
+ throw new ToolError(
129
+ 'session_cap',
130
+ `live session cap (${maxSessions}) reached`,
131
+ )
132
+ }
133
+ return await create()
134
+ },
135
+ )
136
+ locks.set(g, go)
137
+ return go
138
+ }
139
+
140
+ let caller = (ctx?: ToolContext): ToolContext => {
141
+ if (!ctx) throw new ToolError('caller', 'session tool requires a caller')
142
+ return ctx
143
+ }
144
+
145
+ // The name a child was given (`title`), as its own `doc{title}`, which
146
+ // names it wherever a session is named (./name.ts `sessionName`).
147
+ let named = (g: Graph, title: unknown) =>
148
+ typeof title == 'string' && title.trim() && g.vocab.comp('doc')
149
+ ? { doc: { title: title.trim().replace(/\s+/g, ' ') } }
150
+ : {}
151
+
152
+ let FORK_LATEST =
153
+ 'You are a fork of this conversation; do the work the latest message asks for, then report'
154
+
155
+ let forkStarted = (
156
+ child: Eid,
157
+ request: Bundle,
158
+ title: unknown,
159
+ ) =>
160
+ `Fork ${child} started for message ${request.entity.eid}` +
161
+ (typeof title == 'string' ? ` (${title.trim()}).` : '.')
162
+
163
+ let calledFrom = (ctx: ToolContext) => {
164
+ let source = comp(ctx.call, 'call')?.source
165
+ let ask = source
166
+ ? ctx.entries.find((b) => b.entity.eid == source)
167
+ : newestAsk(ctx.entries)
168
+ let through = comp(ask, 'ask')?.through
169
+ return { ask, anchor: ctx.entries.find((b) => b.entity.eid == through) }
170
+ }
171
+
172
+ /** One admission/write path for model delegation and user-created tasks. */
173
+ let delegation = (
174
+ g: Graph,
175
+ limits: ChildLimits,
176
+ fork: boolean | 'latest',
177
+ minted?: Bundle,
178
+ submitted = false,
179
+ ): Tool => ({
180
+ name: fork ? 'fork' : 'spawn',
181
+ ...fork ? { excludeFromForks: true } : {},
182
+ step: fork == 'latest'
183
+ ? { doing: 'Starting work…', done: 'Started work' }
184
+ : { doing: 'Starting a helper…', done: 'Started a helper' },
185
+ description: fork == 'latest'
186
+ ? 'Default for delegating the latest request. The fork sees your conversation through that request and reports back automatically. Give it a short title. The harness supplies its only instruction.'
187
+ : fork
188
+ ? 'Fork your transcript before this tool turn with a prompt OR atomically claimed task (original title/body). Returns the concurrent child session id; completion is delivered automatically. For work of many steps or parts that run side by side; do what takes a call or two yourself.'
189
+ : 'Start a fresh subagent with a prompt OR a task id. A task is claimed atomically and its title/body become the input. Returns a child ID immediately; a shared worker pool queues excess work durably and delivers completion automatically. For work of many steps or that needs a clean start; do what takes a call or two yourself.',
190
+ parameters: {
191
+ type: 'object',
192
+ properties: {
193
+ ...fork != 'latest'
194
+ ? {
195
+ ...limits.childProperties,
196
+ prompt: { type: 'string' },
197
+ task: { type: 'string', description: 'task entity id or T-id' },
198
+ instructions: { type: 'string' },
199
+ model: {
200
+ type: 'string',
201
+ description: 'model name or existing model entity id',
202
+ },
203
+ effort: { type: 'string' },
204
+ }
205
+ : {},
206
+ title: {
207
+ type: 'string',
208
+ description:
209
+ 'A short name for the job, 3 to 6 words, as a person would name it. Lists of helpers show it.',
210
+ },
211
+ ...fork != 'latest'
212
+ ? {
213
+ report: {
214
+ type: 'string',
215
+ enum: ['resume', 'record'],
216
+ description:
217
+ 'Record a successful report without starting a turn, or resume this conversation when it finishes. Failures and reports a turn is waiting for still reach it.',
218
+ },
219
+ }
220
+ : {},
221
+ },
222
+ ...fork == 'latest' ? { additionalProperties: false } : {},
223
+ },
224
+ run: async (args, context) => {
225
+ let ctx = caller(context)
226
+ let latest = fork == 'latest'
227
+ // A cached offer or a replay can still send the earlier tool's fields.
228
+ if (latest) args = { title: args.title, report: 'record' }
229
+ if (
230
+ !latest && (args.task != null) == (args.prompt != null)
231
+ ) {
232
+ throw new ToolError(
233
+ 'spawn',
234
+ 'name exactly one prompt or task',
235
+ )
236
+ }
237
+ if (
238
+ args.task != null && (typeof args.task != 'string' || !args.task.trim())
239
+ ) {
240
+ throw new ToolError('task', 'a nonempty task id is required')
241
+ }
242
+ if (
243
+ !latest && args.task == null &&
244
+ (typeof args.prompt != 'string' || !args.prompt.trim())
245
+ ) {
246
+ throw new ToolError('prompt', 'a nonempty prompt is required')
247
+ }
248
+ let eid = childOf(ctx.call.entity.eid)
249
+ let at = latest ? calledFrom(ctx).anchor : undefined
250
+ let request = at && forkRequest(ctx.session, at, ctx.entries)
251
+ let started = at ? forkStarted(eid, request ?? at, args.title) : eid
252
+ if (await row(g, eid)) return started
253
+ // An older request or a model guessing the tool name can still call it.
254
+ if (fork && !minted && (await row(g, ctx.session))?.fork) {
255
+ throw new ToolError(
256
+ 'fork',
257
+ 'You are a fork already: do this task here yourself, and give your report as your final reply.',
258
+ )
259
+ }
260
+ return admit(g, ctx.session, limits, async () => {
261
+ // A concurrent replay may have waited behind the original admission.
262
+ if (await row(g, eid)) return started
263
+ let task = minted ??
264
+ (args.task == null ? undefined : await taskRow(g, String(args.task)))
265
+ let work = minted
266
+ ? await g.read(line`.task .claim.session=${ctx.session}`)
267
+ : []
268
+ let parents = work.length ? work.map((b) => b.entity.eid) : [ctx.session]
269
+ let doc = comp(task, 'doc')
270
+ let prompt = latest
271
+ ? FORK_LATEST
272
+ : minted
273
+ ? doc?.body || doc?.title || ''
274
+ : task
275
+ ? [doc?.title, doc?.body].filter(Boolean).join('\n\n')
276
+ : args.prompt
277
+ if (minted && limits.taskDefaults) {
278
+ args = { ...await limits.taskDefaults(ctx.session, eid), ...args }
279
+ }
280
+ if (minted) ctx = { ...ctx, entries: await transcript(g, ctx.session) }
281
+ let { ask, anchor } = calledFrom(ctx)
282
+ let inherited = latest
283
+ ? comp(ask, 'using') ??
284
+ usingBefore(ctx.entries, anchor && seqOf(anchor))
285
+ : usingBefore(ctx.entries)
286
+ let using = { ...inherited }
287
+ let models: Bundle[] = []
288
+ if (args.model != null) {
289
+ // A model is named by its id or by its own name. The provider in force
290
+ // stays only while it serves the model; otherwise the resolver picks
291
+ // one of the model's providers. A name nothing knows yet becomes a
292
+ // requested model (@yaks/model `requesting`): the provider in force is
293
+ // asked for it, and only its answer records that it serves it. Until
294
+ // then nobody serves it, so a helper started meanwhile asks the
295
+ // provider in force too.
296
+ let said = String(args.model)
297
+ let known = await row(g, said)
298
+ let model = known?.model ? said : identityEid('model', [said])
299
+ using.model = model
300
+ let held = known?.model ? known : await row(g, model)
301
+ if (held && !held.pending) {
302
+ let offers = await g.read(line`.serves .edge.to=${model}`)
303
+ if (!offers.some((o) => comp(o, 'edge')?.from == using.provider)) {
304
+ delete using.provider
305
+ }
306
+ } else if (!held) {
307
+ models.push({
308
+ entity: { eid: model },
309
+ model: { name: said, offered: false },
310
+ pending: {},
311
+ })
312
+ }
313
+ }
314
+ // Legacy base instructions are inherited; child guidance is additive.
315
+ for (let key of ['effort']) {
316
+ if (args[key] != null) using[key] = String(args[key])
317
+ }
318
+ if (limits.using) using = await limits.using(using, inherited ?? {})
319
+ // Never inherit the unanswered delegation call (or any sibling calls).
320
+ if (minted) {
321
+ // User tasks reference a contiguous parent prefix. Only an active
322
+ // attempt can still change it; terminal attempts must not pin future
323
+ // forks to an old boundary. Inputs after this boundary remain in the
324
+ // parent, rather than being copied into the child.
325
+ let active = ctx.entries.findIndex((b) =>
326
+ (b.attempt as Comp | undefined)?.state == 'inflight'
327
+ )
328
+ anchor = active == 0
329
+ ? undefined
330
+ : ctx.entries.at(active < 0 ? -1 : active - 1)
331
+ }
332
+ if (fork && !anchor && !minted) {
333
+ throw new ToolError('fork', 'no prefix to fork')
334
+ }
335
+ if (
336
+ fork && anchor &&
337
+ ctx.entries.some((b) =>
338
+ (b.attempt as Comp | undefined)?.state == 'inflight' &&
339
+ Number((b.entry as Comp)?.seq) <= Number((anchor!.entry as Comp)?.seq)
340
+ )
341
+ ) {
342
+ throw new ToolError(
343
+ 'fork',
344
+ 'Cannot inherit an in-flight response; wait for its completion',
345
+ )
346
+ }
347
+
348
+ // Fork history is immutable. Fresh children receive the same shared
349
+ // snapshots, never a filesystem reread or a replacement persona.
350
+ let context: Bundle[] = fork
351
+ ? []
352
+ : ctx.entries.filter((b) =>
353
+ (b.prompt as Comp | undefined)?.scope == 'shared'
354
+ ).map((b, i) => ({
355
+ entity: { eid: derivedEid(eid + ':shared:' + i) },
356
+ content: { body: textOf(b) },
357
+ prompt: { ...(b.prompt as Comp) },
358
+ }))
359
+ if (fork && !latest) {
360
+ context.push({
361
+ entity: { eid: derivedEid(eid + ':fork-context') },
362
+ prompt: { scope: 'local', source: 'harness:fork' },
363
+ content: {
364
+ body:
365
+ 'You are a fork of the conversation above, started for the task below. Do it here yourself: you already hold all of its context, so forking it again only repeats you. Start a fresh subagent only for a separate part that needs a clean start. Your final reply is your report to the parent and ends your work, so give it when the task is done, not before.',
366
+ },
367
+ })
368
+ }
369
+ if (args.instructions != null) {
370
+ context.push({
371
+ entity: { eid: derivedEid(eid + ':guidance') },
372
+ prompt: { scope: 'local', source: 'delegation:instructions' },
373
+ content: { body: String(args.instructions) },
374
+ })
375
+ }
376
+ context = context.map((b) => ({
377
+ ...b,
378
+ entry: {
379
+ session: eid,
380
+ ...comp(b, 'prompt')?.source == 'delegation:instructions'
381
+ ? { from: 'your parent session' }
382
+ : {},
383
+ },
384
+ }))
385
+ let cold = latest && request && anchor && limits.forkRecap
386
+ ? coldFork(ctx.entries, ctx.session, request, anchor)
387
+ : undefined
388
+ let recap = cold && request
389
+ ? await limits.forkRecap?.(request, cold.visible)
390
+ : undefined
391
+ let order = await tail(g)
392
+ await g.apply([
393
+ ...minted
394
+ ? [{
395
+ entity: { eid: derivedEid('notice:' + eid) },
396
+ entry: {
397
+ session: ctx.session,
398
+ },
399
+ notice: { child: eid, task: minted.entity.eid },
400
+ content: {
401
+ body: [
402
+ 'Task: ' + String(doc?.title ?? ''),
403
+ 'Origin: user-created task, automatically delegated to child ' +
404
+ eid,
405
+ 'Request:',
406
+ String(doc?.body ?? ''),
407
+ ].join('\n'),
408
+ },
409
+ }]
410
+ : [],
411
+ ...models,
412
+ ...context,
413
+ ...minted
414
+ ? [
415
+ minted,
416
+ ...parents.map((parent) =>
417
+ link(parent, 'contains', minted.entity.eid)
418
+ ),
419
+ ]
420
+ : [],
421
+ ...task ? [{ entity: task.entity, claim: { session: eid } }] : [],
422
+ {
423
+ entity: { eid },
424
+ dispatch: { state: 'queued', args: JSON.stringify(args), order },
425
+ session: { id: eid },
426
+ native: {},
427
+ spawned: {
428
+ parent: ctx.session,
429
+ ...args.report == 'resume' || args.report == 'record'
430
+ ? { report: args.report }
431
+ : {},
432
+ ...(await spawnedOf(g, ctx.session))?.notice
433
+ ? { notice: true }
434
+ : {},
435
+ ...minted || submitted ? {} : { call: ctx.call.entity.eid },
436
+ },
437
+ ...fork && anchor
438
+ ? {
439
+ fork: {
440
+ from: anchor.entity.eid,
441
+ ...request ? { request: request.entity.eid } : {},
442
+ ...recap && cold?.before ? { elided_before: cold.before } : {},
443
+ },
444
+ }
445
+ : {},
446
+ ...named(g, args.title),
447
+ },
448
+ ...recap
449
+ ? [{
450
+ entity: { eid: derivedEid(`${eid}:recap`) },
451
+ entry: { session: eid },
452
+ content: { body: recap },
453
+ prompt: { scope: 'recap', source: 'harness:recap' },
454
+ system: {},
455
+ }]
456
+ : [],
457
+ {
458
+ entity: { eid: derivedEid(`${eid}:input`) },
459
+ entry: {
460
+ session: eid,
461
+ ...latest ? {} : { from: 'your parent session' },
462
+ },
463
+ content: { body: prompt },
464
+ ...latest
465
+ ? {
466
+ prompt: { scope: 'local', source: 'harness:fork' },
467
+ system: {},
468
+ }
469
+ : {},
470
+ using,
471
+ // What a steered turn starts is steered: a call made where someone
472
+ // else's words may be asking hands its child those words' mark, so
473
+ // the child's own turn is steered too (./answer.ts `steered`),
474
+ // judged for whom the call's turn works (`askedFor`).
475
+ ...!minted && !submitted &&
476
+ steered(ctx.entries, askedFor(ctx.entries, ctx.call))
477
+ ? { heard: {} }
478
+ : {},
479
+ },
480
+ ], { trusted: true })
481
+ return started
482
+ })
483
+ },
484
+ })
485
+
486
+ /** Submit helper work from an outside caller, without inventing a model tool
487
+ * call in the parent's transcript. It shares the model's admission path. */
488
+ export let spawnChild = async (
489
+ g: Graph,
490
+ session: Eid,
491
+ args: Record<string, unknown>,
492
+ limits: ChildLimits = {},
493
+ source: Eid = crypto.randomUUID(),
494
+ ): Promise<Eid> =>
495
+ wordsOf(
496
+ await delegation(g, limits, false, undefined, true).run(args, {
497
+ session,
498
+ call: { entity: { eid: source } },
499
+ entries: await transcript(g, session),
500
+ }),
501
+ )
502
+
503
+ /** Submit a microtask under the session's claimed work (or the session when
504
+ * it holds no task). The task, containment, child and claim commit together:
505
+ * queued work is accepted without preparing a checkout. No filing metadata is inherited.
506
+ * The first line is the title; the complete submitted text is kept as body.
507
+ * This is called by a person, not by a model, so delivery is an ordinary
508
+ * input. */
509
+ export let taskEntry = async (
510
+ g: Graph,
511
+ session: Eid,
512
+ text: string,
513
+ limits: ChildLimits = {},
514
+ ): Promise<{ task: Eid; child: Eid }> => {
515
+ if (!text.trim()) throw new ToolError('task', 'a nonempty task is required')
516
+ if (!(await row(g, session))?.session) {
517
+ throw new ToolError('session', `not a session: ${session}`)
518
+ }
519
+ let task = crypto.randomUUID()
520
+ let minted: Bundle = {
521
+ entity: { eid: task },
522
+ doc: { title: text.trim().split('\n')[0].slice(0, 120), body: text },
523
+ task: {},
524
+ }
525
+ let child = await delegation(g, limits, true, minted).run({ task }, {
526
+ session,
527
+ // Identity only; no fabricated tool call is written into the transcript.
528
+ call: { entity: { eid: task } },
529
+ entries: await transcript(g, session),
530
+ })
531
+ return { task, child: wordsOf(child) }
532
+ }
533
+
534
+ /** The model-facing tools use the same admission and spawn write as
535
+ * taskEntry. */
536
+ export let sessionTools = (g: Graph, limits: ChildLimits = {}): Tool[] => {
537
+ let fork = delegation(g, limits, limits.forkLatest ? 'latest' : true)
538
+ let spawn = delegation(g, limits, false)
539
+ return [fork, spawn, {
540
+ name: 'notice',
541
+ description:
542
+ 'Append your words as passive context to a session without waking it, identified as coming from your session. Sequence is assigned atomically; do not guess entry.seq.',
543
+ parameters: {
544
+ type: 'object',
545
+ properties: {
546
+ session: { type: 'string' },
547
+ body: { type: 'string' },
548
+ eid: {
549
+ type: 'string',
550
+ description: 'optional idempotent entry identity',
551
+ },
552
+ },
553
+ required: ['session', 'body'],
554
+ },
555
+ run: async (args, context) => {
556
+ let ctx = caller(context)
557
+ let session = String(args.session)
558
+ if (!(await row(g, session))?.session) {
559
+ throw new ToolError('session', 'not a session: ' + session)
560
+ }
561
+ let added = await appendEntry(g, session, String(args.body), {
562
+ notice: true,
563
+ from: `session ${ctx.session}`,
564
+ eid: args.eid == null ? undefined : String(args.eid),
565
+ })
566
+ return added[0].entity.eid
567
+ },
568
+ }, {
569
+ name: 'wait',
570
+ waits: true,
571
+ description:
572
+ 'Wait on direct children or tasks. Tasks wait until settled with no open dependencies; returns status when complete or the timeout passes.',
573
+ parameters: {
574
+ type: 'object',
575
+ properties: {
576
+ children: { type: 'array', items: { type: 'string' }, minItems: 1 },
577
+ tasks: { type: 'array', items: { type: 'string' }, minItems: 1 },
578
+ timeout: {
579
+ type: 'number',
580
+ description: 'milliseconds (default 60000)',
581
+ },
582
+ },
583
+ },
584
+ run: async (args, context) => {
585
+ let ctx = caller(context)
586
+ if ((args.tasks == null) == (args.children == null)) {
587
+ throw new ToolError('wait', 'name either tasks or child sessions')
588
+ }
589
+ let named = args.tasks ?? args.children
590
+ if (
591
+ !Array.isArray(named) || !named.length ||
592
+ named.some((s) => typeof s != 'string')
593
+ ) {
594
+ throw new ToolError('wait', 'name at least one task or child session')
595
+ }
596
+ let ids = [...new Set(named as string[])]
597
+ // Each look reads only what decides the answer: a task's status marks,
598
+ // a child's place and transcript status. A child's output is read once,
599
+ // for the answer.
600
+ let marks = statusComps(g.vocab)
601
+ if (args.tasks != null) {
602
+ ids = await Promise.all(
603
+ ids.map(async (id) => (await taskRow(g, id, marks)).entity.eid),
604
+ )
605
+ }
606
+ for (let id of args.tasks == null ? ids : []) {
607
+ if (await parentOf(g, id) != ctx.session) {
608
+ throw new ToolError('children', `not your child: ${id}`)
609
+ }
610
+ }
611
+ let ms = Number(args.timeout ?? 60_000)
612
+ if (!Number.isFinite(ms) || ms < 0) {
613
+ throw new ToolError('timeout', 'invalid timeout')
614
+ }
615
+ let clock = limits.clock ?? system
616
+ let end = clock.now() + ms
617
+ let back = await aside(g, ctx.session, limits, ctx.signal)
618
+ let task = async (id: Eid) => ({
619
+ task: id,
620
+ status: taskStatus(g.vocab, await taskRow(g, id, marks)),
621
+ done: await done(g, id),
622
+ })
623
+ let child = async (session: Eid) => {
624
+ let state = dispatchStatus(await childPlace(g, session))
625
+ let now = await entryStatus(g, session)
626
+ return state == 'queued' && now != 'stopped' ? 'queued' : now
627
+ }
628
+ let ended = (status: string) =>
629
+ ['settled', 'failed', 'stopped'].includes(status)
630
+ try {
631
+ for await (
632
+ let over of changes(g, {
633
+ timeout: end - clock.now(),
634
+ signal: ctx.signal,
635
+ clock,
636
+ })
637
+ ) {
638
+ if (ctx.signal?.aborted) return JSON.stringify({ stopped: true })
639
+ if (args.tasks != null) {
640
+ let results = await Promise.all(ids.map(task))
641
+ if (results.every((r) => r.done) || over) {
642
+ return JSON.stringify(results)
643
+ }
644
+ } else {
645
+ let states = await Promise.all(ids.map(child))
646
+ if (states.every(ended) || over) {
647
+ let text = JSON.stringify(
648
+ await Promise.all(ids.map(async (session, n) => {
649
+ let last = await newestOf(g, session)
650
+ return {
651
+ session,
652
+ status: states[n],
653
+ output: last ? textOf(last) : '',
654
+ }
655
+ })),
656
+ )
657
+ // A child's output is its report, `heard` as it is anywhere.
658
+ let heard = (await Promise.all(ids.map((c) => overheard(g, c))))
659
+ .some(Boolean)
660
+ return heard ? { text, with: { heard: {} } } : text
661
+ }
662
+ }
663
+ }
664
+ throw new Error('wait ended without a final read')
665
+ } finally {
666
+ await back()
667
+ }
668
+ },
669
+ }]
670
+ }
671
+
672
+ /** The session `session` works for: up its `spawned` links to a person's
673
+ * conversation, or to a session started on its own (`spawned.quiet`). */
674
+ export let topOf = async (g: Graph, session: Eid): Promise<Eid> => {
675
+ let link = await spawnedOf(g, session)
676
+ if (!link?.parent || link.quiet != null) return session
677
+ return topOf(g, String(link.parent))
678
+ }
679
+
680
+ // What a helper was asked, in a line: its title, else the first words it
681
+ // was started with.
682
+ let askedOf = async (g: Graph, helper: Eid) => {
683
+ let title = String(comp(await row(g, helper, ['doc']), 'doc')?.title ?? '')
684
+ if (title) return title
685
+ let opening = await g.read(
686
+ line`.entry.session=${helper}&.order=entry.seq&.limit=3&*`,
687
+ )
688
+ let first = opening.find((b) => !b.prompt && b.content)
689
+ return textOf(first ?? { entity: { eid: helper } }).trim().split('\n')[0]
690
+ .slice(0, 80) || 'a piece of work'
691
+ }
692
+
693
+ /**
694
+ * Stop `session` and every helper under it, however deep, in one write: the
695
+ * step each is in is withdrawn (./run.ts), and none goes on past it until new
696
+ * words reopen it. A helper `by` stops says who stopped it in its stop, which
697
+ * the session that started it reads in its report (`deliverChild`), and the
698
+ * conversation it works for ({@link topOf}), where that is further up, is told
699
+ * of its end in a notice, as a passive child's is (./child-notice.ts), which
700
+ * no report of its own would tell it and which starts no turn. Answers whether
701
+ * any of them was working; where none was, nothing is written.
702
+ */
703
+ export let stopAll = async (
704
+ g: Graph,
705
+ session: Eid,
706
+ by: Eid,
707
+ via?: Eid,
708
+ ): Promise<boolean> => {
709
+ let helpers: Eid[] = []
710
+ for (let parents = [session]; parents.length;) {
711
+ parents = (await g.read(line`.spawned.parent=${parents}`))
712
+ .map((b) => b.entity.eid)
713
+ helpers.push(...parents)
714
+ }
715
+ // Each one's status as the store computes it (`session.status`): a tree of
716
+ // hundreds read transcript by transcript costs more than a request has.
717
+ let busy: Eid[] = [], idle: Eid[] = []
718
+ for (let b of await g.get([session, ...helpers], ['session'])) {
719
+ let status = comp(b, 'session')?.status
720
+ if (status == 'pending' || status == 'running' || status == 'queued') {
721
+ busy.push(b.entity.eid)
722
+ } else if (status != 'stopped') idle.push(b.entity.eid)
723
+ }
724
+ let link = await spawnedOf(g, session)
725
+ if (!busy.length && !link?.notice) return false
726
+ // The person as the model knows them: the id their own words are labeled
727
+ // with (@yaks/harness `senders`).
728
+ let person = link && !via
729
+ ? human(g.vocab)(await row(g, by) ?? { entity: { eid: by } })
730
+ : ''
731
+ let parent = String(link?.parent ?? '')
732
+ let top = link ? await topOf(g, parent) : ''
733
+ let leave =
734
+ "so leave it stopped, and don't start its work again another way, until you have talked with them."
735
+ await g.apply([
736
+ ...top && top != parent
737
+ ? [{
738
+ entity: { eid: crypto.randomUUID() },
739
+ entry: { session: top },
740
+ notice: { child: session },
741
+ delivery: { child: session, outcome: 'stopped' },
742
+ content: {
743
+ body: via
744
+ ? `Your Operator stopped helper ${session} because the request changed.`
745
+ : `The person (${person}) stopped helper ${session} ("${await askedOf(
746
+ g,
747
+ session,
748
+ )}"), which one of your helpers started, ${leave}`,
749
+ },
750
+ $actor: { by, via: via ?? top },
751
+ }]
752
+ : [],
753
+ ...[...busy, ...idle].map((s) => ({
754
+ entity: { eid: crypto.randomUUID() },
755
+ entry: { session: s },
756
+ stop: {},
757
+ content: {
758
+ body: via
759
+ ? 'Your Operator stopped this work because the request changed.'
760
+ : link && s == session
761
+ ? `The person (${person}) stopped helper ${session}, ${leave}`
762
+ : 'Stopped by the person watching.',
763
+ },
764
+ $actor: { by, via: via ?? s },
765
+ })),
766
+ ], { trusted: true })
767
+ return true
768
+ }
769
+
770
+ /** Stop a fork under the same conversation when its request changes. */
771
+ export let stopFork = (g: Graph, by: Eid): Tool => ({
772
+ name: 'session_stop',
773
+ description:
774
+ 'Stop an earlier fork of this conversation when the person changes what the work is for.',
775
+ parameters: {
776
+ type: 'object',
777
+ properties: {
778
+ session: {
779
+ type: 'string',
780
+ description: 'The earlier fork’s session id.',
781
+ },
782
+ },
783
+ required: ['session'],
784
+ },
785
+ run: async ({ session }, context) => {
786
+ let ctx = caller(context)
787
+ let id = String(session)
788
+ let [target] = await g.get([id], ['spawned', 'fork'])
789
+ if (
790
+ !target?.fork || id == ctx.session ||
791
+ comp(target, 'spawned')?.parent != await topOf(g, ctx.session)
792
+ ) {
793
+ throw new ToolError(
794
+ 'session',
795
+ 'Name an earlier fork of this conversation.',
796
+ )
797
+ }
798
+ return JSON.stringify({
799
+ session: id,
800
+ stopped: await stopAll(g, id, by, ctx.session),
801
+ })
802
+ },
803
+ })
804
+
805
+ // Whether any of a session's helpers, at any depth, has yet to end and be
806
+ // told. A child's dispatch settles after its report is written, or held for
807
+ // helpers of its own (./run.ts), so a settled child still works while one of
808
+ // its own does.
809
+ export let workingChildren = async (
810
+ g: Graph,
811
+ session: Eid,
812
+ repliesOnly = false,
813
+ ): Promise<boolean> => {
814
+ for (let c of await children(g, session)) {
815
+ if (repliesOnly && comp(c, 'spawned')?.notice) continue
816
+ let place = dispatchStatus(c)
817
+ if (place != null && place != 'settled') return true
818
+ let status = await entryStatus(g, c.entity.eid)
819
+ if (!['settled', 'failed', 'stopped'].includes(status)) return true
820
+ if (status == 'settled' && await workingChildren(g, c.entity.eid)) {
821
+ return true
822
+ }
823
+ }
824
+ return false
825
+ }
826
+
827
+ /** Build one idempotent completion receipt, while holding the parent's queue.
828
+ * The final-entry-derived id also allows a child to be sent another turn. */
829
+ export let deliverChild = async (
830
+ g: Graph,
831
+ child: Eid,
832
+ now: number = Date.now(),
833
+ ): Promise<number | undefined> => {
834
+ let link = comp(await row(g, child), 'spawned')
835
+ if (!link?.parent || !await row(g, String(link.parent))) return
836
+ if (link.notice && link.report == null) {
837
+ return childNotice(g, child, link, now, () => workingChildren(g, child))
838
+ }
839
+ // A settled child's receipt usually already exists. Inspect its local tail
840
+ // before materializing the inherited prefix (which can be very large).
841
+ let [tail] = await g.read(
842
+ line`.entry.session=${child}&.order=-entry.seq&.limit=1&*`,
843
+ )
844
+ // The task it was given, which lets go of the child's claim once done.
845
+ let tasks = g.vocab.comps.includes('task')
846
+ ? await g.get(await workedOn(g, child))
847
+ : []
848
+ let task = tasks.find((b) => b?.task)
849
+ let ready = task &&
850
+ await done(g, task.entity.eid)
851
+ let last = tail ?? await newestOf(g, child)
852
+ if (!last) return
853
+ // A parent's own completion is already known to it: the completion came
854
+ // through it (`via`; `by` is the actor it works for). Fall back to the
855
+ // ordinary child receipt identity: a new child response must still arrive,
856
+ // while an already delivered response must not echo on completion/restart.
857
+ let announceTask = ready &&
858
+ (taskStatus(g.vocab, task!) != 'done' ||
859
+ comp(task, 'completed')?.via != String(link.parent))
860
+ let receipt = (last: Bundle) =>
861
+ derivedEid(
862
+ announceTask
863
+ ? `delivery:${child}:task:${task!.entity.eid}:${
864
+ taskStatus(g.vocab, task!)
865
+ }`
866
+ : `delivery:${child}:${last.entity.eid}`,
867
+ )
868
+ let eid = receipt(last)
869
+ if (await row(g, eid)) return
870
+ let status = await entryStatus(g, child)
871
+ // A new receipt still requires the full transcript's terminal outcome.
872
+ if (!['settled', 'failed', 'stopped'].includes(status)) return
873
+ // A child whose own helpers still work has not answered yet: their reports
874
+ // will wake it, and one call reports once, after they end.
875
+ if (status == 'settled' && await workingChildren(g, child)) return
876
+ // The model may have finished while the fast-path reads were awaiting.
877
+ // Use the same terminal snapshot for the receipt identity and its text.
878
+ last = (await newestOf(g, child))!
879
+ eid = receipt(last)
880
+ if (await row(g, eid)) return
881
+ let message = announceTask
882
+ ? `task ${calledIn(g, task!)} ${taskStatus(g.vocab, task!)}`
883
+ : `child ${child} ${status}`
884
+ let notice = await row(g, derivedEid('notice:' + child))
885
+ let context = notice?.notice
886
+ ? textOf(notice) + '\nOutcome: child ' + status +
887
+ (ready ? '; task ' + taskStatus(g.vocab, task!) : '') + '\nResult:\n'
888
+ : ''
889
+ let parent = String(link.parent)
890
+ // A stop is an explicit end, not a request to wake on the next delivery.
891
+ if (await entryStatus(g, parent) == 'stopped') return
892
+ let open = (await openOf(g, parent)).some((b) => b.entity.eid == link.call)
893
+ let record = link.report == 'record' && status == 'settled' &&
894
+ (!task || ready) && !open && !!textOf(last)
895
+ // The parent's `using` in force rides on the receipt: it is the request for
896
+ // the turn the receipt calls for (./run.ts).
897
+ let using = await usingOf(g, parent)
898
+ try {
899
+ await g.apply([
900
+ {
901
+ entity: { eid },
902
+ $was: { entry: { session: token(null) } },
903
+ entry: {
904
+ session: parent,
905
+ },
906
+ content: { body: message + '\n' + context + textOf(last) },
907
+ delivery: {
908
+ child,
909
+ outcome: status,
910
+ ...link.report ? { through: last.entity.eid } : {},
911
+ },
912
+ ...record ? { notice: { child } } : {},
913
+ ...open ? { result: { call: link.call } } : {},
914
+ ...using && !record ? { using } : {},
915
+ ...await overheard(g, child) ? { heard: {} } : {},
916
+ },
917
+ ...link.notice ? [{ entity: { eid: child }, completed: {} }] : [],
918
+ ...link.notice && !record
919
+ ? [{ entity: { eid: parent }, completed: null }]
920
+ : [],
921
+ ], { trusted: true })
922
+ } catch (error) {
923
+ if (!(error instanceof Stale) || error.eid != eid) throw error
924
+ }
925
+ }