@alexwkleung/reika 0.8.0 → 0.10.0

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.
@@ -130,7 +130,7 @@ export function compactHistory(history, contextWindow, calibration = 1, minGen =
130
130
  // lead a request, its assistant parent may have issued sibling calls whose responses are being
131
131
  // folded, and an unmatched tool_call is an API error. Text has none of those failure modes.
132
132
  //
133
- // No extra bound needed — every candidate is capped at TASK_SPEC_PIN_CHARS, so this is a few KB at
133
+ // No extra bound needed — every candidate is capped by taskSpecIndex, so this is a few KB at
134
134
  // most. Note the elected spec stops being findable by taskSpecIndex afterwards (that looks for a
135
135
  // `tool` message), so `spec-pin none` after a compaction is expected, not a regression: the
136
136
  // content is in the recap, and the next turn's opening call becomes the new pin.
@@ -140,8 +140,13 @@ export function compactHistory(history, contextWindow, calibration = 1, minGen =
140
140
  // whatever small tool result had arrived since (a 13-line file read, then a grep of AGENTS.md)
141
141
  // under a header asserting it is the task. The first fold is also the only one whose ballot still
142
142
  // held the real spec, so its answer is the one to keep.
143
+ //
144
+ // Only a recap written since the newest user message is this turn's. One from before it holds an
145
+ // earlier task, and carrying it would present that task as this one under the header above.
143
146
  const span = history.slice(recapStart, keepFrom);
144
- const preserved = carriedSpecBlock(span) ?? electSpecBlock(history, recapStart, keepFrom);
147
+ const turnStart = Math.max(recapStart, lastUserMessageIndex(history) + 1);
148
+ const preserved = carriedSpecBlock(history.slice(turnStart, keepFrom)) ??
149
+ electSpecBlock(history, recapStart, keepFrom);
145
150
  const recap = buildRecap(span, avail, calib, note);
146
151
  history.splice(recapStart, keepFrom - recapStart, {
147
152
  role: 'compaction',
@@ -183,7 +188,7 @@ function ageLowFraction() {
183
188
  // not tokens, deliberately — it is compared against `payload.length`, and the threshold's token
184
189
  // units are a different scale.
185
190
  const SMALL_PAYLOAD_CHARS = 2000;
186
- export function batchAgePayloads(history, estimate, // calibrated request-token estimate; re-read after each mark
191
+ export function batchAgePayloads(history, estimate, // calibrated request-token estimate; read at each probe of the stop point
187
192
  contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS,
188
193
  // Whether marking reasoning can still move the estimate this sweep is chasing. False once the
189
194
  // endpoint has demanded every reasoning byte back (latches.ts): serialization then keeps
@@ -239,50 +244,105 @@ shedReasoning = true) {
239
244
  // the tail IS that message and this loop never reaches it. Promoting the tail into `content` is
240
245
  // what makes it visible to the chat template; this is what keeps that promotion from becoming a
241
246
  // standing window cost only a fold could clear.
242
- for (let i = 0; i < protect; i++) {
243
- if (estimate() <= target) {
244
- out.kept = survivingCrumbs();
245
- return out;
247
+ const marks = shedOrder(history, protect, specIdx, shedReasoning);
248
+ let applied = 0;
249
+ const applyTo = (k) => {
250
+ while (applied < k)
251
+ marks[applied++].apply();
252
+ while (applied > k)
253
+ marks[--applied].undo();
254
+ };
255
+ // #894: the marks fall in a fixed order and the estimate only decides where to stop, so the stop
256
+ // is searched for rather than walked to. Re-estimating at every index cost a full serialization
257
+ // per message — about 1,400 of them, ~5s with the UI frozen, when a resumed session shed whole.
258
+ // Search finds the first stop only while marking never grows the request, which holds unless a
259
+ // fit-to-window cap gives freed room back to another live payload.
260
+ applyTo(marks.length);
261
+ const floor = estimate();
262
+ if (floor > target) {
263
+ out.short = Math.max(0, Math.round(floor - target));
264
+ }
265
+ else {
266
+ let lo = 0;
267
+ let hi = marks.length;
268
+ while (hi - lo > 1) {
269
+ const mid = (lo + hi) >>> 1;
270
+ applyTo(mid);
271
+ if (estimate() <= target)
272
+ hi = mid;
273
+ else
274
+ lo = mid;
246
275
  }
276
+ applyTo(hi);
277
+ }
278
+ for (let i = 0; i < applied; i++) {
279
+ out.marked++;
280
+ if (marks[i].kind === 'bulk')
281
+ out.bulk++;
282
+ else if (marks[i].kind === 'crumb')
283
+ out.crumbs++;
284
+ }
285
+ out.kept = survivingCrumbs();
286
+ return out;
287
+ }
288
+ // The marks batchAgePayloads would make if it never reached its watermark, in the order it makes
289
+ // them: spent continuation tails, then reasoning and bulk payloads oldest-first, then crumbs.
290
+ function shedOrder(history, protect, specIdx, shedReasoning) {
291
+ const marks = [];
292
+ for (let i = 0; i < protect; i++) {
247
293
  const m = history[i];
248
294
  if (m.role === 'assistant' && m.continuationTail && m.content !== CONTINUATION_SHED_NOTE) {
249
- m.content = CONTINUATION_SHED_NOTE;
250
- out.marked++;
295
+ const content = m.content;
296
+ marks.push({
297
+ kind: 'tail',
298
+ apply: () => (m.content = CONTINUATION_SHED_NOTE),
299
+ undo: () => (m.content = content),
300
+ });
251
301
  }
252
302
  }
253
303
  for (const takeCrumbs of [false, true]) {
254
304
  for (let i = 0; i < protect; i++) {
255
- if (estimate() <= target) {
256
- out.kept = survivingCrumbs();
257
- return out;
258
- }
259
305
  if (i === specIdx)
260
306
  continue;
261
307
  const m = history[i];
262
- if (m.role === 'assistant' && m.reasoning && !m.reasoningAged) {
308
+ if (!takeCrumbs && m.role === 'assistant' && m.reasoning && !m.reasoningAged) {
263
309
  if (!shedReasoning)
264
310
  continue;
265
- m.reasoningAged = true;
266
- out.marked++;
311
+ const had = 'reasoningAged' in m;
312
+ const was = m.reasoningAged;
313
+ marks.push({
314
+ kind: 'reasoning',
315
+ apply: () => (m.reasoningAged = true),
316
+ undo: () => (had ? (m.reasoningAged = was) : delete m.reasoningAged),
317
+ });
267
318
  }
268
319
  else if (m.role === 'tool' && m.payload && !m.aged) {
269
- if (!takeCrumbs && m.payload.length < SMALL_PAYLOAD_CHARS)
320
+ const small = m.payload.length < SMALL_PAYLOAD_CHARS;
321
+ if (small !== takeCrumbs)
270
322
  continue;
271
- m.aged = true;
272
- delete m.rendered;
273
- out.marked++;
274
- if (takeCrumbs)
275
- out.crumbs++;
276
- else
277
- out.bulk++;
323
+ const hadAged = 'aged' in m;
324
+ const wasAged = m.aged;
325
+ const hadRendered = 'rendered' in m;
326
+ const rendered = m.rendered;
327
+ marks.push({
328
+ kind: takeCrumbs ? 'crumb' : 'bulk',
329
+ apply: () => {
330
+ m.aged = true;
331
+ delete m.rendered;
332
+ },
333
+ undo: () => {
334
+ if (hadAged)
335
+ m.aged = wasAged;
336
+ else
337
+ delete m.aged;
338
+ if (hadRendered)
339
+ m.rendered = rendered;
340
+ },
341
+ });
278
342
  }
279
343
  }
280
344
  }
281
- out.kept = survivingCrumbs();
282
- // Ran out of candidates while still over: everything sheddable outside the protected tail is
283
- // aged, and what remains is the active round plus whatever the floors hold.
284
- out.short = Math.max(0, Math.round(estimate() - target));
285
- return out;
345
+ return marks;
286
346
  }
287
347
  // Index of the assistant message that issued the trailing tool block's calls (or the final
288
348
  // assistant message when the history ends without tool results) — everything from there on is the
@@ -295,7 +355,7 @@ function protectedTailStart(history) {
295
355
  }
296
356
  // Approximate the characters a message contributes to a request (at rest: tool payloads
297
357
  // are already summarized by aging, so only the summary counts). The one message this under-prices
298
- // is the pinned task spec (#227), which still carries its payload; bounded by TASK_SPEC_PIN_CHARS,
358
+ // is the pinned task spec (#227), which still carries its payload; bounded by taskSpecIndex,
299
359
  // so the keep-budget walk stays close enough.
300
360
  function msgChars(m) {
301
361
  switch (m.role) {
@@ -349,7 +409,7 @@ function stripOmissionNote(content) {
349
409
  }
350
410
  // The preserved task definition that leads a recap (#251), and the closing line that bounds it so a
351
411
  // later fold can find the whole block and carry it forward instead of electing a second one (#275).
352
- // One block per recap, always at the front, always under TASK_SPEC_PIN_CHARS.
412
+ // One block per recap, always at the front, always within taskSpecIndex's cap.
353
413
  const SPEC_BLOCK_END = '(End of the preserved task definition; the recap of earlier work follows.)';
354
414
  // The three things the block can hold, most trustworthy first. Only the first two make the strong
355
415
  // claim, and both have earned it: a skill mandates its opening call (`/issue`, `/review` both fetch
@@ -0,0 +1,58 @@
1
+ import { estimateTokens } from '../provider/tokens.js';
2
+ import { derivedDecodeRate, engineDecodeRate } from './decoderate.js';
3
+ // Estimates from stream text rather than stream events, since a hosted API may batch tokens into
4
+ // one event. The first engine report ends the estimating for the round: the two disagree, so
5
+ // alternating between them would make the chips jump.
6
+ export class LiveRound {
7
+ promptTokens;
8
+ density;
9
+ report;
10
+ now;
11
+ output = '';
12
+ firstOutputAt;
13
+ engineReported = false;
14
+ constructor(promptTokens, density, report, now = Date.now) {
15
+ this.promptTokens = promptTokens;
16
+ this.density = density;
17
+ this.report = report;
18
+ this.now = now;
19
+ report({ promptTokens, completionTokens: 0 });
20
+ }
21
+ add(text) {
22
+ if (this.engineReported)
23
+ return;
24
+ this.output += text;
25
+ const at = this.now();
26
+ this.firstOutputAt ??= at;
27
+ const completionTokens = Math.round(estimateTokens(this.output) * this.density);
28
+ // The chip's own sample bounds apply, so a first burst can't print a wild rate.
29
+ const rate = derivedDecodeRate({ promptTokens: 0, completionTokens }, { ttftMs: 0, totalMs: at - this.firstOutputAt });
30
+ this.report({
31
+ promptTokens: this.promptTokens,
32
+ completionTokens,
33
+ ...(rate != null ? { rate } : {}),
34
+ });
35
+ }
36
+ engine(timings, prompt) {
37
+ this.engineReported = true;
38
+ // Both halves or neither: `prompt_n` alone is only what the cache could not serve.
39
+ const promptReported = prompt?.promptN != null && prompt.cacheN != null;
40
+ const rate = engineDecodeRate(timings);
41
+ this.report({
42
+ promptTokens: promptReported ? prompt.promptN + prompt.cacheN : this.promptTokens,
43
+ completionTokens: timings.predictedN,
44
+ ...(rate != null ? { rate } : {}),
45
+ ...(promptReported ? { exact: true } : {}),
46
+ });
47
+ }
48
+ }
49
+ export function withLiveUsage(total, live) {
50
+ if (!live)
51
+ return total;
52
+ return {
53
+ ...total,
54
+ promptTokens: total.promptTokens + live.promptTokens,
55
+ completionTokens: total.completionTokens + live.completionTokens,
56
+ ...(live.exact ? {} : { estimated: true }),
57
+ };
58
+ }