@yaks/session 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (393) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1392 -2
  3. package/_dist/admission.d.ts +15 -0
  4. package/_dist/admission.d.ts.map +1 -0
  5. package/_dist/announce.d.ts +17 -0
  6. package/_dist/announce.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +200 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/append.d.ts +10 -0
  10. package/_dist/append.d.ts.map +1 -0
  11. package/_dist/archive.d.ts +6 -0
  12. package/_dist/archive.d.ts.map +1 -0
  13. package/_dist/asks.d.ts +11 -0
  14. package/_dist/asks.d.ts.map +1 -0
  15. package/_dist/audit.d.ts +15 -0
  16. package/_dist/audit.d.ts.map +1 -0
  17. package/_dist/bounce.d.ts +19 -0
  18. package/_dist/bounce.d.ts.map +1 -0
  19. package/_dist/bus.d.ts +8 -0
  20. package/_dist/bus.d.ts.map +1 -0
  21. package/_dist/cache.d.ts +45 -0
  22. package/_dist/cache.d.ts.map +1 -0
  23. package/_dist/child-notice.d.ts +6 -0
  24. package/_dist/child-notice.d.ts.map +1 -0
  25. package/_dist/children.d.ts +59 -0
  26. package/_dist/children.d.ts.map +1 -0
  27. package/_dist/cli.d.ts +8 -0
  28. package/_dist/cli.d.ts.map +1 -0
  29. package/_dist/comp.d.ts +9 -0
  30. package/_dist/comp.d.ts.map +1 -0
  31. package/_dist/compact.d.ts +19 -0
  32. package/_dist/compact.d.ts.map +1 -0
  33. package/_dist/conversation.d.ts +158 -0
  34. package/_dist/conversation.d.ts.map +1 -0
  35. package/_dist/cost.d.ts +13 -0
  36. package/_dist/cost.d.ts.map +1 -0
  37. package/_dist/deferred.d.ts +79 -0
  38. package/_dist/deferred.d.ts.map +1 -0
  39. package/_dist/ended.d.ts +27 -0
  40. package/_dist/ended.d.ts.map +1 -0
  41. package/_dist/files.d.ts +73 -0
  42. package/_dist/files.d.ts.map +1 -0
  43. package/_dist/fork.d.ts +23 -0
  44. package/_dist/fork.d.ts.map +1 -0
  45. package/_dist/graft.d.ts +33 -0
  46. package/_dist/graft.d.ts.map +1 -0
  47. package/_dist/graph.d.ts +14 -0
  48. package/_dist/graph.d.ts.map +1 -0
  49. package/_dist/handoff.d.ts +29 -0
  50. package/_dist/handoff.d.ts.map +1 -0
  51. package/_dist/imported.d.ts +63 -0
  52. package/_dist/imported.d.ts.map +1 -0
  53. package/_dist/intake.d.ts +43 -0
  54. package/_dist/intake.d.ts.map +1 -0
  55. package/_dist/joined.d.ts +35 -0
  56. package/_dist/joined.d.ts.map +1 -0
  57. package/_dist/lease.d.ts +21 -0
  58. package/_dist/lease.d.ts.map +1 -0
  59. package/_dist/lines.d.ts +13 -0
  60. package/_dist/lines.d.ts.map +1 -0
  61. package/_dist/mod.d.ts +107 -0
  62. package/_dist/mod.d.ts.map +1 -0
  63. package/_dist/naming.d.ts +10 -0
  64. package/_dist/naming.d.ts.map +1 -0
  65. package/_dist/native.d.ts +13 -0
  66. package/_dist/native.d.ts.map +1 -0
  67. package/_dist/parts.d.ts +145 -0
  68. package/_dist/parts.d.ts.map +1 -0
  69. package/_dist/plugin.d.ts +33 -0
  70. package/_dist/plugin.d.ts.map +1 -0
  71. package/_dist/project.d.ts +67 -0
  72. package/_dist/project.d.ts.map +1 -0
  73. package/_dist/prose.d.ts +7 -0
  74. package/_dist/prose.d.ts.map +1 -0
  75. package/_dist/providers.d.ts +36 -0
  76. package/_dist/providers.d.ts.map +1 -0
  77. package/_dist/reach.d.ts +39 -0
  78. package/_dist/reach.d.ts.map +1 -0
  79. package/_dist/react.d.ts +236 -0
  80. package/_dist/react.d.ts.map +1 -0
  81. package/_dist/readers.d.ts +221 -0
  82. package/_dist/readers.d.ts.map +1 -0
  83. package/_dist/reap.d.ts +21 -0
  84. package/_dist/reap.d.ts.map +1 -0
  85. package/_dist/recall.d.ts +32 -0
  86. package/_dist/recall.d.ts.map +1 -0
  87. package/_dist/routes.d.ts +15 -0
  88. package/_dist/routes.d.ts.map +1 -0
  89. package/_dist/run.d.ts +81 -0
  90. package/_dist/run.d.ts.map +1 -0
  91. package/_dist/service.d.ts +131 -0
  92. package/_dist/service.d.ts.map +1 -0
  93. package/_dist/source.d.ts +9 -0
  94. package/_dist/source.d.ts.map +1 -0
  95. package/_dist/start.d.ts +29 -0
  96. package/_dist/start.d.ts.map +1 -0
  97. package/_dist/state.d.ts +75 -0
  98. package/_dist/state.d.ts.map +1 -0
  99. package/_dist/status.d.ts +38 -0
  100. package/_dist/status.d.ts.map +1 -0
  101. package/_dist/tail.d.ts +121 -0
  102. package/_dist/tail.d.ts.map +1 -0
  103. package/_dist/timing.d.ts +9 -0
  104. package/_dist/timing.d.ts.map +1 -0
  105. package/_dist/told.d.ts +17 -0
  106. package/_dist/told.d.ts.map +1 -0
  107. package/_dist/tools.d.ts +41 -0
  108. package/_dist/tools.d.ts.map +1 -0
  109. package/_dist/transcript.d.ts +5 -0
  110. package/_dist/transcript.d.ts.map +1 -0
  111. package/_dist/turn.d.ts +49 -0
  112. package/_dist/turn.d.ts.map +1 -0
  113. package/_dist/unknown.d.ts +6 -0
  114. package/_dist/unknown.d.ts.map +1 -0
  115. package/_dist/views.d.ts +9 -0
  116. package/_dist/views.d.ts.map +1 -0
  117. package/_dist/vocab.d.ts +9 -0
  118. package/_dist/vocab.d.ts.map +1 -0
  119. package/_dist/wait.d.ts +15 -0
  120. package/_dist/wait.d.ts.map +1 -0
  121. package/_dist/wake.d.ts +116 -0
  122. package/_dist/wake.d.ts.map +1 -0
  123. package/_dist/watch.d.ts +52 -0
  124. package/_dist/watch.d.ts.map +1 -0
  125. package/_dist/who.d.ts +84 -0
  126. package/_dist/who.d.ts.map +1 -0
  127. package/_dist/window.d.ts +43 -0
  128. package/_dist/window.d.ts.map +1 -0
  129. package/admission.js +137 -0
  130. package/admission.js.map +1 -0
  131. package/admission.ts +164 -0
  132. package/announce.js +123 -0
  133. package/announce.js.map +1 -0
  134. package/announce.ts +126 -0
  135. package/answer.js +372 -0
  136. package/answer.js.map +1 -0
  137. package/answer.ts +426 -0
  138. package/append.js +125 -0
  139. package/append.js.map +1 -0
  140. package/append.ts +205 -0
  141. package/archive.js +62 -0
  142. package/archive.js.map +1 -0
  143. package/archive.ts +62 -0
  144. package/asks.js +80 -0
  145. package/asks.js.map +1 -0
  146. package/asks.ts +106 -0
  147. package/attempt.js +46 -0
  148. package/attempt.js.map +1 -0
  149. package/attempt.ts +60 -0
  150. package/audit.js +57 -0
  151. package/audit.js.map +1 -0
  152. package/audit.ts +65 -0
  153. package/bounce.js +29 -0
  154. package/bounce.js.map +1 -0
  155. package/bounce.ts +34 -0
  156. package/bus.js +568 -0
  157. package/bus.js.map +1 -0
  158. package/bus.ts +683 -0
  159. package/cache.js +169 -0
  160. package/cache.js.map +1 -0
  161. package/cache.ts +230 -0
  162. package/child-notice.js +128 -0
  163. package/child-notice.js.map +1 -0
  164. package/child-notice.ts +136 -0
  165. package/children.js +937 -0
  166. package/children.js.map +1 -0
  167. package/children.ts +925 -0
  168. package/claude-control.js +8 -0
  169. package/claude-control.js.map +1 -0
  170. package/claude-control.ts +12 -0
  171. package/cli.js +23 -0
  172. package/cli.js.map +1 -0
  173. package/cli.ts +28 -0
  174. package/comp.js +76 -0
  175. package/comp.js.map +1 -0
  176. package/comp.ts +78 -0
  177. package/compact.js +157 -0
  178. package/compact.js.map +1 -0
  179. package/compact.ts +209 -0
  180. package/compact_ask.js +280 -0
  181. package/compact_ask.js.map +1 -0
  182. package/compact_ask.ts +199 -0
  183. package/continue.js +131 -0
  184. package/continue.js.map +1 -0
  185. package/continue.ts +143 -0
  186. package/conversation.js +337 -0
  187. package/conversation.js.map +1 -0
  188. package/conversation.ts +593 -0
  189. package/cost.js +111 -0
  190. package/cost.js.map +1 -0
  191. package/cost.ts +93 -0
  192. package/deferred.js +207 -0
  193. package/deferred.js.map +1 -0
  194. package/deferred.ts +219 -0
  195. package/deno.json +1 -0
  196. package/dependencies.js +114 -0
  197. package/dependencies.js.map +1 -0
  198. package/dependencies.ts +110 -0
  199. package/draining.js +20 -0
  200. package/draining.js.map +1 -0
  201. package/draining.ts +26 -0
  202. package/ended.js +210 -0
  203. package/ended.js.map +1 -0
  204. package/ended.ts +225 -0
  205. package/files.js +285 -0
  206. package/files.js.map +1 -0
  207. package/files.ts +318 -0
  208. package/fork.js +96 -0
  209. package/fork.js.map +1 -0
  210. package/fork.ts +124 -0
  211. package/graft.js +97 -0
  212. package/graft.js.map +1 -0
  213. package/graft.ts +88 -0
  214. package/graph.js +49 -0
  215. package/graph.js.map +1 -0
  216. package/graph.ts +61 -0
  217. package/handoff.js +111 -0
  218. package/handoff.js.map +1 -0
  219. package/handoff.ts +147 -0
  220. package/help.js +432 -0
  221. package/help.js.map +1 -0
  222. package/help.ts +431 -0
  223. package/hooks.js +253 -0
  224. package/hooks.js.map +1 -0
  225. package/hooks.ts +333 -0
  226. package/imported.js +259 -0
  227. package/imported.js.map +1 -0
  228. package/imported.ts +201 -0
  229. package/inspect.js +353 -0
  230. package/inspect.js.map +1 -0
  231. package/inspect.ts +378 -0
  232. package/intake.js +115 -0
  233. package/intake.js.map +1 -0
  234. package/intake.ts +124 -0
  235. package/joined.js +67 -0
  236. package/joined.js.map +1 -0
  237. package/joined.ts +69 -0
  238. package/lease.js +146 -0
  239. package/lease.js.map +1 -0
  240. package/lease.ts +151 -0
  241. package/lifecycle.js +49 -0
  242. package/lifecycle.js.map +1 -0
  243. package/lifecycle.ts +46 -0
  244. package/lines.js +171 -0
  245. package/lines.js.map +1 -0
  246. package/lines.ts +177 -0
  247. package/listen.js +604 -0
  248. package/listen.js.map +1 -0
  249. package/listen.ts +976 -0
  250. package/log.js +78 -0
  251. package/log.js.map +1 -0
  252. package/log.ts +88 -0
  253. package/mod.js +107 -0
  254. package/mod.js.map +1 -0
  255. package/mod.ts +113 -0
  256. package/name.js +51 -0
  257. package/name.js.map +1 -0
  258. package/name.ts +84 -0
  259. package/naming.js +96 -0
  260. package/naming.js.map +1 -0
  261. package/naming.ts +102 -0
  262. package/native.js +17 -0
  263. package/native.js.map +1 -0
  264. package/native.ts +17 -0
  265. package/package.json +133 -4
  266. package/parts.js +334 -0
  267. package/parts.js.map +1 -0
  268. package/parts.ts +383 -0
  269. package/plugin.js +77 -0
  270. package/plugin.js.map +1 -0
  271. package/plugin.ts +98 -0
  272. package/project.js +354 -0
  273. package/project.js.map +1 -0
  274. package/project.ts +407 -0
  275. package/prompt.js +57 -0
  276. package/prompt.js.map +1 -0
  277. package/prompt.ts +92 -0
  278. package/prose.js +43 -0
  279. package/prose.js.map +1 -0
  280. package/prose.ts +63 -0
  281. package/providers.js +279 -0
  282. package/providers.js.map +1 -0
  283. package/providers.ts +306 -0
  284. package/pruning.js +80 -0
  285. package/pruning.js.map +1 -0
  286. package/pruning.ts +147 -0
  287. package/reach.js +923 -0
  288. package/reach.js.map +1 -0
  289. package/reach.ts +1107 -0
  290. package/react.js +2259 -0
  291. package/react.js.map +1 -0
  292. package/react.ts +2864 -0
  293. package/readers.js +956 -0
  294. package/readers.js.map +1 -0
  295. package/readers.ts +1017 -0
  296. package/reap.js +60 -0
  297. package/reap.js.map +1 -0
  298. package/reap.ts +65 -0
  299. package/recall.js +67 -0
  300. package/recall.js.map +1 -0
  301. package/recall.ts +114 -0
  302. package/reopen.js +45 -0
  303. package/reopen.js.map +1 -0
  304. package/reopen.ts +44 -0
  305. package/result-entry.js +32 -0
  306. package/result-entry.js.map +1 -0
  307. package/result-entry.ts +34 -0
  308. package/resume.js +266 -0
  309. package/resume.js.map +1 -0
  310. package/resume.ts +283 -0
  311. package/routes.js +129 -0
  312. package/routes.js.map +1 -0
  313. package/routes.ts +147 -0
  314. package/routine.js +179 -0
  315. package/routine.js.map +1 -0
  316. package/routine.ts +191 -0
  317. package/run.js +932 -0
  318. package/run.js.map +1 -0
  319. package/run.ts +999 -0
  320. package/service.js +806 -0
  321. package/service.js.map +1 -0
  322. package/service.ts +911 -0
  323. package/source.js +26 -0
  324. package/source.js.map +1 -0
  325. package/source.ts +40 -0
  326. package/start.js +197 -0
  327. package/start.js.map +1 -0
  328. package/start.ts +214 -0
  329. package/state.js +247 -0
  330. package/state.js.map +1 -0
  331. package/state.ts +404 -0
  332. package/status.js +1222 -0
  333. package/status.js.map +1 -0
  334. package/status.ts +1555 -0
  335. package/status_bench.ts +50 -0
  336. package/statusline.js +187 -0
  337. package/statusline.js.map +1 -0
  338. package/statusline.ts +232 -0
  339. package/tail.js +748 -0
  340. package/tail.js.map +1 -0
  341. package/tail.ts +815 -0
  342. package/talk.js +58 -0
  343. package/talk.js.map +1 -0
  344. package/talk.ts +51 -0
  345. package/task-context.js +41 -0
  346. package/task-context.js.map +1 -0
  347. package/task-context.ts +53 -0
  348. package/texted.js +65 -0
  349. package/texted.js.map +1 -0
  350. package/texted.ts +65 -0
  351. package/timing.js +37 -0
  352. package/timing.js.map +1 -0
  353. package/timing.ts +52 -0
  354. package/told.js +56 -0
  355. package/told.js.map +1 -0
  356. package/told.ts +54 -0
  357. package/tools.js +595 -0
  358. package/tools.js.map +1 -0
  359. package/tools.ts +633 -0
  360. package/transcript.js +34 -0
  361. package/transcript.js.map +1 -0
  362. package/transcript.ts +41 -0
  363. package/turn.js +47 -0
  364. package/turn.js.map +1 -0
  365. package/turn.ts +68 -0
  366. package/unknown.js +8 -0
  367. package/unknown.js.map +1 -0
  368. package/unknown.ts +9 -0
  369. package/views.js +15 -0
  370. package/views.js.map +1 -0
  371. package/views.ts +21 -0
  372. package/vocab.js +24 -0
  373. package/vocab.js.map +1 -0
  374. package/vocab.json +1573 -0
  375. package/vocab.ts +30 -0
  376. package/wait.js +30 -0
  377. package/wait.js.map +1 -0
  378. package/wait.ts +45 -0
  379. package/wake.js +552 -0
  380. package/wake.js.map +1 -0
  381. package/wake.ts +597 -0
  382. package/watch.js +520 -0
  383. package/watch.js.map +1 -0
  384. package/watch.ts +596 -0
  385. package/who.js +309 -0
  386. package/who.js.map +1 -0
  387. package/who.ts +347 -0
  388. package/window.js +179 -0
  389. package/window.js.map +1 -0
  390. package/window.ts +268 -0
  391. package/woken.js +129 -0
  392. package/woken.js.map +1 -0
  393. package/woken.ts +127 -0
@@ -0,0 +1,8 @@
1
+ // Claude's cancellation controls, shared by the importer and status readers.
2
+ export let claudeStops = [
3
+ '[Request interrupted by user]',
4
+ '[Request interrupted by user for tool use]'
5
+ ];
6
+ // Consumed logs do not replay. Older imports kept these controls as notices.
7
+ export let stoppedNotice = (b)=>!!b.lines && !!b.notice && claudeStops.includes(String(b.content?.body ?? ''));
8
+ //# sourceMappingURL=claude-control.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-control.js","sources":["./claude-control.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAG7E,OAAO,IAAI,cAAc;EACvB;EACA;CACD,CAAA;AAED,6EAA6E;AAC7E,OAAO,IAAI,gBAAgB,CAAC,IAC1B,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,CAAC,EAAE,MAAM,IACvB,YAAY,QAAQ,CAAC,OAAO,AAAC,EAAE,OAAO,EAAuB,QAAQ,KAAI"}
@@ -0,0 +1,12 @@
1
+ // Claude's cancellation controls, shared by the importer and status readers.
2
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
3
+
4
+ export let claudeStops = [
5
+ '[Request interrupted by user]',
6
+ '[Request interrupted by user for tool use]',
7
+ ]
8
+
9
+ // Consumed logs do not replay. Older imports kept these controls as notices.
10
+ export let stoppedNotice = (b: Bundle): boolean =>
11
+ !!b.lines && !!b.notice &&
12
+ claudeStops.includes(String((b.content as Comp | undefined)?.body ?? ''))
package/cli.js ADDED
@@ -0,0 +1,23 @@
1
+ import { tailTextSync } from "@yaks/file/io";
2
+ // Prompt timing is local. The hook reads its transcript without retrieving
3
+ // historical context or opening a graph.
4
+ import { promptContext, promptHook } from "./prompt.js";
5
+ export let tools = {
6
+ session_context: (args, context)=>{
7
+ // Structured output retains the ordinary tool runner's bundle contract.
8
+ if (context.json) return undefined;
9
+ let prompt = promptHook(args.hook);
10
+ if (prompt) {
11
+ let body = promptContext(prompt, tailTextSync);
12
+ if (body) context.out(body);
13
+ return 0;
14
+ }
15
+ // Missing/malformed hooks without an explicit session are no-ops too.
16
+ if (args.session) return undefined;
17
+ try {
18
+ if (JSON.parse(String(args.hook))?.session_id) return undefined;
19
+ } catch {}
20
+ return 0;
21
+ }
22
+ };
23
+ //# sourceMappingURL=cli.js.map
package/cli.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sources":["./cli.ts"],"names":[],"mappings":"AAAA,SAAS,YAAY,6BAAkC;AACvD,2EAA2E;AAC3E,yCAAyC;AACzC,SAAS,aAAa,EAAE,UAAU,sBAAqB;AAEvD,OAAO,IAAI,QAKP;EACF,iBAAiB,CAAC,MAAM;IACtB,wEAAwE;IACxE,IAAI,QAAQ,IAAI,EAAE,OAAO;IACzB,IAAI,SAAS,WAAW,KAAK,IAAI;IACjC,IAAI,QAAQ;MACV,IAAI,OAAO,cAAc,QAAQ;MACjC,IAAI,MAAM,QAAQ,GAAG,CAAC;MACtB,OAAO;IACT;IACA,sEAAsE;IACtE,IAAI,KAAK,OAAO,EAAE,OAAO;IACzB,IAAI;MACF,IAAI,KAAK,KAAK,CAAC,OAAO,KAAK,IAAI,IAAI,YAAY,OAAO;IACxD,EAAE,OAAM,CAAuC;IAC/C,OAAO;EACT;AACF,EAAC"}
package/cli.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { tailTextSync } from '@yaks/file/io'
2
+ // Prompt timing is local. The hook reads its transcript without retrieving
3
+ // historical context or opening a graph.
4
+ import { promptContext, promptHook } from './prompt.js'
5
+
6
+ export let tools: {
7
+ session_context: (
8
+ args: Record<string, unknown>,
9
+ context: { json: boolean; config?: string; out: (text: string) => void },
10
+ ) => number | undefined
11
+ } = {
12
+ session_context: (args, context) => {
13
+ // Structured output retains the ordinary tool runner's bundle contract.
14
+ if (context.json) return undefined
15
+ let prompt = promptHook(args.hook)
16
+ if (prompt) {
17
+ let body = promptContext(prompt, tailTextSync)
18
+ if (body) context.out(body)
19
+ return 0
20
+ }
21
+ // Missing/malformed hooks without an explicit session are no-ops too.
22
+ if (args.session) return undefined
23
+ try {
24
+ if (JSON.parse(String(args.hook))?.session_id) return undefined
25
+ } catch { /* A malformed hook says nothing. */ }
26
+ return 0
27
+ },
28
+ }
package/comp.js ADDED
@@ -0,0 +1,76 @@
1
+ // The vocabulary this package ships, as one document to load beside your own
2
+ // (./vocab.json — plain JSON Schema). A session is a transcript: no process is
3
+ // launched — entries appear, and the runner reacts to the newest one. The
4
+ // components are the session's identity, its lock, and the kinds of entry; the
5
+ // components a run's process needs (pid, pane, a log to tail) belong to the
6
+ // application that runs processes, never here.
7
+ //
8
+ // session{id, status, cost}
9
+ // identity only; `status` and `cost` are computed,
10
+ // never stored
11
+ // spawned{parent, call} delegated by a parent, from a tool call
12
+ // fork{from} continues another transcript from one entry
13
+ // claim{session} the session's lock on the entity it rides
14
+ // conflict{target, loser, holder, at}
15
+ // two sessions wanted one thing (stamped: audit)
16
+ // entry{session, seq} one line; the component beside it is its kind
17
+ // + content{body} its prose, when it has any. Alone, an input: an
18
+ // instruction (the first one is the request).
19
+ // Beside a result, refusal or exception, theirs
20
+ // + output{source} what produced the prose beside it: the ask, for
21
+ // what a model said
22
+ // + using{provider, model, effort}
23
+ // + sending{input, instructions, window, tools, told, offer}
24
+ // set or switch on an input; served on an ask
25
+ // + questions{asked} typed questions the next ask carries
26
+ // + ask{to, served, through} the model was asked, from the prefix at
27
+ // `through`; `served` answered, where it differs
28
+ // + answer{question, …} beside output: the model's answer to one of them
29
+ // + call{to, id, args, source}
30
+ // a tool the model asked for, from that ask
31
+ // + result{call} what a tool answered
32
+ // + stop the runner performs nothing after this
33
+ // + refusal{code} a deliberate no, never tracked
34
+ // + finding{level} measured check results
35
+ // + exception{type, value} what was thrown while producing this entry
36
+ //
37
+ // An ask and a call share no properties on purpose: one is the runner reaching
38
+ // a model, the other the model reaching a tool. What a provider keeps about an
39
+ // ask — OpenAI's response id, for instance — is that provider's own component
40
+ // on the same entry (`@yaks/openai` declares `openai{response_id}`), never a
41
+ // property here. There is no `input` component: prose with no `output` beside
42
+ // it is one, so the invalid state "input and output at once" cannot be written.
43
+ //
44
+ // Half the entry components above are declared by other packages, and this
45
+ // document declares only its own: `content`, `output`, `call`, `result`,
46
+ // `refusal` and `exception` are @yaks/tools's — a call is the record of having
47
+ // asked a tool, whoever asked it — and an instruction assembled from parts is
48
+ // @yaks/context's `prompt`. What a `using` names — `provider`, `model` — is
49
+ // @yaks/model's, as are `questions` and `answer`, and what a `call.to` names is
50
+ // @yaks/tools's `tool`. An application whose provider returns images wants
51
+ // @yaks/blob too, since that is what ./react.ts writes a reply's artifacts as.
52
+ // An application that wants a
53
+ // transcript composes those packages beside this one; that is what a plugin
54
+ // list is for, and one component declared in two documents is a vocabulary
55
+ // `loadVocab` refuses to load.
56
+ //
57
+ // The shape worth noticing is the CLAIM. A lock is not a row about a document
58
+ // somewhere else — it is a component on the document, so "who holds this?" is
59
+ // answered by the entity itself, one lock per entity by construction, and a
60
+ // query for locked documents is a query for entities that have a `claim`.
61
+ // `claim.session` is declared `death: 'release'`: when a session's entity is
62
+ // deleted its lock row goes and the document it was on survives — declared
63
+ // here, carried out by @yaks/graph's cascade, with no code in this package at
64
+ // all. Every `conflict` property is server-owned: the audit row is written by
65
+ // the graph after a refusal, never sent by a client.
66
+ import doc from './vocab.json' with {
67
+ type: 'json'
68
+ };
69
+ /** The session vocabulary, to load beside the packages whose components a
70
+ * transcript uses — what serves an ask (@yaks/model), what a call and its
71
+ * result are (@yaks/tools), what an instruction is made of (@yaks/context):
72
+ * `loadVocab([sessionDoc, modelDoc, toolsDoc, contextDoc, ...mine])`. */ export let sessionDoc = doc;
73
+ export let SESSION = 'session';
74
+ export let CLAIM = 'claim';
75
+ export let CONFLICT = 'conflict';
76
+ //# sourceMappingUR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AAC1B,OAAO,IAAI,WAAW,WAAU"}
package/comp.ts ADDED
@@ -0,0 +1,78 @@
1
+ // The vocabulary this package ships, as one document to load beside your own
2
+ // (./vocab.json — plain JSON Schema). A session is a transcript: no process is
3
+ // launched — entries appear, and the runner reacts to the newest one. The
4
+ // components are the session's identity, its lock, and the kinds of entry; the
5
+ // components a run's process needs (pid, pane, a log to tail) belong to the
6
+ // application that runs processes, never here.
7
+ //
8
+ // session{id, status, cost}
9
+ // identity only; `status` and `cost` are computed,
10
+ // never stored
11
+ // spawned{parent, call} delegated by a parent, from a tool call
12
+ // fork{from} continues another transcript from one entry
13
+ // claim{session} the session's lock on the entity it rides
14
+ // conflict{target, loser, holder, at}
15
+ // two sessions wanted one thing (stamped: audit)
16
+ // entry{session, seq} one line; the component beside it is its kind
17
+ // + content{body} its prose, when it has any. Alone, an input: an
18
+ // instruction (the first one is the request).
19
+ // Beside a result, refusal or exception, theirs
20
+ // + output{source} what produced the prose beside it: the ask, for
21
+ // what a model said
22
+ // + using{provider, model, effort}
23
+ // + sending{input, instructions, window, tools, told, offer}
24
+ // set or switch on an input; served on an ask
25
+ // + questions{asked} typed questions the next ask carries
26
+ // + ask{to, served, through} the model was asked, from the prefix at
27
+ // `through`; `served` answered, where it differs
28
+ // + answer{question, …} beside output: the model's answer to one of them
29
+ // + call{to, id, args, source}
30
+ // a tool the model asked for, from that ask
31
+ // + result{call} what a tool answered
32
+ // + stop the runner performs nothing after this
33
+ // + refusal{code} a deliberate no, never tracked
34
+ // + finding{level} measured check results
35
+ // + exception{type, value} what was thrown while producing this entry
36
+ //
37
+ // An ask and a call share no properties on purpose: one is the runner reaching
38
+ // a model, the other the model reaching a tool. What a provider keeps about an
39
+ // ask — OpenAI's response id, for instance — is that provider's own component
40
+ // on the same entry (`@yaks/openai` declares `openai{response_id}`), never a
41
+ // property here. There is no `input` component: prose with no `output` beside
42
+ // it is one, so the invalid state "input and output at once" cannot be written.
43
+ //
44
+ // Half the entry components above are declared by other packages, and this
45
+ // document declares only its own: `content`, `output`, `call`, `result`,
46
+ // `refusal` and `exception` are @yaks/tools's — a call is the record of having
47
+ // asked a tool, whoever asked it — and an instruction assembled from parts is
48
+ // @yaks/context's `prompt`. What a `using` names — `provider`, `model` — is
49
+ // @yaks/model's, as are `questions` and `answer`, and what a `call.to` names is
50
+ // @yaks/tools's `tool`. An application whose provider returns images wants
51
+ // @yaks/blob too, since that is what ./react.ts writes a reply's artifacts as.
52
+ // An application that wants a
53
+ // transcript composes those packages beside this one; that is what a plugin
54
+ // list is for, and one component declared in two documents is a vocabulary
55
+ // `loadVocab` refuses to load.
56
+ //
57
+ // The shape worth noticing is the CLAIM. A lock is not a row about a document
58
+ // somewhere else — it is a component on the document, so "who holds this?" is
59
+ // answered by the entity itself, one lock per entity by construction, and a
60
+ // query for locked documents is a query for entities that have a `claim`.
61
+ // `claim.session` is declared `death: 'release'`: when a session's entity is
62
+ // deleted its lock row goes and the document it was on survives — declared
63
+ // here, carried out by @yaks/graph's cascade, with no code in this package at
64
+ // all. Every `conflict` property is server-owned: the audit row is written by
65
+ // the graph after a refusal, never sent by a client.
66
+
67
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
68
+ import doc from './vocab.json' with { type: 'json' }
69
+
70
+ /** The session vocabulary, to load beside the packages whose components a
71
+ * transcript uses — what serves an ask (@yaks/model), what a call and its
72
+ * result are (@yaks/tools), what an instruction is made of (@yaks/context):
73
+ * `loadVocab([sessionDoc, modelDoc, toolsDoc, contextDoc, ...mine])`. */
74
+ export let sessionDoc: VocabDoc = doc
75
+
76
+ export let SESSION = 'session'
77
+ export let CLAIM = 'claim'
78
+ export let CONFLICT = 'conflict'
package/compact.js ADDED
@@ -0,0 +1,157 @@
1
+ // A checkpoint is the summary of a transcript prefix. The summary can be
2
+ // appended after newer entries: `through` names the last entry it replaces,
3
+ // so the next model sees retained instructions, the summary, then a
4
+ // protocol-complete suffix.
5
+ import { sizeOf } from "@yaks/blob";
6
+ import { ANSWER, QUESTIONS } from "@yaks/model";
7
+ import { USING } from "./native.js";
8
+ import { kindOf, newestAsk, seqOf } from "./state.js";
9
+ import { checkpointOf, turnNote, unarchived } from "./pruning.js";
10
+ let callOf = (b)=>{
11
+ let call = (b.result ?? b.tool_progress)?.call;
12
+ return call == null ? undefined : String(call);
13
+ };
14
+ // A result always travels with the call that gives it its provider id. An
15
+ // input may land while that call is running, so an input boundary alone does
16
+ // not keep the pair together.
17
+ let paired = (entries, end)=>{
18
+ let calls = new Map(entries.flatMap((b, i)=>b.call ? [
19
+ [
20
+ b.entity.eid,
21
+ i
22
+ ]
23
+ ] : []));
24
+ while(true){
25
+ let split = entries.slice(end).map(callOf).flatMap((eid)=>eid == null ? [] : [
26
+ calls.get(eid)
27
+ ]).filter((i)=>i != null && i < end);
28
+ let next = split.length ? Math.min(...split) : end;
29
+ if (next == end) return end;
30
+ end = next;
31
+ }
32
+ };
33
+ /** A suffix beginning no later than any call its results refer to. */ export let suffix = (entries, from)=>entries.slice(paired(entries, from));
34
+ /** Explicitly admitted context (persona, skills, delegation instructions) is
35
+ * kept verbatim. Ordinary file reads and tool results are history, not a way
36
+ * to admit instructions. */ export let retained = (entries)=>entries.filter((b)=>b.prompt && !b.archived && !turnNote(b));
37
+ export let history = (entries)=>entries.filter((b)=>!b.prompt && !b.task_context);
38
+ export let context = (entries)=>{
39
+ let mark = checkpointOf(entries);
40
+ entries = unarchived(entries);
41
+ if (!mark) return entries;
42
+ let through = mark.checkpoint.through;
43
+ let boundary = through ? entries.find((b)=>b.entity.eid == through) : mark;
44
+ let seq = boundary ? seqOf(boundary) : Number(mark.checkpoint.seq);
45
+ if (!Number.isSafeInteger(seq) || seq < 1) {
46
+ throw new Error('Checkpoint has no boundary: ' + through);
47
+ }
48
+ let rest = entries.filter((b)=>(!b.prompt || turnNote(b)) && b != mark);
49
+ let from = rest.findIndex((b)=>seqOf(b) > seq);
50
+ return [
51
+ ...retained(entries),
52
+ mark,
53
+ ...suffix(rest, from < 0 ? rest.length : from)
54
+ ];
55
+ };
56
+ /** The context window, in tokens, of a model whose row and provider name
57
+ * none (@yaks/model `model.context`, `provider.context`). */ export let CONTEXT = 128_000;
58
+ /** The share of its model's context window a transcript fills before it is
59
+ * compacted, for every model, unless a runner names another (`Deps.compactAt`):
60
+ * half, so a summary and the lines kept after it leave room to work. */ export let SHARE = 0.5;
61
+ /** Asks a transcript takes after a checkpoint before another may be written,
62
+ * whatever it weighs, except a length refusal that needs an immediate cut. */ export let GAP = 4;
63
+ /** What a share of `window` comes to, a share outside 10 to 90 percent held
64
+ * to the nearer bound, so a reply always has room. */ /// limit(1_000_000, 0.5) -> 500_000
65
+ /// limit(100_000, 2) -> 90_000
66
+ export let limit = (window, share)=>Math.floor(window * Math.min(0.9, Math.max(0.1, share)));
67
+ let utf8 = new TextEncoder();
68
+ /** Estimate the tokens in serialized text. Multibyte text gets a larger
69
+ * allowance because a single character may take several tokens. */ export let tokens = (value)=>{
70
+ let text = JSON.stringify(value) ?? '';
71
+ let bytes = utf8.encode(text).length;
72
+ return Math.ceil(text.length / 4 + bytes - text.length);
73
+ };
74
+ /** A provider tokenizes images by their dimensions. Documents have no
75
+ * portable page count, so estimate from their byte size. */ export let itemTokens = (item)=>{
76
+ if (item.kind != 'image' && item.kind != 'document') return tokens(item);
77
+ let { bytes, ...label } = item;
78
+ let size = item.kind == 'image' ? sizeOf(bytes) : undefined;
79
+ let media = size ? Math.ceil(size.w / 32) * Math.ceil(size.h / 32) : Math.ceil(bytes.byteLength / 4);
80
+ return tokens(label) + Math.max(1024, media);
81
+ };
82
+ export let itemsTokens = (items)=>items.reduce((total, item)=>total + itemTokens(item), 0);
83
+ /** The instructions, native input and schemas that accompany the items. */ export let requestTokens = (req)=>tokens([
84
+ req.instructions,
85
+ req.tools,
86
+ req.questions,
87
+ req.input
88
+ ]) + itemsTokens(req.items) + itemsTokens(req.turnContext ?? []);
89
+ /** The oldest lines to summarize, so that the newest ones kept weigh at most
90
+ * `keep` (each line's weight is its place in `sizes`), cut where no result is
91
+ * parted from its call: all of them when no such cut keeps anything. */ /// let line = (seq: number) => ({ entity: { eid: `e${seq}` }, entry: { seq } })
92
+ /// prefix([1, 2, 3, 4].map(line), [10, 10, 10, 10], 25).length -> 2
93
+ /// prefix([1, 2].map(line), [10, 50], 25).length -> 2
94
+ export let prefix = (entries, sizes, keep)=>{
95
+ let from = entries.length, kept = 0;
96
+ while(from > 1 && kept + sizes[from - 1] <= keep)kept += sizes[--from];
97
+ let end = entries.findIndex((_, i)=>i >= from && paired(entries, i) == i);
98
+ return end < 0 ? entries : entries.slice(0, end);
99
+ };
100
+ /** A provider's length refusal, including providers that use a generic input
101
+ * code and say what exceeded the window in their message. */ export let tooLong = (code, text)=>[
102
+ 'context_length_exceeded',
103
+ 'prompt_too_long',
104
+ 'request_too_large',
105
+ 'max_tokens_exceeded',
106
+ 'context_window_exceeded'
107
+ ].includes(code) || /input too big|prompt is too long|exceeds? (?:the )?(?:maximum|context|token)|(?:context|input|prompt)[\s\S]{0,80}(?:too long|length exceeded)/i.test(text);
108
+ /** Only an explicitly stated token limit, never the request's token count.
109
+ * The catalog and a configured window are not evidence of enforcement. */ /// ceiling("maximum context length is 272,000 tokens; sent 350,000") -> 272000
110
+ /// ceiling("prompt is too long: 350000 tokens > 272000 maximum") -> 272000
111
+ /// ceiling("your request has 350000 tokens") -> undefined
112
+ export let ceiling = (text)=>{
113
+ let match = [
114
+ /maximum context length (?:is|of) ([\d,]+) tokens/i,
115
+ /(?:context window|token limit|context limit)(?: is| of|:)?\s*([\d,]+)(?: tokens)?/i,
116
+ /([\d,]+) tokens?\s*>\s*([\d,]+)\s*(?:maximum|max|tokens? allowed)/i,
117
+ /maximum (?:number of )?(?:input )?tokens(?: allowed)?\s*[:(]?\s*([\d,]+)/i
118
+ ].map((re)=>re.exec(text)).find(Boolean);
119
+ let value = match && Number((match[2] ?? match[1]).replaceAll(',', ''));
120
+ return value && Number.isSafeInteger(value) && value > 0 ? value : undefined;
121
+ };
122
+ /**
123
+ * The lines of a transcript a turn reads: what a model is sent (inputs,
124
+ * replies, calls and their results), without the record kept beside them
125
+ * (asks, errors), and without the typed questions other turns asked or the
126
+ * answers they got. Those are rows for whoever asked (a page acts on them),
127
+ * not lines of the conversation, so a wake that asks every few minutes never
128
+ * crowds out what was said. `asking` is the entry whose questions this turn
129
+ * asks: it reads that one.
130
+ */ export let lines = (entries, asking)=>entries.filter((b)=>b == asking || !b.notice?.display_only && !(b.notice && b.output && !b.checkpoint && !b.delivery) && !(QUESTIONS in b || ANSWER in b) && [
131
+ 'input',
132
+ 'output',
133
+ 'call',
134
+ 'result'
135
+ ].includes(kindOf(b) ?? ''));
136
+ /** The newest `n` lines of a transcript, reaching back to the input that
137
+ * began the turn they cut into, so no call or result is sent without its
138
+ * pair: what a turn sends when its `sending.window` is `n`. All of them when
139
+ * `n` is not a count. */ export let recent = (entries, n)=>{
140
+ let size = Math.floor(Number(n));
141
+ if (!(size >= 1)) return entries;
142
+ let from = Math.max(0, entries.length - size);
143
+ while(from > 0 && kindOf(entries[from]) != 'input')from--;
144
+ return suffix(entries, from);
145
+ };
146
+ /** The entry whose typed questions a turn asks: the newest since the
147
+ * transcript's last ask that asks for anything, questions or a model, when it
148
+ * carries questions. So a retry after an error asks them again, and neither a
149
+ * later turn nor a later line choosing a model of its own does: the questions
150
+ * were that model's. */ export let askingOf = (entries)=>{
151
+ let last = newestAsk(entries);
152
+ let since = last ? seqOf(last) : 0;
153
+ let asking = entries.filter((b)=>(QUESTIONS in b || USING in b || 'sending' in b) && seqOf(b) > since).at(-1);
154
+ let asked = asking && asking[QUESTIONS]?.asked;
155
+ return asked && typeof asked == 'object' && !Array.isArray(asked) ? asking : undefined;
156
+ };
157
+ //# sourceMappingURL=compact.js.map
package/compact.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact.js","sources":["./compact.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,oEAAoE;AACpE,4BAA4B;AAG5B,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,KAAK,aAAa,CAAC,KAAK,MAAM,KAAK,OAC/D,EAAE,CAAC,CAAC;EACN,IAAI,QAAQ,UAAW,MAAM,CAAC,UAAU,EAAuB;EAC/D,OAAO,SAAS,OAAO,SAAS,YAAY,CAAC,MAAM,OAAO,CAAC,SACvD,SACA;AACN,EAAC"}
package/compact.ts ADDED
@@ -0,0 +1,209 @@
1
+ // A checkpoint is the summary of a transcript prefix. The summary can be
2
+ // appended after newer entries: `through` names the last entry it replaces,
3
+ // so the next model sees retained instructions, the summary, then a
4
+ // protocol-complete suffix.
5
+
6
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
7
+ import { sizeOf } from '@yaks/blob'
8
+ import { ANSWER, type Item, QUESTIONS, type Request } from '@yaks/model'
9
+ import { USING } from './native.js'
10
+ import { kindOf, newestAsk, seqOf } from './state.js'
11
+ import { checkpointOf, turnNote, unarchived } from './pruning.js'
12
+
13
+ let callOf = (b: Bundle): string | undefined => {
14
+ let call = ((b.result ?? b.tool_progress) as Comp | undefined)?.call
15
+ return call == null ? undefined : String(call)
16
+ }
17
+
18
+ // A result always travels with the call that gives it its provider id. An
19
+ // input may land while that call is running, so an input boundary alone does
20
+ // not keep the pair together.
21
+ let paired = (entries: Bundle[], end: number): number => {
22
+ let calls = new Map(
23
+ entries.flatMap((b, i) => b.call ? [[b.entity.eid, i] as const] : []),
24
+ )
25
+ while (true) {
26
+ let split = entries.slice(end)
27
+ .map(callOf)
28
+ .flatMap((eid) => eid == null ? [] : [calls.get(eid)])
29
+ .filter((i): i is number => i != null && i < end)
30
+ let next = split.length ? Math.min(...split) : end
31
+ if (next == end) return end
32
+ end = next
33
+ }
34
+ }
35
+
36
+ /** A suffix beginning no later than any call its results refer to. */
37
+ export let suffix = (entries: Bundle[], from: number): Bundle[] =>
38
+ entries.slice(paired(entries, from))
39
+
40
+ /** Explicitly admitted context (persona, skills, delegation instructions) is
41
+ * kept verbatim. Ordinary file reads and tool results are history, not a way
42
+ * to admit instructions. */
43
+ export let retained = (entries: Bundle[]): Bundle[] =>
44
+ entries.filter((b) => b.prompt && !b.archived && !turnNote(b))
45
+
46
+ export let history = (entries: Bundle[]): Bundle[] =>
47
+ entries.filter((b) => !b.prompt && !b.task_context)
48
+
49
+ export let context = (entries: Bundle[]): Bundle[] => {
50
+ let mark = checkpointOf(entries)
51
+ entries = unarchived(entries)
52
+ if (!mark) return entries
53
+ let through = (mark.checkpoint as Comp).through
54
+ let boundary = through ? entries.find((b) => b.entity.eid == through) : mark
55
+ let seq = boundary ? seqOf(boundary) : Number((mark.checkpoint as Comp).seq)
56
+ if (!Number.isSafeInteger(seq) || seq < 1) {
57
+ throw new Error('Checkpoint has no boundary: ' + through)
58
+ }
59
+ let rest = entries.filter((b) => (!b.prompt || turnNote(b)) && b != mark)
60
+ let from = rest.findIndex((b) => seqOf(b) > seq)
61
+ return [
62
+ ...retained(entries),
63
+ mark,
64
+ ...suffix(rest, from < 0 ? rest.length : from),
65
+ ]
66
+ }
67
+
68
+ /** The context window, in tokens, of a model whose row and provider name
69
+ * none (@yaks/model `model.context`, `provider.context`). */
70
+ export let CONTEXT = 128_000
71
+
72
+ /** The share of its model's context window a transcript fills before it is
73
+ * compacted, for every model, unless a runner names another (`Deps.compactAt`):
74
+ * half, so a summary and the lines kept after it leave room to work. */
75
+ export let SHARE = 0.5
76
+
77
+ /** Asks a transcript takes after a checkpoint before another may be written,
78
+ * whatever it weighs, except a length refusal that needs an immediate cut. */
79
+ export let GAP = 4
80
+
81
+ /** What a share of `window` comes to, a share outside 10 to 90 percent held
82
+ * to the nearer bound, so a reply always has room. */
83
+ /// limit(1_000_000, 0.5) -> 500_000
84
+ /// limit(100_000, 2) -> 90_000
85
+ export let limit = (window: number, share: number): number =>
86
+ Math.floor(window * Math.min(0.9, Math.max(0.1, share)))
87
+
88
+ let utf8 = new TextEncoder()
89
+
90
+ /** Estimate the tokens in serialized text. Multibyte text gets a larger
91
+ * allowance because a single character may take several tokens. */
92
+ export let tokens = (value: unknown): number => {
93
+ let text = JSON.stringify(value) ?? ''
94
+ let bytes = utf8.encode(text).length
95
+ return Math.ceil(text.length / 4 + bytes - text.length)
96
+ }
97
+
98
+ /** A provider tokenizes images by their dimensions. Documents have no
99
+ * portable page count, so estimate from their byte size. */
100
+ export let itemTokens = (item: Item): number => {
101
+ if (item.kind != 'image' && item.kind != 'document') return tokens(item)
102
+ let { bytes, ...label } = item
103
+ let size = item.kind == 'image' ? sizeOf(bytes) : undefined
104
+ let media = size
105
+ ? Math.ceil(size.w / 32) * Math.ceil(size.h / 32)
106
+ : Math.ceil(bytes.byteLength / 4)
107
+ return tokens(label) + Math.max(1024, media)
108
+ }
109
+
110
+ export let itemsTokens = (items: readonly Item[]): number =>
111
+ items.reduce((total, item) => total + itemTokens(item), 0)
112
+
113
+ /** The instructions, native input and schemas that accompany the items. */
114
+ export let requestTokens = (req: Request): number =>
115
+ tokens([req.instructions, req.tools, req.questions, req.input]) +
116
+ itemsTokens(req.items) + itemsTokens(req.turnContext ?? [])
117
+
118
+ /** The oldest lines to summarize, so that the newest ones kept weigh at most
119
+ * `keep` (each line's weight is its place in `sizes`), cut where no result is
120
+ * parted from its call: all of them when no such cut keeps anything. */
121
+ /// let line = (seq: number) => ({ entity: { eid: `e${seq}` }, entry: { seq } })
122
+ /// prefix([1, 2, 3, 4].map(line), [10, 10, 10, 10], 25).length -> 2
123
+ /// prefix([1, 2].map(line), [10, 50], 25).length -> 2
124
+ export let prefix = (
125
+ entries: Bundle[],
126
+ sizes: number[],
127
+ keep: number,
128
+ ): Bundle[] => {
129
+ let from = entries.length, kept = 0
130
+ while (from > 1 && kept + sizes[from - 1] <= keep) kept += sizes[--from]
131
+ let end = entries.findIndex((_, i) => i >= from && paired(entries, i) == i)
132
+ return end < 0 ? entries : entries.slice(0, end)
133
+ }
134
+
135
+ /** A provider's length refusal, including providers that use a generic input
136
+ * code and say what exceeded the window in their message. */
137
+ export let tooLong = (code: string, text: string): boolean =>
138
+ [
139
+ 'context_length_exceeded',
140
+ 'prompt_too_long',
141
+ 'request_too_large',
142
+ 'max_tokens_exceeded',
143
+ 'context_window_exceeded',
144
+ ].includes(code) ||
145
+ /input too big|prompt is too long|exceeds? (?:the )?(?:maximum|context|token)|(?:context|input|prompt)[\s\S]{0,80}(?:too long|length exceeded)/i
146
+ .test(text)
147
+
148
+ /** Only an explicitly stated token limit, never the request's token count.
149
+ * The catalog and a configured window are not evidence of enforcement. */
150
+ /// ceiling("maximum context length is 272,000 tokens; sent 350,000") -> 272000
151
+ /// ceiling("prompt is too long: 350000 tokens > 272000 maximum") -> 272000
152
+ /// ceiling("your request has 350000 tokens") -> undefined
153
+ export let ceiling = (text: string): number | undefined => {
154
+ let match = [
155
+ /maximum context length (?:is|of) ([\d,]+) tokens/i,
156
+ /(?:context window|token limit|context limit)(?: is| of|:)?\s*([\d,]+)(?: tokens)?/i,
157
+ /([\d,]+) tokens?\s*>\s*([\d,]+)\s*(?:maximum|max|tokens? allowed)/i,
158
+ /maximum (?:number of )?(?:input )?tokens(?: allowed)?\s*[:(]?\s*([\d,]+)/i,
159
+ ].map((re) => re.exec(text)).find(Boolean)
160
+ let value = match && Number((match[2] ?? match[1]).replaceAll(',', ''))
161
+ return value && Number.isSafeInteger(value) && value > 0 ? value : undefined
162
+ }
163
+
164
+ /**
165
+ * The lines of a transcript a turn reads: what a model is sent (inputs,
166
+ * replies, calls and their results), without the record kept beside them
167
+ * (asks, errors), and without the typed questions other turns asked or the
168
+ * answers they got. Those are rows for whoever asked (a page acts on them),
169
+ * not lines of the conversation, so a wake that asks every few minutes never
170
+ * crowds out what was said. `asking` is the entry whose questions this turn
171
+ * asks: it reads that one.
172
+ */
173
+ export let lines = (entries: Bundle[], asking?: Bundle): Bundle[] =>
174
+ entries.filter((b) =>
175
+ b == asking ||
176
+ !(b.notice as Comp | undefined)?.display_only &&
177
+ !(b.notice && b.output && !b.checkpoint && !b.delivery) &&
178
+ !(QUESTIONS in b || ANSWER in b) &&
179
+ ['input', 'output', 'call', 'result'].includes(kindOf(b) ?? '')
180
+ )
181
+
182
+ /** The newest `n` lines of a transcript, reaching back to the input that
183
+ * began the turn they cut into, so no call or result is sent without its
184
+ * pair: what a turn sends when its `sending.window` is `n`. All of them when
185
+ * `n` is not a count. */
186
+ export let recent = (entries: Bundle[], n?: unknown): Bundle[] => {
187
+ let size = Math.floor(Number(n))
188
+ if (!(size >= 1)) return entries
189
+ let from = Math.max(0, entries.length - size)
190
+ while (from > 0 && kindOf(entries[from]) != 'input') from--
191
+ return suffix(entries, from)
192
+ }
193
+
194
+ /** The entry whose typed questions a turn asks: the newest since the
195
+ * transcript's last ask that asks for anything, questions or a model, when it
196
+ * carries questions. So a retry after an error asks them again, and neither a
197
+ * later turn nor a later line choosing a model of its own does: the questions
198
+ * were that model's. */
199
+ export let askingOf = (entries: Bundle[]): Bundle | undefined => {
200
+ let last = newestAsk(entries)
201
+ let since = last ? seqOf(last) : 0
202
+ let asking = entries.filter((b) =>
203
+ (QUESTIONS in b || USING in b || 'sending' in b) && seqOf(b) > since
204
+ ).at(-1)
205
+ let asked = asking && (asking[QUESTIONS] as Comp | undefined)?.asked
206
+ return asked && typeof asked == 'object' && !Array.isArray(asked)
207
+ ? asking
208
+ : undefined
209
+ }