@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/project.ts ADDED
@@ -0,0 +1,407 @@
1
+ // The model's view of a transcript: the items a request carries, made from
2
+ // entries. A step projects the whole transcript it sends, so this runs once
3
+ // per request over every line a long session holds; it is linear in the
4
+ // transcript, never a pass over it per ask or per result.
5
+
6
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
7
+ import { type Item, message, type Tool as Declared } from '@yaks/model'
8
+ import { type InputText, source } from './source.js'
9
+ import { ASK, CALL, OUTPUT, RESULT } from './native.js'
10
+ import { kindOf, ordered, seqOf, textOf } from './state.js'
11
+ import { items as taskItems, type Tasks } from './task-context.js'
12
+ import { took } from './timing.js'
13
+
14
+ let comp = (b: Bundle | undefined, name: string) =>
15
+ b?.[name] as Comp | undefined
16
+
17
+ /** What a background call (`tool_async`) answers while it runs: its interim
18
+ * result, paired with the call like any other, and saying what it means where
19
+ * the model reads it. A request derives it from the call; a call that outlasts
20
+ * its patience is also given it as an entry (`tool_progress`, ./react.ts), the
21
+ * new line that lets the model take a turn while it runs. The final arrives
22
+ * later, naming its call ({@link project}). */
23
+ export let PENDING = 'Pending; its result will follow.'
24
+
25
+ /** What closes a request whose conversation ends on the agent's own words,
26
+ * such as a voice's on a call said outside a model turn (`notice.own`):
27
+ * asked to go on from its own words, a model would finish them, and some
28
+ * refuse to (Anthropic's "must end with a user message"). */
29
+ export let TURN = 'Nothing has been said since your words above; this is ' +
30
+ 'your turn.'
31
+
32
+ /// let said = { kind: 'assistant' as const, text: 'One moment.' }
33
+ /// let asked = { kind: 'user' as const, text: 'Add a recipe.' }
34
+ /// closed([asked, said]) -> [asked, said, { kind: 'instruction', text: 'From the system:\n' + TURN }]
35
+ /// closed([said, asked]) -> [said, asked]
36
+ /** A request's items as a turn the model takes: ending on its own words, they
37
+ * are closed by {@link TURN}, so every line stays where it was said and the
38
+ * model answers rather than continues. */
39
+ export let closed = (items: Item[]): Item[] =>
40
+ items.at(-1)?.kind == 'assistant'
41
+ ? [...items, message({ kind: 'instruction', text: TURN }, 'the system')]
42
+ : items
43
+
44
+ // The call an entry answers: a final's or a Pending's.
45
+ let answers = (b: Bundle) =>
46
+ comp(b, RESULT)?.call ?? comp(b, 'tool_progress')?.call
47
+
48
+ let clip = (text: string, max = 120) =>
49
+ text.length > max ? text.slice(0, max) + '…' : text
50
+
51
+ // The ask an entry answers: an output's or a call's source, or for a call's
52
+ // progress, the source of that call.
53
+ let sourceOf = (b: Bundle, byId: Map<Eid, Bundle>): unknown =>
54
+ comp(b, OUTPUT)?.source ?? comp(b, CALL)?.source ??
55
+ comp(byId.get(String(comp(b, 'tool_progress')?.call)), CALL)?.source
56
+
57
+ // The index of the first of ascending `seqs` at or past `seq`.
58
+ let reaching = (seqs: number[], seq: number) => {
59
+ let lo = 0, hi = seqs.length
60
+ while (lo < hi) {
61
+ let mid = (lo + hi) >> 1
62
+ if (seqs[mid] < seq) lo = mid + 1
63
+ else hi = mid
64
+ }
65
+ return lo
66
+ }
67
+
68
+ /**
69
+ * Each reply moved to just after the line its ask was sent through
70
+ * (`ask.through`), asks taken oldest first; a reply whose boundary is not
71
+ * among `lines` stays where it is. A reply is its entries in their order in
72
+ * `lines`. The list is linked by index, so every move costs the reply's own
73
+ * length.
74
+ *
75
+ * ```ts
76
+ * import { replied } from './project.ts'
77
+ * let e = (eid: string, more = {}) => ({ entity: { eid }, ...more })
78
+ * let lines = [
79
+ * e('in'),
80
+ * e('late'), // landed while the ask was answered
81
+ * e('out', { output: { source: 'ask' } }),
82
+ * ]
83
+ * let asks = [e('ask', { ask: { through: 'in' } })]
84
+ * replied(asks, lines, new Map()).map((b) => b.entity.eid)
85
+ * // -> ['in', 'out', 'late']
86
+ * ```
87
+ */
88
+ export let replied = (
89
+ asks: Bundle[],
90
+ lines: Bundle[],
91
+ byId: Map<Eid, Bundle>,
92
+ ): Bundle[] => {
93
+ let n = lines.length
94
+ // Node n is the head; next and prev make a ring through it.
95
+ let next = new Int32Array(n + 1), prev = new Int32Array(n + 1)
96
+ for (let i = 0; i <= n; i++) {
97
+ next[i] = (i + 1) % (n + 1)
98
+ prev[i] = (i + n) % (n + 1)
99
+ }
100
+ let at = new Map<Eid, number>()
101
+ let replies = new Map<string, number[]>()
102
+ lines.forEach((b, i) => {
103
+ if (!at.has(b.entity.eid)) at.set(b.entity.eid, i)
104
+ let source = sourceOf(b, byId)
105
+ if (source == null) return
106
+ let reply = replies.get(String(source))
107
+ if (reply) reply.push(i)
108
+ else replies.set(String(source), [i])
109
+ })
110
+ for (let ask of asks) {
111
+ let reply = replies.get(ask.entity.eid)
112
+ let boundary = at.get(String(comp(ask, ASK)?.through))
113
+ if (!reply || boundary == null || reply.includes(boundary)) continue
114
+ for (let i of reply) {
115
+ next[prev[i]] = next[i]
116
+ prev[next[i]] = prev[i]
117
+ }
118
+ let cursor = boundary
119
+ for (let i of reply) {
120
+ next[i] = next[cursor]
121
+ prev[i] = cursor
122
+ prev[next[cursor]] = i
123
+ next[cursor] = i
124
+ cursor = i
125
+ }
126
+ }
127
+ let out: Bundle[] = []
128
+ for (let i = next[n]; i != n; i = next[i]) out.push(lines[i])
129
+ return out
130
+ }
131
+
132
+ /** The model's view of a window of the transcript: inputs as user turns, what
133
+ * the model returned as assistant turns, tool calls and results as the pair a
134
+ * model expects. The full transcript resolves a result's call even when that
135
+ * call is outside the window. Ask entries are our record, not the model's;
136
+ * what the anchored reply itself said and the tool calls it asked for are
137
+ * already in the provider's state, so only the calls' results travel.
138
+ *
139
+ * Each call's answer (its Pending where a request sent one, else its final)
140
+ * follows the reply's last call, in the order of the calls, whatever order
141
+ * they landed in: many models pair a result with its call by position, never
142
+ * by id (GLM's chat template renders `<tool_response>` blocks in order and
143
+ * no ids). A final whose Pending a request already sent stays where it
144
+ * landed, and names its call by tool, id and arguments.
145
+ *
146
+ * ```ts
147
+ * import { project } from './project.ts'
148
+ * let n = 0
149
+ * let e = (comps: Record<string, unknown>) =>
150
+ * ({ entity: { eid: `e${++n}` }, entry: { session: 's', seq: n }, ...comps })
151
+ * let ask = (through: string) => e({ ask: { through } })
152
+ * let call = (id: string) =>
153
+ * e({ call: { to: 'echo', id, args: { id }, source: 'e2' }, tool_async: {} })
154
+ * let tools = new Map([
155
+ * ['echo', { name: 'echo', description: 'Echoes its id.', parameters: {} }],
156
+ * ])
157
+ * let entries = [
158
+ * e({ content: { body: 'go' } }), ask('e1'), call('a'), call('b'),
159
+ * e({ result: { call: 'e4' }, content: { body: 'B' } }), // landed first
160
+ * ask('e5'), // sent b's final and a's Pending
161
+ * e({ result: { call: 'e3' }, content: { body: 'A' } }),
162
+ * ]
163
+ * project(entries, entries, tools).map((i) =>
164
+ * i.kind == 'call'
165
+ * ? i.id
166
+ * : i.kind == 'result'
167
+ * ? i.output
168
+ * : 'text' in i
169
+ * ? i.text
170
+ * : i.label
171
+ * )
172
+ * // -> ['From an unknown sender:\ngo', 'a', 'b', 'From the system:\nPending; its result will follow.', 'From the echo tool:\nB',
173
+ * // 'From the echo tool:\nThe pending echo call a {"id":"a"} finished:\nA']
174
+ * ```
175
+ */
176
+ export let project = (
177
+ transcript: Bundle[],
178
+ window: Bundle[],
179
+ tools: Map<Eid, Declared>,
180
+ opts: {
181
+ anchor?: Eid
182
+ /** The model receiving this history; inherited assistant messages name
183
+ * their original session rather than posing as this model's output. */
184
+ session?: Eid
185
+ results?: Map<Eid, string>
186
+ media?: Map<Eid, Item[]>
187
+ history?: boolean
188
+ /** Each input's prose as the model reads it, rendered for this
189
+ * transcript (react's `Deps.inputText`). */
190
+ inputText?: (entry: Bundle) => InputText
191
+ /** The model takes one output per tool call (@yaks/model `lateResults`
192
+ * unset): a later update is told as user text. */
193
+ resultUpdatesAsUser?: boolean
194
+ /** Collect transient prompt entries at the request tail. */
195
+ turnItems?: Item[]
196
+ /** Observe the projected items associated with a transcript entry. */
197
+ projected?: (entry: Bundle, items: Item[]) => void
198
+ } = {},
199
+ ): Item[] => {
200
+ let out: Item[] = []
201
+ let receiver = opts.session ?? comp(window.at(-1), 'entry')?.session
202
+ let inherited = (b: Bundle) => {
203
+ let author = comp(b, 'entry')?.session
204
+ return receiver && author && receiver != author
205
+ ? 'your parent session'
206
+ : undefined
207
+ }
208
+ let byId = new Map(transcript.map((b) => [b.entity.eid, b]))
209
+ let asks = ordered(transcript).filter((b) => b.ask)
210
+ // A tool can finish (or a person steer) while the provider is answering.
211
+ // Those entries were not in that request. Keep its response immediately
212
+ // after its frozen boundary, then append the unsent updates. Never move or
213
+ // replace a previously submitted running result: the next full-context
214
+ // request must extend the previous request + response byte-for-byte.
215
+ let bounds = asks.map((ask) =>
216
+ seqOf(byId.get(String(comp(ask, ASK)?.through)) ?? ask)
217
+ ).sort((a, b) => a - b)
218
+ let finals = new Set(
219
+ window.flatMap((b) => b.result ? [String(comp(b, RESULT)?.call)] : []),
220
+ )
221
+ // Each call's final, and the seqs of its Pending entries: one written when
222
+ // it outlasted its patience, or, in older transcripts, beside every
223
+ // background call.
224
+ let landed = new Map<string, number>()
225
+ let progress = new Map<string, number[]>()
226
+ for (let b of transcript) {
227
+ if (b.result) landed.set(String(comp(b, RESULT)?.call), seqOf(b))
228
+ let call = comp(b, 'tool_progress')?.call
229
+ if (call == null) continue
230
+ let seqs = progress.get(String(call))
231
+ if (seqs) seqs.push(seqOf(b))
232
+ else progress.set(String(call), [seqOf(b)])
233
+ }
234
+ // A fast tool needs only its final answer. A request sent a Pending when its
235
+ // boundary reached the Pending but not yet its final; one that reached both
236
+ // sent the final alone. Keep a sent Pending: that immutable prefix cannot be
237
+ // rewritten afterwards, and a Pending no request sent is never sent late.
238
+ // The first boundary at or past the Pending decides it. A background call's
239
+ // Pending stands at the call, and at each Pending entry it has.
240
+ let sent = (call: string, seq: number) =>
241
+ (bounds[reaching(bounds, seq)] ?? Infinity) <
242
+ (landed.get(call) ?? Infinity)
243
+ let pendings = (call: string): number[] => {
244
+ let b = byId.get(call)
245
+ return [...progress.get(call) ?? [], ...b?.tool_async ? [seqOf(b)] : []]
246
+ }
247
+ let logical = replied(
248
+ asks,
249
+ window.filter((b) => {
250
+ let call = comp(b, 'tool_progress')?.call
251
+ return call == null || sent(String(call), seqOf(b)) ||
252
+ !finals.has(String(call))
253
+ }),
254
+ byId,
255
+ )
256
+ let recaps = logical.filter((b) => comp(b, 'prompt')?.scope == 'recap')
257
+ if (recaps.length) {
258
+ logical = logical.filter((b) => !recaps.includes(b))
259
+ let at = logical.findIndex((b) =>
260
+ !b.prompt && !b.checkpoint && !b.task_context
261
+ )
262
+ logical.splice(at < 0 ? logical.length : at, 0, ...recaps)
263
+ }
264
+ // A final that follows a Pending some request sent: the call was answered.
265
+ let late = (b: Bundle, call: string) =>
266
+ !!b.result &&
267
+ pendings(call).some((seq) => seq < seqOf(b) && sent(call, seq))
268
+ // A background call nothing in the window answers: its derived Pending
269
+ // travels where a request sent it, or while its final has not landed.
270
+ let pending = (call: Bundle) =>
271
+ !!call.tool_async &&
272
+ (sent(call.entity.eid, seqOf(call)) || !finals.has(call.entity.eid))
273
+ let spelled = (call: Bundle) => {
274
+ let c = comp(call, CALL)!
275
+ return {
276
+ id: String(c.id ?? ''),
277
+ name: tools.get(String(c.to))?.name ?? String(c.name ?? 'tool'),
278
+ args: c.args == null ? textOf(call) || '{}' : JSON.stringify(c.args),
279
+ }
280
+ }
281
+ // Each call's answer, and the calls of each reply, in order: an anchored
282
+ // reply's calls are the provider's already, yet their answers travel.
283
+ let answer = new Map<string, Bundle>()
284
+ let replies = new Map<string, Bundle[]>()
285
+ for (let b of logical) {
286
+ let call = answers(b)
287
+ if (call != null && !late(b, String(call)) && !answer.has(String(call))) {
288
+ answer.set(String(call), b)
289
+ }
290
+ let c = comp(b, CALL)
291
+ if (kindOf(b) != 'call') continue
292
+ let reply = replies.get(String(c?.source))
293
+ if (reply) reply.push(b)
294
+ else replies.set(String(c?.source), [b])
295
+ }
296
+ let index = new Map(logical.map((b, at) => [b, at]))
297
+ let taken = new Set<Bundle>()
298
+ let emit = (b: Bundle) => {
299
+ taken.add(b)
300
+ let kind = kindOf(b)
301
+ let c = comp(b, CALL)
302
+ if (b.prompt || b.checkpoint || b.task_context) {
303
+ if (b.checkpoint && !opts.history) {
304
+ out.push(
305
+ ...taskItems(
306
+ (b.checkpoint as Comp).tasks as Tasks ??
307
+ {},
308
+ ),
309
+ )
310
+ }
311
+ let scope = comp(b, 'prompt')?.scope
312
+ if (scope == 'recap') {
313
+ out.push(
314
+ message(
315
+ { kind: 'user', text: textOf(b) },
316
+ 'earlier in this conversation',
317
+ ),
318
+ )
319
+ return
320
+ }
321
+ let items = scope == 'turn' && opts.turnItems ? opts.turnItems : out
322
+ items.push(message({ kind: 'instruction', text: textOf(b) }, source(b)))
323
+ } else if (kind == 'input') {
324
+ let input = opts.inputText?.(b) ?? textOf(b)
325
+ out.push(message({
326
+ kind: 'user',
327
+ text: typeof input == 'string' ? input : input.text,
328
+ }, (typeof input == 'string' ? undefined : input.from) ?? source(b)))
329
+ } else if (kind == 'output') {
330
+ if (opts.anchor && comp(b, 'output')?.source == opts.anchor) return
331
+ out.push(
332
+ message(
333
+ { kind: 'assistant', text: textOf(b) },
334
+ comp(b, 'entry')?.from as string | undefined ?? inherited(b),
335
+ ),
336
+ )
337
+ } else if (kind == 'call' && (!opts.anchor || c?.source != opts.anchor)) {
338
+ if (inherited(b) && replies.get(String(c?.source))?.[0] == b) {
339
+ out.push(
340
+ message({
341
+ kind: 'instruction',
342
+ text:
343
+ 'The following tool calls were made by your parent session in the inherited conversation.',
344
+ }, 'the system'),
345
+ )
346
+ }
347
+ out.push({ kind: 'call', ...spelled(b) })
348
+ } else if (kind == 'result') {
349
+ let eid = String(answers(b))
350
+ let call = byId.get(eid)
351
+ if (!call?.call) {
352
+ throw new Error(
353
+ `Result ${b.entity.eid} references missing call ${eid}`,
354
+ )
355
+ }
356
+ let text = opts.results?.get(b.entity.eid) ?? textOf(b)
357
+ let ms = comp(b, RESULT)?.ms
358
+ let output = typeof ms == 'number' ? took(text, ms) : text
359
+ let from = source(b) ??
360
+ (spelled(call).name == 'tool'
361
+ ? 'the tool'
362
+ : `the ${spelled(call).name} tool`)
363
+ let { id, name, args } = spelled(call)
364
+ if (late(b, eid)) {
365
+ // Strict routes take one tool output per call; the rest take it again.
366
+ let named = `The pending ${name} call ${id} ${clip(args)} finished:\n` +
367
+ output
368
+ out.push(
369
+ opts.resultUpdatesAsUser
370
+ ? message({ kind: 'user', text: named }, from)
371
+ : message({ kind: 'result', id, output: named }, from),
372
+ )
373
+ } else out.push(message({ kind: 'result', id, output }, from))
374
+ }
375
+ out.push(
376
+ ...(opts.media?.get(b.entity.eid) ?? []).map((item) =>
377
+ message(item, item.from ?? 'the attached document')
378
+ ),
379
+ )
380
+ }
381
+ let emitting = (b: Bundle) => {
382
+ let start = out.length
383
+ emit(b)
384
+ opts.projected?.(b, out.slice(start))
385
+ }
386
+ logical.forEach((b, at) => {
387
+ if (taken.has(b)) return
388
+ emitting(b)
389
+ let reply = replies.get(String(comp(b, CALL)?.source))
390
+ if (reply?.at(-1) != b) return
391
+ for (let call of reply) {
392
+ let a = answer.get(call.entity.eid)
393
+ if (a) {
394
+ if (!taken.has(a) && index.get(a)! > at) emitting(a)
395
+ } else if (pending(call)) {
396
+ let item = message({
397
+ kind: 'result',
398
+ id: spelled(call).id,
399
+ output: PENDING,
400
+ }, 'the system')
401
+ out.push(item)
402
+ opts.projected?.(call, [item])
403
+ }
404
+ }
405
+ })
406
+ return out
407
+ }
package/prompt.js ADDED
@@ -0,0 +1,57 @@
1
+ // UserPromptSubmit has prompt, prompt_id and transcript_path, but no sent
2
+ // timestamp: https://code.claude.com/docs/en/hooks#userpromptsubmit-input.
3
+ // Its exit-0 plain stdout is context. Never return a blocking decision.
4
+ // The transcript may lag the hook. Prefer a matching queued submission's
5
+ // timestamp; otherwise label the hook's clock as an observation, not a send.
6
+ let object = (value)=>value && typeof value == 'object' ? value : {};
7
+ let stamp = (value)=>typeof value == 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : '';
8
+ /** One line, without prompt text; a partial or malformed JSONL row is ignored.
9
+ * Only end_turn finishes a reply: a tool-use block and a sidechain do not. */ export let promptTiming = (hook, transcript, now)=>{
10
+ let ended = '';
11
+ let sent = '';
12
+ let queued = '';
13
+ for (let line of transcript.split('\n')){
14
+ let row;
15
+ try {
16
+ row = object(JSON.parse(line));
17
+ } catch {
18
+ continue;
19
+ }
20
+ if (row.isSidechain) continue;
21
+ let session = row.sessionId ?? row.session_id;
22
+ if (hook.session_id && session && session != hook.session_id) continue;
23
+ let at = stamp(row.timestamp);
24
+ if (!at) continue;
25
+ let message = object(row.message);
26
+ if (row.type == 'assistant' && message.stop_reason == 'end_turn') {
27
+ ended = at;
28
+ }
29
+ if (row.type == 'user') {
30
+ // A previous copy of the same text is not this submission. Queue rows
31
+ // before an already-recorded user turn have been consumed.
32
+ if (hook.prompt_id && row.promptId == hook.prompt_id) sent = queued || at;
33
+ queued = '';
34
+ }
35
+ if (row.type == 'queue-operation' && row.operation == 'dequeue') queued = '';
36
+ if (row.type == 'queue-operation' && row.operation == 'remove' && row.content == hook.prompt) queued = '';
37
+ if (row.type == 'queue-operation' && row.operation == 'enqueue' && typeof hook.prompt == 'string' && row.content == hook.prompt) queued = at;
38
+ }
39
+ let submitted = sent || queued;
40
+ return `${submitted ? `Prompt sent: ${submitted}` : `Prompt observed: ${now.toISOString()}`}; previous reply ended: ${ended || 'unknown'}.`;
41
+ };
42
+ /** Timing from the retained end of a local transcript. */ export let promptContext = (hook, read, now = new Date())=>{
43
+ if (typeof hook.transcript_path != 'string') return '';
44
+ let tail = read?.(hook.transcript_path, 1024 * 1024);
45
+ if (!tail) return '';
46
+ let { text, truncated } = tail;
47
+ return promptTiming(hook, truncated ? text.slice(text.indexOf('\n') + 1) : text, now);
48
+ };
49
+ /** Bad JSON is deliberately not an error at a hook boundary. */ export let promptHook = (value)=>{
50
+ try {
51
+ let hook = object(JSON.parse(String(value)));
52
+ return hook.hook_event_name == 'UserPromptSubmit' ? hook : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ };
57
+ //# sourceMappingURL=prompt.js.map
package/prompt.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.js","sources":["./prompt.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,2EAA2E;AAC3E,wEAAwE;AACxE,yEAAyE;AACzE,6EAA6E;AAK7E,IAAI,SAAS,CAAC,QACZ,SAAS,OAAO,SAAS,WAAW,QAAe,CAAC;AACtD,IAAI,QAAQ,CAAC,QACX,OAAO,SAAS,YAAY,OAAO,QAAQ,CAAC,KAAK,KAAK,CAAC,UACnD,IAAI,KAAK,OAAO,WAAW,KAC3B;AAEN;4EAC4E,GAC5E,OAAO,IAAI,eAAe,CACxB,MACA,YACA;EAEA,IAAI,QAAQ;EACZ,IAAI,OAAO;EACX,IAAI,SAAS;EACb,KAAK,IAAI,QAAQ,WAAW,KAAK,CAAC,MAAO;IACvC,IAAI;IACJ,IAAI;MACF,MAAM,OAAO,KAAK,KAAK,CAAC;IAC1B,EAAE,OAAM;MACN;IACF;IACA,IAAI,IAAI,WAAW,EAAE;IACrB,IAAI,UAAU,IAAI,SAAS,IAAI,IAAI,UAAU;IAC7C,IAAI,KAAK,UAAU,IAAI,WAAW,WAAW,KAAK,UAAU,EAAE;IAC9D,IAAI,KAAK,MAAM,IAAI,SAAS;IAC5B,IAAI,CAAC,IAAI;IACT,IAAI,UAAU,OAAO,IAAI,OAAO;IAChC,IAAI,IAAI,IAAI,IAAI,eAAe,QAAQ,WAAW,IAAI,YAAY;MAChE,QAAQ;IACV;IACA,IAAI,IAAI,IAAI,IAAI,QAAQ;MACtB,sEAAsE;MACtE,2DAA2D;MAC3D,IAAI,KAAK,SAAS,IAAI,IAAI,QAAQ,IAAI,KAAK,SAAS,EAAE,OAAO,UAAU;MACvE,SAAS;IACX;IACA,IAAI,IAAI,IAAI,IAAI,qBAAqB,IAAI,SAAS,IAAI,WAAW,SAAS;IAC1E,IACE,IAAI,IAAI,IAAI,qBAAqB,IAAI,SAAS,IAAI,YAClD,IAAI,OAAO,IAAI,KAAK,MAAM,EAC1B,SAAS;IACX,IACE,IAAI,IAAI,IAAI,qBAAqB,IAAI,SAAS,IAAI,aAClD,OAAO,KAAK,MAAM,IAAI,YAAY,IAAI,OAAO,IAAI,KAAK,MAAM,EAC5D,SAAS;EACb;EACA,IAAI,YAAY,QAAQ;EACxB,OAAO,GACL,YACI,CAAC,aAAa,EAAE,WAAW,GAC3B,CAAC,iBAAiB,EAAE,IAAI,WAAW,IAAI,CAC5C,wBAAwB,EAAE,SAAS,UAAU,CAAC,CAAC;AAClD,EAAC;AAED,wDAAwD,GACxD,OAAO,IAAI,gBAAgB,CACzB,MACA,MACA,MAAM,IAAI,MAAM;EAEhB,IAAI,OAAO,KAAK,eAAe,IAAI,UAAU,OAAO;EACpD,IAAI,OAAO,OAAO,KAAK,eAAe,EAAE,OAAO;EAC/C,IAAI,CAAC,MAAM,OAAO;EAClB,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG;EAC1B,OAAO,aACL,MACA,YAAY,KAAK,KAAK,CAAC,KAAK,OAAO,CAAC,QAAQ,KAAK,MACjD;AAEJ,EAAC;AAED,8DAA8D,GAC9D,OAAO,IAAI,aAAa,CAAC;EACvB,IAAI;IACF,IAAI,OAAO,OAAO,KAAK,KAAK,CAAC,OAAO;IACpC,OAAO,KAAK,eAAe,IAAI,qBAAqB,OAAO;EAC7D,EAAE,OAAM;IACN,OAAO;EACT;AACF,EAAC"}
package/prompt.ts ADDED
@@ -0,0 +1,92 @@
1
+ // UserPromptSubmit has prompt, prompt_id and transcript_path, but no sent
2
+ // timestamp: https://code.claude.com/docs/en/hooks#userpromptsubmit-input.
3
+ // Its exit-0 plain stdout is context. Never return a blocking decision.
4
+ // The transcript may lag the hook. Prefer a matching queued submission's
5
+ // timestamp; otherwise label the hook's clock as an observation, not a send.
6
+
7
+ import type { TextTail } from 'jsr:@yaks/file@0.2.36'
8
+
9
+ type Row = Record<string, unknown>
10
+ let object = (value: unknown): Row =>
11
+ value && typeof value == 'object' ? value as Row : {}
12
+ let stamp = (value: unknown): string =>
13
+ typeof value == 'string' && Number.isFinite(Date.parse(value))
14
+ ? new Date(value).toISOString()
15
+ : ''
16
+
17
+ /** One line, without prompt text; a partial or malformed JSONL row is ignored.
18
+ * Only end_turn finishes a reply: a tool-use block and a sidechain do not. */
19
+ export let promptTiming = (
20
+ hook: Row,
21
+ transcript: string,
22
+ now: Date,
23
+ ): string => {
24
+ let ended = ''
25
+ let sent = ''
26
+ let queued = ''
27
+ for (let line of transcript.split('\n')) {
28
+ let row: Row
29
+ try {
30
+ row = object(JSON.parse(line))
31
+ } catch {
32
+ continue
33
+ }
34
+ if (row.isSidechain) continue
35
+ let session = row.sessionId ?? row.session_id
36
+ if (hook.session_id && session && session != hook.session_id) continue
37
+ let at = stamp(row.timestamp)
38
+ if (!at) continue
39
+ let message = object(row.message)
40
+ if (row.type == 'assistant' && message.stop_reason == 'end_turn') {
41
+ ended = at
42
+ }
43
+ if (row.type == 'user') {
44
+ // A previous copy of the same text is not this submission. Queue rows
45
+ // before an already-recorded user turn have been consumed.
46
+ if (hook.prompt_id && row.promptId == hook.prompt_id) sent = queued || at
47
+ queued = ''
48
+ }
49
+ if (row.type == 'queue-operation' && row.operation == 'dequeue') queued = ''
50
+ if (
51
+ row.type == 'queue-operation' && row.operation == 'remove' &&
52
+ row.content == hook.prompt
53
+ ) queued = ''
54
+ if (
55
+ row.type == 'queue-operation' && row.operation == 'enqueue' &&
56
+ typeof hook.prompt == 'string' && row.content == hook.prompt
57
+ ) queued = at
58
+ }
59
+ let submitted = sent || queued
60
+ return `${
61
+ submitted
62
+ ? `Prompt sent: ${submitted}`
63
+ : `Prompt observed: ${now.toISOString()}`
64
+ }; previous reply ended: ${ended || 'unknown'}.`
65
+ }
66
+
67
+ /** Timing from the retained end of a local transcript. */
68
+ export let promptContext = (
69
+ hook: Row,
70
+ read: TextTail | undefined,
71
+ now = new Date(),
72
+ ): string => {
73
+ if (typeof hook.transcript_path != 'string') return ''
74
+ let tail = read?.(hook.transcript_path, 1024 * 1024)
75
+ if (!tail) return ''
76
+ let { text, truncated } = tail
77
+ return promptTiming(
78
+ hook,
79
+ truncated ? text.slice(text.indexOf('\n') + 1) : text,
80
+ now,
81
+ )
82
+ }
83
+
84
+ /** Bad JSON is deliberately not an error at a hook boundary. */
85
+ export let promptHook = (value: unknown): Row | undefined => {
86
+ try {
87
+ let hook = object(JSON.parse(String(value)))
88
+ return hook.hook_event_name == 'UserPromptSubmit' ? hook : undefined
89
+ } catch {
90
+ return undefined
91
+ }
92
+ }
package/prose.js ADDED
@@ -0,0 +1,43 @@
1
+ /** Formatted prose for conversation replies and cards. @module */ /* @ts-types="npm:@types/react@19.3.0" */ import { createElement as h, Fragment } from "react";
2
+ import { blocks, parse, useHost } from "@yaks/markdown";
3
+ import { Body, Button } from "@yaks/ui/parts";
4
+ // A bare URL is drawn as its hostname.
5
+ let shortened = (href, kids)=>{
6
+ let url = typeof href == 'string' && /^https?:/.test(href) && URL.parse(href);
7
+ return url && kids.flat().join('') == href ? [
8
+ url.host.replace(/^www\./, '')
9
+ ] : kids;
10
+ };
11
+ // What a link to an act is drawn as: the kit's button that does it, saying
12
+ // it in its first words ("Approve" of "Approve: make the recipes public"),
13
+ // the whole of them its tooltip, opening in a tab of its own so the page it
14
+ // is pressed on stays.
15
+ let act = (href, kids)=>{
16
+ let words = kids.flat().filter((k)=>typeof k == 'string').join('');
17
+ let [, does] = words.match(/^([^:]{1,24}):\s*\S/) ?? [];
18
+ return /*#__PURE__*/ h(Button, {
19
+ href,
20
+ mod: 'go',
21
+ target: '_blank',
22
+ rel: 'noopener',
23
+ ...does ? {
24
+ 'data-tip': words,
25
+ 'aria-label': words
26
+ } : {}
27
+ }, ...does ? [
28
+ does
29
+ ] : kids);
30
+ };
31
+ let drawn = (action)=>(tag, props, ...kids)=>tag == 'a' && typeof props?.href == 'string' && action?.(props.href) ? act(props.href, kids) : /*#__PURE__*/ h(tag, props, ...tag == 'a' ? shortened(props?.href, kids) : kids);
32
+ let Prose = ({ text, action })=>/*#__PURE__*/ h(Fragment, null, ...blocks(parse(text), drawn(action), useHost()));
33
+ /** Draw Markdown in the kit's Body, with entity links supplied by the page's
34
+ * `Host` from @yaks/markdown, and a link off the page's site opening in a new
35
+ * tab (@yaks/markdown/away). A link whose address `action` picks is an act,
36
+ * such as an approval's: the kit's `Button` that does it, in a tab of its
37
+ * own. */ export let markdown = (text, { action } = {})=>/*#__PURE__*/ h(Body, {
38
+ mod: 'flow'
39
+ }, /*#__PURE__*/ h(Prose, {
40
+ text,
41
+ action
42
+ }));
43
+ //# sourceMappingURL=prose.js.map
package/prose.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prose.js","sources":["./prose.ts"],"names":[],"mappings":"AAAA,gEAAgE,GAChE,uCAAuC,GAAG,SACxC,iBAAiB,CAAC,EAClB,QAAQ,gBAGe;AACzB,SAAS,MAAM,EAAE,KAAK,EAAE,OAAO,8BAAmC;AAClE,SAAS,IAAI,EAAE,MAAM,8BAAmC;AAExD,uCAAuC;AACvC,IAAI,YAAY,CAAC,MAAe;EAC9B,IAAI,MAAM,OAAO,QAAQ,YAAY,WAAW,IAAI,CAAC,SACnD,IAAI,KAAK,CAAC;EACZ,OAAO,OAAO,KAAK,IAAI,GAAG,IAAI,CAAC,OAAO,OAClC;IAAC,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU;GAAI,GAChC;AACN;AAEA,2EAA2E;AAC3E,2EAA2E;AAC3E,4EAA4E;AAC5E,uBAAuB;AACvB,IAAI,MAAM,CAAC,MAAc;EACvB,IAAI,QAAQ,KAAK,IAAI,GAAG,MAAM,CAAC,CAAC,IAAM,OAAO,KAAK,UAAU,IAAI,CAAC;EACjE,IAAI,GAAG,KAAK,GAAG,MAAM,KAAK,CAAC,0BAA0B,EAAE;EACvD,qBAAO,EACL,QACA;IACE;IACA,KAAK;IACL,QAAQ;IACR,KAAK;IACL,GAAG,OAAO;MAAE,YAAY;MAAO,cAAc;IAAM,IAAI,CAAC,CAAC;EAC3D,MACG,OAAO;IAAC;GAAK,GAAG;AAEvB;AAEA,IAAI,QAAQ,CAAC,SACV,CAAC,KAAa,OAAuC,GAAG,OACvD,OAAO,OAAO,OAAO,OAAO,QAAQ,YAAY,SAAS,MAAM,IAAI,IAC/D,IAAI,MAAM,IAAI,EAAE,sBAChB,EACA,KACA,UACG,OAAO,MAAM,UAAU,OAAO,MAAM,QAAQ;AAGvD,IAAI,QAAQ,CACV,EAAE,IAAI,EAAE,MAAM,EAAwD,iBAEtE,EAAE,UAAU,SAAS,OAAO,MAAM,OAAO,MAAM,SAAS;AAE1D;;;;QAIQ,GACR,OAAO,IAAI,WAAW,CACpB,MACA,EAAE,MAAM,EAA0C,GAAG,CAAC,CAAC,iBACtC,EAAE,MAAM;IAAE,KAAK;EAAO,iBAAG,EAAE,OAAO;IAAE;IAAM;EAAO,IAAG"}
package/prose.ts ADDED
@@ -0,0 +1,63 @@
1
+ /** Formatted prose for conversation replies and cards. @module */
2
+ /* @ts-types="npm:@types/react@19.3.0" */ import {
3
+ createElement as h,
4
+ Fragment,
5
+ type ReactElement,
6
+ type ReactNode as Node,
7
+ } from 'react'
8
+ import { blocks, parse, useHost } from '@yaks/markdown'
9
+ import { Body, Button } from '@yaks/ui/parts'
10
+
11
+ // A bare URL is drawn as its hostname.
12
+ let shortened = (href: unknown, kids: Node[]): Node[] => {
13
+ let url = typeof href == 'string' && /^https?:/.test(href) &&
14
+ URL.parse(href)
15
+ return url && kids.flat().join('') == href
16
+ ? [url.host.replace(/^www\./, '')]
17
+ : kids
18
+ }
19
+
20
+ // What a link to an act is drawn as: the kit's button that does it, saying
21
+ // it in its first words ("Approve" of "Approve: make the recipes public"),
22
+ // the whole of them its tooltip, opening in a tab of its own so the page it
23
+ // is pressed on stays.
24
+ let act = (href: string, kids: Node[]) => {
25
+ let words = kids.flat().filter((k) => typeof k == 'string').join('')
26
+ let [, does] = words.match(/^([^:]{1,24}):\s*\S/) ?? []
27
+ return h(
28
+ Button,
29
+ {
30
+ href,
31
+ mod: 'go',
32
+ target: '_blank',
33
+ rel: 'noopener',
34
+ ...does ? { 'data-tip': words, 'aria-label': words } : {},
35
+ },
36
+ ...does ? [does] : kids,
37
+ )
38
+ }
39
+
40
+ let drawn = (action?: (href: string) => boolean) =>
41
+ ((tag: string, props: Record<string, unknown> | null, ...kids: Node[]) =>
42
+ tag == 'a' && typeof props?.href == 'string' && action?.(props.href)
43
+ ? act(props.href, kids)
44
+ : h(
45
+ tag,
46
+ props,
47
+ ...tag == 'a' ? shortened(props?.href, kids) : kids,
48
+ )) as typeof h
49
+
50
+ let Prose = (
51
+ { text, action }: { text: string; action?: (href: string) => boolean },
52
+ ): ReactElement =>
53
+ h(Fragment, null, ...blocks(parse(text), drawn(action), useHost()))
54
+
55
+ /** Draw Markdown in the kit's Body, with entity links supplied by the page's
56
+ * `Host` from @yaks/markdown, and a link off the page's site opening in a new
57
+ * tab (@yaks/markdown/away). A link whose address `action` picks is an act,
58
+ * such as an approval's: the kit's `Button` that does it, in a tab of its
59
+ * own. */
60
+ export let markdown = (
61
+ text: string,
62
+ { action }: { action?: (href: string) => boolean } = {},
63
+ ): ReactElement => h(Body, { mod: 'flow' }, h(Prose, { text, action }))