1
import type { Context } from "@earendil-works/chord";2
import type { AssistantMessage, Message, ToolCall, ToolResultMessage } from "@earendil-works/pi-ai";3
import { SystemEntry } from "../entries.ts";4
import { idFromNumber } from "../ids.ts";5
import type { SessionImpl } from "../session/session.ts";6
import type { ContextEdit, ConversationId, Cursor, EntryId, EntryQuery, EntryRecord, Storage } from "../types.ts";7
import type { ContextView } from "./types.ts";9
const SCAN_PAGE_SIZE = 256;10
const EXCLUDED_STOP_REASONS: ReadonlySet<AssistantMessage["stopReason"]> = new Set(["aborted", "error", "deferred"]);11
const MISSING_RESULT_TEXT = "Tool result unavailable: history ends before this call completed.";13
/** Head marker and newest visible entry that fix one committed context range. */14
export type ContextBounds = {15
readonly head: (EntryRecord & { readonly head: EntryId }) | undefined;16
readonly tail: EntryId;17
};19
/**20
* Capture the bounds of the current context, or of the context cut off at the visible entry `at`, with two O(1)21
* reads. Run this on the Session line; entries at or below the tail are immutable, so `deriveContext()` can then scan22
* them off the line.23
*/24
export async function captureContextBounds(25
storage: Storage,26
conversationId: ConversationId,27
context: Context,28
at?: EntryId,29
): Promise<ContextBounds | undefined> {30
let tail: EntryId | undefined;31
if (at === undefined) {32
tail = (await storage.scanEntries({ conversationId }, 1, undefined, context)).items[0]?.id;33
if (tail === undefined) return undefined;34
} else {35
if ((await storage.entry(conversationId, at, context)) === undefined) {36
throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);37
}38
tail = at;39
}40
return { head: await storage.findLatestHeadMarker(conversationId, tail, context), tail };41
}43
/**44
* One context read: the visible entries it scanned, from the head marker's head, or transcript start, through45
* `bounds.tail`, oldest first, and the view derived from them. Entries at or below the tail never change, so a later46
* read with the same head marker extends both.47
*/48
export type ContextRange = {49
readonly bounds: ContextBounds;50
readonly entries: readonly EntryRecord[];51
readonly view: ContextView;52
/** Targets of the edits in `entries`. */53
readonly edited: ReadonlySet<EntryId>;54
/**55
* `view.messages` from the contributed messages before the last assistant message. Tool results are ordered within56
* the messages up to the next assistant message, so later entries cannot change these.57
*/58
readonly settled: readonly Message[];59
/** Contributed messages from the last assistant message on, before tool result ordering. */60
readonly open: readonly Message[];61
/** The baseline's system message; see `findBaseline()`. */62
readonly baseline: Baseline;63
};65
/** A baseline's system message, `null` when the range cannot have one, or `undefined` while a later entry may be one. */66
type Baseline = Message | null | undefined;68
/**69
* `readContext()` that reuses `previous`, an earlier range of the same conversation: with the same head marker, only70
* entries after its tail are scanned. Returns the view and the range to pass to the next read. A range outlives the71
* read, so its entries are frozen like `MemoryStorage` records, and the returned view has its own arrays.72
*/73
export async function readContextFrom(74
session: SessionImpl,75
storage: Storage,76
conversationId: ConversationId,77
context: Context,78
at: EntryId | undefined,79
previous: ContextRange | undefined,80
): Promise<{ readonly view: ContextView; readonly range: ContextRange | undefined }> {81
const bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context, at));82
if (bounds === undefined) return { view: emptyView(), range: undefined };83
freezeJson(bounds.head);84
let range: ContextRange;85
if (previous === undefined || previous.bounds.head?.id !== bounds.head?.id) {86
range = deriveRange(bounds, freezeJson(await scanRange(storage, conversationId, rangeQuery(bounds), context)));87
} else if (bounds.tail === previous.bounds.tail) {88
range = previous;89
} else if (bounds.tail < previous.bounds.tail) {90
range = deriveRange(91
bounds,92
previous.entries.filter((entry) => entry.id <= bounds.tail),93
);94
} else {95
const minEntryId = idFromNumber<EntryId>(previous.bounds.tail + 1);96
const added = await scanRange(storage, conversationId, { minEntryId, maxEntryId: bounds.tail }, context);97
range = extendRange(previous, bounds, freezeJson(added));98
}99
const { view } = range;100
return {101
view: {102
...view,103
entries: [...view.entries],104
contributions: [...view.contributions],105
messages: [...view.messages],106
},107
range,108
};109
}111
/** Committed context of one conversation: bounds captured on the Session line, entries derived off it. */112
export async function readContext(113
session: SessionImpl,114
storage: Storage,115
conversationId: ConversationId,116
context: Context,117
at?: EntryId,118
): Promise<ContextView> {119
const bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context, at));120
return deriveContext(storage, conversationId, bounds, context);121
}123
/**124
* Derive the active transcript and model context of one conversation within captured bounds.125
*126
* H = newest visible head marker; the range runs from `H.head` (or transcript start) through the tail. Per target,127
* the newest edit in the range wins. Context entries are H followed by the range's non-head entries.128
*/129
export async function deriveContext(130
storage: Storage,131
conversationId: ConversationId,132
bounds: ContextBounds | undefined,133
context: Context,134
): Promise<ContextView> {135
if (bounds === undefined) return emptyView();136
return deriveRange(bounds, await scanRange(storage, conversationId, rangeQuery(bounds), context)).view;137
}139
function emptyView(): ContextView {140
return { head: undefined, entries: [], contributions: [], messages: [] };141
}143
/** Derive the context view from the entries scanned within `bounds`. */144
function deriveRange(bounds: ContextBounds, entries: readonly EntryRecord[]): ContextRange {145
const edits = new Map<EntryId, ContextEdit>();146
// Edits of every entry in the range count, including older head markers that `selectActive()` drops.147
for (const entry of entries) for (const edit of entry.edits ?? []) edits.set(edit.target, edit);148
const active = selectActive(bounds.head, entries);149
const contributions = active.map((entry) => contribute(entry, edits.get(entry.id)));150
const { settled, open } = settle([], contributions.flat());151
const baseline = findBaseline(bounds.head, active);152
const messages = leadWithSystem([...settled, ...orderToolResults(open)], baseline);153
const view = { head: bounds.head, entries: active, contributions, messages };154
return { bounds, entries, view, edited: new Set(edits.keys()), settled, open, baseline };155
}157
/**158
* `previous` extended by the entries `added` after its tail under the same head marker: only their contributions and159
* the open messages are derived. An added edit can change an earlier entry, so it derives the whole range again.160
*/161
function extendRange(previous: ContextRange, bounds: ContextBounds, added: readonly EntryRecord[]): ContextRange {162
const entries = [...previous.entries, ...added];163
if (added.some((entry) => entry.edits !== undefined || entry.head !== undefined || previous.edited.has(entry.id))) {164
return deriveRange(bounds, entries);165
}166
const contributions = added.map((entry) => contribute(entry, undefined));167
const { settled, open } = settle(previous.settled, [...previous.open, ...contributions.flat()]);168
const baseline = previous.baseline !== undefined ? previous.baseline : findBaseline(bounds.head, added);169
const view = {170
head: bounds.head,171
entries: [...previous.view.entries, ...added],172
contributions: [...previous.view.contributions, ...contributions],173
messages: leadWithSystem([...settled, ...orderToolResults(open)], baseline),174
};175
return { bounds, entries, view, edited: previous.edited, settled, open, baseline };176
}178
/**179
* The baseline among `entries`, oldest first: the system message of the first `pi.system` entry after the head180
* marker, or of the transcript without one, when generation wrote it with every section and tool in effect. After a181
* head marker it always does, and omits the retained `pi.system` entries. Without one it does when it saw no system182
* message before, which holds unless an earlier entry carries one, even if an edit omits it later. An edit that targets183
* the baseline contributes other messages, or none, so none leads; a later entry does not take its place.184
*/185
function findBaseline(head: ContextBounds["head"], entries: readonly EntryRecord[]): Baseline {186
for (const entry of entries) {187
if (head !== undefined && entry.id <= head.id) continue;188
if (SystemEntry.is(entry)) return entry.model?.find((message) => message.role === "system") ?? null;189
if (head === undefined && carriesSystemMessage(entry)) return null;190
}191
return undefined;192
}194
/** Whether an entry's own messages, or the replacement messages of its edits, include a system message. */195
function carriesSystemMessage(entry: EntryRecord): boolean {196
const isSystem = (message: Message) => message.role === "system";197
return (198
(entry.model?.some(isSystem) ?? false) ||199
(entry.edits?.some((edit) => edit.action === "replace" && edit.messages.some(isSystem)) ?? false)200
);201
}203
/**204
* Move the first system message to the front when only user messages precede it, or when it is the baseline's. A run's205
* input is committed before generation renders the system prompt, so a transcript starts with the input followed by206
* the baseline, and the range after a compaction with the kept history, assistant messages included. Providers treat207
* only a leading system message as the initial prompt and tool set; without it, a later tool change rewrites the208
* request's tool list and invalidates the whole prompt cache. Only the first system message moves, so replaying209
* system messages in order gives the same sections and tools. Any other system message, before an assistant message,210
* stays where it was committed: moving it would change what it means to the model.211
*/212
function leadWithSystem(messages: Message[], baseline: Baseline): Message[] {213
const index = messages.findIndex((message) => message.role === "system");214
if (index <= 0) return messages;215
const system = messages[index]!;216
if (system !== baseline && messages.slice(0, index).some((message) => message.role !== "user")) {217
return messages;218
}219
return [system, ...messages.slice(0, index), ...messages.slice(index + 1)];220
}222
/** One active entry's model messages after its edit and excluded stop reasons, before tool result ordering. */223
function contribute(entry: EntryRecord, edit: ContextEdit | undefined): readonly Message[] {224
if (edit?.action === "omit") return Object.freeze([]);225
const contributed = edit?.action === "replace" ? edit.messages : (entry.model ?? []);226
return Object.freeze(227
contributed.filter((message) => message.role !== "assistant" || !EXCLUDED_STOP_REASONS.has(message.stopReason)),228
);229
}231
/** Objects `freezeJson()` froze with everything in them. `Object.isFrozen()` holds for shallow freezes too. */232
const deeplyFrozen = new WeakSet<object>();234
/** Freeze a JSON value and everything in it. */235
function freezeJson<T>(value: T): T {236
if (value === null || typeof value !== "object" || deeplyFrozen.has(value)) return value;237
for (const child of Object.values(value)) freezeJson(child);238
Object.freeze(value);239
deeplyFrozen.add(value);240
return value;241
}243
/**244
* Move the ordered messages before the last assistant message of `open` to `settled`. `orderToolResults()` of a245
* sequence equals the concatenation over its parts when each later part starts with an assistant message.246
*/247
function settle(248
settled: readonly Message[],249
open: readonly Message[],250
): { readonly settled: readonly Message[]; readonly open: readonly Message[] } {251
const last = open.findLastIndex((message) => message.role === "assistant");252
if (last <= 0) return { settled, open };253
return { settled: [...settled, ...orderToolResults(open.slice(0, last))], open: open.slice(last) };254
}256
/** The raw active entries within captured bounds, without deriving model context. */257
export async function activeEntries(258
storage: Storage,259
conversationId: ConversationId,260
bounds: ContextBounds | undefined,261
context: Context,262
): Promise<readonly EntryRecord[]> {263
if (bounds === undefined) return [];264
return selectActive(bounds.head, await scanRange(storage, conversationId, rangeQuery(bounds), context));265
}267
/** The visible range of `bounds`: from the head marker's head, or transcript start, through the tail. */268
function rangeQuery(bounds: ContextBounds): Omit<EntryQuery, "conversationId"> {269
const head = bounds.head;270
return head === undefined ? { maxEntryId: bounds.tail } : { minEntryId: head.head, maxEntryId: bounds.tail };271
}273
/** Visible entries within `range`, oldest first. */274
async function scanRange(275
storage: Storage,276
conversationId: ConversationId,277
range: Omit<EntryQuery, "conversationId">,278
context: Context,279
): Promise<EntryRecord[]> {280
const entries: EntryRecord[] = [];281
let cursor: Cursor | undefined;282
do {283
const page = await storage.scanEntries({ conversationId, ...range }, SCAN_PAGE_SIZE, cursor, context);284
entries.push(...page.items);285
cursor = page.next;286
} while (cursor !== undefined);287
return entries.reverse();288
}290
/** The head marker followed by the range's non-head entries, or the whole range without a marker. */291
function selectActive(head: ContextBounds["head"], range: readonly EntryRecord[]): readonly EntryRecord[] {292
return head === undefined ? range : [head, ...range.filter((entry) => entry.head === undefined)];293
}295
/**296
* Place each assistant's tool results directly after it in call order. Results are taken from the messages before297
* the next assistant; a missing result is synthesized and unmatched results are dropped.298
*/299
export function orderToolResults(messages: readonly Message[]): Message[] {300
const ordered: Message[] = [];301
for (let index = 0; index < messages.length; index++) {302
const message = messages[index]!;303
if (message.role === "toolResult") continue;304
ordered.push(message);305
if (message.role !== "assistant") continue;306
const calls = message.content.filter((content): content is ToolCall => content.type === "toolCall");307
if (calls.length === 0) continue;308
const results = new Map<string, number>();309
for (let next = index + 1; next < messages.length && messages[next]!.role !== "assistant"; next++) {310
const candidate = messages[next]!;311
if (candidate.role === "toolResult" && !results.has(candidate.toolCallId)) {312
results.set(candidate.toolCallId, next);313
}314
}315
for (const call of calls) {316
const resultIndex = results.get(call.id);317
ordered.push(resultIndex === undefined ? missingResult(call, message.timestamp) : messages[resultIndex]!);318
}319
}320
return ordered;321
}323
function missingResult(call: ToolCall, timestamp: number): ToolResultMessage {324
return freezeJson({325
role: "toolResult",326
toolCallId: call.id,327
toolName: call.name,328
content: [{ type: "text", text: MISSING_RESULT_TEXT }],329
isError: true,330
details: { reason: "missing_result" },331
timestamp,332
});333
}