session-report.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import type { AgentExtension, LlmCallPreparedHandler } from '@mavis/agent-runtime';
  2. import type { SessionLlmCallReportCapability } from '@mavis/session-report';
  3. export interface SessionReportExtensionOptions {
  4. readonly reports: Pick<SessionLlmCallReportCapability, 'writeCurrent'>;
  5. readonly reportFailure?: (sessionId: string, message: string) => void;
  6. }
  7. /**
  8. * Agent-call adapter only. The host owns the report store and binds committed
  9. * compaction/rewind/fork notifications independently of the turn lifecycle.
  10. */
  11. export function sessionReportExtension(options: SessionReportExtensionOptions): AgentExtension {
  12. const capture: LlmCallPreparedHandler = async (input, context) => {
  13. try {
  14. await options.reports.writeCurrent({
  15. sessionId: input.sessionId,
  16. turnId: input.turnId,
  17. envelope: {
  18. schemaVersion: 1,
  19. systemPrompt: input.systemPrompt,
  20. tools: input.tools.map(({ name, description, parameters }) => ({
  21. name,
  22. description,
  23. parameters,
  24. })),
  25. model: String(input.model.id),
  26. provider: String(input.model.provider),
  27. api: String(input.model.api),
  28. thinkingLevel: String(input.thinkingLevel),
  29. ...(input.maxTokens === undefined ? {} : { maxTokens: input.maxTokens }),
  30. ...(input.hostMaxOutputTokens === undefined
  31. ? {}
  32. : { hostMaxOutputTokens: input.hostMaxOutputTokens }),
  33. ...(input.maxSerializedInputBytes === undefined
  34. ? {}
  35. : { maxSerializedInputBytes: input.maxSerializedInputBytes }),
  36. ...(input.cacheRetention === undefined
  37. ? {}
  38. : { cacheRetention: String(input.cacheRetention) }),
  39. ...(context.outputContract?.schema === undefined
  40. ? {}
  41. : { outputSchema: context.outputContract.schema }),
  42. ...(context.outputContract?.revisionInstruction === undefined
  43. ? {}
  44. : { outputRevisionInstruction: context.outputContract.revisionInstruction }),
  45. },
  46. });
  47. } catch (error) {
  48. try {
  49. options.reportFailure?.(
  50. input.sessionId,
  51. `session_llm_call_evidence_failed:${error instanceof Error ? error.message : String(error)}`,
  52. );
  53. } catch {
  54. // Neither evidence IO nor its diagnostics may interrupt a provider call.
  55. }
  56. }
  57. };
  58. return {
  59. id: 'session-report',
  60. description: 'Capture the non-message environment of prepared agent LLM calls.',
  61. init(api) {
  62. api.on('on_llm_call_prepared', capture);
  63. },
  64. };
  65. }