@yaks/model 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 (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +868 -2
  3. package/_dist/afford.d.ts +69 -0
  4. package/_dist/afford.d.ts.map +1 -0
  5. package/_dist/attribute.d.ts +52 -0
  6. package/_dist/attribute.d.ts.map +1 -0
  7. package/_dist/batch.d.ts +28 -0
  8. package/_dist/batch.d.ts.map +1 -0
  9. package/_dist/cache.d.ts +15 -0
  10. package/_dist/cache.d.ts.map +1 -0
  11. package/_dist/deferred.d.ts +9 -0
  12. package/_dist/deferred.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +3 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/image.d.ts +46 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/inference.d.ts +58 -0
  18. package/_dist/inference.d.ts.map +1 -0
  19. package/_dist/limits.d.ts +142 -0
  20. package/_dist/limits.d.ts.map +1 -0
  21. package/_dist/media.d.ts +28 -0
  22. package/_dist/media.d.ts.map +1 -0
  23. package/_dist/message.d.ts +5 -0
  24. package/_dist/message.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +298 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/offers.d.ts +19 -0
  28. package/_dist/offers.d.ts.map +1 -0
  29. package/_dist/onward.d.ts +77 -0
  30. package/_dist/onward.d.ts.map +1 -0
  31. package/_dist/prices.d.ts +27 -0
  32. package/_dist/prices.d.ts.map +1 -0
  33. package/_dist/provider.d.ts +49 -0
  34. package/_dist/provider.d.ts.map +1 -0
  35. package/_dist/results.d.ts +21 -0
  36. package/_dist/results.d.ts.map +1 -0
  37. package/_dist/route.d.ts +189 -0
  38. package/_dist/route.d.ts.map +1 -0
  39. package/_dist/sse.d.ts +4 -0
  40. package/_dist/sse.d.ts.map +1 -0
  41. package/_dist/stall.d.ts +47 -0
  42. package/_dist/stall.d.ts.map +1 -0
  43. package/_dist/step.d.ts +71 -0
  44. package/_dist/step.d.ts.map +1 -0
  45. package/_dist/submission.d.ts +7 -0
  46. package/_dist/submission.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +82 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/_dist/windows.d.ts +6 -0
  50. package/_dist/windows.d.ts.map +1 -0
  51. package/afford.js +135 -0
  52. package/afford.js.map +1 -0
  53. package/afford.ts +208 -0
  54. package/attribute.js +109 -0
  55. package/attribute.js.map +1 -0
  56. package/attribute.ts +120 -0
  57. package/batch.js +8 -0
  58. package/batch.js.map +1 -0
  59. package/batch.ts +37 -0
  60. package/cache.js +28 -0
  61. package/cache.js.map +1 -0
  62. package/cache.ts +53 -0
  63. package/deferred.js +29 -0
  64. package/deferred.js.map +1 -0
  65. package/deferred.ts +54 -0
  66. package/deno.json +1 -0
  67. package/graph.js +8 -0
  68. package/graph.js.map +1 -0
  69. package/graph.ts +9 -0
  70. package/image.js +118 -0
  71. package/image.js.map +1 -0
  72. package/image.ts +108 -0
  73. package/inference.js +119 -0
  74. package/inference.js.map +1 -0
  75. package/inference.ts +223 -0
  76. package/limits.js +204 -0
  77. package/limits.js.map +1 -0
  78. package/limits.ts +230 -0
  79. package/media.js +76 -0
  80. package/media.js.map +1 -0
  81. package/media.ts +139 -0
  82. package/message.js +21 -0
  83. package/message.js.map +1 -0
  84. package/message.ts +17 -0
  85. package/mod.js +396 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +695 -0
  88. package/offers.js +53 -0
  89. package/offers.js.map +1 -0
  90. package/offers.ts +84 -0
  91. package/onward.js +110 -0
  92. package/onward.js.map +1 -0
  93. package/onward.ts +123 -0
  94. package/package.json +53 -4
  95. package/prices.js +61 -0
  96. package/prices.js.map +1 -0
  97. package/prices.json +643 -0
  98. package/prices.ts +60 -0
  99. package/provider.js +6 -0
  100. package/provider.js.map +1 -0
  101. package/provider.ts +89 -0
  102. package/results.js +51 -0
  103. package/results.js.map +1 -0
  104. package/results.ts +47 -0
  105. package/route.js +263 -0
  106. package/route.js.map +1 -0
  107. package/route.ts +359 -0
  108. package/sse.js +71 -0
  109. package/sse.js.map +1 -0
  110. package/sse.ts +82 -0
  111. package/stall.js +166 -0
  112. package/stall.js.map +1 -0
  113. package/stall.ts +201 -0
  114. package/step.js +226 -0
  115. package/step.js.map +1 -0
  116. package/step.ts +265 -0
  117. package/submission.js +38 -0
  118. package/submission.js.map +1 -0
  119. package/submission.ts +38 -0
  120. package/vocab.js +83 -0
  121. package/vocab.js.map +1 -0
  122. package/vocab.json +613 -0
  123. package/vocab.ts +139 -0
  124. package/windows.js +35 -0
  125. package/windows.js.map +1 -0
  126. package/windows.ts +28 -0
package/route.ts ADDED
@@ -0,0 +1,359 @@
1
+ // The router: which of several offerings a default runs on. Pure, and its
2
+ // own module (`@yaks/model/route`) so what reads a default loads nothing else.
3
+ // The offerings are graph data, `routes` edges to `serves` edges, and so are
4
+ // the readings (`rate_limit`); the one who asks reads both and hands them
5
+ // here. Each rule orders the offerings it can speak for, best first, and the
6
+ // first rule that speaks for any answers. There are two: a pinned offering,
7
+ // then the plan with the most usage left. Which of a provider's accounts an
8
+ // offering runs on is chosen here too ({@link freest}).
9
+
10
+ import type { Eid } from 'jsr:@yaks/graph@0.2.36'
11
+
12
+ /** One offering a default may run on. */
13
+ export type Route = {
14
+ provider: Eid
15
+ model: Eid
16
+ /** what the model is called, for the reason */
17
+ name: string
18
+ /** the provider whose plan limits meter it (`provider.plan`, else its own) */
19
+ plan: Eid
20
+ /** when it was pinned (`routes.pinned`): a pinned offering is the answer,
21
+ * whatever the plans read */
22
+ pinned?: string
23
+ }
24
+
25
+ /** A plan limit's latest reading, as its `rate_limit` row holds it. */
26
+ export type Reading = {
27
+ provider: Eid
28
+ /** the account whose plan it is, where the reading came from one */
29
+ account?: Eid
30
+ /** minutes: 10080 a week, 300 five hours */
31
+ window: number
32
+ /** the model whose requests it meters, where it is a limit on one model */
33
+ model?: Eid
34
+ /** percent used */
35
+ used: number
36
+ resets?: string
37
+ at?: string
38
+ }
39
+
40
+ /** What a router is asked: the offerings, what is known of their plans, and
41
+ * the moment. A later rule's parameter (the work's kind) is another property
42
+ * here. */
43
+ export type Asked = { routes: Route[]; readings: Reading[]; now: number }
44
+
45
+ /** The offering chosen and, in one line, why. */
46
+ export type Routed = { provider: Eid; model: Eid; why: string }
47
+
48
+ // An offering and what a rule learned of it, as the reason says it.
49
+ type Weighed = Route & { note?: string }
50
+ type Rule = (routes: Weighed[], asked: Asked) => Weighed[]
51
+
52
+ let span = (window: number) =>
53
+ window == 10080 ? 'week' : window == 300 ? 'five hours' : `${window} min`
54
+
55
+ // A plan's reading, and its limit's on `model` where it has one: each one's
56
+ // longest window's, the newest where accounts differ.
57
+ let reading = (
58
+ plan: Eid,
59
+ readings: Reading[],
60
+ model?: Eid,
61
+ ): Reading | undefined =>
62
+ readings.filter((r) => r.provider == plan && r.window > 0 && r.model == model)
63
+ .sort((a, b) =>
64
+ b.window - a.window || (b.at ?? '').localeCompare(a.at ?? '')
65
+ )[0]
66
+
67
+ // The offerings whose plan has a reading, the most usage left first: what is
68
+ // left of the plan, or of its limit on the offering's model where that is
69
+ // less. A window that has reset since its reading is unused.
70
+ let roomiest: Rule = (routes, { readings, now }) =>
71
+ routes.flatMap((route) => {
72
+ let left = (r: Reading) =>
73
+ r.resets && Date.parse(r.resets) <= now ? 100 : 100 - r.used
74
+ let [r] = [
75
+ reading(route.plan, readings),
76
+ reading(route.plan, readings, route.model),
77
+ ].filter((r) => r != null).sort((a, b) => left(a) - left(b))
78
+ if (!r) return []
79
+ let note = `has ${left(r)}% of its ${span(r.window)} left`
80
+ return [{ left: left(r), route, note }]
81
+ }).sort((a, b) => b.left - a.left)
82
+ .map(({ route, note }) => ({ ...route, note }))
83
+
84
+ // The pinned offering, the newest pin where more than one is.
85
+ let pinned: Rule = (routes) =>
86
+ routes.filter((r) => r.pinned)
87
+ .sort((a, b) => b.pinned!.localeCompare(a.pinned!))
88
+ .slice(0, 1).map((r) => ({ ...r, note: 'is pinned' }))
89
+
90
+ let rules: Rule[] = [pinned, roomiest]
91
+
92
+ /**
93
+ * The offering to ask, or nothing where no rule can say: no routes, or none
94
+ * pinned and no reading of any of their plans.
95
+ *
96
+ * ```ts
97
+ * import { type Reading, route } from './route.ts'
98
+ * import { equal } from '@yaks/testing'
99
+ *
100
+ * let routes = [
101
+ * { provider: 'claude', model: 'opus', name: 'opus', plan: 'claude' },
102
+ * { provider: 'openai', model: 'sol', name: 'sol', plan: 'codex' },
103
+ * ]
104
+ * let week = (provider: string, used: number, resets = '2026-11-17T00:00:00Z') =>
105
+ * ({ provider, window: 10080, used, resets })
106
+ * let now = Date.parse('2026-11-11T00:00:00Z')
107
+ * let ask = (readings: Reading[]) =>
108
+ * route({ routes, readings, now })
109
+ *
110
+ * equal(ask([week('claude', 84), week('codex', 82)]), {
111
+ * provider: 'openai',
112
+ * model: 'sol',
113
+ * why: 'sol has 18% of its week left, opus has 16% of its week left',
114
+ * })
115
+ * // A week that has reset since it was read is unused.
116
+ * equal(ask([week('claude', 84, '2026-11-10T00:00:00Z'), week('codex', 82)])?.model, 'opus')
117
+ * // A plan nothing has read can't win, and with no reading nothing is chosen.
118
+ * equal(ask([week('claude', 99)])?.why, 'opus has 1% of its week left')
119
+ * equal(ask([]), undefined)
120
+ * // A limit on one model counts for that model where it leaves less.
121
+ * equal(ask([week('claude', 40), { ...week('claude', 95), model: 'opus' }, week('codex', 82)])?.model, 'sol')
122
+ * // A pinned offering wins over usage, and needs no reading.
123
+ * let pin = { ...routes[0], pinned: '2026-11-11T00:00:00Z' }
124
+ * equal(route({ routes: [pin, routes[1]], readings: [week('codex', 0)], now }), {
125
+ * provider: 'claude',
126
+ * model: 'opus',
127
+ * why: 'opus is pinned',
128
+ * })
129
+ * equal(route({ routes: [pin], readings: [], now })?.model, 'opus')
130
+ * ```
131
+ */
132
+ export let route = (asked: Asked): Routed | undefined => {
133
+ let left = rules.map((rule) => rule(asked.routes, asked))
134
+ .find((routes) => routes.length) ?? []
135
+ return left.length
136
+ ? {
137
+ provider: left[0].provider,
138
+ model: left[0].model,
139
+ why: left.map((r) => `${r.name} ${r.note}`).join(', '),
140
+ }
141
+ : undefined
142
+ }
143
+
144
+ /**
145
+ * Where a conversation goes on once the plan `from` runs on is spent: of the
146
+ * offerings on another plan whose readings leave room, the one {@link route}
147
+ * chooses, else the first of them. Nothing where every other plan is spent
148
+ * too, or none is routed. The reason says which plan ran out.
149
+ *
150
+ * ```ts
151
+ * import { onward } from './route.ts'
152
+ * import { equal } from '@yaks/testing'
153
+ *
154
+ * let routes = [
155
+ * { provider: 'claude', model: 'opus', name: 'opus', plan: 'claude' },
156
+ * { provider: 'openai', model: 'sol', name: 'sol', plan: 'codex' },
157
+ * { provider: 'grok', model: 'grok-5', name: 'grok-5', plan: 'grok' },
158
+ * ]
159
+ * let now = Date.parse('2026-11-23T12:00:00Z')
160
+ * let full = { provider: 'codex', window: 10080, used: 100, resets: '2026-11-25T00:00:00Z' }
161
+ * let from = { provider: 'claude', model: 'opus' }
162
+ * // With no readings, the next routed offering.
163
+ * equal(onward({ routes, readings: [], now, from }), {
164
+ * provider: 'openai', model: 'sol', why: "opus's plan is spent; sol is next",
165
+ * })
166
+ * // A plan read full is passed over.
167
+ * equal(onward({ routes, readings: [full], now, from })?.model, 'grok-5')
168
+ * equal(onward({ routes: routes.slice(0, 2), readings: [full], now, from }), undefined)
169
+ * ```
170
+ */
171
+ export let onward = (
172
+ asked: Asked & {
173
+ from: { provider: Eid; model?: Eid }
174
+ passed?: ReadonlySet<Eid>
175
+ available?: ReadonlySet<Eid>
176
+ },
177
+ ): Routed | undefined => {
178
+ let { routes, readings, now, from } = asked
179
+ let was =
180
+ routes.find((r) =>
181
+ r.provider == from.provider && (!from.model || r.model == from.model)
182
+ ) ?? routes.find((r) => r.provider == from.provider)
183
+ let plan = was?.plan ?? from.provider
184
+ let passed = new Set([plan, ...asked.passed ?? []])
185
+ for (let r of routes) if (asked.passed?.has(r.provider)) passed.add(r.plan)
186
+ let full = (plan: Eid) =>
187
+ readings.some((r) =>
188
+ r.provider == plan && r.used >= 100 &&
189
+ !(r.resets && Date.parse(r.resets) <= now)
190
+ )
191
+ let open = routes.filter((r) =>
192
+ (!asked.available || asked.available.has(r.provider)) &&
193
+ !passed.has(r.plan) && !full(r.plan)
194
+ )
195
+ if (!open.length) return undefined
196
+ let chosen = route({ ...asked, routes: open }) ??
197
+ {
198
+ provider: open[0].provider,
199
+ model: open[0].model,
200
+ why: `${open[0].name} is next`,
201
+ }
202
+ return {
203
+ ...chosen,
204
+ why: `${was ? `${was.name}'s plan` : 'its plan'} is spent; ${chosen.why}`,
205
+ }
206
+ }
207
+
208
+ /** An account an offering may run on (`account`), and what it is called,
209
+ * for the reason. */
210
+ export type Account = { account: Eid; name: string }
211
+
212
+ /** The account chosen and, in one line, why; `full` where its plan has no
213
+ * room, as every account's had none. */
214
+ export type Freest = { account: Eid; why: string; full?: true }
215
+
216
+ const WEEK = 10080
217
+ const HOURS = 300
218
+
219
+ /** A window's usage against its pace, in points of the window. */
220
+ export type Pace = {
221
+ /** the share of the window gone, rounded */
222
+ gone: number
223
+ /** the points used that its reset does not give back */
224
+ spent: number
225
+ /** `gone` less `spent`: below zero, over pace */
226
+ under: number
227
+ }
228
+
229
+ /**
230
+ * A window's usage against the share of it gone: `used` less the points
231
+ * `back` a reset gives back (Fable's share of Claude's week), set against the
232
+ * share of the window gone by `now`. A window that resets at an unknown time
233
+ * is taken as all gone. The pace `claude-budget` prints (`bin/pace.ts`) and
234
+ * the one {@link freest} picks an account by.
235
+ *
236
+ * ```ts
237
+ * import { pace } from './route.ts'
238
+ * import { equal } from '@yaks/testing'
239
+ *
240
+ * let now = Date.parse('2026-11-14T00:00:00Z') // three days into the week
241
+ * let week = { window: 10080, used: 40, resets: '2026-11-18T00:00:00Z' }
242
+ * equal(pace(week, now), { gone: 43, spent: 40, under: 3 })
243
+ * equal(pace(week, now, 7), { gone: 43, spent: 33, under: 10 })
244
+ * equal(pace({ ...week, used: 5 }, now, 7).spent, 0)
245
+ * equal(pace({ window: 10080, used: 40 }, now).gone, 100)
246
+ * ```
247
+ */
248
+ export let pace = (
249
+ window: { window: number; used: number; resets?: string },
250
+ now: number,
251
+ back = 0,
252
+ ): Pace => {
253
+ let ends = window.resets ? Date.parse(window.resets) : NaN
254
+ let left = (ends - now) / (window.window * 60000)
255
+ let gone = isNaN(left)
256
+ ? 100
257
+ : Math.round(100 * Math.min(1, Math.max(0, 1 - left)))
258
+ let spent = Math.max(0, window.used - back)
259
+ return { gone, spent, under: gone - spent }
260
+ }
261
+
262
+ // The points of the week a plan's limit on one model holds: Claude's cap on
263
+ // Fable is half the week, and a Fable reset gives its share back.
264
+ const CAP = 0.5
265
+
266
+ // Five hours are spent from this share on: an account whose five hours read
267
+ // this much used has no room for a run until they reset. The week is its
268
+ // pace's to weigh.
269
+ const FULL = 90
270
+
271
+ /**
272
+ * The account further under its weekly pace ({@link pace}): the most points
273
+ * between the share of its week gone and the share used, less what a reset of
274
+ * its limit on one model gives back, half that limit's reading. A week that
275
+ * has reset since its reading is unused, and an account nothing has read yet
276
+ * goes first, so its first run reads it. An account whose five hours are
277
+ * spent or nearly so goes after every account with room, and the answer says
278
+ * `full` where none has any. Nothing where
279
+ * there are no accounts.
280
+ *
281
+ * ```ts
282
+ * import { freest } from './route.ts'
283
+ * import { equal } from '@yaks/testing'
284
+ *
285
+ * let accounts = [{ account: 'a', name: '.claude' }, { account: 'b', name: '.claude-teams' }]
286
+ * let now = Date.parse('2026-11-14T00:00:00Z') // three days into the week
287
+ * let week = (account: string, used: number, resets = '2026-11-18T00:00:00Z') =>
288
+ * ({ provider: 'claude', account, window: 10080, used, resets })
289
+ * equal(freest({ accounts, readings: [week('a', 20), week('b', 50)], now }), {
290
+ * account: 'a',
291
+ * why: '.claude is 23 points under its weekly pace, ' +
292
+ * '.claude-teams is 7 points over its weekly pace',
293
+ * })
294
+ * // Fable's share, half its cap's reading, is not held against the week.
295
+ * let fable = { ...week('b', 80), model: 'fable' }
296
+ * equal(freest({ accounts, readings: [week('a', 20), week('b', 50), fable], now })?.account, 'b')
297
+ * equal(freest({ accounts, readings: [week('a', 20)], now })?.account, 'b')
298
+ * equal(freest({ accounts, readings: [week('a', 20), week('b', 90, '2026-11-13T00:00:00Z')], now })?.account, 'b')
299
+ * // Five hours used up put an account last, until they reset.
300
+ * let hours = (account: string, used: number, resets = '2026-11-14T02:00:00Z') =>
301
+ * ({ provider: 'claude', account, window: 300, used, resets })
302
+ * equal(freest({ accounts, readings: [week('a', 20), hours('a', 95), week('b', 50)], now }), {
303
+ * account: 'b',
304
+ * why: '.claude-teams is 7 points over its weekly pace, ' +
305
+ * '.claude has used 95% of its five hours',
306
+ * })
307
+ * equal(freest({ accounts, readings: [hours('a', 100, '2026-11-13T23:00:00Z')], now })?.account, 'a')
308
+ * equal(freest({ accounts: accounts.slice(0, 1), readings: [hours('a', 100)], now })?.full, true)
309
+ * equal(freest({ accounts: [], readings: [], now }), undefined)
310
+ * ```
311
+ */
312
+ export let freest = (
313
+ asked: { accounts: Account[]; readings: Reading[]; now: number },
314
+ ): Freest | undefined => {
315
+ let { readings, now } = asked
316
+ let current = (r: Reading) => !(r.resets && Date.parse(r.resets) <= now)
317
+ // An account's newest reading of a window, of the plan or of its limit on
318
+ // one model.
319
+ let newest = (a: Account, window: number, capped = false) =>
320
+ readings.filter((r) =>
321
+ r.account == a.account && r.window == window && !r.model == !capped
322
+ ).sort((x, y) => (y.at ?? '').localeCompare(x.at ?? ''))[0]
323
+ // Its five hours' reading, where they are spent.
324
+ let spent = (a: Account) => {
325
+ let r = newest(a, HOURS)
326
+ return r && current(r) && r.used >= FULL ? r : undefined
327
+ }
328
+ // Points under pace, and what the reason says where it is not a number.
329
+ let weigh = (a: Account): { under: number; fresh?: string } => {
330
+ let r = newest(a, WEEK)
331
+ if (!r) return { under: Infinity, fresh: 'has no reading of its week' }
332
+ if (!current(r)) return { under: Infinity, fresh: 'has a fresh week' }
333
+ let cap = newest(a, WEEK, true)
334
+ let running = cap && current(cap)
335
+ return {
336
+ under: Math.round(pace(r, now, running ? cap.used * CAP : 0).under),
337
+ }
338
+ }
339
+ let weighed = asked.accounts.map((a) => ({
340
+ ...a,
341
+ ...weigh(a),
342
+ spent: spent(a),
343
+ }))
344
+ .sort((x, y) => Number(!!x.spent) - Number(!!y.spent) || y.under - x.under)
345
+ if (!weighed.length) return
346
+ let said = (w: typeof weighed[0]) =>
347
+ `${w.name} ${
348
+ w.spent
349
+ ? `has used ${w.spent.used}% of its ${span(w.spent.window)}`
350
+ : w.fresh ??
351
+ `is ${Math.abs(w.under)} points ${w.under < 0 ? 'over' : 'under'} ` +
352
+ 'its weekly pace'
353
+ }`
354
+ return {
355
+ account: weighed[0].account,
356
+ why: weighed.map(said).join(', '),
357
+ ...weighed[0].spent ? { full: true as const } : {},
358
+ }
359
+ }
package/sse.js ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The server-sent events a provider streams a reply as, each `data:` field
3
+ * read as one JSON object. Providers frame them alike and fail differently, so
4
+ * the caller names its own errors: `fault` makes one for a dropped connection,
5
+ * a stream that went quiet (a body read through `@yaks/model/stall`) or a
6
+ * frame that is not JSON, and `check` may throw one for an event the provider
7
+ * sends to say it failed.
8
+ *
9
+ * @module
10
+ */ import { Stalled } from "./stall.js";
11
+ /** JSON SSE frames across arbitrary byte chunks, CRLF and a final frame with
12
+ * no blank line after it; `done` hears a `[DONE]` sentinel. The reader is
13
+ * released even if a consumer stops early or throws. */ export let jsonFrames = async function*(body, fault, check, done) {
14
+ let reader = body.getReader();
15
+ let frame = (block)=>{
16
+ let data = block.split(/\r?\n/).filter((line)=>line.startsWith('data:')).map((line)=>line.slice(5).trimStart()).join('\n');
17
+ if (!data) return;
18
+ if (data == '[DONE]') {
19
+ done?.();
20
+ return;
21
+ }
22
+ let value;
23
+ try {
24
+ value = JSON.parse(data);
25
+ } catch {
26
+ throw fault('malformed_stream', 'malformed SSE data');
27
+ }
28
+ if (!value || typeof value != 'object' || Array.isArray(value)) {
29
+ throw fault('malformed_stream', 'SSE data is not an object');
30
+ }
31
+ let parsed = value;
32
+ check?.(parsed);
33
+ return parsed;
34
+ };
35
+ try {
36
+ let decoder = new TextDecoder();
37
+ let pending = '';
38
+ let boundary = /\r?\n\r?\n/;
39
+ while(true){
40
+ let part;
41
+ try {
42
+ part = await reader.read();
43
+ } catch (error) {
44
+ if (error?.name == 'AbortError') throw error;
45
+ if (error instanceof Stalled) {
46
+ throw fault('stalled', `stream stalled — ${error.message}`);
47
+ }
48
+ throw fault('transport', 'error reading a body from connection');
49
+ }
50
+ pending += decoder.decode(part.value, {
51
+ stream: !part.done
52
+ });
53
+ let end;
54
+ while(end = boundary.exec(pending)){
55
+ let block = pending.slice(0, end.index);
56
+ pending = pending.slice(end.index + end[0].length);
57
+ let value = frame(block);
58
+ if (value) yield value;
59
+ }
60
+ if (part.done) break;
61
+ }
62
+ if (pending.trim()) {
63
+ let value = frame(pending);
64
+ if (value) yield value;
65
+ }
66
+ } finally{
67
+ await reader.cancel().catch(()=>{});
68
+ reader.releaseLock();
69
+ }
70
+ };
71
+ //# sourceMappingURL=sse.js.map
package/sse.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sources":["./sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;CASC,GAED,SAAS,OAAO,qBAAoB;AAEpC;;sDAEsD,GACtD,OAAO,IAAI,aAAa,gBACtB,IAAgC,EAChC,KAGU,EACV,KAAgD,EAChD,IAAiB;EAEjB,IAAI,SAAS,KAAK,SAAS;EAC3B,IAAI,QAAQ,CAAC;IACX,IAAI,OAAO,MAAM,KAAK,CAAC,SACpB,MAAM,CAAC,CAAC,OAAS,KAAK,UAAU,CAAC,UACjC,GAAG,CAAC,CAAC,OAAS,KAAK,KAAK,CAAC,GAAG,SAAS,IAAI,IAAI,CAAC;IACjD,IAAI,CAAC,MAA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a reply as, each `data:` field
3
+ * read as one JSON object. Providers frame them alike and fail differently, so
4
+ * the caller names its own errors: `fault` makes one for a dropped connection,
5
+ * a stream that went quiet (a body read through `@yaks/model/stall`) or a
6
+ * frame that is not JSON, and `check` may throw one for an event the provider
7
+ * sends to say it failed.
8
+ *
9
+ * @module
10
+ */
11
+
12
+ import { Stalled } from './stall.js'
13
+
14
+ /** JSON SSE frames across arbitrary byte chunks, CRLF and a final frame with
15
+ * no blank line after it; `done` hears a `[DONE]` sentinel. The reader is
16
+ * released even if a consumer stops early or throws. */
17
+ export let jsonFrames = async function* (
18
+ body: ReadableStream<Uint8Array>,
19
+ fault: (
20
+ kind: 'transport' | 'stalled' | 'malformed_stream',
21
+ message: string,
22
+ ) => Error,
23
+ check?: (value: Record<string, unknown>) => void,
24
+ done?: () => void,
25
+ ): AsyncGenerator<Record<string, unknown>> {
26
+ let reader = body.getReader()
27
+ let frame = (block: string) => {
28
+ let data = block.split(/\r?\n/)
29
+ .filter((line) => line.startsWith('data:'))
30
+ .map((line) => line.slice(5).trimStart()).join('\n')
31
+ if (!data) return
32
+ if (data == '[DONE]') {
33
+ done?.()
34
+ return
35
+ }
36
+ let value: unknown
37
+ try {
38
+ value = JSON.parse(data)
39
+ } catch {
40
+ throw fault('malformed_stream', 'malformed SSE data')
41
+ }
42
+ if (!value || typeof value != 'object' || Array.isArray(value)) {
43
+ throw fault('malformed_stream', 'SSE data is not an object')
44
+ }
45
+ let parsed = value as Record<string, unknown>
46
+ check?.(parsed)
47
+ return parsed
48
+ }
49
+ try {
50
+ let decoder = new TextDecoder()
51
+ let pending = ''
52
+ let boundary = /\r?\n\r?\n/
53
+ while (true) {
54
+ let part: ReadableStreamReadResult<Uint8Array>
55
+ try {
56
+ part = await reader.read()
57
+ } catch (error) {
58
+ if ((error as Error)?.name == 'AbortError') throw error
59
+ if (error instanceof Stalled) {
60
+ throw fault('stalled', `stream stalled — ${error.message}`)
61
+ }
62
+ throw fault('transport', 'error reading a body from connection')
63
+ }
64
+ pending += decoder.decode(part.value, { stream: !part.done })
65
+ let end: RegExpExecArray | null
66
+ while ((end = boundary.exec(pending))) {
67
+ let block = pending.slice(0, end.index)
68
+ pending = pending.slice(end.index + end[0].length)
69
+ let value = frame(block)
70
+ if (value) yield value
71
+ }
72
+ if (part.done) break
73
+ }
74
+ if (pending.trim()) {
75
+ let value = frame(pending)
76
+ if (value) yield value
77
+ }
78
+ } finally {
79
+ await reader.cancel().catch(() => {})
80
+ reader.releaseLock()
81
+ }
82
+ }
package/stall.js ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * How long a provider's stream may go quiet. A request whose connection, first
3
+ * byte or any later gap in its stream goes that long without progress fails
4
+ * as stalled, instead of waiting for ever on a server that stopped talking.
5
+ *
6
+ * ```ts
7
+ * import { stallMs, watched } from '@yaks/model/stall'
8
+ *
9
+ * let ask = watched(fetch, stallMs({ stallTimeout: 60 }))
10
+ * // a call through `ask` fails with `Stalled` after 60s without a byte
11
+ * ```
12
+ *
13
+ * @module
14
+ */ import { system } from "@yaks/fp";
15
+ /** Seconds a stream may go without progress before its request fails as
16
+ * stalled, where neither the request nor its provider's row names its own
17
+ * (`Request.stallTimeout`, `provider{stall_timeout}`). Five minutes, the Codex
18
+ * CLI's own stream idle timeout: a reasoning model can think in silence for
19
+ * minutes, and none answers after hours. */ export const STALL_TIMEOUT = 300;
20
+ /** The milliseconds a request's stream may stay quiet: its own
21
+ * `stallTimeout`, else {@link STALL_TIMEOUT}. 0 waits for ever. */ export let stallMs = (req)=>Math.max(0, req.stallTimeout ?? STALL_TIMEOUT) * 1000;
22
+ /** What a stalled exchange's call or read fails with. */ export class Stalled extends Error {
23
+ constructor(ms){
24
+ super(`no progress for ${ms / 1000}s`);
25
+ this.name = 'Stalled';
26
+ }
27
+ }
28
+ /** A resettable idle deadline for one exchange. It aborts its own signal,
29
+ * never the caller's `stop`, when `ms` passes with no progress, and each sign
30
+ * of progress calls kick() to push the deadline out. The caller reads
31
+ * stalled() to turn that self-abort into a named failure instead of a silent
32
+ * hang. A relayed stop aborts too, with its own reason, but leaves stalled()
33
+ * false so the caller keeps its own path. `ms` 0 sets no deadline. */ export let watchdog = (ms, clock = system, stop)=>{
34
+ // With no deadline and nothing to relay, there is nothing to abort. A relayed
35
+ // stop still goes through a signal of its own, so it arrives as an abort.
36
+ if (!ms && !stop) {
37
+ return {
38
+ signal: undefined,
39
+ kick: ()=>{},
40
+ rest: ()=>{},
41
+ stalled: ()=>false,
42
+ close: ()=>{}
43
+ };
44
+ }
45
+ let control = new AbortController();
46
+ let stalled = false;
47
+ let cancel = ()=>{};
48
+ let relay = ()=>control.abort(stop?.reason);
49
+ let rest = ()=>{
50
+ cancel();
51
+ cancel = ()=>{};
52
+ };
53
+ let kick = ()=>{
54
+ if (!ms || control.signal.aborted) return;
55
+ cancel();
56
+ cancel = clock.after(ms, ()=>{
57
+ stalled = true;
58
+ control.abort(new Stalled(ms));
59
+ });
60
+ };
61
+ if (stop?.aborted) control.abort(stop.reason);
62
+ else stop?.addEventListener('abort', relay, {
63
+ once: true
64
+ });
65
+ kick();
66
+ return {
67
+ signal: control.signal,
68
+ kick,
69
+ rest,
70
+ stalled: ()=>stalled,
71
+ close: ()=>{
72
+ rest();
73
+ stop?.removeEventListener('abort', relay);
74
+ }
75
+ };
76
+ };
77
+ // `body` read under `dog`: only the wait on the source counts, so the deadline
78
+ // runs from each read asked for to the chunk that answers it, and a reader
79
+ // slow to ask again is not a stalled server. A trip fails the read in progress
80
+ // with Stalled, a relayed stop with its reason, and either cancels the source.
81
+ let guard = (body, dog)=>{
82
+ let signal = dog.signal;
83
+ let reader = body.getReader();
84
+ let end = ()=>{};
85
+ return new ReadableStream({
86
+ start (controller) {
87
+ let fail = ()=>{
88
+ controller.error(signal.reason);
89
+ reader.cancel(signal.reason).catch(()=>{});
90
+ };
91
+ if (signal.aborted) return fail();
92
+ signal.addEventListener('abort', fail, {
93
+ once: true
94
+ });
95
+ end = ()=>{
96
+ signal.removeEventListener('abort', fail);
97
+ dog.close();
98
+ };
99
+ dog.rest();
100
+ },
101
+ async pull (controller) {
102
+ dog.kick();
103
+ let part;
104
+ try {
105
+ part = await reader.read();
106
+ } catch (error) {
107
+ if (signal.aborted) return;
108
+ end();
109
+ return controller.error(error);
110
+ }
111
+ // A trip already ended the stream; what the source said after is
112
+ // nobody's.
113
+ if (signal.aborted) return;
114
+ if (part.done) {
115
+ end();
116
+ controller.close();
117
+ } else {
118
+ dog.rest();
119
+ controller.enqueue(part.value);
120
+ }
121
+ },
122
+ cancel (reason) {
123
+ end();
124
+ return reader.cancel(reason);
125
+ }
126
+ }, {
127
+ highWaterMark: 0
128
+ });
129
+ };
130
+ /** `body`, failing with {@link Stalled} once a read waits `ms` on it, or with
131
+ * `stop`'s reason when it aborts. `ms` 0 and no `stop` leave it as it is. */ export let watchedBody = (body, ms, clock = system, stop)=>{
132
+ let dog = watchdog(ms, clock, stop);
133
+ return dog.signal ? guard(body, dog) : body;
134
+ };
135
+ /** `fetch` whose every exchange is watched: the connection and the head get
136
+ * `ms` to arrive, then each read of the body gets `ms` for its next chunk.
137
+ * Passing a deadline aborts the exchange and fails the waiting call or read
138
+ * with {@link Stalled}; the caller's own signal still stops it with its own
139
+ * reason. `ms` 0 leaves `fetch` as it is. */ export let watched = (fetch, ms, clock = system)=>!ms ? fetch : async (input, init)=>{
140
+ let stop = init?.signal ?? (input instanceof Request ? input.signal : undefined);
141
+ let dog = watchdog(ms, clock, stop);
142
+ let response;
143
+ try {
144
+ response = await fetch(input, {
145
+ ...init,
146
+ signal: dog.signal
147
+ });
148
+ } catch (error) {
149
+ dog.close();
150
+ throw dog.stalled() ? new Stalled(ms) : error;
151
+ }
152
+ if (!response.body) {
153
+ dog.close();
154
+ return response;
155
+ }
156
+ let answer = new Response(guard(response.body, dog), {
157
+ status: response.status,
158
+ statusText: response.statusText,
159
+ headers: response.headers
160
+ });
161
+ Object.defineProperty(answer, 'url', {
162
+ value: response.url
163
+ });
164
+ return answer;
165
+ };
166
+ //# sourceMappingURL=stall.js.map
package/stall.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stall.js","sources":["./stall.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;CAaC,GAED,SAAqB,MAAM,wBAA6B;AAExD;;;;0CAI0C,GAC1C,OAAO,MAAM,gBAAgB,IAAG;AAEhC;iEACiE,GACjE,OAAO,IAAI,UAAU,CAAC,MACpB,KAAK,GAAG,CAAC,GAAG,IAAI,YAAY,IAAI,iBAAiB,KAAI;AAEvD,uDAAuD,GACvD,OAAO,MAAM,gBAAgB;EAC3B,YAAY,EAAU,CAAE;IACtB,KAAK,CAAC,CAAC,gBAAgB,EAAE,KAAK,KAAK,CAAC,CAAC;IACrC,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AAeA;;;;;oEAKoE,GACpE,OAAO,IAAI,WAAW,CACpB,IACA,QAAe,MAAM,EACrB;EAEA,8EAA8E;EAC9E,0EAA0E;EAC1E,IAAI,CAAC,MAAM,CAAC,MAAM;IAChB,OAAO;MACL,QAAQ;MACR,MAAM,KAAO;MACb,MAAM,KAAO;MACb,SAAS,IAAM;MACf,OAAO,KAAO;IAChB;EACF;EACA,IAAI,UAAU,IAAI;EAClB,IAAI,UAAU;EACd,IAAI,SAAS,KAAO;EACpB,IAAI,QAAQ,IAAM,QAAQ,KAAK,CAAC,MAAM;EACtC,IAAI,OAAO;IACT;IACA,SAAS,KAAO;EAClB;EACA,IAAI,OAAO;IACT,IAAI,CAAC,MAAM,QAAQ,MAAM,CAAC,OAAO,EAAE;IACnC;IACA,SAAS,MAAM,KAAK,CAAC,IAAI;MACvB,UAAU;MACV,QAAQ,KAAK,CAAC,IAAI,QAAQ;IAC5B;EACF;EACA,IAAI,MAAM,SAAS,QAAQ,KAAK,CAAC,KAAK,MAAM;OACvC,MAAM,iBAAiB,SAAS,OAAO;IAAE,MAAM;EAAK;EACzD;EACA,OAAO;IACL,QAAQ,QAAQ,MAAM;IACtB;IACA;IACA,SAA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