context-manager.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * `contextManagerExtension`: Installs `ContextManager` through the `@mavis/agent-runtime` extension
  3. * SPI, letting hosts mount it with `createAgentRuntime({ base: [contextManagerExtension(mgr)] })`
  4. * instead of manually assigning `hooks.beforeLlmCallHook = [manager.beforeLlmCall]`.
  5. *
  6. * The design document §4.3 table identifies context-manager as the first extension to migrate. The
  7. * SPI uses `pi.on('before_llm_call')` to install `manager.beforeLlmCall`, which returns
  8. * `PiBeforeLlmCallHookDecision`: `replaceMessages` maps directly to compaction replacement, while
  9. * `continue`/`skip` mean no compaction is needed.
  10. *
  11. * The extension is a stateless factory: the host constructs and passes in `ContextManager`. It
  12. * performs no IO, creates no locks, and reads no settings, preserving the §4.4 FAQ Q6 boundary that
  13. * authors isolate extension state with `Map<sessionId, ...>`.
  14. */
  15. import type {
  16. AgentExtension,
  17. ExtensionAPI,
  18. PiBeforeLlmCallHookDecision,
  19. PiBeforeLlmCallHookInput,
  20. PiHistoryChangedHookInput,
  21. } from '@mavis/agent-runtime';
  22. import type { ContextManager } from '@mavis/context-manager';
  23. /**
  24. * Optional side-effect observer for the extension. Host compaction ownership can wrap
  25. * `beforeLlmCallHook` with bus-broadcast side effects (`session.compaction.started` / `completed` /
  26. * `failed`) without adding another host wrapper layer.
  27. *
  28. * `onDecision` runs after the manager decision resolves. Its broadcast / metrics side effects are
  29. * isolated on failure and cannot block a successful manager decision. `onError` runs only when the
  30. * manager throws; reporter errors are swallowed while the original manager exception propagates to
  31. * the pi loop.
  32. * `onHistoryChanged` covers the `pi.on('on_history_changed')` subscription required for
  33. * context-manager by the design document §4.3 table, for example to persist replacement history
  34. * through the compaction owner. Observer errors propagate to `PiTurnRunner` after optional
  35. * reporting. The runner decides by reason whether to warn/continue for `messageDelta` or use
  36. * `failClosed: true` for `replaceMessages`; the adapter preserves this distinction.
  37. */
  38. export interface ContextManagerExtensionObserver {
  39. onDecision?(
  40. decision: PiBeforeLlmCallHookDecision,
  41. input: PiBeforeLlmCallHookInput,
  42. ): void | Promise<void>;
  43. onError?(error: unknown, input: PiBeforeLlmCallHookInput): void | Promise<void>;
  44. onHistoryChanged?(input: PiHistoryChangedHookInput): void | Promise<void>;
  45. /**
  46. * Optional reporter invoked when `onHistoryChanged` throws. Host decides
  47. * logging / metrics policy. Reporter errors are swallowed only so they do not
  48. * shadow the original observer error, which is rethrown to `PiTurnRunner`.
  49. */
  50. onHistoryChangedError?(error: unknown, input: PiHistoryChangedHookInput): void | Promise<void>;
  51. }
  52. export interface ContextManagerExtensionOptions {
  53. readonly manager: ContextManager;
  54. /** Extension id override; default `'context-manager'` per design doc §4.3. */
  55. readonly id?: string;
  56. readonly description?: string;
  57. /** Side-effect observer for bus broadcasts / metrics; see `ContextManagerExtensionObserver`. */
  58. readonly observer?: ContextManagerExtensionObserver;
  59. }
  60. /**
  61. * Build the extension. The factory closes over `manager` so downstream code
  62. * can call `pi.on(...)` with a stable handler reference in `init`.
  63. */
  64. export function contextManagerExtension(options: ContextManagerExtensionOptions): AgentExtension {
  65. const { manager, observer } = options;
  66. const id = options.id ?? 'context-manager';
  67. const description =
  68. options.description ??
  69. 'Compact conversation history before each LLM call to keep the context window under threshold.';
  70. return {
  71. id,
  72. description,
  73. init(pi: ExtensionAPI): void {
  74. // `manager.beforeLlmCall` is bound to the manager instance and satisfies
  75. // the pi-native `PiBeforeLlmCallHook` shape (input) => decision. The SPI
  76. // adapter re-signs it to (event, ctx) — we drop ctx here since the
  77. // manager only needs the pi payload it already accepts. Arity is 1 so a
  78. // future `(...a) => manager.beforeLlmCall(...a)` regression would show up
  79. // in `context-manager.test.ts` (see arity assertion there).
  80. pi.on('before_llm_call', async (input) => {
  81. let decision: PiBeforeLlmCallHookDecision | undefined;
  82. try {
  83. decision = await manager.beforeLlmCall(input);
  84. } catch (err) {
  85. if (observer?.onError) {
  86. try {
  87. await observer.onError(err, input);
  88. } catch {
  89. // Observer errors must not shadow the original manager error —
  90. // swallow so pi loop still sees the manager failure.
  91. }
  92. }
  93. throw err;
  94. }
  95. if (observer?.onDecision && decision !== undefined) {
  96. try {
  97. await observer.onDecision(decision, input);
  98. } catch {
  99. // Decision observers are optional bus / metrics side effects. A
  100. // reporting failure must not replace a successful manager result.
  101. }
  102. }
  103. return decision;
  104. });
  105. if (observer?.onHistoryChanged) {
  106. const handler = observer.onHistoryChanged;
  107. const errorSink = observer.onHistoryChangedError;
  108. pi.on('on_history_changed', async (input) => {
  109. try {
  110. await handler(input);
  111. } catch (err) {
  112. if (errorSink) {
  113. try {
  114. await errorSink(err, input);
  115. } catch {
  116. // Reporter failure must not shadow the original persistence error.
  117. }
  118. }
  119. // Preserve the original error so PiTurnRunner can apply its
  120. // reason-specific policy: messageDelta warns/continues, while
  121. // replaceMessages is fail-closed.
  122. throw err;
  123. }
  124. });
  125. }
  126. },
  127. };
  128. }