@supa-media/tex-contract 0.6.0 → 0.9.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.
- package/README.md +12 -0
- package/package.json +1 -1
- package/texContract/doorBatch.cjs +27 -0
- package/texContract/doorBatch.d.cts +6 -0
- package/texContract/identity.cjs +2 -1
- package/texContract/membersSeal.cjs +202 -0
- package/texContract/membersSeal.d.cts +13 -0
- package/texContract/shownEmail.cjs +1 -1
- package/texShared/models/promptBudget.cjs +132 -11
package/README.md
CHANGED
|
@@ -26,6 +26,18 @@ Since 0.5.0:
|
|
|
26
26
|
|
|
27
27
|
- `texContract/labLedger.cjs` (with its types) names the Lab's read-only ledger door, `tex_lab_ledger`: one op, `read`, with `owner` (`{ person }` or `{ chat }`) and that owner's own `chat` (`labLedgerChatOf`). It reaches the chats the Lab page shows the developer, their own, their group chats and the ones shared with developers, which `tex_ledger` cannot, and the gateway asks the control plane on the caller's token before it opens one.
|
|
28
28
|
|
|
29
|
+
Since 0.7.0:
|
|
30
|
+
|
|
31
|
+
- `texShared/models/promptBudget.cjs` keeps a reserved share for the newest history (`HISTORY_RESERVE`) so a system prompt over the cut no longer drops every earlier turn.
|
|
32
|
+
|
|
33
|
+
Since 0.8.0:
|
|
34
|
+
|
|
35
|
+
- `texContract/membersSeal.cjs` (with its types) reads a group chat's members log from its ledger's `members` steps (`membersSnapshot`) and seals what readers outside a turn see (`roomSealOf`, `sealedAnswer`, `sealedThreadIds`). It leaves out anything said while someone in the chat now was away, unless a member released it to them, and strips the plain hashes `from.who` and `people`.
|
|
36
|
+
|
|
37
|
+
Since 0.9.0:
|
|
38
|
+
|
|
39
|
+
- `texContract/doorBatch.cjs` (with its types) names the door's batch: `BATCH_PATH` (`/tex-mcp/batch`), `BATCH_METHOD`, `MAX_BATCH_CALLS` (16) and `NOT_BATCHED`. Several calls of one turn go in one request, so the door resolves the token, opens the storage binding and opens and saves the turn once for all of them. Each entry answers `{ result }` or `{ error: { status, code } }`; a call to an outside service answers `not_batched` and goes alone, and a gateway without the path answers 404.
|
|
40
|
+
|
|
29
41
|
The contract carries facts, never Tex's wording, and Tex's titles, lines and judge questions stay in Tex.
|
|
30
42
|
|
|
31
43
|
The snapshots are written by `node scripts/tex-contract/snapshot.mjs [--tex <Tex checkout>]`, and `--check` fails when they are stale. When Tex adds a model step or changes what a person can get it to do, it runs the snapshot against its checkout and a Context pull request bumps the contract.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supa-media/tex-contract",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "The contract Context's gateway and Tex both keep: tool names, the MCP catalog snapshot, wire formats and the shared readings Tex takes with it",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Several calls to Context's door in one request (`apps/mcp/src/http/texMcpBatch.js`): how Tex's Worker sends the calls
|
|
3
|
+
* one turn makes together, so the door resolves the token, opens the storage binding and opens and saves the turn once
|
|
4
|
+
* for all of them instead of once each.
|
|
5
|
+
*
|
|
6
|
+
* `POST BATCH_PATH` on the `TexMcp` binding, the person's own grant token in `Authorization: Bearer`, body
|
|
7
|
+
* `{ jsonrpc: "2.0", id, method: BATCH_METHOD, params: { calls, _meta } }`:
|
|
8
|
+
*
|
|
9
|
+
* - `calls`: 1 to `MAX_BATCH_CALLS` entries, each `{ kind: "call", name, arguments, legacy? }` (a tool, as
|
|
10
|
+
* `/tex-mcp/call`), `{ kind: "action", name, arguments }` (a Tex action, as `/tex-mcp/action`) or
|
|
11
|
+
* `{ kind: "list", shape? }` (`tools/list`).
|
|
12
|
+
* - `_meta`: the batch's one turn meta (`turn`, `ownRun`, `mailTurn`, `search`), as a single call carries it.
|
|
13
|
+
*
|
|
14
|
+
* The answer is `{ result: { answers } }`, one per entry in order: `{ result }`, or `{ error: { status, code } }` with
|
|
15
|
+
* the status and code that entry's single request would have been refused with. `not_batched` (400) means send that
|
|
16
|
+
* call alone (a call to an outside service). A refusal of the whole request (no token, no read scope, a bad body) is
|
|
17
|
+
* an HTTP status as on the single paths; a gateway without this path answers 404, and the caller sends each call alone.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
"use strict";
|
|
21
|
+
|
|
22
|
+
const BATCH_PATH = "/tex-mcp/batch";
|
|
23
|
+
const BATCH_METHOD = "tools/batch";
|
|
24
|
+
const MAX_BATCH_CALLS = 16;
|
|
25
|
+
const NOT_BATCHED = "not_batched";
|
|
26
|
+
|
|
27
|
+
module.exports = { BATCH_PATH, BATCH_METHOD, MAX_BATCH_CALLS, NOT_BATCHED };
|
package/texContract/identity.cjs
CHANGED
|
@@ -166,7 +166,8 @@ function contextsFor(session) {
|
|
|
166
166
|
current: entry.workspaceId === session.workspaceId,
|
|
167
167
|
canWrite: reach.canWrite,
|
|
168
168
|
grantWrites: reach.grantWrites,
|
|
169
|
-
tier
|
|
169
|
+
// A group asker's own personal workspace reads at the grant's tier and opens none of its notes to the chat (P-8).
|
|
170
|
+
tier: reach.tier,
|
|
170
171
|
...(entry.askerOwn === true ? { askerOwn: true } : {}),
|
|
171
172
|
};
|
|
172
173
|
});
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHAT A GROUP CHAT'S PEOPLE MAY READ OF ITS HISTORY OUTSIDE A TURN: nothing said while someone in the chat now was
|
|
3
|
+
* away from it, unless a member who was there released it to them, and never a plain hash of anyone's number.
|
|
4
|
+
*
|
|
5
|
+
* The chat's members log is kept by Tex's texting Worker in the chat's own object, as keyed ids and times only, and
|
|
6
|
+
* mirrored into the chat's ledger as `members` steps: one snapshot `{snap, part, of, started, members: {w: spans},
|
|
7
|
+
* releases}` split into parts. A turn reads the chat under its own seal; every other reader of a group chat's ledger
|
|
8
|
+
* (its history and conversations files, the Tex page, a person's Download as folders, the Lab) reads it through
|
|
9
|
+
* this one, with no asker: a text is shown only when everyone here now was here when it was said, or was released
|
|
10
|
+
* it. Decided by the owner's security review, 2026-11-30.
|
|
11
|
+
*
|
|
12
|
+
* - A chat whose ledger holds no `members` step has no log, and reads as before.
|
|
13
|
+
* - A `members` step that can't be read as a whole snapshot, or a snapshot read that fails, seals everything but the
|
|
14
|
+
* log's own steps (fail closed).
|
|
15
|
+
* - A day summary is sealed when any sealed time falls within a day either side of its day; a thread when any of its
|
|
16
|
+
* texts, or its start, is sealed, and then every one of its entries is.
|
|
17
|
+
* - Every entry kept loses `from.who` and `people`: plain hashes of numbers, never shown outside a turn.
|
|
18
|
+
*
|
|
19
|
+
* Pure, with no imports: the gateway's object (synchronously) and its Workers (over the wire) read it alike.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const MEMBERS_STEP = "members";
|
|
23
|
+
const RELEASE_STEP = "release";
|
|
24
|
+
const MEMBER_ID = /^[0-9a-f]{32}$/;
|
|
25
|
+
const RELEASE_ID = /^r[0-9a-z]{8,32}$/;
|
|
26
|
+
const MAX_SPANS = 64;
|
|
27
|
+
const DAY_MS = 86_400_000;
|
|
28
|
+
const DAY_ID = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
29
|
+
const TIME_IN_ID = /^\D*(\d{13})/;
|
|
30
|
+
|
|
31
|
+
/** The read that finds a chat's newest snapshot: its `members` steps, newest first. */
|
|
32
|
+
const MEMBERS_SNAPSHOT_READ = Object.freeze({ kinds: ["step"], steps: [MEMBERS_STEP], before: Number.MAX_SAFE_INTEGER, limit: 200 });
|
|
33
|
+
|
|
34
|
+
const finite = (value) => typeof value === "number" && Number.isFinite(value);
|
|
35
|
+
const endOf = (value) => (value === null ? null : finite(value) ? value : undefined);
|
|
36
|
+
|
|
37
|
+
function spansOf(value) {
|
|
38
|
+
if (!Array.isArray(value) || value.length > MAX_SPANS) return null;
|
|
39
|
+
const spans = [];
|
|
40
|
+
for (const span of value) {
|
|
41
|
+
if (!Array.isArray(span) || span.length !== 2) return null;
|
|
42
|
+
const [from, to] = [endOf(span[0]), endOf(span[1])];
|
|
43
|
+
if (from === undefined || to === undefined || (from !== null && to !== null && from >= to)) return null;
|
|
44
|
+
spans.push([from, to]);
|
|
45
|
+
}
|
|
46
|
+
return spans;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function releaseOf(value) {
|
|
50
|
+
if (value === null || typeof value !== "object") return null;
|
|
51
|
+
const spans = spansOf(value.spans);
|
|
52
|
+
if (typeof value.id !== "string" || !RELEASE_ID.test(value.id) || !MEMBER_ID.test(String(value.by)) || !MEMBER_ID.test(String(value.to)) || spans === null || !finite(value.at)) return null;
|
|
53
|
+
return { to: value.to, spans, stopped: finite(value.stopped) ? value.stopped : null };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isLogStep = (entry) => entry?.kind === "step" && (entry.step === MEMBERS_STEP || entry.step === RELEASE_STEP);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The newest whole snapshot in `entries` (a chat's `members` steps, any order): `{started, members: Map<w, spans>,
|
|
60
|
+
* releases}`, `null` when there is no `members` step at all, or `{broken: true}` when there is one but no whole,
|
|
61
|
+
* readable snapshot.
|
|
62
|
+
*/
|
|
63
|
+
function membersSnapshot(entries) {
|
|
64
|
+
const parts = new Map();
|
|
65
|
+
let seen = false;
|
|
66
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
67
|
+
if (entry?.kind !== "step" || entry.step !== MEMBERS_STEP) continue;
|
|
68
|
+
seen = true;
|
|
69
|
+
const out = entry.output;
|
|
70
|
+
if (out === null || typeof out !== "object" || typeof out.snap !== "string" || !Number.isSafeInteger(out.part) || !Number.isSafeInteger(out.of) || out.of < 1 || out.part < 0 || out.part >= out.of) continue;
|
|
71
|
+
const held = parts.get(out.snap) ?? { at: 0, of: out.of, got: new Map() };
|
|
72
|
+
held.got.set(out.part, out);
|
|
73
|
+
held.at = Math.max(held.at, finite(entry.at) ? entry.at : 0);
|
|
74
|
+
parts.set(out.snap, held);
|
|
75
|
+
}
|
|
76
|
+
if (!seen) return null;
|
|
77
|
+
const whole = [...parts.values()].filter((held) => held.got.size === held.of).sort((a, b) => b.at - a.at);
|
|
78
|
+
if (whole.length === 0) return { broken: true };
|
|
79
|
+
const members = new Map();
|
|
80
|
+
const releases = [];
|
|
81
|
+
let started = null;
|
|
82
|
+
for (const out of whole[0].got.values()) {
|
|
83
|
+
if (finite(out.started)) started = out.started;
|
|
84
|
+
for (const [w, raw] of Object.entries(out.members ?? {})) {
|
|
85
|
+
const spans = spansOf(raw);
|
|
86
|
+
if (!MEMBER_ID.test(w) || spans === null) return { broken: true };
|
|
87
|
+
members.set(w, spans);
|
|
88
|
+
}
|
|
89
|
+
for (const raw of Array.isArray(out.releases) ? out.releases : []) {
|
|
90
|
+
const release = releaseOf(raw);
|
|
91
|
+
if (release !== null) releases.push(release);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return started === null || members.size === 0 ? { broken: true } : { started, members, releases };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `[from, to)` windows (null open) not covered by `spans`, from the beginning of time to the end. */
|
|
98
|
+
function gapsOf(spans) {
|
|
99
|
+
const sorted = spans.map(([from, to]) => [from ?? -Infinity, to ?? Infinity]).sort((a, b) => a[0] - b[0]);
|
|
100
|
+
const gaps = [];
|
|
101
|
+
let cursor = -Infinity;
|
|
102
|
+
for (const [from, to] of sorted) {
|
|
103
|
+
if (from > cursor) gaps.push([cursor, from]);
|
|
104
|
+
cursor = Math.max(cursor, to);
|
|
105
|
+
}
|
|
106
|
+
if (cursor < Infinity) gaps.push([cursor, Infinity]);
|
|
107
|
+
return gaps;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `windows` with `spans` taken out. */
|
|
111
|
+
function without(windows, spans) {
|
|
112
|
+
let out = windows;
|
|
113
|
+
for (const [rawFrom, rawTo] of spans) {
|
|
114
|
+
const [from, to] = [rawFrom ?? -Infinity, rawTo ?? Infinity];
|
|
115
|
+
out = out.flatMap(([a, b]) => (to <= a || from >= b ? [[a, b]] : [...(a < from ? [[a, from]] : []), ...(to < b ? [[to, b]] : [])]));
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The seal a group chat's history is read under, from its `members` steps (`MEMBERS_SNAPSHOT_READ`), or null when it
|
|
122
|
+
* keeps no log. `{sealedAt(at), sealedEntry(entry), broken}`: the windows when someone here now was away, less what a
|
|
123
|
+
* member released to them and has not stopped.
|
|
124
|
+
*/
|
|
125
|
+
function roomSealOf(snapshotEntries) {
|
|
126
|
+
const snapshot = membersSnapshot(snapshotEntries);
|
|
127
|
+
if (snapshot === null) return null;
|
|
128
|
+
if (snapshot.broken) return brokenSeal();
|
|
129
|
+
const windows = [];
|
|
130
|
+
for (const [w, spans] of snapshot.members) {
|
|
131
|
+
// Only someone here now: a member who left reads nothing here.
|
|
132
|
+
if (!spans.some(([, to]) => to === null)) continue;
|
|
133
|
+
const released = snapshot.releases.filter((release) => release.to === w && release.stopped === null).flatMap((release) => release.spans);
|
|
134
|
+
windows.push(...without(gapsOf(spans), released).filter(([from, to]) => from < to));
|
|
135
|
+
}
|
|
136
|
+
const sealedAt = (at) => !finite(at) || windows.some(([from, to]) => at >= from && at < to);
|
|
137
|
+
const overlaps = (lo, hi) => windows.some(([from, to]) => from < hi && to > lo);
|
|
138
|
+
const sealedEntry = (entry) => {
|
|
139
|
+
if (isLogStep(entry)) return false;
|
|
140
|
+
if (entry?.kind === "day") {
|
|
141
|
+
const day = typeof entry.day === "string" ? DAY_ID.exec(entry.day) : null;
|
|
142
|
+
if (day === null) return true;
|
|
143
|
+
const midnight = Date.UTC(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
|
|
144
|
+
// A day is in its chat's own time zone: a day either side of UTC covers every one.
|
|
145
|
+
return !finite(midnight) || overlaps(midnight - DAY_MS, midnight + 2 * DAY_MS);
|
|
146
|
+
}
|
|
147
|
+
if (Array.isArray(entry?.texts) && entry.texts.some((id) => sealedAt(timeOfId(id)))) return true;
|
|
148
|
+
return sealedAt(entry?.at);
|
|
149
|
+
};
|
|
150
|
+
return { broken: false, sealedAt, sealedEntry, windows: windows.length };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function brokenSeal() {
|
|
154
|
+
return { broken: true, sealedAt: () => true, sealedEntry: (entry) => !isLogStep(entry), windows: 1 };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The time a text's id carries (its first 13 digits), or NaN. */
|
|
158
|
+
function timeOfId(id) {
|
|
159
|
+
const found = TIME_IN_ID.exec(String(id ?? ""));
|
|
160
|
+
return found === null ? Number.NaN : Number(found[1]);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** An entry as a reader outside a turn may see it: no plain hash of anyone's number. */
|
|
164
|
+
function shownEntry(entry) {
|
|
165
|
+
if (entry === null || typeof entry !== "object") return entry;
|
|
166
|
+
const { people: _people, ...rest } = entry;
|
|
167
|
+
if (rest.from && typeof rest.from === "object" && "who" in rest.from) {
|
|
168
|
+
const { who: _who, ...from } = rest.from;
|
|
169
|
+
rest.from = from;
|
|
170
|
+
}
|
|
171
|
+
return rest;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `answer` (a ledger read's `{entries, ...}`) as a reader outside a turn may see it, under `seal` (`roomSealOf`, null
|
|
176
|
+
* for a chat with no log): sealed entries left out and counted in `sealed`, every kept entry without plain hashes.
|
|
177
|
+
* `threadIds`, for a chat's threads ledger: the threads sealed whole (`sealedThreadIds`).
|
|
178
|
+
*/
|
|
179
|
+
function sealedAnswer(answer, seal, { threadIds = null } = {}) {
|
|
180
|
+
const entries = Array.isArray(answer?.entries) ? answer.entries : [];
|
|
181
|
+
const kept = [];
|
|
182
|
+
let sealed = 0;
|
|
183
|
+
for (const entry of entries) {
|
|
184
|
+
const out = seal !== null && (seal.sealedEntry(entry) || (threadIds !== null && typeof entry?.thread === "string" && threadIds.has(entry.thread)));
|
|
185
|
+
if (out) sealed += 1;
|
|
186
|
+
else kept.push(shownEntry(entry));
|
|
187
|
+
}
|
|
188
|
+
return { ...(answer && typeof answer === "object" ? answer : {}), entries: kept, ...(seal !== null ? { sealed } : {}) };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Of a threads ledger's entries (all of them, any order), the thread ids sealed whole: any entry of theirs sealed. */
|
|
192
|
+
function sealedThreadIds(threadEntries, seal) {
|
|
193
|
+
const ids = new Set();
|
|
194
|
+
if (seal === null) return ids;
|
|
195
|
+
for (const entry of Array.isArray(threadEntries) ? threadEntries : []) {
|
|
196
|
+
if (entry?.kind !== "thread" || typeof entry.thread !== "string") continue;
|
|
197
|
+
if (seal.broken || seal.sealedEntry(entry)) ids.add(entry.thread);
|
|
198
|
+
}
|
|
199
|
+
return ids;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
module.exports = { MEMBERS_STEP, RELEASE_STEP, MEMBERS_SNAPSHOT_READ, membersSnapshot, roomSealOf, brokenSeal, sealedAnswer, sealedThreadIds, shownEntry, timeOfId };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const MEMBERS_STEP: "members";
|
|
2
|
+
export declare const RELEASE_STEP: "release";
|
|
3
|
+
export declare const MEMBERS_SNAPSHOT_READ: Readonly<{ kinds: string[]; steps: string[]; before: number; limit: number }>;
|
|
4
|
+
export type Span = [number | null, number | null];
|
|
5
|
+
export type MembersSnapshot = { started: number; members: Map<string, Span[]>; releases: { to: string; spans: Span[]; stopped: number | null }[] } | { broken: true } | null;
|
|
6
|
+
export declare function membersSnapshot(entries: unknown): MembersSnapshot;
|
|
7
|
+
export type RoomSeal = { broken: boolean; sealedAt(at: unknown): boolean; sealedEntry(entry: unknown): boolean; windows: number };
|
|
8
|
+
export declare function roomSealOf(snapshotEntries: unknown): RoomSeal | null;
|
|
9
|
+
export declare function brokenSeal(): RoomSeal;
|
|
10
|
+
export declare function sealedAnswer<T extends { entries?: unknown[] }>(answer: T, seal: RoomSeal | null, options?: { threadIds?: Set<string> | null }): T & { entries: unknown[]; sealed?: number };
|
|
11
|
+
export declare function sealedThreadIds(threadEntries: unknown, seal: RoomSeal | null): Set<string>;
|
|
12
|
+
export declare function shownEntry<T>(entry: T): T;
|
|
13
|
+
export declare function timeOfId(id: unknown): number;
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
|
|
20
20
|
const { folded } = require("./folded.cjs");
|
|
21
21
|
|
|
22
|
-
/** A text that ends by asking whether to send: "Send?", "Send it? 👍 or 👎?", "Send to bram@
|
|
22
|
+
/** A text that ends by asking whether to send: "Send?", "Send it? 👍 or 👎?", "Send to bram@example.com on his thread?". */
|
|
23
23
|
const SEND_ASK = /(?:^|\n)\s*(?:(?:ok(?:ay)?\s+to|should\s+I|shall\s+I)\s+)?send(?:\s+(?:it|this|that|the email|the reply))?(?:\s+(?:to|on|as)\b[^?\n]{0,160})?\s*\?[\s\u{1F44D}\u{1F44E}or?]*$/iu;
|
|
24
24
|
|
|
25
25
|
/** Whether Tex's text ends by asking whether to send what it showed. */
|
|
@@ -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,21 @@ 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
|
+
|
|
54
79
|
/** A picture or a PDF page, counted once. The base64 is not tokens. */
|
|
55
80
|
const IMAGE_TOKENS = 1_600;
|
|
56
81
|
|
|
@@ -82,12 +107,82 @@ function messageTokens(message) {
|
|
|
82
107
|
return 0;
|
|
83
108
|
}
|
|
84
109
|
|
|
85
|
-
/** Tokens in
|
|
86
|
-
function
|
|
110
|
+
/** Tokens in a gateway body's system prompt and tool list (the "bulk"). */
|
|
111
|
+
function bulkTokens(body) {
|
|
87
112
|
const system = Array.isArray(body?.system) ? body.system.reduce((sum, block) => sum + blockTokens(block), 0) : textTokens(body?.system);
|
|
88
113
|
const tools = textTokens(JSON.stringify(body?.tools ?? []));
|
|
114
|
+
return system + tools;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Tokens in one gateway body: system, tools, and messages. */
|
|
118
|
+
function estimateBodyTokens(body) {
|
|
89
119
|
const messages = (body?.messages ?? []).reduce((sum, message) => sum + messageTokens(message), 0);
|
|
90
|
-
return
|
|
120
|
+
return bulkTokens(body) + messages;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The newest messages before `end` that fit in `reserve`, walking back from `end - 1`. `from` is the
|
|
125
|
+
* first wholly reserved index (`end` if none), `used` the reserved tokens. The message at `from - 1`,
|
|
126
|
+
* if there is one, is the straddler: it crosses the reserve's edge.
|
|
127
|
+
*/
|
|
128
|
+
function reservedFrom(messages, end, reserve) {
|
|
129
|
+
let from = end;
|
|
130
|
+
let used = 0;
|
|
131
|
+
for (let i = end - 1; i >= 0; i -= 1) {
|
|
132
|
+
const tokens = messageTokens(messages[i]);
|
|
133
|
+
if (used + tokens > reserve) break;
|
|
134
|
+
used += tokens;
|
|
135
|
+
from = i;
|
|
136
|
+
}
|
|
137
|
+
return { from, used };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The longest plain text of a message (its string content, or its longest `text` block), as { text, set }, or null. */
|
|
141
|
+
function messagePlainText(message) {
|
|
142
|
+
if (typeof message?.content === "string") return { text: message.content, set: (value) => { message.content = value; } };
|
|
143
|
+
if (!Array.isArray(message?.content)) return null;
|
|
144
|
+
let index = -1;
|
|
145
|
+
message.content.forEach((block, i) => {
|
|
146
|
+
if (block?.type === "text" && typeof block.text === "string" && (index < 0 || block.text.length > message.content[index].text.length)) index = i;
|
|
147
|
+
});
|
|
148
|
+
if (index < 0) return null;
|
|
149
|
+
return { text: message.content[index].text, set: (value) => { message.content[index] = { ...message.content[index], text: value }; } };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Drop about `dropTokens` of a message's longest text from its start, keeping its end. Tool calls,
|
|
154
|
+
* tool results and pictures are never clipped. Mutates `message`. Returns false when there is no text
|
|
155
|
+
* to clip or the result would not be shorter.
|
|
156
|
+
*/
|
|
157
|
+
function clipMessageTail(message, dropTokens) {
|
|
158
|
+
const found = messagePlainText(message);
|
|
159
|
+
if (!found || found.text.length <= EARLIER.length + 1) return false;
|
|
160
|
+
const kept = found.text.slice(Math.ceil(dropTokens * TEXT_CHARS_PER_TOKEN));
|
|
161
|
+
const clipped = kept === "" ? EARLIER : `${EARLIER}\n${kept}`;
|
|
162
|
+
if (clipped.length >= found.text.length) return false;
|
|
163
|
+
found.set(clipped);
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Clip the system prompt and tool descriptions by about `dropTokens`, longest first, keeping each
|
|
169
|
+
* one's end. Messages are not touched. Returns the number of clips made.
|
|
170
|
+
*/
|
|
171
|
+
function clipBulk(body, dropTokens) {
|
|
172
|
+
let remaining = Math.ceil(dropTokens * TEXT_CHARS_PER_TOKEN);
|
|
173
|
+
let clips = 0;
|
|
174
|
+
while (remaining > 0) {
|
|
175
|
+
const best = largestText(body, 0);
|
|
176
|
+
if (!best || best.text.length <= EARLIER.length + 1) break;
|
|
177
|
+
const cutChars = Math.min(remaining, best.text.length - EARLIER.length - 1);
|
|
178
|
+
const tail = best.text.slice(cutChars);
|
|
179
|
+
const clipped = tail === "" ? EARLIER : `${EARLIER}\n${tail}`;
|
|
180
|
+
if (clipped.length >= best.text.length) break;
|
|
181
|
+
remaining -= best.text.length - clipped.length;
|
|
182
|
+
best.set(clipped);
|
|
183
|
+
clips += 1;
|
|
184
|
+
}
|
|
185
|
+
return clips;
|
|
91
186
|
}
|
|
92
187
|
|
|
93
188
|
function resultText(block) {
|
|
@@ -197,15 +292,17 @@ const messageList = (body) => (Array.isArray(body?.messages) ? body.messages : [
|
|
|
197
292
|
* Stubs `body` in the fixed order until its estimate is at or under `target`. `older`: tool results
|
|
198
293
|
* before message `keepFrom`, then history text before it. `newest`: a tool result anywhere, oldest
|
|
199
294
|
* first. `clip`: the longest text, last of all, outside messages from `clipFrom` on. `keepFrom`
|
|
200
|
-
* defaults to the body's last message.
|
|
295
|
+
* defaults to the body's last message. `historyEnd` bounds the history stubbed (default `end`); `history: false`
|
|
296
|
+
* skips history altogether. Returns how many cuts it made.
|
|
201
297
|
*/
|
|
202
|
-
function cut(body, target, { older = true, newest = true, clip = true, keepFrom, clipFrom = Infinity } = {}) {
|
|
298
|
+
function cut(body, target, { older = true, newest = true, clip = true, keepFrom, clipFrom = Infinity, historyEnd, history: withHistory = true } = {}) {
|
|
203
299
|
const messages = messageList(body);
|
|
204
300
|
const end = Math.max(0, Math.min(keepFrom ?? messages.length - 1, messages.length));
|
|
301
|
+
const historyLimit = historyEnd ?? end;
|
|
205
302
|
let shed = 0;
|
|
206
303
|
while (estimateBodyTokens(body) > target) {
|
|
207
304
|
const result = older ? oldestResult(messages, end) : null;
|
|
208
|
-
const history = older && !result ? oldestHistory(messages,
|
|
305
|
+
const history = older && withHistory && !result ? oldestHistory(messages, historyLimit) : null;
|
|
209
306
|
const any = newest && !result && !history ? oldestResult(messages, messages.length) : null;
|
|
210
307
|
const where = result ?? any;
|
|
211
308
|
if (where) messages[where.message].content[where.block] = stubResult(messages[where.message].content[where.block]);
|
|
@@ -232,9 +329,14 @@ const stepOf = (tokens) => Math.max(0, Math.ceil((tokens - HAIKU_INPUT_BUDGET) /
|
|
|
232
329
|
* made on the shortest leading run of messages already in that step (the
|
|
233
330
|
* "frame"), the newest of them standing in for the newest message; the
|
|
234
331
|
* 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.
|
|
236
|
-
*
|
|
237
|
-
*
|
|
332
|
+
* step finds the same frame and makes the same cut, byte for byte. The newest
|
|
333
|
+
* history before the turn has a reserved share (`HISTORY_RESERVE`): older tool
|
|
334
|
+
* results go first, then history older than the reserve, then the message across
|
|
335
|
+
* the reserve's edge keeps its newest part, then the system prompt and tools are
|
|
336
|
+
* clipped (keeping their end) when that alone brings the call to the step, and
|
|
337
|
+
* only then the reserved history. Only when stubbing whole older units cannot
|
|
338
|
+
* reach the step does the frame's newest tool result go, and then a clip, and
|
|
339
|
+
* only on the frame.
|
|
238
340
|
*/
|
|
239
341
|
function fitHaikuBody(body, { turnFrom } = {}) {
|
|
240
342
|
const before = estimateBodyTokens(body);
|
|
@@ -263,7 +365,26 @@ function fitHaikuBody(body, { turnFrom } = {}) {
|
|
|
263
365
|
// Whole older units, down to a step under: the cut that holds while the body grows. The frame's
|
|
264
366
|
// last message is kept as if it were the newest, whatever follows it, so a newer message cannot
|
|
265
367
|
// change this cut.
|
|
266
|
-
|
|
368
|
+
// (a) Older tool results first, as before: the model can call them again.
|
|
369
|
+
let shed = cut(frame, low, { newest: false, clip: false, keepFrom, history: false });
|
|
370
|
+
// (b) The newest history before the turn is reserved (HISTORY_RESERVE); older history goes first, oldest first.
|
|
371
|
+
const fm = frame.messages;
|
|
372
|
+
const { from: reserveFrom, used } = reservedFrom(fm, keepFrom, HISTORY_RESERVE);
|
|
373
|
+
const straddler = reserveFrom - 1;
|
|
374
|
+
shed += cut(frame, low, { newest: false, clip: false, keepFrom, historyEnd: Math.max(0, straddler) });
|
|
375
|
+
// (c) The message across the reserve's edge keeps its newest part, up to what is left of the reserve.
|
|
376
|
+
if (straddler >= 0 && estimateBodyTokens(frame) > low) {
|
|
377
|
+
const room = HISTORY_RESERVE - used;
|
|
378
|
+
const excess = messageTokens(fm[straddler]) - room;
|
|
379
|
+
const need = estimateBodyTokens(frame) - low;
|
|
380
|
+
const drop = Math.min(excess, need);
|
|
381
|
+
if (drop > 0 && clipMessageTail(fm[straddler], drop)) shed += 1;
|
|
382
|
+
}
|
|
383
|
+
// (d) The system prompt and tools yield to the reserved history, when they alone can bring the call to the step.
|
|
384
|
+
const need = estimateBodyTokens(frame) - low;
|
|
385
|
+
if (need > 0 && bulkTokens(frame) - need >= BULK_FLOOR) shed += clipBulk(frame, need);
|
|
386
|
+
// (e) Then everything as before: the reserved history, oldest first.
|
|
387
|
+
shed += cut(frame, low, { newest: false, clip: false, keepFrom });
|
|
267
388
|
const over = () => estimateBodyTokens(frame) + restTokens > HAIKU_INPUT_BUDGET;
|
|
268
389
|
// Still over, and newer messages follow the frame with its last message before the ask: that
|
|
269
390
|
// message is older history to them, down to the step.
|
|
@@ -292,4 +413,4 @@ function fitHaikuBody(body, { turnFrom } = {}) {
|
|
|
292
413
|
return { body: fitted, before, after: estimateBodyTokens(fitted), shed };
|
|
293
414
|
}
|
|
294
415
|
|
|
295
|
-
module.exports = { HAIKU_INPUT_BUDGET, TRIM_STEP, LEFT_OUT, EARLIER, estimateBodyTokens, fitHaikuBody };
|
|
416
|
+
module.exports = { HAIKU_INPUT_BUDGET, TRIM_STEP, HISTORY_RESERVE, LEFT_OUT, EARLIER, estimateBodyTokens, fitHaikuBody };
|