@loomwork/conversation 0.0.0-stage → 0.1.1

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 (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +117 -2
  4. package/dist/access.d.ts +59 -0
  5. package/dist/access.d.ts.map +1 -0
  6. package/dist/access.js +178 -0
  7. package/dist/access.js.map +1 -0
  8. package/dist/bargeIn.d.ts +62 -0
  9. package/dist/bargeIn.d.ts.map +1 -0
  10. package/dist/bargeIn.js +110 -0
  11. package/dist/bargeIn.js.map +1 -0
  12. package/dist/budget.d.ts +82 -0
  13. package/dist/budget.d.ts.map +1 -0
  14. package/dist/budget.js +134 -0
  15. package/dist/budget.js.map +1 -0
  16. package/dist/conversation.d.ts +59 -0
  17. package/dist/conversation.d.ts.map +1 -0
  18. package/dist/conversation.js +786 -0
  19. package/dist/conversation.js.map +1 -0
  20. package/dist/conversations.d.ts +149 -0
  21. package/dist/conversations.d.ts.map +1 -0
  22. package/dist/conversations.js +498 -0
  23. package/dist/conversations.js.map +1 -0
  24. package/dist/feed.d.ts +32 -0
  25. package/dist/feed.d.ts.map +1 -0
  26. package/dist/feed.js +83 -0
  27. package/dist/feed.js.map +1 -0
  28. package/dist/hub.d.ts +119 -0
  29. package/dist/hub.d.ts.map +1 -0
  30. package/dist/hub.js +257 -0
  31. package/dist/hub.js.map +1 -0
  32. package/dist/ids.d.ts +9 -0
  33. package/dist/ids.d.ts.map +1 -0
  34. package/dist/ids.js +29 -0
  35. package/dist/ids.js.map +1 -0
  36. package/dist/index.d.ts +27 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +65 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/providerError.d.ts +10 -0
  41. package/dist/providerError.d.ts.map +1 -0
  42. package/dist/providerError.js +16 -0
  43. package/dist/providerError.js.map +1 -0
  44. package/dist/reader.d.ts +53 -0
  45. package/dist/reader.d.ts.map +1 -0
  46. package/dist/reader.js +217 -0
  47. package/dist/reader.js.map +1 -0
  48. package/dist/settled.d.ts +49 -0
  49. package/dist/settled.d.ts.map +1 -0
  50. package/dist/settled.js +51 -0
  51. package/dist/settled.js.map +1 -0
  52. package/dist/signEnvelope.d.ts +51 -0
  53. package/dist/signEnvelope.d.ts.map +1 -0
  54. package/dist/signEnvelope.js +55 -0
  55. package/dist/signEnvelope.js.map +1 -0
  56. package/dist/summarizerText.d.ts +2 -0
  57. package/dist/summarizerText.d.ts.map +1 -0
  58. package/dist/summarizerText.js +9 -0
  59. package/dist/summarizerText.js.map +1 -0
  60. package/dist/turn.d.ts +67 -0
  61. package/dist/turn.d.ts.map +1 -0
  62. package/dist/turn.js +213 -0
  63. package/dist/turn.js.map +1 -0
  64. package/dist/types.d.ts +267 -0
  65. package/dist/types.d.ts.map +1 -0
  66. package/dist/types.js +18 -0
  67. package/dist/types.js.map +1 -0
  68. package/package.json +61 -3
  69. package/src/access.ts +221 -0
  70. package/src/bargeIn.ts +172 -0
  71. package/src/budget.ts +170 -0
  72. package/src/conversation.ts +961 -0
  73. package/src/conversations.ts +690 -0
  74. package/src/feed.ts +112 -0
  75. package/src/hub.ts +336 -0
  76. package/src/ids.ts +25 -0
  77. package/src/index.ts +75 -0
  78. package/src/reader.ts +274 -0
  79. package/src/settled.ts +80 -0
  80. package/src/signEnvelope.ts +76 -0
  81. package/src/summarizerText.ts +3 -0
  82. package/src/turn.ts +344 -0
  83. package/src/types.ts +271 -0
package/src/access.ts ADDED
@@ -0,0 +1,221 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { type PrincipalChain, identityKeyOf } from "@loomwork/effect-runtime";
3
+ import {
4
+ DuplicateSequenceError,
5
+ type EventStore,
6
+ headOf,
7
+ readRangeOf,
8
+ } from "@loomwork/event-runtime";
9
+
10
+ // ── Who a conversation belongs to, and who else may take part (ADR 0122 D8, D10) ────────────────────
11
+ //
12
+ // IDENTITY. The same bounded subset ADR 0111 records and `runtime.send` stamps on a message:
13
+ // `{ tenant?, actor, onBehalfOf? }`. Two principals are the same identity iff ALL THREE fields are
14
+ // equal (an absent field equals only an absent field). A delegated principal acting `onBehalfOf` someone
15
+ // is therefore a DIFFERENT identity from that someone: delegation narrows authority, it never widens
16
+ // who counts as the owner. A credential (a delegation token) is not part of identity.
17
+
18
+ export interface Identity {
19
+ tenant?: string;
20
+ actor: string;
21
+ onBehalfOf?: string;
22
+ }
23
+
24
+ /** The identity of a principal, or `undefined` when it names no actor (it cannot own or join anything). */
25
+ export function identityOf(principal: PrincipalChain | undefined): Identity | undefined {
26
+ if (principal === undefined) return undefined;
27
+ const actor = principal.actor;
28
+ if (typeof actor !== "string" || actor.trim() === "") return undefined;
29
+ return {
30
+ actor,
31
+ ...(typeof principal.tenant === "string" && { tenant: principal.tenant }),
32
+ ...(typeof principal.onBehalfOf === "string" && { onBehalfOf: principal.onBehalfOf }),
33
+ };
34
+ }
35
+
36
+ /** A stable key for an identity. */
37
+ export function identityKey(i: Identity): string {
38
+ return identityKeyOf(i);
39
+ }
40
+
41
+ export function sameIdentity(a: Identity | undefined, b: Identity | undefined): boolean {
42
+ return a !== undefined && b !== undefined && identityKey(a) === identityKey(b);
43
+ }
44
+
45
+ /** Validate an untrusted value as an identity (log content, a request body). */
46
+ export function parseIdentity(v: unknown): Identity | undefined {
47
+ if (typeof v !== "object" || v === null) return undefined;
48
+ const o = v as Record<string, unknown>;
49
+ if (typeof o.actor !== "string" || o.actor.trim() === "" || o.actor.length > 256)
50
+ return undefined;
51
+ for (const k of ["tenant", "onBehalfOf"] as const) {
52
+ if (o[k] !== undefined && (typeof o[k] !== "string" || (o[k] as string).length > 256)) {
53
+ return undefined;
54
+ }
55
+ }
56
+ return {
57
+ actor: o.actor,
58
+ ...(typeof o.tenant === "string" && { tenant: o.tenant }),
59
+ ...(typeof o.onBehalfOf === "string" && { onBehalfOf: o.onBehalfOf }),
60
+ };
61
+ }
62
+
63
+ /**
64
+ * The key the kernel dedupes a message on (`MESSAGE_CONSUMED.messageId`, ADR 0110 D6): SHA-256 of
65
+ * `[tenant, actor, onBehalfOf, messageId]` for the SENDER the runtime recorded. The client stamps it into
66
+ * the payload so a barge-in watcher can tell a sender's own retry from someone else replaying the id.
67
+ */
68
+ export function senderKey(
69
+ sender: { tenant?: string; actor?: string; onBehalfOf?: string },
70
+ messageId: string
71
+ ): string {
72
+ return createHash("sha256")
73
+ .update(
74
+ JSON.stringify([sender.tenant ?? "", sender.actor ?? "", sender.onBehalfOf ?? "", messageId])
75
+ )
76
+ .digest("hex");
77
+ }
78
+
79
+ // ── Host-signed envelopes (shared mode) ───────────────────────────────────────────────────────────
80
+ //
81
+ // In shared mode the asker is named INSIDE the message, because the sender the runtime records is the
82
+ // host. The inbox is writable by anything the runtime's policy admits, so the body accepts an asker only
83
+ // from an envelope signed with the host's key: a colleague who can raw-`send` cannot speak as someone else.
84
+
85
+ function canonical(v: unknown): string {
86
+ return JSON.stringify(v, (_k, x) =>
87
+ x !== null && typeof x === "object" && !Array.isArray(x)
88
+ ? Object.fromEntries(Object.entries(x as object).sort(([a], [b]) => (a < b ? -1 : 1)))
89
+ : x
90
+ );
91
+ }
92
+
93
+ /** The domain every inbox envelope is signed under, so a MAC made for another purpose with the same key is not one. */
94
+ export const ENVELOPE_DOMAIN = "loom/conversation/envelope/v1";
95
+
96
+ /**
97
+ * HMAC-SHA-256 of the canonical body under `key`, separated by `domain` (empty = none: the turn-id derivation
98
+ * keeps its original input so ids of in-flight turn executions do not move).
99
+ */
100
+ export function sign(key: string, body: Record<string, unknown>, domain = ""): string {
101
+ const input = domain === "" ? canonical(body) : `${domain}\u0000${canonical(body)}`;
102
+ return createHmac("sha256", key).update(input).digest("hex");
103
+ }
104
+
105
+ /** Verify against `key` and, for a rotation window, any of `previous`. */
106
+ export function verifySignature(
107
+ key: string | readonly string[],
108
+ body: Record<string, unknown>,
109
+ sig: unknown,
110
+ domain = ""
111
+ ): boolean {
112
+ if (typeof sig !== "string" || sig.length !== 64) return false;
113
+ const got = Buffer.from(sig, "hex");
114
+ let ok = false;
115
+ for (const k of typeof key === "string" ? [key] : key) {
116
+ const want = Buffer.from(sign(k, body, domain), "hex");
117
+ // no early exit: the time taken does not say which key matched
118
+ if (got.length === want.length && timingSafeEqual(got, want)) ok = true;
119
+ }
120
+ return ok;
121
+ }
122
+
123
+ // ── Participants ─────────────────────────────────────────────────────────────────────────────────────
124
+
125
+ export interface ParticipantChange {
126
+ op: "add" | "remove";
127
+ identity: Identity;
128
+ by: Identity;
129
+ }
130
+
131
+ /**
132
+ * The participant set of shared conversations. Reads are consulted on EVERY request (a removal takes
133
+ * effect on the next one) and by the conversation body, inside a recorded decision, when it dequeues a turn.
134
+ */
135
+ export interface ParticipantDirectory {
136
+ list(conversationId: string): Promise<Identity[]>;
137
+ apply(conversationId: string, change: ParticipantChange): Promise<void>;
138
+ }
139
+
140
+ export const MAX_PARTICIPANTS = 100;
141
+ const MAX_CHANGES = 2000;
142
+ const MEMBERS_WORKFLOW = "conversation-participants";
143
+
144
+ export class ParticipantLimitError extends Error {
145
+ readonly code = "PARTICIPANT_LIMIT";
146
+ constructor() {
147
+ super(`a conversation holds at most ${MAX_PARTICIPANTS} participants`);
148
+ this.name = "ParticipantLimitError";
149
+ }
150
+ }
151
+
152
+ function fold(
153
+ events: readonly { eventType?: string; workflowId?: string; payload: unknown }[]
154
+ ): Identity[] {
155
+ const set = new Map<string, Identity>();
156
+ for (const e of events) {
157
+ // Anyone who can start an execution under this stream's id can write ITS first event; only our own
158
+ // change events count, whoever else has written there.
159
+ if (e.eventType !== "PARTICIPANT_CHANGED" || e.workflowId !== MEMBERS_WORKFLOW) continue;
160
+ const p = e.payload as { op?: unknown; identity?: unknown } | null;
161
+ const identity = parseIdentity(p?.identity);
162
+ if (identity === undefined) continue;
163
+ if (p?.op === "add") set.set(identityKey(identity), identity);
164
+ else if (p?.op === "remove") set.delete(identityKey(identity));
165
+ }
166
+ return [...set.values()];
167
+ }
168
+
169
+ /**
170
+ * The standard directory: an append-only side stream `conversation-participants:<id>` on the event store,
171
+ * one `PARTICIPANT_CHANGED` event per change, so membership is a durable, ordered, auditable log (who added
172
+ * whom, when) shared by every node that reads the same store. It is NOT the conversation's own log (a
173
+ * sender must never append to the owner's log; ADR 0110 D1) and not a kernel stream.
174
+ */
175
+ export function logParticipants(
176
+ store: EventStore,
177
+ now: () => number = Date.now
178
+ ): ParticipantDirectory {
179
+ const streamOf = (id: string) => `conversation-participants:${id}`;
180
+ return {
181
+ async list(conversationId) {
182
+ const stream = streamOf(conversationId);
183
+ const tip = await headOf(store, stream);
184
+ if (tip === null) return [];
185
+ return fold(await readRangeOf(store, stream, 0, Math.min(tip, MAX_CHANGES)));
186
+ },
187
+ async apply(conversationId, change) {
188
+ const stream = streamOf(conversationId);
189
+ for (let attempt = 0; attempt < 32; attempt++) {
190
+ const tip = await headOf(store, stream);
191
+ const next = (tip ?? -1) + 1;
192
+ if (next >= MAX_CHANGES) throw new Error("participant change log is full; compact it");
193
+ const events = tip === null ? [] : await readRangeOf(store, stream, 0, tip);
194
+ const current = fold(events);
195
+ if (
196
+ change.op === "add" &&
197
+ current.length >= MAX_PARTICIPANTS &&
198
+ !current.some((i) => sameIdentity(i, change.identity))
199
+ ) {
200
+ throw new ParticipantLimitError();
201
+ }
202
+ try {
203
+ await store.append({
204
+ id: `${stream}#${next}`,
205
+ workflowId: MEMBERS_WORKFLOW,
206
+ executionId: stream,
207
+ eventType: "PARTICIPANT_CHANGED",
208
+ sequence: next,
209
+ timestamp: now(),
210
+ payload: change,
211
+ });
212
+ return;
213
+ } catch (err) {
214
+ if (err instanceof DuplicateSequenceError) continue; // another writer took the slot: re-read
215
+ throw err;
216
+ }
217
+ }
218
+ throw new Error("could not record the participant change (contended)");
219
+ },
220
+ };
221
+ }
package/src/bargeIn.ts ADDED
@@ -0,0 +1,172 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ import { type EventStore, headOf, readRangeOf } from "@loomwork/event-runtime";
3
+ import { createInboxSource, inboxStreamId, inboxTopicStreamId } from "@loomwork/workflow-runtime";
4
+ import { senderKey } from "./access";
5
+ import { CONVERSATION_TOPIC } from "./types";
6
+
7
+ // ── What notices a message while a turn is running (ADR 0122 D2) ──────────────────────────────────
8
+ //
9
+ // A registered `ctx.receive` is NOT woken while the owner has a step in flight: the kernel delivers an
10
+ // inbox message at the owner's quiescence commit (ADR 0110 D5), and a model call IS an in-flight step.
11
+ // So the flow cannot learn of a barge-in from the inbox primitives it already has. The signal has to
12
+ // come from OUTSIDE the flow body: the process running the turn subscribes to the conversation's
13
+ // inbox stream (a store-level subscription, the same seam `liveQuery` uses) and fires the turn's
14
+ // AbortSignal when a message lands.
15
+ //
16
+ // That signal is not data and the flow never branches on it directly. `agentLoop$` reads it only
17
+ // through RECORDED checkpoints (ADR 0121 D3), so what the interruption did is in the log and a replay
18
+ // reproduces it without any subscription at all. The consumption of the interrupting message is the
19
+ // ordinary `ctx.receive` that follows the interrupted turn.
20
+ //
21
+ // A RETRY is not a barge-in. The kernel delivers a duplicate `messageId` once, but a subscription
22
+ // sees every append, so the signal must not fire for a message the conversation already took: the
23
+ // client stamps each turn with its idempotency key (`id`), the flow remembers the keys of recent
24
+ // turns (including the one running), and the source ignores a message whose key is known.
25
+
26
+ export interface BargeInHandlers {
27
+ /** Fire the running turn's abort signal. */
28
+ onMessage: () => void;
29
+ /** Whether a client idempotency key belongs to a turn this conversation already took (or is running). */
30
+ isKnown: (id: string) => boolean;
31
+ /**
32
+ * Whether a stored inbox message may interrupt the running turn at all. Default: any message on the
33
+ * conversation topic. Shared mode passes a check that the envelope is signed AND from the SAME asker
34
+ * as the running turn: a participant interrupts only their own turn.
35
+ */
36
+ accept?: (stored: StoredInboxMessage) => boolean;
37
+ /**
38
+ * The idempotency key a stored message claims. Default (owner mode): the payload `id`, honoured only
39
+ * when it equals the kernel's dedupe identity of THIS message (`senderKey(sender, messageId)`), so a
40
+ * different sender replaying someone's id is a new message, not a retry.
41
+ */
42
+ idOf?: (stored: StoredInboxMessage) => string | undefined;
43
+ }
44
+
45
+ /** What the inbox stream holds per message (the shape `runtime.send` appends). */
46
+ export interface StoredInboxMessage {
47
+ topic?: unknown;
48
+ messageId?: unknown;
49
+ payload?: unknown;
50
+ sender?: { tenant?: string; actor?: string; onBehalfOf?: string };
51
+ }
52
+
53
+ /**
54
+ * Tell `handlers.onMessage` when a NEW message lands for `conversationId`, and return the way to stop
55
+ * listening. `ownerId` is the execution (generation) running the turn. Supplied to
56
+ * `ConversationConfig.bargeIn`; the standard source is {@link inboxBargeIn}. Without one a
57
+ * conversation QUEUES: a message sent mid-turn waits for the turn to finish.
58
+ */
59
+ export type BargeInSource = (
60
+ conversationId: string,
61
+ ownerId: string,
62
+ handlers: BargeInHandlers
63
+ ) => Promise<() => void> | (() => void);
64
+
65
+ /** How far back in the owner's log the consumed cursor is looked for, at most. */
66
+ const MAX_LOOKBACK = 8192;
67
+ const TAIL_BLOCK = 128;
68
+ /** How many waiting messages a peek inspects. */
69
+ const PEEK_LIMIT = 16;
70
+
71
+ const ownerModeId = (m: StoredInboxMessage): string | undefined => {
72
+ const id = (m.payload as { id?: unknown } | null | undefined)?.id;
73
+ if (typeof id !== "string" || typeof m.messageId !== "string") return undefined;
74
+ return id === senderKey(m.sender ?? {}, m.messageId) ? id : undefined;
75
+ };
76
+
77
+ /** Whether `m` is a NEW message by the handlers' rules (on the topic, accepted, not a known retry). */
78
+ export function isNew(
79
+ m: StoredInboxMessage,
80
+ h: Pick<BargeInHandlers, "isKnown" | "accept" | "idOf">
81
+ ): boolean {
82
+ if (m.topic !== CONVERSATION_TOPIC) return false;
83
+ if (h.accept !== undefined && !h.accept(m)) return false;
84
+ const id = (h.idOf ?? ownerModeId)(m);
85
+ return id === undefined || !h.isKnown(id);
86
+ }
87
+
88
+ /**
89
+ * Whether the inbox holds a message the owner has not consumed and the conversation does not already
90
+ * know: the stream past the newest `MESSAGE_CONSUMED` cursor in the owner's log. The owner's log is read
91
+ * BACKWARDS in blocks until a consumption is found (bounded by {@link MAX_LOOKBACK} events), so a turn
92
+ * with any amount of tool traffic, or a recovery re-running one, is still compared against the right
93
+ * cursor. Conservative: when no consumption is found (a fresh generation whose first message rode the
94
+ * carry) it says `false` and the message is simply handled after the turn.
95
+ */
96
+ export async function pendingInbox(
97
+ store: EventStore,
98
+ conversationId: string,
99
+ ownerId: string,
100
+ h: Pick<BargeInHandlers, "isKnown" | "accept" | "idOf"> = { isKnown: () => false }
101
+ ): Promise<boolean> {
102
+ const waiting = await pendingMessages(store, conversationId, ownerId, PEEK_LIMIT);
103
+ return waiting?.some((m) => isNew(m, h)) === true;
104
+ }
105
+
106
+ /**
107
+ * The messages waiting in the inbox past the owner's consumed cursor (at most `limit`), or `undefined`
108
+ * when the cursor cannot be established. The owner's log is read BACKWARDS in blocks until a consumption
109
+ * is found, bounded by {@link MAX_LOOKBACK}.
110
+ */
111
+ export async function pendingMessages(
112
+ store: EventStore,
113
+ conversationId: string,
114
+ ownerId: string,
115
+ limit: number
116
+ ): Promise<StoredInboxMessage[] | undefined> {
117
+ // The conversation topic's messages live in the legacy stream or, once the fleet writes per-topic
118
+ // streams (ADR 0110 D10b), in the topic's own; the cursor is one number space across both.
119
+ const legacyHead = await headOf(store, inboxStreamId(conversationId));
120
+ const topicHead = await headOf(store, inboxTopicStreamId(conversationId, CONVERSATION_TOPIC));
121
+ if (legacyHead === null && topicHead === null) return [];
122
+ const newest = Math.max(legacyHead ?? -1, topicHead ?? -1);
123
+ const tip = await headOf(store, ownerId);
124
+ if (tip === null) return undefined;
125
+ let consumed = -1;
126
+ let upper = tip;
127
+ while (upper >= 0 && tip - upper < MAX_LOOKBACK && consumed < 0) {
128
+ const lo = Math.max(0, upper - TAIL_BLOCK + 1);
129
+ const block = await readRangeOf(store, ownerId, lo, upper);
130
+ for (const ev of block as EventEnvelope[]) {
131
+ if (ev.eventType !== "MESSAGE_CONSUMED") continue;
132
+ const seq = (ev.payload as { inboxSeq?: unknown } | null)?.inboxSeq;
133
+ if (typeof seq === "number" && seq > consumed) consumed = seq;
134
+ }
135
+ upper = lo - 1;
136
+ }
137
+ if (consumed < 0) return undefined;
138
+ if (newest <= consumed) return [];
139
+ return createInboxSource(store)(conversationId, CONVERSATION_TOPIC, consumed, limit);
140
+ }
141
+
142
+ /**
143
+ * The standard {@link BargeInSource}: subscribe to the conversation's inbox stream on `eventStore`
144
+ * (an in-process notification for the in-memory store, LISTEN/NOTIFY for Postgres), and, once
145
+ * subscribed, look for a message that is ALREADY waiting (one sent between the previous turn's
146
+ * consumption and now), so a message cannot be missed by arriving a moment early.
147
+ */
148
+ export function inboxBargeIn(eventStore: EventStore): BargeInSource {
149
+ return async (conversationId, ownerId, handlers) => {
150
+ const onEvent = (ev: EventEnvelope): void => {
151
+ if (isNew(ev.payload as StoredInboxMessage, handlers)) handlers.onMessage();
152
+ };
153
+ // Both layouts (ADR 0110 D10b): a message lands in the legacy stream or in the topic's own.
154
+ const unsubLegacy = await eventStore.subscribe(inboxStreamId(conversationId), onEvent);
155
+ let unsubTopic: (() => void) | undefined;
156
+ const unsubscribe = (): void => {
157
+ unsubLegacy();
158
+ unsubTopic?.();
159
+ };
160
+ try {
161
+ unsubTopic = await eventStore.subscribe(
162
+ inboxTopicStreamId(conversationId, CONVERSATION_TOPIC),
163
+ onEvent
164
+ );
165
+ if (await pendingInbox(eventStore, conversationId, ownerId, handlers)) handlers.onMessage();
166
+ } catch (err) {
167
+ unsubscribe();
168
+ throw err;
169
+ }
170
+ return unsubscribe;
171
+ };
172
+ }
package/src/budget.ts ADDED
@@ -0,0 +1,170 @@
1
+ // ── Token-aware context budgeting (ADR 0122 D3) ───────────────────────────────────────────────
2
+ //
3
+ // `agentLoop$`'s `compaction` triggers on message COUNT and UTF-8 BYTES, never on tokens, and it
4
+ // folds the transcript of ONE run. A dialogue outlives a run: the question here is "which of the
5
+ // turns I hold fit the model's window beside the system prompt and the new message", asked once per
6
+ // user turn. This module answers it as a PURE function over counted tokens, so the only
7
+ // non-deterministic ingredient (a provider's exact counter) is isolated behind a seam the caller
8
+ // records (`conversation$` journals the verdict as a decision; a replay never calls the counter).
9
+
10
+ /** Counts the tokens of a text. Sync or async; a provider may supply its exact tokenizer. */
11
+ export interface TokenCounter {
12
+ count(text: string): number | Promise<number>;
13
+ /** Tokens a single message costs beyond its text (role markers, separators). Default 4. */
14
+ readonly perMessage?: number;
15
+ }
16
+
17
+ /**
18
+ * The default counter: no tokenizer, no dependency, deterministic and CONSERVATIVE. ASCII costs a
19
+ * quarter token per character (the usual English rule of thumb, rounded UP), every other code point
20
+ * costs a whole token (CJK, emoji and symbols tokenize at roughly one token or more per character,
21
+ * so a flat chars/4 would under-count them by 4x and overflow the window). Over-counting only costs
22
+ * some history; under-counting costs the request.
23
+ */
24
+ export function heuristicTokenCounter(options: { asciiCharsPerToken?: number } = {}): TokenCounter {
25
+ const per = options.asciiCharsPerToken ?? 4;
26
+ if (!(per >= 1) || !Number.isFinite(per)) {
27
+ throw new RangeError("heuristicTokenCounter: asciiCharsPerToken must be a number >= 1");
28
+ }
29
+ return {
30
+ perMessage: 4,
31
+ count(text: string): number {
32
+ let ascii = 0;
33
+ let wide = 0;
34
+ for (const ch of text) {
35
+ if ((ch.codePointAt(0) as number) < 0x80) ascii++;
36
+ else wide++;
37
+ }
38
+ return Math.ceil(ascii / per) + wide;
39
+ },
40
+ };
41
+ }
42
+
43
+ export class ContextBudgetError extends Error {
44
+ readonly code = "CONTEXT_BUDGET";
45
+ constructor(message: string) {
46
+ super(message);
47
+ this.name = "ContextBudgetError";
48
+ }
49
+ }
50
+
51
+ /** One turn of the history the budgeter weighs: its token cost is counted once and cached. */
52
+ export interface BudgetTurn {
53
+ /** The tokens of the turn's messages (user + assistant), if already counted. */
54
+ tokens?: number;
55
+ user: string;
56
+ assistant?: string;
57
+ }
58
+
59
+ export interface BudgetRequest {
60
+ /** The model's context window, in tokens. */
61
+ contextWindow: number;
62
+ /** Tokens held back for the reply. Default `min(4096, window / 4)`. */
63
+ reserveOutputTokens?: number;
64
+ /** The system prompt (counted once). */
65
+ system?: string;
66
+ /** The rolling summary of evicted turns (counted once), if any. */
67
+ summary?: string;
68
+ /** The new user message. */
69
+ prompt: string;
70
+ /** Turns oldest first. */
71
+ turns: readonly BudgetTurn[];
72
+ counter?: TokenCounter;
73
+ }
74
+
75
+ export type BudgetVerdict =
76
+ | {
77
+ ok: true;
78
+ /** How many of the NEWEST turns fit (the rest are to be dropped / summarized). */
79
+ keep: number;
80
+ /** Tokens counted for each turn that had none: `[index, tokens]`. */
81
+ counted: [number, number][];
82
+ /** The total the request will cost (fixed parts + kept turns), reply reserve excluded. */
83
+ tokens: number;
84
+ /** The rolling summary alone made the request not fit, so it was left out of this fit (and is to be dropped). */
85
+ dropSummary?: true;
86
+ }
87
+ | { ok: false; reason: "prompt-too-large"; tokens: number; available: number };
88
+
89
+ /**
90
+ * Fit `system + summary + turns + prompt` into `contextWindow - reserveOutputTokens`. Keeps the
91
+ * longest NEWEST suffix of whole turns that fits (a turn is never split); the prompt is never
92
+ * dropped, and when system + summary + prompt alone exceed the window the verdict is
93
+ * `prompt-too-large` (the caller refuses the turn rather than send a request the provider will
94
+ * reject). Pure of the counter's answers: the same counts give the same verdict.
95
+ *
96
+ * Cost: one `count` per turn that has no cached `tokens`, then a single backwards pass; the caller
97
+ * caches `counted` on its turns, so a steady-state conversation counts only the NEW turn per call.
98
+ */
99
+ export async function fitToWindow(req: BudgetRequest): Promise<BudgetVerdict> {
100
+ const counter = req.counter ?? heuristicTokenCounter();
101
+ const overhead = counter.perMessage ?? 4;
102
+ if (!Number.isFinite(req.contextWindow) || req.contextWindow <= 0) {
103
+ throw new RangeError("fitToWindow: contextWindow must be a positive number");
104
+ }
105
+ const reserve = req.reserveOutputTokens ?? Math.min(4096, Math.floor(req.contextWindow / 4));
106
+ const available = req.contextWindow - reserve;
107
+ let fixed = overhead; // the prompt message
108
+ fixed += await counter.count(req.prompt);
109
+ if (req.system !== undefined && req.system !== "") fixed += await counter.count(req.system);
110
+ if (req.summary !== undefined && req.summary !== "") {
111
+ fixed += overhead + (await counter.count(req.summary));
112
+ }
113
+ if (fixed > available) return { ok: false, reason: "prompt-too-large", tokens: fixed, available };
114
+ const counted: [number, number][] = [];
115
+ const weights: number[] = new Array<number>(req.turns.length);
116
+ // Walk newest -> oldest and stop at the first turn that does not fit: older turns are never
117
+ // counted, so a long window costs O(kept), not O(held).
118
+ let used = fixed;
119
+ let keep = 0;
120
+ for (let i = req.turns.length - 1; i >= 0; i--) {
121
+ const turn = req.turns[i] as BudgetTurn;
122
+ let w = turn.tokens;
123
+ if (w === undefined) {
124
+ w = overhead + (await counter.count(turn.user));
125
+ if (turn.assistant !== undefined && turn.assistant !== "") {
126
+ w += overhead + (await counter.count(turn.assistant));
127
+ }
128
+ counted.push([i, w]);
129
+ }
130
+ weights[i] = w;
131
+ if (used + w > available) break;
132
+ used += w;
133
+ keep++;
134
+ }
135
+ return { ok: true, keep, counted, tokens: used };
136
+ }
137
+
138
+ /**
139
+ * `fitToWindow`, but a rolling summary that is itself too big to leave room for the prompt is DROPPED
140
+ * rather than wedging the conversation: with no summary the same request may fit. The verdict says so
141
+ * (`dropSummary`) and the caller discards the summary. Still `prompt-too-large` when it cannot fit even so.
142
+ */
143
+ export async function fitWithSummaryFallback(req: BudgetRequest): Promise<BudgetVerdict> {
144
+ const v = await fitToWindow(req);
145
+ if (v.ok || req.summary === undefined || req.summary === "") return v;
146
+ const { summary: _dropped, ...rest } = req;
147
+ const again = await fitToWindow(rest);
148
+ return again.ok ? { ...again, dropSummary: true } : again;
149
+ }
150
+
151
+ /**
152
+ * The longest prefix of `text` that costs at most `maxTokens`, with an ellipsis when cut: a binary
153
+ * search over prefix lengths, O(log n) counts. Deterministic for a deterministic counter, and the
154
+ * caller records its answer anyway.
155
+ */
156
+ export async function truncateToTokens(
157
+ text: string,
158
+ maxTokens: number,
159
+ counter: TokenCounter
160
+ ): Promise<string> {
161
+ if ((await counter.count(text)) <= maxTokens) return text;
162
+ let lo = 0;
163
+ let hi = text.length;
164
+ while (lo < hi) {
165
+ const mid = Math.ceil((lo + hi) / 2);
166
+ if ((await counter.count(text.slice(0, mid))) <= maxTokens) lo = mid;
167
+ else hi = mid - 1;
168
+ }
169
+ return lo === 0 ? "" : `${text.slice(0, lo)}…`;
170
+ }