import type { ContextBreakdown } from "../shared/events/events"; import type { ChatMessage, ToolDefinition } from "../shared/types/core"; import { serializeCanonicalJson } from "./session/request-header"; import { sanitizeToolPairingMessages } from "./session/surface"; export interface ContextLifecycleBudgets { contextWindowTokens: number; responseReserveTokens: number; maxToolResultChars: number; maxArtifactChars: number; maxToolSchemaTokens: number; maxToolDescriptionChars: number; maxPrefetchItems: number; compactionThreshold: number; } export interface ContextLifecycleOptions { budgets?: Partial; estimateTokens?: (value: string) => number; now?: () => string; } export type ObservationArtifactKind = "tool_result" | "compaction" | "prefetch" | "checkpoint"; export interface ObservationArtifact { id: string; kind: ObservationArtifactKind; content: string; source?: string; toolCallId?: string; round?: number; createdAt: string; truncated: boolean; sourceMessageIndexes?: number[]; } export interface SemanticContextCheckpoint { id: string; summary: string; sourceMessageIndexes: number[]; artifactIds: string[]; createdAt: string; } export interface ContextProvenance { sourceMessageIndexes: number[]; artifactIds: string[]; omittedMessageIndexes: number[]; omittedToolNames: string[]; checkpointId?: string; compactionReason?: "micro" | "reactive" | "manual"; } export interface CachePrefixDescriptor { key: string; messageCount: number; stable: boolean; } export interface ContextLifecycleProjection { messages: ChatMessage[]; tools: ToolDefinition[]; artifacts: ObservationArtifact[]; checkpoint?: SemanticContextCheckpoint; provenance: ContextProvenance; breakdown: ContextBreakdown; cachePrefix: CachePrefixDescriptor; } export interface PrefetchRequest { id: string; reason: string; readOnly: true; execute: () => Promise; } const DEFAULT_BUDGETS: ContextLifecycleBudgets = { contextWindowTokens: 128_000, responseReserveTokens: 16_384, maxToolResultChars: 5_000, maxArtifactChars: 32_000, maxToolSchemaTokens: 8_000, maxToolDescriptionChars: 1_200, maxPrefetchItems: 2, compactionThreshold: 0.85, }; function defaultEstimateTokens(value: string): number { return Math.ceil(value.length / 4); } function bounded(value: string, max: number): { value: string; truncated: boolean } { if (value.length <= max) return { value, truncated: false }; const marker = "\n[truncated]"; return { value: `${value.slice(0, Math.max(0, max - marker.length))}${marker}`, truncated: true }; } function cloneMessage(message: ChatMessage): ChatMessage { return { ...message, ...(message.toolCalls ? { toolCalls: message.toolCalls.map((call) => ({ ...call })) } : {}), }; } function messageText(message: ChatMessage): string { return `${message.role}: ${message.content}`; } function toolSchemaCost(tool: ToolDefinition, estimateTokens: (value: string) => number): number { return estimateTokens(JSON.stringify(tool)); } /** * Owns the bounded model projection for one run. Session history remains the * replay source of truth; this class only chooses what the next provider call * receives and records why it made that choice. */ export class ContextLifecycleManager { readonly budgets: ContextLifecycleBudgets; private readonly estimateTokens: (value: string) => number; private readonly now: () => string; private artifacts: ObservationArtifact[] = []; private checkpoint?: SemanticContextCheckpoint; private lastProjection?: ContextLifecycleProjection; private readonly prefetched = new Set(); constructor(options: ContextLifecycleOptions = {}) { this.budgets = { ...DEFAULT_BUDGETS, ...options.budgets }; this.estimateTokens = options.estimateTokens ?? defaultEstimateTokens; this.now = options.now ?? (() => new Date().toISOString()); } observeToolResult(input: { content: string; toolName: string; toolCallId?: string; round?: number; sourceMessageIndexes?: number[]; }): { content: string; artifact: ObservationArtifact } { const result = bounded(input.content, this.budgets.maxToolResultChars); const artifactContent = bounded(input.content, this.budgets.maxArtifactChars); const artifact: ObservationArtifact = { id: `observation-${this.artifacts.length + 1}`, kind: "tool_result", content: artifactContent.value, source: input.toolName, ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}), ...(input.round === undefined ? {} : { round: input.round }), createdAt: this.now(), truncated: artifactContent.truncated, ...(input.sourceMessageIndexes ? { sourceMessageIndexes: [...input.sourceMessageIndexes] } : {}), }; this.artifacts.push(artifact); return { content: result.value, artifact }; } addArtifact(artifact: Omit): ObservationArtifact { const boundedContent = bounded(artifact.content, this.budgets.maxArtifactChars); const next: ObservationArtifact = { ...artifact, id: `artifact-${this.artifacts.length + 1}`, content: boundedContent.value, createdAt: this.now(), truncated: artifact.truncated || boundedContent.truncated, }; this.artifacts.push(next); return next; } /** Run bounded read-only enrichment without allowing hidden model calls. */ async prefetch(requests: readonly PrefetchRequest[]): Promise { const selected = requests .filter((request) => request.readOnly && !this.prefetched.has(request.id)) .slice(0, this.budgets.maxPrefetchItems); const results: ObservationArtifact[] = []; for (const request of selected) { this.prefetched.add(request.id); const artifact = await request.execute(); if (!artifact) continue; results.push( this.addArtifact({ ...artifact, kind: "prefetch", source: artifact.source ?? request.reason, truncated: artifact.truncated, }), ); } return results; } /** Rebuild a model projection from a durable semantic checkpoint. */ rebuildFromCheckpoint(checkpoint: SemanticContextCheckpoint, recentMessages: readonly ChatMessage[]): ChatMessage[] { this.checkpoint = checkpoint; return [ { role: "system", content: `## Semantic checkpoint\n${checkpoint.summary}` }, ...recentMessages.map(cloneMessage), ]; } project(input: { systemPrompt: string; messages: readonly ChatMessage[]; tools: readonly ToolDefinition[]; roundContext?: string; compactionReason?: "micro" | "reactive" | "manual"; }): ContextLifecycleProjection { const toolSelection = this.budgetTools(input.tools); const availableTokens = Math.max(1, this.budgets.contextWindowTokens - this.budgets.responseReserveTokens); const stablePrefix: ChatMessage[] = [ { role: "system", content: input.systemPrompt }, ...(input.roundContext?.trim() ? [{ role: "system" as const, content: `## Working Context\n${input.roundContext.trim()}` }] : []), ]; const prefixTokens = stablePrefix.reduce((total, message) => total + this.estimateTokens(messageText(message)), 0); const source = input.messages.map(cloneMessage); const allTokens = prefixTokens + source.reduce((total, message) => total + this.estimateTokens(messageText(message)), 0); const shouldCompact = allTokens > availableTokens * this.budgets.compactionThreshold; const kept = this.pruneMessages(source, Math.max(1, availableTokens - prefixTokens)); const omittedIndexes = source.map((_, index) => index).filter((index) => !kept.indexes.includes(index)); let checkpoint = this.checkpoint; let compactionReason = input.compactionReason; if (omittedIndexes.length > 0 || shouldCompact) { compactionReason = compactionReason ?? (allTokens > availableTokens ? "reactive" : "micro"); checkpoint = this.createCheckpoint(source, omittedIndexes, compactionReason); } const checkpointMessages = checkpoint ? [{ role: "system" as const, content: `## Semantic checkpoint\n${checkpoint.summary}` }] : []; const messages = sanitizeToolPairingMessages([...stablePrefix, ...checkpointMessages, ...kept.messages]); const breakdown = this.breakdown(messages, toolSelection.tools); const artifacts = this.artifacts.slice(-32).map((artifact) => ({ ...artifact })); const provenance: ContextProvenance = { sourceMessageIndexes: kept.indexes, artifactIds: artifacts.map((artifact) => artifact.id), omittedMessageIndexes: omittedIndexes, omittedToolNames: toolSelection.omittedToolNames, ...(checkpoint ? { checkpointId: checkpoint.id } : {}), ...(compactionReason ? { compactionReason } : {}), }; const projection: ContextLifecycleProjection = { messages, tools: toolSelection.tools, artifacts, ...(checkpoint ? { checkpoint } : {}), provenance, breakdown, cachePrefix: { key: serializeCanonicalJson({ systemPrompt: input.systemPrompt, tools: toolSelection.tools }), messageCount: stablePrefix.length, stable: !input.roundContext?.trim(), }, }; this.lastProjection = projection; return projection; } explain(): ContextLifecycleProjection | undefined { return this.lastProjection; } private budgetTools(tools: readonly ToolDefinition[]): { tools: ToolDefinition[]; omittedToolNames: string[] } { let used = 0; const selected: ToolDefinition[] = []; const omittedToolNames: string[] = []; for (const tool of tools) { const candidate: ToolDefinition = { ...tool, description: tool.description.slice(0, this.budgets.maxToolDescriptionChars), }; const cost = toolSchemaCost(candidate, this.estimateTokens); if (used + cost > this.budgets.maxToolSchemaTokens) { omittedToolNames.push(tool.name); continue; } used += cost; selected.push(candidate); } return { tools: selected, omittedToolNames }; } private pruneMessages( messages: readonly ChatMessage[], budgetTokens: number, ): { messages: ChatMessage[]; indexes: number[] } { const kept: ChatMessage[] = []; const indexes: number[] = []; let used = 0; for (let index = messages.length - 1; index >= 0; index--) { const message = messages[index]; const cost = this.estimateTokens(messageText(message)); if (used + cost > budgetTokens && kept.length > 0) break; kept.unshift(message); indexes.unshift(index); used += cost; if (message.role === "tool" && index > 0 && messages[index - 1].role === "assistant") { const assistant = messages[index - 1]; if (!indexes.includes(index - 1)) { kept.unshift(assistant); indexes.unshift(index - 1); used += this.estimateTokens(messageText(assistant)); } } } return { messages: kept, indexes }; } private createCheckpoint( messages: readonly ChatMessage[], omittedIndexes: readonly number[], reason: "micro" | "reactive" | "manual", ): SemanticContextCheckpoint { const omitted = omittedIndexes.map((index) => messageText(messages[index]).slice(0, 500)); const checkpoint: SemanticContextCheckpoint = { id: `checkpoint-${this.now()}-${omittedIndexes.length}`, summary: `${reason} context checkpoint. ${omitted.join(" | ") || "Retained recent observations."}`.slice( 0, 8_000, ), sourceMessageIndexes: [...omittedIndexes], artifactIds: this.artifacts.slice(-16).map((artifact) => artifact.id), createdAt: this.now(), }; this.checkpoint = checkpoint; this.addArtifact({ kind: "checkpoint", content: checkpoint.summary, source: reason, truncated: false }); return checkpoint; } private breakdown(messages: readonly ChatMessage[], tools: readonly ToolDefinition[]): ContextBreakdown { const systemPromptTokens = messages .filter((message) => message.role === "system") .reduce((total, message) => total + this.estimateTokens(message.content), 0); const conversationTokens = messages .filter((message) => message.role !== "system") .reduce((total, message) => total + this.estimateTokens(messageText(message)), 0); const toolTokens = tools.reduce((total, tool) => total + toolSchemaCost(tool, this.estimateTokens), 0); const usedTokens = systemPromptTokens + conversationTokens + toolTokens; return { contextWindow: this.budgets.contextWindowTokens, systemPromptTokens, longTermMemoryTokens: 0, shortTermMemoryTokens: 0, conversationTokens, assetsTokens: toolTokens, usedTokens, freeTokens: Math.max(0, this.budgets.contextWindowTokens - usedTokens), }; } }