manager.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import {
  2. generateSummary,
  3. type AgentMessage,
  4. type CompactionSummaryMessage,
  5. } from '@earendil-works/pi-agent-core';
  6. import type {
  7. PiBeforeLlmCallHook,
  8. PiBeforeLlmCallHookDecision,
  9. PiBeforeLlmCallHookInput,
  10. } from '@mavis/agent-core/pi-turn-runner';
  11. import { computeCompactionTriggerAt, DEFAULT_CONTEXT_MANAGER_SETTINGS } from './settings.js';
  12. import { createDefaultContextTokenEstimator, type TokenEstimator } from './token-estimator.js';
  13. import type {
  14. ContextCompactionPlan,
  15. ContextManagerCheckpointOptions,
  16. ContextManagerLock,
  17. ContextManagerObserver,
  18. ContextManagerOptions,
  19. ContextManagerSettings,
  20. ContextSummaryGenerator,
  21. ContextTokenCounter,
  22. } from './types.js';
  23. type SkipReason =
  24. | 'context_manager_disabled'
  25. | 'context_manager_not_enough_messages'
  26. | 'context_manager_below_threshold'
  27. | 'context_manager_no_safe_cut_point'
  28. | 'context_manager_deferred_by_plugin_hook'
  29. | 'context_manager_token_count_failed'
  30. | 'context_manager_summary_failed'
  31. | 'context_manager_summary_empty';
  32. interface TriggerEvaluation {
  33. shouldCompact: boolean;
  34. reason?: SkipReason;
  35. tokens: number;
  36. source: string;
  37. triggerAt: number;
  38. }
  39. export class ContextManager {
  40. readonly beforeLlmCall: PiBeforeLlmCallHook;
  41. private readonly settings: ContextManagerSettings;
  42. private readonly tokenEstimator: TokenEstimator;
  43. private readonly tokenCounter?: ContextTokenCounter;
  44. private readonly summaryGenerator?: ContextSummaryGenerator;
  45. private readonly lock: ContextManagerLock;
  46. private readonly observer?: ContextManagerObserver;
  47. private readonly nowMs: () => number;
  48. private readonly idGenerator: () => string;
  49. constructor(options: ContextManagerOptions = {}) {
  50. this.settings = { ...DEFAULT_CONTEXT_MANAGER_SETTINGS, ...(options.settings ?? {}) };
  51. this.tokenEstimator = createDefaultContextTokenEstimator();
  52. this.tokenCounter = options.tokenCounter;
  53. this.summaryGenerator = options.summaryGenerator;
  54. this.lock = options.lock ?? new InProcessContextManagerLock();
  55. this.observer = options.observer;
  56. this.nowMs = options.nowMs ?? Date.now;
  57. this.idGenerator = options.idGenerator ?? defaultReplacementId;
  58. this.beforeLlmCall = (input) => this.checkpoint(input);
  59. }
  60. checkpoint(
  61. input: PiBeforeLlmCallHookInput,
  62. options: ContextManagerCheckpointOptions = {},
  63. ): Promise<PiBeforeLlmCallHookDecision> {
  64. return this.lock.withSessionLock(input.sessionId, () => this.checkpointLocked(input, options));
  65. }
  66. private async checkpointLocked(
  67. input: PiBeforeLlmCallHookInput,
  68. options: ContextManagerCheckpointOptions,
  69. ): Promise<PiBeforeLlmCallHookDecision> {
  70. const activeMessages = [...input.messages];
  71. const trigger = await this.evaluateTrigger(activeMessages, input);
  72. await this.notify('onTriggerEvaluated', {
  73. sessionId: input.sessionId,
  74. turnId: input.turnId,
  75. phase: input.phase,
  76. source: trigger.source,
  77. tokens: trigger.tokens,
  78. triggerAt: trigger.triggerAt,
  79. shouldCompact: trigger.shouldCompact,
  80. });
  81. if (!trigger.shouldCompact) {
  82. return this.skip(input, trigger.reason ?? 'context_manager_below_threshold');
  83. }
  84. const plan = this.selectPlan(activeMessages, trigger.tokens, trigger.triggerAt);
  85. if (!plan) {
  86. return this.skip(input, 'context_manager_no_safe_cut_point');
  87. }
  88. if (options.beforeCompaction && !(await options.beforeCompaction())) {
  89. return this.skip(input, 'context_manager_deferred_by_plugin_hook');
  90. }
  91. let summary: string;
  92. try {
  93. summary = await this.generateSummary(input, plan);
  94. } catch (err) {
  95. await this.notify('onCompactionFailed', {
  96. sessionId: input.sessionId,
  97. turnId: input.turnId,
  98. phase: input.phase,
  99. reason: errorReason('context_manager_summary_failed', err),
  100. });
  101. return this.skip(input, 'context_manager_summary_failed');
  102. }
  103. if (!summary.trim()) {
  104. return this.skip(input, 'context_manager_summary_empty');
  105. }
  106. const replacementId = this.idGenerator();
  107. const replacementMessages = [
  108. createCompactionSummary(summary, plan.tokensBefore, this.nowMs()),
  109. ...plan.keptMessages,
  110. ];
  111. const tokensAfter = this.tokenEstimator.estimateContextTokens(replacementMessages).tokens;
  112. await this.notify('onCompactionCommitted', {
  113. sessionId: input.sessionId,
  114. turnId: input.turnId,
  115. phase: input.phase,
  116. replacementId,
  117. tokensBefore: plan.tokensBefore,
  118. tokensAfter,
  119. messagesBefore: activeMessages.length,
  120. messagesAfter: replacementMessages.length,
  121. });
  122. return {
  123. type: 'replaceMessages',
  124. messages: replacementMessages,
  125. metadata: {
  126. replacementId,
  127. strategyVersion: this.settings.strategyVersion,
  128. summary,
  129. compactedMessages: plan.compactedMessages,
  130. keptMessages: plan.keptMessages,
  131. firstKeptIndex: plan.firstKeptIndex,
  132. tokensBefore: plan.tokensBefore,
  133. tokensAfter,
  134. messagesBefore: activeMessages.length,
  135. messagesAfter: replacementMessages.length,
  136. },
  137. };
  138. }
  139. private async evaluateTrigger(
  140. messages: AgentMessage[],
  141. input: PiBeforeLlmCallHookInput,
  142. ): Promise<TriggerEvaluation> {
  143. const contextWindow =
  144. input.model.contextWindow > 0
  145. ? input.model.contextWindow
  146. : this.settings.contextWindowFallback;
  147. // Cloud/legacy retains its existing configured-output trigger policy; local-runtime-v2's
  148. // dynamic provider budget is supplied separately by provider-budget.ts.
  149. const triggerAt = computeCompactionTriggerAt({
  150. modelId: input.model.id,
  151. contextWindow,
  152. perTurnMaxTokens: input.model.maxTokens,
  153. reserveTokens: this.settings.reserveTokens,
  154. safetyMarginTokens: this.settings.safetyMarginTokens,
  155. });
  156. if (!this.settings.enabled) {
  157. return {
  158. shouldCompact: false,
  159. reason: 'context_manager_disabled',
  160. tokens: 0,
  161. source: 'disabled',
  162. triggerAt,
  163. };
  164. }
  165. if (messages.length <= 1 || messages.length < this.settings.minMessagesToCompact) {
  166. return {
  167. shouldCompact: false,
  168. reason: 'context_manager_not_enough_messages',
  169. tokens: 0,
  170. source: 'not_counted',
  171. triggerAt,
  172. };
  173. }
  174. let count: { tokens: number; source: string };
  175. try {
  176. count = this.tokenCounter
  177. ? // Forward headers and tools unchanged to the counter: headers may carry gateway authentication
  178. // (without it, remote count_tokens returns 401), and tool declarations are part of the real LLM payload
  179. // (tens of thousands of tokens in MCP-heavy sessions). Omitting them systematically undercounts
  180. // and delays compaction triggers.
  181. await this.tokenCounter.countContextTokens({
  182. messages,
  183. model: input.model,
  184. apiKey: input.apiKey,
  185. headers: input.headers,
  186. systemPrompt: input.systemPrompt,
  187. tools: input.tools,
  188. thinkingLevel: input.thinkingLevel,
  189. signal: input.signal,
  190. })
  191. : {
  192. tokens: this.tokenEstimator.estimateContextTokens(messages).tokens,
  193. source: 'local_estimate',
  194. };
  195. } catch {
  196. return {
  197. shouldCompact: false,
  198. reason: 'context_manager_token_count_failed',
  199. tokens: 0,
  200. source: this.tokenCounter ? 'remote_count_tokens' : 'local_estimate',
  201. triggerAt,
  202. };
  203. }
  204. const shouldCompact = count.tokens > triggerAt;
  205. return {
  206. shouldCompact,
  207. reason: shouldCompact ? undefined : 'context_manager_below_threshold',
  208. tokens: count.tokens,
  209. source: count.source,
  210. triggerAt,
  211. };
  212. }
  213. private selectPlan(
  214. activeMessages: AgentMessage[],
  215. tokensBefore: number,
  216. triggerAt: number,
  217. ): ContextCompactionPlan | undefined {
  218. const previousSummaryIndex = findLatestCompactionSummaryIndex(activeMessages);
  219. const boundaryStartIndex = previousSummaryIndex >= 0 ? previousSummaryIndex + 1 : 0;
  220. const compactableCount = activeMessages.length - boundaryStartIndex;
  221. if (compactableCount < this.settings.minMessagesToCompact) return undefined;
  222. const effectiveKeepRecentTokens = Math.min(
  223. this.settings.keepRecentTokens,
  224. Math.max(1, triggerAt),
  225. );
  226. const firstKeptIndex = selectFirstKeptIndex(
  227. activeMessages,
  228. boundaryStartIndex,
  229. effectiveKeepRecentTokens,
  230. this.tokenEstimator,
  231. );
  232. if (firstKeptIndex <= boundaryStartIndex || firstKeptIndex >= activeMessages.length) {
  233. return undefined;
  234. }
  235. const compactedMessages = activeMessages.slice(boundaryStartIndex, firstKeptIndex);
  236. const keptMessages = activeMessages.slice(firstKeptIndex);
  237. if (
  238. compactedMessages.length < this.settings.minMessagesToCompact ||
  239. keptMessages.length === 0
  240. ) {
  241. return undefined;
  242. }
  243. return {
  244. previousSummary:
  245. previousSummaryIndex >= 0
  246. ? compactionSummaryText(activeMessages[previousSummaryIndex])
  247. : undefined,
  248. compactedMessages,
  249. keptMessages,
  250. firstKeptIndex,
  251. boundaryStartIndex,
  252. tokensBefore,
  253. };
  254. }
  255. private async generateSummary(
  256. input: PiBeforeLlmCallHookInput,
  257. plan: ContextCompactionPlan,
  258. ): Promise<string> {
  259. if (this.summaryGenerator) {
  260. return this.summaryGenerator.generateSummary({
  261. messages: plan.compactedMessages,
  262. previousSummary: plan.previousSummary,
  263. model: input.model,
  264. apiKey: input.apiKey,
  265. thinkingLevel: input.thinkingLevel,
  266. reserveTokens: this.settings.reserveTokens,
  267. signal: input.signal,
  268. });
  269. }
  270. if (!input.apiKey) {
  271. throw new Error('context_manager_summary_unavailable: missing apiKey for current model');
  272. }
  273. const result = await generateSummary(
  274. plan.compactedMessages,
  275. input.model,
  276. this.settings.reserveTokens,
  277. input.apiKey,
  278. undefined,
  279. input.signal,
  280. undefined,
  281. plan.previousSummary,
  282. input.thinkingLevel,
  283. );
  284. if (!result.ok) {
  285. throw new Error(
  286. `context_manager_summary_failed: ${result.error.code}: ${result.error.message}`,
  287. );
  288. }
  289. return result.value;
  290. }
  291. private async skip(
  292. input: PiBeforeLlmCallHookInput,
  293. reason: SkipReason,
  294. ): Promise<PiBeforeLlmCallHookDecision> {
  295. await this.notify('onCompactionSkipped', {
  296. sessionId: input.sessionId,
  297. turnId: input.turnId,
  298. phase: input.phase,
  299. reason,
  300. });
  301. return { type: 'skip', reason };
  302. }
  303. private async notify(
  304. key: keyof ContextManagerObserver,
  305. event:
  306. | Parameters<NonNullable<ContextManagerObserver['onTriggerEvaluated']>>[0]
  307. | Parameters<NonNullable<ContextManagerObserver['onCompactionSkipped']>>[0]
  308. | Parameters<NonNullable<ContextManagerObserver['onCompactionCommitted']>>[0]
  309. | Parameters<NonNullable<ContextManagerObserver['onCompactionFailed']>>[0],
  310. ): Promise<void> {
  311. const fn = this.observer?.[key] as ((value: unknown) => void | Promise<void>) | undefined;
  312. if (!fn) return;
  313. try {
  314. await fn(event);
  315. } catch {
  316. // Observer errors must never change compaction decisions.
  317. }
  318. }
  319. }
  320. class InProcessContextManagerLock implements ContextManagerLock {
  321. private readonly sessionLocks = new Map<string, Promise<void>>();
  322. async withSessionLock<T>(sessionId: string, action: () => Promise<T>): Promise<T> {
  323. const previous = this.sessionLocks.get(sessionId) ?? Promise.resolve();
  324. let release: () => void = () => undefined;
  325. const current = new Promise<void>((resolve) => {
  326. release = resolve;
  327. });
  328. const chained = previous.catch(() => undefined).then(() => current);
  329. this.sessionLocks.set(sessionId, chained);
  330. await previous.catch(() => undefined);
  331. try {
  332. return await action();
  333. } finally {
  334. release();
  335. if (this.sessionLocks.get(sessionId) === chained) {
  336. this.sessionLocks.delete(sessionId);
  337. }
  338. }
  339. }
  340. }
  341. function selectFirstKeptIndex(
  342. messages: AgentMessage[],
  343. boundaryStart: number,
  344. keepRecentTokens: number,
  345. tokenEstimator: TokenEstimator,
  346. ): number {
  347. let candidate = firstValidCutAtOrAfter(messages, boundaryStart, boundaryStart);
  348. if (candidate < 0) return -1;
  349. let tokens = 0;
  350. for (let i = messages.length - 1; i >= boundaryStart; i -= 1) {
  351. tokens += tokenEstimator.estimateMessage(messages[i]!);
  352. if (tokens >= keepRecentTokens) {
  353. candidate = safeCutForIndex(messages, i, boundaryStart);
  354. break;
  355. }
  356. }
  357. return candidate;
  358. }
  359. function safeCutForIndex(messages: AgentMessage[], index: number, boundaryStart: number): number {
  360. const message = messages[index];
  361. if (!message) return -1;
  362. const toolGroupStart = findToolGroupStartForIndex(messages, index, boundaryStart);
  363. if (toolGroupStart >= boundaryStart) return toolGroupStart;
  364. if (message.role === 'toolResult') {
  365. return findAssistantForToolResult(messages, index, boundaryStart);
  366. }
  367. if (isValidFirstKeptMessage(message)) return index;
  368. return firstValidCutAtOrAfter(messages, index, boundaryStart);
  369. }
  370. function firstValidCutAtOrAfter(
  371. messages: AgentMessage[],
  372. index: number,
  373. boundaryStart: number,
  374. ): number {
  375. for (let i = Math.max(index, boundaryStart); i < messages.length; i += 1) {
  376. const message = messages[i];
  377. if (!message) continue;
  378. if (message.role === 'toolResult') {
  379. const assistantIndex = findAssistantForToolResult(messages, i, boundaryStart);
  380. if (assistantIndex >= boundaryStart) return assistantIndex;
  381. continue;
  382. }
  383. if (isValidFirstKeptMessage(message)) return i;
  384. }
  385. return -1;
  386. }
  387. function isValidFirstKeptMessage(message: AgentMessage): boolean {
  388. return message.role !== 'toolResult';
  389. }
  390. function findToolGroupStartForIndex(
  391. messages: AgentMessage[],
  392. index: number,
  393. boundaryStart: number,
  394. ): number {
  395. for (let i = index; i >= boundaryStart; i -= 1) {
  396. const candidate = messages[i];
  397. if (!candidate) continue;
  398. if (candidate.role === 'assistant') {
  399. const toolCallIds = assistantToolCallIds(candidate);
  400. if (toolCallIds.size === 0) return -1;
  401. const groupEnd = findToolGroupEnd(messages, i, toolCallIds);
  402. return index <= groupEnd ? i : -1;
  403. }
  404. if (isHardToolGroupBoundary(candidate)) break;
  405. }
  406. return -1;
  407. }
  408. function findToolGroupEnd(
  409. messages: AgentMessage[],
  410. assistantIndex: number,
  411. toolCallIds: ReadonlySet<string>,
  412. ): number {
  413. let groupEnd = assistantIndex;
  414. for (let i = assistantIndex + 1; i < messages.length; i += 1) {
  415. const message = messages[i];
  416. if (!message) continue;
  417. if (isHardToolGroupBoundary(message) || message.role === 'assistant') break;
  418. if (message.role === 'toolResult' && toolCallIds.has(message.toolCallId)) {
  419. groupEnd = i;
  420. }
  421. }
  422. return groupEnd;
  423. }
  424. function assistantToolCallIds(message: Extract<AgentMessage, { role: 'assistant' }>): Set<string> {
  425. const ids = new Set<string>();
  426. for (const block of message.content) {
  427. if (block.type === 'toolCall') ids.add(block.id);
  428. }
  429. return ids;
  430. }
  431. function isHardToolGroupBoundary(message: AgentMessage): boolean {
  432. return (
  433. message.role === 'user' ||
  434. message.role === 'branchSummary' ||
  435. message.role === 'compactionSummary'
  436. );
  437. }
  438. function findAssistantForToolResult(
  439. messages: AgentMessage[],
  440. toolResultIndex: number,
  441. boundaryStart: number,
  442. ): number {
  443. const result = messages[toolResultIndex] as Extract<AgentMessage, { role: 'toolResult' }>;
  444. const toolCallId = result.toolCallId;
  445. for (let i = toolResultIndex - 1; i >= boundaryStart; i -= 1) {
  446. const candidate = messages[i];
  447. if (!candidate) continue;
  448. if (candidate.role === 'assistant' && assistantHasToolCall(candidate, toolCallId)) return i;
  449. if (isHardToolGroupBoundary(candidate)) break;
  450. }
  451. return -1;
  452. }
  453. function assistantHasToolCall(
  454. message: Extract<AgentMessage, { role: 'assistant' }>,
  455. toolCallId: string,
  456. ): boolean {
  457. return message.content.some((block) => block.type === 'toolCall' && block.id === toolCallId);
  458. }
  459. function findLatestCompactionSummaryIndex(messages: AgentMessage[]): number {
  460. for (let i = messages.length - 1; i >= 0; i -= 1) {
  461. if (compactionSummaryText(messages[i]) !== undefined) return i;
  462. }
  463. return -1;
  464. }
  465. function compactionSummaryText(message: AgentMessage | undefined): string | undefined {
  466. if (!message || message.role !== 'compactionSummary') return undefined;
  467. return message.summary;
  468. }
  469. function createCompactionSummary(
  470. summary: string,
  471. tokensBefore: number,
  472. timestamp: number,
  473. ): CompactionSummaryMessage {
  474. return {
  475. role: 'compactionSummary',
  476. summary,
  477. tokensBefore,
  478. timestamp,
  479. };
  480. }
  481. function errorReason(prefix: string, err: unknown): string {
  482. const message = err instanceof Error ? err.message : String(err);
  483. return message.startsWith(`${prefix}:`) ? message : `${prefix}: ${message}`;
  484. }
  485. function defaultReplacementId(): string {
  486. return `ctx-${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`;
  487. }