@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/cost.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cost.js","sources":["./cost.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,wEAAwE;AACxE,4EAA4E;AAC5E,wDAAwD;AACxD,0DAA0D;AAC1D,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,qCAAqC;AAGrC,SAAS,KAAK,wBAA6B;AAC3C,SACE,IAAI,EACJ,KAAK,EAEL,KAAK,EAEL,KAAK,iCAC8B;AAErC,SAAS,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,8BAAmC;AACjF,SAAS,GAAG,EAAE,KAAK,sBAAqB;AAExC,6EAA6E;AAC7E,2EAA2E;AAC3E,SAAS;AACT,IAAI,SAAS,CAAC;EACZ,IAAI,MAAM,GAAG,CAAC,IAAI;EAClB,IAAI,KAAK,KAAK,MAAO,GAAG,CAAC,MAAM,EAAuB;EACtD,OAAO;IAAC,KAAK;IAAQ;GAAG,CAAC,MAAM,CAAC,CAAC,IAAM,KAAK,MAAM,GAAG,CAAC;AACxD;AAEA;;;;;;;CAOC,GACD,OAAO,IAAI,WAAiB,CAAC,SAAS;EACpC,IAAI,OAAO,QAAQ,MAAM,CAAC,CAAC,IAAM,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,QAAQ,CAAC;EACxD,IAAI,CAAC,KAAK,MAAM,EAAE,OAAO;EACzB,IAAI,OAAO,KAAK,GAAG,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,GAAG;EACvC,OAAO,MAAM,GAAG,GAAG,CAAC,MAAM;IAAC;IAAK;IAAO;I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AAC,KAAK,EAAE;YAAE;YAAS,UAAU;UAAM;QAAE;MACtD;IACF;EACF;AACF,EAAC;AAED;kEACkE,GAClE,OAAO,IAAI,cAA2B;EACpC,QAAQ;EACR,KAAK;EACL,OAAO;EACP,MAAM,CAAC,QACL,IAAI,OAAO;MACT,MAAM;QAAC,GAAG,OAAO,IAAI,WAAW;OAAM;MACtC,MAAM,MAAM,SAAS;MACrB,OAAO;QACL,KAAK,MAAM,MAAM,MAAM,GAAG,IAAI,UAAU,MAAM,IAAI,UAAU;OAC7D;MACD,OAAO,GAAG,IAAI,WAAW,MAAM;IACjC;AACJ,EAAC"}
package/cost.ts ADDED
@@ -0,0 +1,93 @@
1
+ // What a transcript cost, in dollars. Each request's `cost` (@yaks/model) is
2
+ // stored on its entry, beside its `usage`: the dollars the provider reported
3
+ // wherever it reports them (OpenRouter's usage, Claude Code's closing line),
4
+ // and otherwise the usage weighed at the `price` on the row of the model that
5
+ // answered it, in the transaction that writes the usage: the price that
6
+ // transaction gives it, as a model's first request does, or else the one it
7
+ // has (@yaks/model `requesting`). A model with no price
8
+ // leaves its requests unweighed, since absent beats zero.
9
+ //
10
+ // A session's `cost` is the sum of its entries' and is never stored: a second
11
+ // copy would drift from the entries it sums, and a transcript whose entries
12
+ // record no cost has none, not zero.
13
+
14
+ import type { Bundle, Comp, Hook } from 'jsr:@yaks/graph@0.2.36'
15
+ import { after } from '@yaks/fp'
16
+ import {
17
+ COST,
18
+ PRICE,
19
+ type Price,
20
+ USAGE,
21
+ type Usage,
22
+ weigh,
23
+ } from '@yaks/model/vocab'
24
+ import type { DerivedProp } from 'jsr:@yaks/sql@0.2.36'
25
+ import { col, eq, fn, join, select, sub, table } from '@yaks/sql/core'
26
+ import { ASK, USING } from './native.js'
27
+
28
+ // The models whose price weighs an entry, first that has one: the model that
29
+ // answered (`ask.served`), then the one it asked (`ask.to`) or its `using`
30
+ // names.
31
+ let served = (b: Bundle | undefined): string[] => {
32
+ let ask = b?.[ASK] as Comp | undefined
33
+ let to = ask?.to ?? (b?.[USING] as Comp | undefined)?.model
34
+ return [ask?.served, to].filter((m) => m != null).map(String)
35
+ }
36
+
37
+ /**
38
+ * The precondition that weighs a request its provider named no price for: a
39
+ * bundle carrying `usage` and no `cost` gains `cost{dollars, reported: false}`
40
+ * when the model that answered it has a `price`, the batch's or else the
41
+ * stored one. The model and the counts are the bundle's over the entry as
42
+ * stored, so a patch that only adds the usage is weighed whole; a cost the
43
+ * entry already records stands.
44
+ */
45
+ export let weighing: Hook = (bundles, tx) => {
46
+ let owed = bundles.filter((b) => b[USAGE] && !(COST in b))
47
+ if (!owed.length) return bundles
48
+ let eids = owed.map((b) => b.entity.eid)
49
+ return after(tx.get(eids, [ASK, USING, USAGE, COST]), (held) => {
50
+ let stored = new Map(held.map((b) => [b.entity.eid, b]))
51
+ let was = (b: Bundle) => stored.get(b.entity.eid)
52
+ let fresh = owed.filter((b) => !was(b)?.[COST])
53
+ let model = (b: Bundle) => {
54
+ let w = was(b)
55
+ let over = (c: string) => ({ ...w?.[c] as Comp, ...b[c] as Comp })
56
+ return served({ ...b, [ASK]: over(ASK), [USING]: over(USING) })
57
+ }
58
+ let models = [...new Set(fresh.flatMap(model))]
59
+ return after(models.length ? tx.get(models, [PRICE]) : [], (rows) => {
60
+ let price = new Map(
61
+ [...rows, ...bundles].filter((r) => r[PRICE]).map((r) => [
62
+ r.entity.eid,
63
+ r[PRICE],
64
+ ]),
65
+ )
66
+ return bundles.map((b) => {
67
+ let at = fresh.includes(b) &&
68
+ model(b).map((m) => price.get(m)).find(Boolean)
69
+ if (!at) return b
70
+ let usage = { ...was(b)?.[USAGE] as Usage, ...b[USAGE] as Usage }
71
+ let dollars = weigh(at as Price, usage)
72
+ return { ...b, [COST]: { dollars, reported: false } }
73
+ })
74
+ })
75
+ })
76
+ }
77
+
78
+ /** `session.cost` as SQL, for @yaks/sqlite's derived-property registry: the
79
+ * dollars its entries record, or nothing where none records any. */
80
+ export let sessionCost: DerivedProp = {
81
+ stable: true,
82
+ tag: 'number',
83
+ whole: false,
84
+ expr: (owner) =>
85
+ sub(select({
86
+ cols: [fn('sum', col('dollars', 'k'))],
87
+ from: table('entry', 'e'),
88
+ joins: [
89
+ join(table(COST, 'k'), eq(col('entity', 'k'), col('entity', 'e'))),
90
+ ],
91
+ where: eq(col('session', 'e'), owner),
92
+ })),
93
+ }
package/deferred.js ADDED
@@ -0,0 +1,207 @@
1
+ // Tools a transcript is offered by name until it loads them. A runner that
2
+ // holds more tools than a turn needs marks the rest `deferred`: their schemas
3
+ // stay out of the request, and one tool, `tool_load`, lists them by name and
4
+ // title. A transcript that calls it is sent their schemas from then on: a
5
+ // turn sends what the newest ask sent, and what the entries since loaded. A
6
+ // deferred tool runs whenever it is called, loaded or not, and once called it
7
+ // is sent too, so a request never replays a call to a tool it does not carry.
8
+ // The tools come first in a provider's cached prefix, so a set that only grows
9
+ // keeps that prefix whatever a turn reads of its transcript (an anchor, a
10
+ // window, a summary). A tool the runner holds but a turn does not is
11
+ // `withheld`: neither listed, sent nor run, and a `tool_load` naming it is told
12
+ // why, so the turn works with what it holds instead of guessing at names. A
13
+ // call naming some it cannot load loads the rest and names those it refused.
14
+ import { argsOf } from "@yaks/graph/call";
15
+ import { CallError } from "@yaks/tools/errors";
16
+ import { found } from "@yaks/tools/registry";
17
+ import { toolEid } from "@yaks/tools/result";
18
+ import { validateToolInput } from "@yaks/vocab/tools";
19
+ import { CALL } from "./native.js";
20
+ /** The name of the tool that loads deferred ones. */ export let LOAD = 'tool_load';
21
+ /** What the loader says of itself wherever it is offered: its name, title,
22
+ * how a call to it reads to the person (@yaks/tools `stepOf`), and the first
23
+ * of its description, which a turn follows with the tools it can load. */ export let LOADER = {
24
+ name: LOAD,
25
+ title: 'Load tools',
26
+ step: {
27
+ doing: 'Getting ready…',
28
+ done: 'Got ready'
29
+ },
30
+ description: 'Load tools you are not sent yet by name. Their schemas are sent with your next turn. Load every one a task needs in one call.'
31
+ };
32
+ // A deferred tool as the catalog lists it: its title, or its description's
33
+ // first sentence.
34
+ let line = (t)=>`- ${t.name}: ${t.title ?? t.description.split(/(?<=\.)\s/)[0].slice(0, 120)}`;
35
+ /** The turn's available deferred tools, independent of the loader schema. */ export let catalog = (tools)=>tools.filter((t)=>t.deferred && !t.withheld).map(line).sort().join('\n');
36
+ /**
37
+ * The tool among `known` a loaded name means: the name itself, or the name
38
+ * without the `<server>__` prefixes a caller wrote before it.
39
+ *
40
+ * ```ts
41
+ * let known = new Set(['task_list'])
42
+ * named('tasks__task_list', known) // 'task_list'
43
+ * named('mcp__tasks__task_list', known) // 'task_list'
44
+ * named('task_lists', known) // undefined
45
+ * ```
46
+ */ export let named = (name, known)=>{
47
+ for(let n = name;; n = n.slice(n.indexOf('__') + 2)){
48
+ if (known.has(n)) return n;
49
+ if (!n.includes('__')) return undefined;
50
+ }
51
+ };
52
+ /**
53
+ * The refusal of names a turn cannot load: a withheld tool with why it is
54
+ * withheld, and a name no tool has with the tools whose name, title or
55
+ * description say what its words do (@yaks/tools/registry `found`), so the
56
+ * next call names one that is there.
57
+ *
58
+ * ```ts
59
+ * let tool = (name: string, description: string) => ({ name, description })
60
+ * let tools = [
61
+ * tool('mail_send', 'Send a letter.'),
62
+ * tool('attachment_read', 'Read a file the person sent.'),
63
+ * ]
64
+ * unknown(['file_attach'], tools)
65
+ * // 'There is no tool called file_attach; nearest: attachment_read. Load one by a name tool_load lists.'
66
+ * unknown(['code_mode'], tools, new Map([['code_mode', 'it writes']]))
67
+ * // 'code_mode is not held in this turn: it writes. Load one by a name tool_load lists.'
68
+ * ```
69
+ */ export let unknown = (missing, tools, withheld = new Map())=>{
70
+ let said = (t)=>`${t.name} ${t.title ?? ''} ${t.description}`;
71
+ return missing.map((n)=>{
72
+ let why = withheld.get(named(n, new Set(withheld.keys())) ?? '');
73
+ if (why) return `${n} is not held in this turn: ${why.replace(/\.+$/, '')}`;
74
+ let near = found(n.split('__').at(-1), tools, said).slice(0, 5);
75
+ return `There is no tool called ${n}` + (near.length ? `; nearest: ${near.map((t)=>t.name).join(', ')}` : '');
76
+ }).join('. ') + `. Load one by a name ${LOAD} lists.`;
77
+ };
78
+ // What `tool_load` takes: the names of the tools to load.
79
+ let parameters = {
80
+ type: 'object',
81
+ properties: {
82
+ names: {
83
+ type: 'array',
84
+ items: {
85
+ type: 'string'
86
+ },
87
+ description: 'The tools to load.'
88
+ }
89
+ },
90
+ required: [
91
+ 'names'
92
+ ]
93
+ };
94
+ // The names a `tool_load` call gives, read as its run is handed them
95
+ // (@yaks/vocab/tools `validateToolInput`), so a list a model wrote as a
96
+ // string of JSON loads what it names; arguments its run refuses load nothing.
97
+ let namesOf = (call)=>{
98
+ try {
99
+ return validateToolInput({
100
+ inputSchema: parameters
101
+ }, argsOf(call)).names;
102
+ } catch {
103
+ return [];
104
+ }
105
+ };
106
+ /**
107
+ * The tools a runner offers, with `tool_load` beside them when any is
108
+ * deferred: its description lists each deferred one, and its call names
109
+ * those to send from then on. A withheld tool is left out, and named in
110
+ * `tool_load`'s refusal with why.
111
+ *
112
+ * ```ts
113
+ * let tool = (name: string, deferred = false) =>
114
+ * ({ name, description: `${name}.`, parameters: {}, deferred, run: () => name })
115
+ * loading([tool('search'), tool('buy', true)]).map((t) => t.name)
116
+ * // ['search', 'buy', 'tool_load']
117
+ * let sell = { ...tool('sell'), withheld: 'it spends' }
118
+ * loading([tool('search'), tool('buy', true), sell]).map((t) => t.name)
119
+ * // ['search', 'buy', 'tool_load']
120
+ * ```
121
+ */ export let loading = (offered, separate = false)=>{
122
+ let withheld = new Map(offered.flatMap((t)=>t.withheld ? [
123
+ [
124
+ t.name,
125
+ t.withheld
126
+ ]
127
+ ] : []));
128
+ let tools = offered.filter((t)=>!t.withheld);
129
+ let later = tools.filter((t)=>t.deferred);
130
+ if (!later.length || tools.some((t)=>t.name == LOAD)) {
131
+ return tools;
132
+ }
133
+ let known = new Set(later.map((t)=>t.name));
134
+ let sent = new Set(tools.filter((t)=>!t.deferred).map((t)=>t.name));
135
+ let load = {
136
+ ...LOADER,
137
+ description: LOADER.description + (separate ? ' The current context lists the tools you can load.' : ' These are the tools you can load:\n' + later.map(line).join('\n')),
138
+ parameters,
139
+ readOnly: true,
140
+ run: (args)=>{
141
+ let names = args.names ?? [];
142
+ let held = names.flatMap((n)=>named(n, sent) ?? []);
143
+ let missing = names.filter((n)=>!named(n, known) && !named(n, sent));
144
+ let refused = missing.length ? unknown(missing, tools, withheld) : '';
145
+ let loaded = names.flatMap((n)=>named(n, known) ?? []);
146
+ if (!loaded.length && !held.length) throw new CallError('tool', refused);
147
+ return [
148
+ ...loaded.length ? [
149
+ `Loaded ${loaded.join(', ')}.`
150
+ ] : [],
151
+ ...held.length ? [
152
+ `${held.join(', ')} you hold already.`
153
+ ] : [],
154
+ 'Call them directly.',
155
+ ...refused ? [
156
+ refused
157
+ ] : []
158
+ ].join(' ');
159
+ }
160
+ };
161
+ return [
162
+ ...tools,
163
+ load
164
+ ];
165
+ };
166
+ /**
167
+ * The tools a request sends: every one not deferred, and the deferred ones
168
+ * `sent` names (what the newest ask sent), a `tool_load` call among `entries`
169
+ * named or a call among them called.
170
+ *
171
+ * ```ts
172
+ * import { found } from '@yaks/tools/registry'
173
+ import { toolEid } from '@yaks/tools/result'
174
+ *
175
+ * let tool = (name: string, deferred = false) =>
176
+ * ({ name, description: name, parameters: {}, deferred, run: () => name })
177
+ * let load = {
178
+ * entity: { eid: 'c' },
179
+ * call: { to: toolEid('tool_load'), args: { names: ['shop__buy'] } },
180
+ * }
181
+ * let sold = { entity: { eid: 'd' }, call: { to: toolEid('sell') } }
182
+ * let tools = [tool('search'), tool('buy', true), tool('sell', true)]
183
+ * schemas(tools, [load]).map((t) => t.name) // ['search', 'buy']
184
+ * schemas(tools, [sold]).map((t) => t.name) // ['search', 'sell']
185
+ * let quoted = { ...load, call: { ...load.call, args: { names: '["buy"]' } } }
186
+ * schemas(tools, [quoted]).map((t) => t.name) // ['search', 'buy']
187
+ * let wrong = { ...load, call: { ...load.call, args: { names: 7 } } }
188
+ * schemas(tools, [wrong]).map((t) => t.name) // ['search']
189
+ * schemas(tools, [], ['sell', 'search']).map((t) => t.name) // ['search', 'sell']
190
+ * ```
191
+ */ export let schemas = (tools, entries, sent = [])=>{
192
+ if (!tools.some((t)=>t.deferred)) return tools;
193
+ let known = new Set(tools.filter((t)=>t.deferred).map((t)=>t.name));
194
+ let load = toolEid(LOAD);
195
+ let loaded = new Set([
196
+ ...sent.map(toolEid),
197
+ ...entries.flatMap((b)=>{
198
+ let to = b[CALL]?.to;
199
+ if (to != load) return to ? [
200
+ to
201
+ ] : [];
202
+ return namesOf(b).map((n)=>toolEid(named(n, known) ?? n));
203
+ })
204
+ ]);
205
+ return tools.filter((t)=>!t.deferred || loaded.has(toolEid(t.name)));
206
+ };
207
+ //# sourceMappingURL=deferred.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferred.js","sources":["./deferred.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,6EAA6E;AAC7E,0EAA0E;AAC1E,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,0EAA0E;AAC1E,qEAAqE;AACrE,gFAAgF;AAChF,4EAA4E;AAC5E,6EAA6E;AAE7E,SAAS,MAAM,gCAAqC;AACpD,SAAS,SAAS,kCAAuC;AACzD,SAAS,KAAK,oCAAyC;AACvD,SAAS,OAAO,kCAAuC;AACvD,SAAS,iBAAiB,iCAAsC;AAChE,SAAS,IAAI,sBAAqB;AAGlC,mDAAmD,GACnD,OAAO,IAAI,OAAO,YAAW;AAE7B;;wEAEwE,GACxE,OAAO,IAAI,SAAgE;EACzE,MAAM;EACN,OAAO;EACP,MAAM;IAAE,OAAO;IAAkB,MAAM;EAAY;EACnD,aACE;AACJ,EAAC;AAED,2EAA2E;AAC3E,kBAAkB;AAClB,IAAI,OAAO,CAAC,IACV,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,EAAE,KAAK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;MACrC,OAAO,QAAQ,GAAG,GAAG,CAAC,CAAC,IAAM,QAAQ,MAAM,GAAG,UAAU;IAC1D;GACD;EACD,OAAO,MAAM,MAAM,CAAC,CAAC,IAAM,CAAC,EAAE,QAAQ,IAAI,OAAO,GAAG,CAAC,QAAQ,EAAE,IAAI;AACrE,EAAC"}
package/deferred.ts ADDED
@@ -0,0 +1,219 @@
1
+ // Tools a transcript is offered by name until it loads them. A runner that
2
+ // holds more tools than a turn needs marks the rest `deferred`: their schemas
3
+ // stay out of the request, and one tool, `tool_load`, lists them by name and
4
+ // title. A transcript that calls it is sent their schemas from then on: a
5
+ // turn sends what the newest ask sent, and what the entries since loaded. A
6
+ // deferred tool runs whenever it is called, loaded or not, and once called it
7
+ // is sent too, so a request never replays a call to a tool it does not carry.
8
+ // The tools come first in a provider's cached prefix, so a set that only grows
9
+ // keeps that prefix whatever a turn reads of its transcript (an anchor, a
10
+ // window, a summary). A tool the runner holds but a turn does not is
11
+ // `withheld`: neither listed, sent nor run, and a `tool_load` naming it is told
12
+ // why, so the turn works with what it holds instead of guessing at names. A
13
+ // call naming some it cannot load loads the rest and names those it refused.
14
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
15
+ import { argsOf } from '@yaks/graph/call'
16
+ import { CallError } from '@yaks/tools/errors'
17
+ import { found } from '@yaks/tools/registry'
18
+ import { toolEid } from '@yaks/tools/result'
19
+ import { validateToolInput } from '@yaks/vocab/tools'
20
+ import { CALL } from './native.js'
21
+ import type { Tool } from './react.ts'
22
+
23
+ /** The name of the tool that loads deferred ones. */
24
+ export let LOAD = 'tool_load'
25
+
26
+ /** What the loader says of itself wherever it is offered: its name, title,
27
+ * how a call to it reads to the person (@yaks/tools `stepOf`), and the first
28
+ * of its description, which a turn follows with the tools it can load. */
29
+ export let LOADER: Pick<Tool, 'name' | 'title' | 'step' | 'description'> = {
30
+ name: LOAD,
31
+ title: 'Load tools',
32
+ step: { doing: 'Getting ready…', done: 'Got ready' },
33
+ description:
34
+ 'Load tools you are not sent yet by name. Their schemas are sent with your next turn. Load every one a task needs in one call.',
35
+ }
36
+
37
+ // A deferred tool as the catalog lists it: its title, or its description's
38
+ // first sentence.
39
+ let line = (t: Tool) =>
40
+ `- ${t.name}: ${t.title ?? t.description.split(/(?<=\.)\s/)[0].slice(0, 120)}`
41
+
42
+ /** The turn's available deferred tools, independent of the loader schema. */
43
+ export let catalog = (tools: Tool[]): string =>
44
+ tools.filter((t) => t.deferred && !t.withheld).map(line).sort().join('\n')
45
+
46
+ /**
47
+ * The tool among `known` a loaded name means: the name itself, or the name
48
+ * without the `<server>__` prefixes a caller wrote before it.
49
+ *
50
+ * ```ts
51
+ * let known = new Set(['task_list'])
52
+ * named('tasks__task_list', known) // 'task_list'
53
+ * named('mcp__tasks__task_list', known) // 'task_list'
54
+ * named('task_lists', known) // undefined
55
+ * ```
56
+ */
57
+ export let named = (name: string, known: Set<string>): string | undefined => {
58
+ for (let n = name;; n = n.slice(n.indexOf('__') + 2)) {
59
+ if (known.has(n)) return n
60
+ if (!n.includes('__')) return undefined
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The refusal of names a turn cannot load: a withheld tool with why it is
66
+ * withheld, and a name no tool has with the tools whose name, title or
67
+ * description say what its words do (@yaks/tools/registry `found`), so the
68
+ * next call names one that is there.
69
+ *
70
+ * ```ts
71
+ * let tool = (name: string, description: string) => ({ name, description })
72
+ * let tools = [
73
+ * tool('mail_send', 'Send a letter.'),
74
+ * tool('attachment_read', 'Read a file the person sent.'),
75
+ * ]
76
+ * unknown(['file_attach'], tools)
77
+ * // 'There is no tool called file_attach; nearest: attachment_read. Load one by a name tool_load lists.'
78
+ * unknown(['code_mode'], tools, new Map([['code_mode', 'it writes']]))
79
+ * // 'code_mode is not held in this turn: it writes. Load one by a name tool_load lists.'
80
+ * ```
81
+ */
82
+ export let unknown = (
83
+ missing: string[],
84
+ tools: Pick<Tool, 'name' | 'title' | 'description'>[],
85
+ withheld: Map<string, string> = new Map(),
86
+ ): string => {
87
+ let said = (t: (typeof tools)[number]) =>
88
+ `${t.name} ${t.title ?? ''} ${t.description}`
89
+ return missing.map((n) => {
90
+ let why = withheld.get(named(n, new Set(withheld.keys())) ?? '')
91
+ if (why) return `${n} is not held in this turn: ${why.replace(/\.+$/, '')}`
92
+ let near = found(n.split('__').at(-1)!, tools, said).slice(0, 5)
93
+ return `There is no tool called ${n}` +
94
+ (near.length ? `; nearest: ${near.map((t) => t.name).join(', ')}` : '')
95
+ }).join('. ') + `. Load one by a name ${LOAD} lists.`
96
+ }
97
+
98
+ // What `tool_load` takes: the names of the tools to load.
99
+ let parameters = {
100
+ type: 'object',
101
+ properties: {
102
+ names: {
103
+ type: 'array',
104
+ items: { type: 'string' },
105
+ description: 'The tools to load.',
106
+ },
107
+ },
108
+ required: ['names'],
109
+ }
110
+
111
+ // The names a `tool_load` call gives, read as its run is handed them
112
+ // (@yaks/vocab/tools `validateToolInput`), so a list a model wrote as a
113
+ // string of JSON loads what it names; arguments its run refuses load nothing.
114
+ let namesOf = (call: Bundle): string[] => {
115
+ try {
116
+ return validateToolInput({ inputSchema: parameters }, argsOf(call))
117
+ .names as string[]
118
+ } catch {
119
+ return []
120
+ }
121
+ }
122
+
123
+ /**
124
+ * The tools a runner offers, with `tool_load` beside them when any is
125
+ * deferred: its description lists each deferred one, and its call names
126
+ * those to send from then on. A withheld tool is left out, and named in
127
+ * `tool_load`'s refusal with why.
128
+ *
129
+ * ```ts
130
+ * let tool = (name: string, deferred = false) =>
131
+ * ({ name, description: `${name}.`, parameters: {}, deferred, run: () => name })
132
+ * loading([tool('search'), tool('buy', true)]).map((t) => t.name)
133
+ * // ['search', 'buy', 'tool_load']
134
+ * let sell = { ...tool('sell'), withheld: 'it spends' }
135
+ * loading([tool('search'), tool('buy', true), sell]).map((t) => t.name)
136
+ * // ['search', 'buy', 'tool_load']
137
+ * ```
138
+ */
139
+ export let loading = (offered: Tool[], separate = false): Tool[] => {
140
+ let withheld = new Map(
141
+ offered.flatMap((t) => t.withheld ? [[t.name, t.withheld]] : []),
142
+ )
143
+ let tools = offered.filter((t) => !t.withheld)
144
+ let later = tools.filter((t) => t.deferred)
145
+ if (!later.length || tools.some((t) => t.name == LOAD)) {
146
+ return tools
147
+ }
148
+ let known = new Set(later.map((t) => t.name))
149
+ let sent = new Set(tools.filter((t) => !t.deferred).map((t) => t.name))
150
+ let load: Tool = {
151
+ ...LOADER,
152
+ description: LOADER.description +
153
+ (separate
154
+ ? ' The current context lists the tools you can load.'
155
+ : ' These are the tools you can load:\n' + later.map(line).join('\n')),
156
+ parameters,
157
+ readOnly: true,
158
+ run: (args) => {
159
+ let names = (args.names ?? []) as string[]
160
+ let held = names.flatMap((n) => named(n, sent) ?? [])
161
+ let missing = names.filter((n) => !named(n, known) && !named(n, sent))
162
+ let refused = missing.length ? unknown(missing, tools, withheld) : ''
163
+ let loaded = names.flatMap((n) => named(n, known) ?? [])
164
+ if (!loaded.length && !held.length) throw new CallError('tool', refused)
165
+ return [
166
+ ...loaded.length ? [`Loaded ${loaded.join(', ')}.`] : [],
167
+ ...held.length ? [`${held.join(', ')} you hold already.`] : [],
168
+ 'Call them directly.',
169
+ ...refused ? [refused] : [],
170
+ ].join(' ')
171
+ },
172
+ }
173
+ return [...tools, load]
174
+ }
175
+
176
+ /**
177
+ * The tools a request sends: every one not deferred, and the deferred ones
178
+ * `sent` names (what the newest ask sent), a `tool_load` call among `entries`
179
+ * named or a call among them called.
180
+ *
181
+ * ```ts
182
+ * import { found } from '@yaks/tools/registry'
183
+ import { toolEid } from '@yaks/tools/result'
184
+ *
185
+ * let tool = (name: string, deferred = false) =>
186
+ * ({ name, description: name, parameters: {}, deferred, run: () => name })
187
+ * let load = {
188
+ * entity: { eid: 'c' },
189
+ * call: { to: toolEid('tool_load'), args: { names: ['shop__buy'] } },
190
+ * }
191
+ * let sold = { entity: { eid: 'd' }, call: { to: toolEid('sell') } }
192
+ * let tools = [tool('search'), tool('buy', true), tool('sell', true)]
193
+ * schemas(tools, [load]).map((t) => t.name) // ['search', 'buy']
194
+ * schemas(tools, [sold]).map((t) => t.name) // ['search', 'sell']
195
+ * let quoted = { ...load, call: { ...load.call, args: { names: '["buy"]' } } }
196
+ * schemas(tools, [quoted]).map((t) => t.name) // ['search', 'buy']
197
+ * let wrong = { ...load, call: { ...load.call, args: { names: 7 } } }
198
+ * schemas(tools, [wrong]).map((t) => t.name) // ['search']
199
+ * schemas(tools, [], ['sell', 'search']).map((t) => t.name) // ['search', 'sell']
200
+ * ```
201
+ */
202
+ export let schemas = (
203
+ tools: Tool[],
204
+ entries: Bundle[],
205
+ sent: string[] = [],
206
+ ): Tool[] => {
207
+ if (!tools.some((t) => t.deferred)) return tools
208
+ let known = new Set(tools.filter((t) => t.deferred).map((t) => t.name))
209
+ let load = toolEid(LOAD)
210
+ let loaded = new Set([
211
+ ...sent.map(toolEid),
212
+ ...entries.flatMap((b) => {
213
+ let to = (b[CALL] as { to?: unknown } | undefined)?.to
214
+ if (to != load) return to ? [to] : []
215
+ return namesOf(b).map((n) => toolEid(named(n, known) ?? n))
216
+ }),
217
+ ])
218
+ return tools.filter((t) => !t.deferred || loaded.has(toolEid(t.name)))
219
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","./testing.ts"]},"name":"@yaks/session","version":"0.2.36","license":"Apache-2.0","description":"Represents sessions as graph transcripts, derives status from their entries, manages claims, and runs a transcript wherever its effects are worked.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./graph":"./graph.ts","./who":"./who.ts","./tools":"./tools.ts","./views":"./views.ts","./conversation":"./conversation.ts","./prose":"./prose.ts","./intake":"./intake.ts","./service":"./service.ts","./routes":"./routes.ts","./parts":"./parts.ts","./files":"./files.ts","./tail":"./tail.ts","./status":"./status.ts","./wait":"./wait.ts","./admission":"./admission.ts","./deferred":"./deferred.ts","./cli":"./cli.ts","./ended":"./ended.ts","./transcript":"./transcript.ts","./told":"./told.ts","./turn":"./turn.ts"},"imports":{"@yaks/session":"./mod.ts","@yaks/session/vocab":"./vocab.ts","@yaks/session/graph":"./graph.ts","@yaks/session/who":"./who.ts","@yaks/session/tools":"./tools.ts","@yaks/session/views":"./views.ts","@yaks/session/conversation":"./conversation.ts","@yaks/session/prose":"./prose.ts","@yaks/session/intake":"./intake.ts","@yaks/session/service":"./service.ts","@yaks/session/routes":"./routes.ts","@yaks/session/parts":"./parts.ts","@yaks/session/files":"./files.ts","@yaks/session/tail":"./tail.ts","@yaks/session/status":"./status.ts","@yaks/session/wait":"./wait.ts","@yaks/session/admission":"./admission.ts","@yaks/session/deferred":"./deferred.ts","@yaks/session/cli":"./cli.ts","@yaks/session/ended":"./ended.ts","@yaks/session/transcript":"./transcript.ts","@yaks/session/told":"./told.ts","@yaks/session/turn":"./turn.ts"}}
@@ -0,0 +1,114 @@
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 { token } from "@yaks/graph/sha256";
5
+ import { dependencies, settled, statusOf } from "@yaks/task";
6
+ import { currentStatus } from "./react.js";
7
+ let comp = (b, name)=>b?.[name];
8
+ let external = async (g, row)=>{
9
+ if (row.decision || row.blocked) return true;
10
+ let assignee = comp(row, 'filed')?.assignee;
11
+ return !!assignee && !!g.vocab.comp('person') && !!(await g.get([
12
+ String(assignee)
13
+ ], [
14
+ 'person'
15
+ ]))[0]?.person;
16
+ };
17
+ /** Follow unfinished dependencies to their runnable leaves. Other active
18
+ * workers keep their work; missing or terminal holders can be replaced. */ export let unattended = async (g, session, roots)=>{
19
+ let found = {
20
+ tasks: [],
21
+ claims: [],
22
+ problems: [],
23
+ resume: new Map(),
24
+ release: []
25
+ };
26
+ let seen = new Set();
27
+ let visit = async (eid, path)=>{
28
+ if (path.includes(eid)) {
29
+ found.problems.push(`Dependency cycle: ${[
30
+ ...path,
31
+ eid
32
+ ].join(' -> ')}`);
33
+ return;
34
+ }
35
+ if (seen.has(eid)) return;
36
+ seen.add(eid);
37
+ let [row] = await g.get([
38
+ eid
39
+ ]);
40
+ if (!row?.task) {
41
+ found.problems.push(`Dependency ${eid} is missing or is not a task`);
42
+ return;
43
+ }
44
+ if (settled(statusOf(g.vocab, row)) || await external(g, row)) return;
45
+ let holder = comp(row, 'claim')?.session;
46
+ let [owner] = holder && holder != session ? await g.get([
47
+ String(holder)
48
+ ], [
49
+ 'session',
50
+ 'process',
51
+ 'exit',
52
+ 'stop'
53
+ ]) : [];
54
+ // Wrapping a managed run marks the session ended before its process exits.
55
+ // Its process remains the authority, including while it is winding down.
56
+ if (owner?.session && owner.process && !owner.exit) return;
57
+ let ended = !owner?.process && comp(owner, 'session')?.ended === true || !!owner?.stop;
58
+ let status = owner?.session && !owner.process ? await currentStatus(g, String(holder)) : undefined;
59
+ let abandoned = !owner?.session || ended || status == 'failed' || status == 'stopped' || !!owner?.exit && comp(owner, 'exit')?.code !== 0;
60
+ if (holder && holder != session && abandoned) {
61
+ // Claim release owns this transition. Never overwrite another holder,
62
+ // including one whose terminal entry has not been reconciled yet.
63
+ found.release.push(eid);
64
+ return;
65
+ }
66
+ if (holder && holder != session && !abandoned) {
67
+ // A running/queued worker owns its whole dependency chain. A resting
68
+ // worker's leaves are inspected too, so nested parking cannot hide work.
69
+ if (owner?.process ? !owner.exit : status != 'settled') return;
70
+ }
71
+ let kids = await dependencies(g, eid);
72
+ let open = [];
73
+ for (let kid of kids){
74
+ let [child] = await g.get([
75
+ kid
76
+ ]);
77
+ if (!child || !settled(statusOf(g.vocab, child))) open.push(kid);
78
+ }
79
+ if (open.length) {
80
+ for (let kid of open)await visit(kid, [
81
+ ...path,
82
+ eid
83
+ ]);
84
+ return;
85
+ }
86
+ if (holder && holder != session && !abandoned) {
87
+ let tasks = found.resume.get(String(holder)) ?? [];
88
+ tasks.push(row);
89
+ found.resume.set(String(holder), tasks);
90
+ return;
91
+ }
92
+ found.tasks.push(row);
93
+ found.claims.push({
94
+ entity: row.entity,
95
+ claim: {
96
+ session
97
+ },
98
+ $was: {
99
+ claim: {
100
+ session: token(holder)
101
+ }
102
+ }
103
+ });
104
+ };
105
+ for (let root of roots){
106
+ for (let dep of (await dependencies(g, root.entity.eid))){
107
+ await visit(dep, [
108
+ root.entity.eid
109
+ ]);
110
+ }
111
+ }
112
+ return found;
113
+ };
114
+ //# sourceMappingURL=dependencies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dependencies.js","sources":["./dependencies.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,+EAA+E;AAC/E,oEAAoE;AAEpE,SAAS,KAAK,kCAAuC;AACrD,SAAS,YAAY,EAAE,OAAO,EAAE,QAAQ,0BAA+B;AACvE,SAAS,aAAa,qBAAoB;AAE1C,IAAI,OAAO,CAAC,GAAuB,OACjC,GAAG,CAAC,KAAK;AAUX,IAAI,WAAW,OAAO,GAAU;EAC9B,IAAI,IAAI,QAAQ,IAAI,IAAI,OAAO,EAAE,OAAO;EACxC,IAAI,WAAW,KAAK,KAAK,UAAU;EACnC,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,aAClC,CAAC,CAAC,CAAC,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO;GAAU,EAAE;IAAC;GAAS,CAAC,CAAC,CAAC,EAAE,EAAE;AACxD;AAEA;yEACyE,GACzE,OAAO,IAAI,aAAa,OACtB,GACA,SACA;EAEA,IAAI,QAAc;IAChB,OAAO,EAAE;IACT,QAAQ,EAAE;IACV,UAAU,EAAE;IACZ,QAAQ,IAAI;IACZ,SAAS,EAAE;EACb;EACA,IAAI,OAAO,IAAI;EACf,IAAI,QAAQ,OAAO,KAAU;IAC3B,IAAI,KAAK,QAAQ,CAAC,MAAM;MACtB,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC,kBAAkB,EAAE;WAAI;QAAM;OAAI,CAAC,IAAI,CAAC,SAAS;MACtE;IACF;IACA,IAAI,KAAK,GAAG,CAAC,M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