@supa-media/tex-contract 0.6.0 → 0.13.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.
@@ -24,6 +24,16 @@
24
24
  * so a newer message leaves it exactly as it was until the body has grown by
25
25
  * about a step more. See docs/decisions/texting-assistant/week-history.md.
26
26
  *
27
+ * The newest history before the turn has a reserved share (`HISTORY_RESERVE`).
28
+ * Older tool results go first, then history older than the reserve, oldest
29
+ * first. The message across the reserve's edge keeps its newest part. Then the
30
+ * system prompt and the tool list are clipped, keeping their end, when that
31
+ * alone brings the call to its step. Only then does the reserved history go.
32
+ * On 2026-11-30 Tex's front door's system prompt and tools (about 90,000
33
+ * estimated tokens) were over the step-under cut on their own, so every
34
+ * earlier turn was stubbed and the front door saw no history (Tex Quality,
35
+ * merge-gate finding).
36
+ *
27
37
  * Shared by Tex (`aiGateway.js`) and Context's own model client
28
38
  * (`apps/mcp/src/models/client.js`): every Haiku call either side makes is fitted the same way.
29
39
  */
@@ -51,6 +61,30 @@ const TEXT_CHARS_PER_TOKEN = 2.68;
51
61
  */
52
62
  const TRIM_STEP = 16_000;
53
63
 
64
+ /**
65
+ * The newest history before the turn, in estimated tokens, kept whole where it can be. About 43,000
66
+ * characters at `TEXT_CHARS_PER_TOKEN`: it holds Tex's front door's whole chat window on main
67
+ * (`chat:2:16000`, 16,000 characters, about 6,000 tokens) plus about 27,000 characters of its newest
68
+ * day summaries or tool rounds. It is one `TRIM_STEP`, so at a cut a step under the budget the system
69
+ * prompt and tools keep a share of about 64,000 tokens.
70
+ */
71
+ const HISTORY_RESERVE = 16_000;
72
+
73
+ /**
74
+ * The system prompt and tools never yield below this, in estimated tokens, to keep history. Below it,
75
+ * history yields as before.
76
+ */
77
+ const BULK_FLOOR = 8_000;
78
+
79
+ /**
80
+ * The most the system prompt and the tool list are kept to once a clip reaches them, in estimated tokens: two steps
81
+ * under the budget, the share `HISTORY_RESERVE` leaves them, so the person's ask and this turn's lookups still fit
82
+ * beside them. The cut to it depends on their own words only, never on the step, so every round of a turn that is
83
+ * trimmed sends the same prefix and reads it from the cache (production, 2026-11-27, app 1:1 turn 447ed548: a per-step
84
+ * clip changed the stable block mid-turn, and that round read 0 and wrote 84,495 tokens in 6.4 s).
85
+ */
86
+ const PREFIX_CAP = HAIKU_INPUT_BUDGET - 2 * TRIM_STEP;
87
+
54
88
  /** A picture or a PDF page, counted once. The base64 is not tokens. */
55
89
  const IMAGE_TOKENS = 1_600;
56
90
 
@@ -82,12 +116,82 @@ function messageTokens(message) {
82
116
  return 0;
83
117
  }
84
118
 
85
- /** Tokens in one gateway body: system, tools, and messages. */
86
- function estimateBodyTokens(body) {
119
+ /** Tokens in a gateway body's system prompt and tool list (the "bulk"). */
120
+ function bulkTokens(body) {
87
121
  const system = Array.isArray(body?.system) ? body.system.reduce((sum, block) => sum + blockTokens(block), 0) : textTokens(body?.system);
88
122
  const tools = textTokens(JSON.stringify(body?.tools ?? []));
123
+ return system + tools;
124
+ }
125
+
126
+ /** Tokens in one gateway body: system, tools, and messages. */
127
+ function estimateBodyTokens(body) {
89
128
  const messages = (body?.messages ?? []).reduce((sum, message) => sum + messageTokens(message), 0);
90
- return system + tools + messages;
129
+ return bulkTokens(body) + messages;
130
+ }
131
+
132
+ /**
133
+ * The newest messages before `end` that fit in `reserve`, walking back from `end - 1`. `from` is the
134
+ * first wholly reserved index (`end` if none), `used` the reserved tokens. The message at `from - 1`,
135
+ * if there is one, is the straddler: it crosses the reserve's edge.
136
+ */
137
+ function reservedFrom(messages, end, reserve) {
138
+ let from = end;
139
+ let used = 0;
140
+ for (let i = end - 1; i >= 0; i -= 1) {
141
+ const tokens = messageTokens(messages[i]);
142
+ if (used + tokens > reserve) break;
143
+ used += tokens;
144
+ from = i;
145
+ }
146
+ return { from, used };
147
+ }
148
+
149
+ /** The longest plain text of a message (its string content, or its longest `text` block), as { text, set }, or null. */
150
+ function messagePlainText(message) {
151
+ if (typeof message?.content === "string") return { text: message.content, set: (value) => { message.content = value; } };
152
+ if (!Array.isArray(message?.content)) return null;
153
+ let index = -1;
154
+ message.content.forEach((block, i) => {
155
+ if (block?.type === "text" && typeof block.text === "string" && (index < 0 || block.text.length > message.content[index].text.length)) index = i;
156
+ });
157
+ if (index < 0) return null;
158
+ return { text: message.content[index].text, set: (value) => { message.content[index] = { ...message.content[index], text: value }; } };
159
+ }
160
+
161
+ /**
162
+ * Drop about `dropTokens` of a message's longest text from its start, keeping its end. Tool calls,
163
+ * tool results and pictures are never clipped. Mutates `message`. Returns false when there is no text
164
+ * to clip or the result would not be shorter.
165
+ */
166
+ function clipMessageTail(message, dropTokens) {
167
+ const found = messagePlainText(message);
168
+ if (!found || found.text.length <= EARLIER.length + 1) return false;
169
+ const kept = found.text.slice(Math.ceil(dropTokens * TEXT_CHARS_PER_TOKEN));
170
+ const clipped = kept === "" ? EARLIER : `${EARLIER}\n${kept}`;
171
+ if (clipped.length >= found.text.length) return false;
172
+ found.set(clipped);
173
+ return true;
174
+ }
175
+
176
+ /**
177
+ * Clip the system prompt and tool descriptions by about `dropTokens`, longest first, keeping each
178
+ * one's end. Messages are not touched. Returns the number of clips made.
179
+ */
180
+ function clipBulk(body, dropTokens, once = null) {
181
+ let remaining = Math.ceil(dropTokens * TEXT_CHARS_PER_TOKEN);
182
+ let clips = 0;
183
+ while (remaining > 0) {
184
+ const best = largestText(body, 0, once);
185
+ if (!best || best.text.length <= EARLIER.length + 1) break;
186
+ const cutChars = Math.min(remaining, best.text.length - EARLIER.length - 1);
187
+ const tail = best.text.slice(cutChars);
188
+ const clipped = tail === "" ? EARLIER : `${EARLIER}\n${tail}`;
189
+ if (clipped.length >= best.text.length) break;
190
+ remaining -= best.text.length - clipped.length;
191
+ best.set(clipped);
192
+ clips += 1;
193
+ }
194
+ return clips;
91
195
  }
92
196
 
93
197
  function resultText(block) {
@@ -140,8 +244,8 @@ function stubHistory(messages, where) {
140
244
  * Messages from `end` on are left whole. Returns false when nothing long is
141
245
  * left, so the loop stops.
142
246
  */
143
- function clipLargest(body, end = Infinity) {
144
- const best = largestText(body, end);
247
+ function clipLargest(body, end = Infinity, once = null) {
248
+ const best = largestText(body, end, once);
145
249
  if (!best || best.text.length <= EARLIER.length + 1) return false;
146
250
  const tail = Math.max(0, Math.floor(best.text.length / 2) - EARLIER.length - 1);
147
251
  const clipped = tail === 0 ? EARLIER : `${EARLIER}\n${best.text.slice(-tail)}`;
@@ -150,21 +254,18 @@ function clipLargest(body, end = Infinity) {
150
254
  return true;
151
255
  }
152
256
 
153
- /** The longest text `clipLargest` may clip, as { text, set }, or null. */
154
- function largestText(body, end = Infinity) {
257
+ /**
258
+ * The longest text `clipLargest` may clip, as { text, set, key }, or null. `key` names a system block or a tool
259
+ * description (null for a message's text); one named in `once` was already cut to `PREFIX_CAP` in this call and is not
260
+ * offered again.
261
+ */
262
+ function largestText(body, end = Infinity, once = null) {
155
263
  let best = null;
156
- const offer = (text, set) => {
157
- if (typeof text === "string" && text.length > (best?.text.length ?? EARLIER.length + 1)) best = { text, set };
264
+ const offer = (text, set, key = null) => {
265
+ if (key !== null && once?.has(key)) return;
266
+ if (typeof text === "string" && text.length > (best?.text.length ?? EARLIER.length + 1)) best = { text, set, key };
158
267
  };
159
- if (typeof body.system === "string") offer(body.system, (value) => { body.system = value; });
160
- else if (Array.isArray(body.system)) {
161
- body.system.forEach((block, index) => {
162
- if (typeof block?.text === "string") offer(block.text, (value) => { body.system[index] = { ...block, text: value }; });
163
- });
164
- }
165
- (body.tools ?? []).forEach((tool, index) => {
166
- if (typeof tool?.description === "string") offer(tool.description, (value) => { body.tools[index] = { ...tool, description: value }; });
167
- });
268
+ eachPrefixText(body, offer);
168
269
  (body.messages ?? []).forEach((message, index) => {
169
270
  if (index >= end) return; // the turn's own messages, when the cut keeps them
170
271
  if (typeof message?.content === "string") offer(message.content, (value) => { body.messages[index] = { ...message, content: value }; });
@@ -178,6 +279,42 @@ function largestText(body, end = Infinity) {
178
279
  return best;
179
280
  }
180
281
 
282
+ /** Each system block and tool description of `body`, as offer(text, set, key). */
283
+ function eachPrefixText(body, offer) {
284
+ if (typeof body.system === "string") offer(body.system, (value) => { body.system = value; }, "sys");
285
+ else if (Array.isArray(body.system)) {
286
+ body.system.forEach((block, index) => {
287
+ if (typeof block?.text === "string") offer(block.text, (value) => { body.system[index] = { ...block, text: value }; }, `sys/${index}`);
288
+ });
289
+ }
290
+ (body.tools ?? []).forEach((tool, index) => {
291
+ if (typeof tool?.description === "string") offer(tool.description, (value) => { body.tools[index] = { ...tool, description: value }; }, `tool/${index}`);
292
+ });
293
+ }
294
+
295
+ /**
296
+ * Halve the longest system block or tool description until the two are under `PREFIX_CAP`, keeping each text's start
297
+ * (where the setup says who Tex is and its rules) and ending it on a whole line, then mark every one of them in
298
+ * `once` so nothing in this call but the last-resort clip cuts them again. Their words alone decide the cut, so every
299
+ * step makes the same one. Returns how many clips it made.
300
+ */
301
+ function capPrefix(body, once) {
302
+ let shed = 0;
303
+ while (bulkTokens(body) > PREFIX_CAP) {
304
+ let best = null;
305
+ eachPrefixText(body, (text, set) => {
306
+ if (text.length > (best?.text.length ?? 1)) best = { text, set };
307
+ });
308
+ if (!best) break;
309
+ const half = Math.floor(best.text.length / 2);
310
+ const line = best.text.lastIndexOf("\n", half);
311
+ best.set(best.text.slice(0, line > half * 0.8 ? line : half));
312
+ shed += 1;
313
+ }
314
+ eachPrefixText(body, (_text, _set, key) => once.add(key));
315
+ return shed;
316
+ }
317
+
181
318
  /** The longest tool result that still holds more than the stub, as { message, block, length }, or null. */
182
319
  function largestResult(messages) {
183
320
  let best = null;
@@ -197,15 +334,17 @@ const messageList = (body) => (Array.isArray(body?.messages) ? body.messages : [
197
334
  * Stubs `body` in the fixed order until its estimate is at or under `target`. `older`: tool results
198
335
  * before message `keepFrom`, then history text before it. `newest`: a tool result anywhere, oldest
199
336
  * first. `clip`: the longest text, last of all, outside messages from `clipFrom` on. `keepFrom`
200
- * defaults to the body's last message. Returns how many cuts it made.
337
+ * defaults to the body's last message. `historyEnd` bounds the history stubbed (default `end`); `history: false`
338
+ * skips history altogether. Returns how many cuts it made.
201
339
  */
202
- function cut(body, target, { older = true, newest = true, clip = true, keepFrom, clipFrom = Infinity } = {}) {
340
+ function cut(body, target, { older = true, newest = true, clip = true, keepFrom, clipFrom = Infinity, historyEnd, history: withHistory = true } = {}) {
203
341
  const messages = messageList(body);
204
342
  const end = Math.max(0, Math.min(keepFrom ?? messages.length - 1, messages.length));
343
+ const historyLimit = historyEnd ?? end;
205
344
  let shed = 0;
206
345
  while (estimateBodyTokens(body) > target) {
207
346
  const result = older ? oldestResult(messages, end) : null;
208
- const history = older && !result ? oldestHistory(messages, end) : null;
347
+ const history = older && withHistory && !result ? oldestHistory(messages, historyLimit) : null;
209
348
  const any = newest && !result && !history ? oldestResult(messages, messages.length) : null;
210
349
  const where = result ?? any;
211
350
  if (where) messages[where.message].content[where.block] = stubResult(messages[where.message].content[where.block]);
@@ -232,11 +371,16 @@ const stepOf = (tokens) => Math.max(0, Math.ceil((tokens - HAIKU_INPUT_BUDGET) /
232
371
  * made on the shortest leading run of messages already in that step (the
233
372
  * "frame"), the newest of them standing in for the newest message; the
234
373
  * messages after it go as they came. A newer text or tool round in the same
235
- * step finds the same frame and makes the same cut, byte for byte. Only when
236
- * stubbing whole older units cannot reach the step does the frame's newest
237
- * tool result go, and then a clip, and only on the frame.
374
+ * step finds the same frame and makes the same cut, byte for byte. The newest
375
+ * history before the turn has a reserved share (`HISTORY_RESERVE`): older tool
376
+ * results go first, then history older than the reserve, then the message across
377
+ * the reserve's edge keeps its newest part, then the system prompt and tools are
378
+ * clipped (keeping their end) when that alone brings the call to the step, and
379
+ * only then the reserved history. Only when stubbing whole older units cannot
380
+ * reach the step does the frame's newest tool result go, and then a clip, and
381
+ * only on the frame.
238
382
  */
239
- function fitHaikuBody(body, { turnFrom } = {}) {
383
+ function fitHaikuBody(body, { turnFrom, capPrefix: withCap = false } = {}) {
240
384
  const before = estimateBodyTokens(body);
241
385
  if (before <= HAIKU_INPUT_BUDGET) return { body, before, after: before, shed: 0 };
242
386
  const next = JSON.parse(JSON.stringify(body));
@@ -263,7 +407,32 @@ function fitHaikuBody(body, { turnFrom } = {}) {
263
407
  // Whole older units, down to a step under: the cut that holds while the body grows. The frame's
264
408
  // last message is kept as if it were the newest, whatever follows it, so a newer message cannot
265
409
  // change this cut.
266
- let shed = cut(frame, low, { newest: false, clip: false, keepFrom });
410
+ // (a) Older tool results first, as before: the model can call them again.
411
+ let shed = cut(frame, low, { newest: false, clip: false, keepFrom, history: false });
412
+ // (b) The newest history before the turn is reserved (HISTORY_RESERVE); older history goes first, oldest first.
413
+ const fm = frame.messages;
414
+ const { from: reserveFrom, used } = reservedFrom(fm, keepFrom, HISTORY_RESERVE);
415
+ const straddler = reserveFrom - 1;
416
+ shed += cut(frame, low, { newest: false, clip: false, keepFrom, historyEnd: Math.max(0, straddler) });
417
+ // (c) The message across the reserve's edge keeps its newest part, up to what is left of the reserve.
418
+ if (straddler >= 0 && estimateBodyTokens(frame) > low) {
419
+ const room = HISTORY_RESERVE - used;
420
+ const excess = messageTokens(fm[straddler]) - room;
421
+ const need = estimateBodyTokens(frame) - low;
422
+ const drop = Math.min(excess, need);
423
+ if (drop > 0 && clipMessageTail(fm[straddler], drop)) shed += 1;
424
+ }
425
+ // (d) The system prompt and tools yield to the reserved history, when they alone can bring the call to the step.
426
+ // With `capPrefix` (Tex's calls, opted in from Tex's own repository; Grok Bot, 2026-11-30: the contract change does
427
+ // nothing until Tex takes it, and Context's own client stays as it was), over `PREFIX_CAP` they are cut once, to the cap, from their ends, and not clipped again in this call: a clip sized
428
+ // to the step changed their bytes at every step a turn crossed, and each such round wrote the whole prompt to the
429
+ // cache again (2026-11-27). Under the cap they are not the overflow, and yield by what the step needs, as before.
430
+ const once = new Set();
431
+ const need = estimateBodyTokens(frame) - low;
432
+ if (withCap && need > 0 && bulkTokens(frame) > PREFIX_CAP) shed += capPrefix(frame, once);
433
+ else if (need > 0 && bulkTokens(frame) - need >= BULK_FLOOR) shed += clipBulk(frame, need);
434
+ // (e) Then everything as before: the reserved history, oldest first.
435
+ shed += cut(frame, low, { newest: false, clip: false, keepFrom });
267
436
  const over = () => estimateBodyTokens(frame) + restTokens > HAIKU_INPUT_BUDGET;
268
437
  // Still over, and newer messages follow the frame with its last message before the ask: that
269
438
  // message is older history to them, down to the step.
@@ -273,13 +442,18 @@ function fitHaikuBody(body, { turnFrom } = {}) {
273
442
  // turn, whichever is longer, down to the step so the same clip holds next round; a tool result goes
274
443
  // only while the call is over the budget. The turn's words are never clipped here: a lookup of a
275
444
  // few thousand characters is no reason to drop it while the system prompt is the overflow.
445
+ // The first time this clip reaches a system block or tool description over `PREFIX_CAP`, they are cut to the cap
446
+ // as in (d) instead of halved.
276
447
  if (over()) {
277
448
  while (estimateBodyTokens(frame) > low) {
278
- const clip = largestText(frame, start);
449
+ const clip = largestText(frame, start, once);
279
450
  const result = over() ? largestResult(frame.messages) : null;
280
451
  if (result && (!clip || result.length >= clip.text.length)) {
281
452
  frame.messages[result.message].content[result.block] = stubResult(frame.messages[result.message].content[result.block]);
282
- } else if (!clip || !clipLargest(frame, start)) break;
453
+ } else if (withCap && clip?.key != null && once.size === 0 && bulkTokens(frame) > PREFIX_CAP) {
454
+ shed += capPrefix(frame, once);
455
+ continue;
456
+ } else if (!clip || !clipLargest(frame, start, once)) break;
283
457
  shed += 1;
284
458
  }
285
459
  }
@@ -292,4 +466,4 @@ function fitHaikuBody(body, { turnFrom } = {}) {
292
466
  return { body: fitted, before, after: estimateBodyTokens(fitted), shed };
293
467
  }
294
468
 
295
- module.exports = { HAIKU_INPUT_BUDGET, TRIM_STEP, LEFT_OUT, EARLIER, estimateBodyTokens, fitHaikuBody };
469
+ module.exports = { HAIKU_INPUT_BUDGET, TRIM_STEP, HISTORY_RESERVE, PREFIX_CAP, LEFT_OUT, EARLIER, estimateBodyTokens, fitHaikuBody };