File size: 8,090 Bytes
7a1ad33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | /**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Content } from '@google/genai';
import type { ConcreteNode } from './types.js';
import { debugLogger } from '../../utils/debugLogger.js';
import type { ContextTracer } from '../tracer.js';
import type { ContextProfile } from '../config/profiles.js';
import type { PipelineOrchestrator } from '../pipeline/orchestrator.js';
import type { ContextEnvironment } from '../pipeline/environment.js';
import { performCalibration } from '../utils/tokenCalibration.js';
import type { AdvancedTokenCalculator } from '../utils/contextTokenCalculator.js';
import type { HistoryTurn } from '../../core/agentChatHistory.js';
import { ContextWorkingBufferImpl } from '../pipeline/contextWorkingBuffer.js';
export interface RenderOptions {
protectionReasons?: Map<string, string>;
header?: Content;
/**
* If true, the most recent turn in the graph will not be considered for
* consolidation (snapshots) or included in the returned history.
* This is used for "late-binding" the prompt.
*/
lateBindPrompt?: boolean;
}
/**
* Maps the Episodic Context Graph back into a list of HistoryTurns for transmission.
* It applies synchronous context management (GC backstop) if the budget is exceeded.
*/
export async function render(
nodes: readonly ConcreteNode[],
orchestrator: PipelineOrchestrator,
sidecar: ContextProfile,
tracer: ContextTracer,
env: ContextEnvironment,
advancedTokenCalculator: AdvancedTokenCalculator,
options: RenderOptions = {},
): Promise<{
history: HistoryTurn[];
pendingHistory: HistoryTurn[];
didApplyManagement: boolean;
baseUnits: number;
processedNodes: readonly ConcreteNode[];
}> {
const { protectionReasons = new Map(), header, lateBindPrompt } = options;
let headerTokens = 0;
let headerBaseUnits = 0;
if (header) {
const costs =
advancedTokenCalculator.calculateContentTokensAndBaseUnits(header);
headerTokens = costs.tokens;
headerBaseUnits = costs.baseUnits;
}
const lastTurnId = nodes[nodes.length - 1]?.turnId;
if (!sidecar.config.budget) {
const allVisibleNodes = nodes;
const managedNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId !== lastTurnId)
: allVisibleNodes;
const pendingNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId === lastTurnId)
: [];
const history = env.graphMapper.fromGraph(managedNodes);
const pendingHistory = env.graphMapper.fromGraph(pendingNodes);
tracer.logEvent('Render', 'Render Context to LLM (No Budget)', {
renderedContext: history,
pendingContext: pendingHistory,
});
const baseUnits =
advancedTokenCalculator.getRawBaseUnits(allVisibleNodes) +
headerBaseUnits;
return {
history,
pendingHistory,
didApplyManagement: false,
baseUnits,
processedNodes: nodes,
};
}
const maxTokens = sidecar.config.budget.maxTokens;
const { tokens: graphTokens } =
advancedTokenCalculator.calculateTokensAndBaseUnits(nodes);
const currentTokens = graphTokens + headerTokens;
const protectedIds = new Set(protectionReasons.keys());
tracer.logEvent('Render', 'Budget Audit', {
maxTokens,
retainedTokens: sidecar.config.budget.retainedTokens,
graphTokens,
headerTokens,
currentTokens,
pressure: (currentTokens / maxTokens).toFixed(2),
isOverBudget: currentTokens > maxTokens,
});
tracer.logEvent('Render', 'Estimation Calibration', {
breakdown: env.tokenCalculator.calculateTokenBreakdown(nodes),
});
tracer.logEvent('Render', 'Protection Audit', {
reasons: Object.fromEntries(protectionReasons),
});
if (currentTokens <= maxTokens) {
tracer.logEvent(
'Render',
`View is within maxTokens (${currentTokens} <= ${maxTokens}). Returning view.`,
);
const allVisibleNodes = nodes;
const managedNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId !== lastTurnId)
: allVisibleNodes;
const pendingNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId === lastTurnId)
: [];
const history = env.graphMapper.fromGraph(managedNodes);
const pendingHistory = env.graphMapper.fromGraph(pendingNodes);
tracer.logEvent('Render', 'Render Context for LLM', {
renderedContext: history,
pendingContext: pendingHistory,
});
performCalibration(env, allVisibleNodes, [
...history.map((h) => h.content),
...pendingHistory.map((h) => h.content),
]);
return {
history,
pendingHistory,
didApplyManagement: false,
baseUnits:
advancedTokenCalculator.getRawBaseUnits(allVisibleNodes) +
headerBaseUnits,
processedNodes: nodes,
};
}
const targetDelta = currentTokens - sidecar.config.budget.retainedTokens;
tracer.logEvent(
'Render',
`View exceeds maxTokens (${currentTokens} > ${maxTokens}). Hitting Synchronous Pressure Barrier.`,
{ targetDelta },
);
debugLogger.log(
`Context Manager Synchronous Barrier triggered: View at ${currentTokens} tokens (limit: ${maxTokens}).`,
);
const agedOutNodes = new Set<string>();
let rollingTokens = 0;
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
const priorTokens = rollingTokens;
const nodeTokens = env.tokenCalculator.calculateConcreteListTokens([node]);
rollingTokens += nodeTokens;
if (priorTokens > sidecar.config.budget.retainedTokens) {
if (sidecar.config.gcStrategy === 'incremental') {
// Only target enough of the oldest nodes to get back under maxTokens
// priorTokens represents tokens newer than this node.
// If the newer tokens alone are enough to push us over maxTokens, we MUST compress this node.
// If the newer tokens are under maxTokens, we can stop compressing.
if (priorTokens > maxTokens) {
agedOutNodes.add(node.id);
} else if (rollingTokens > maxTokens) {
// This is the boundary node that pushes us over maxTokens. Compress it.
agedOutNodes.add(node.id);
}
} else {
agedOutNodes.add(node.id);
}
}
}
if (lateBindPrompt && lastTurnId) {
for (const node of nodes) {
if (node.turnId === lastTurnId) {
agedOutNodes.delete(node.id);
}
}
}
const processedBuffer = await orchestrator.executeTriggerSync(
'gc_backstop',
ContextWorkingBufferImpl.initialize(nodes),
agedOutNodes,
protectedIds,
);
const processedNodes = processedBuffer.nodes;
const skipList = new Set<string>();
for (const node of processedNodes) {
if (node.abstractsIds) {
for (const id of node.abstractsIds) skipList.add(id);
}
}
const allVisibleNodes = processedNodes.filter((n) => !skipList.has(n.id));
const managedNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId !== lastTurnId)
: allVisibleNodes;
const pendingNodes =
lateBindPrompt && lastTurnId
? allVisibleNodes.filter((n) => n.turnId === lastTurnId)
: [];
const history = env.graphMapper.fromGraph(managedNodes);
const pendingHistory = env.graphMapper.fromGraph(pendingNodes);
const finalTokens =
advancedTokenCalculator.calculateConcreteListTokens(allVisibleNodes);
tracer.logEvent('Render', 'Render Sanitized Context for LLM', {
renderedContextSanitized: history,
pendingContextSanitized: pendingHistory,
});
debugLogger.log(
`Context Manager finished. Final actual token count: ${finalTokens}.`,
);
performCalibration(env, allVisibleNodes, [
...history.map((h) => h.content),
...pendingHistory.map((h) => h.content),
]);
return {
history,
pendingHistory,
didApplyManagement: true,
baseUnits:
advancedTokenCalculator.getRawBaseUnits(allVisibleNodes) +
headerBaseUnits,
processedNodes,
};
}
|