replay.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import type { PiStepEndHookInput } from '@mavis/agent-core/pi-turn-runner';
  2. import type {
  3. RunawayGuardObservation,
  4. RunawayGuardReplayInput,
  5. RunawayGuardReplayResult,
  6. RunawayGuardReplayStep,
  7. RunawayGuardRunIdentity,
  8. } from './contracts.js';
  9. import { DEFAULT_MAX_FINGERPRINT_BYTES, positiveInteger } from './fingerprint.js';
  10. import { newShadowState, snapshotTurnSummary } from './state.js';
  11. import {
  12. projectStep,
  13. toolCallIdsFromMessage,
  14. trustedToolProvenanceMap,
  15. verifiedProgressMap,
  16. } from './step-view.js';
  17. import { observeStep } from './signals.js';
  18. /**
  19. * Replays the exact production StepView projector and deterministic Detector
  20. * over a captured trajectory. It never steers and has no persistence side effect.
  21. */
  22. export function replayRunawayGuardTrajectory(
  23. input: RunawayGuardReplayInput,
  24. ): RunawayGuardReplayResult {
  25. const maxFingerprintBytes = positiveInteger(
  26. input.maxFingerprintBytes ?? DEFAULT_MAX_FINGERPRINT_BYTES,
  27. 'maxFingerprintBytes',
  28. );
  29. const policies = new Map(Object.entries(input.toolPolicies ?? {}));
  30. const state = newShadowState();
  31. const observations: RunawayGuardObservation[] = [];
  32. const ctx: RunawayGuardRunIdentity = {
  33. sessionId: input.sessionId,
  34. turnId: input.turnId,
  35. agentName: input.agentName,
  36. };
  37. for (const step of input.steps) {
  38. state.stepIndex += 1;
  39. const toolCallIds = toolCallIdsFromMessage(step.message);
  40. const view = projectStep(
  41. step.message,
  42. step.toolResults,
  43. state,
  44. policies,
  45. maxFingerprintBytes,
  46. verifiedProgressMap(step.verifiedProgress ?? [], new Set(toolCallIds)),
  47. trustedToolProvenanceMap(step.trustedToolProvenance ?? [], new Set(toolCallIds)),
  48. step.blockedToolCalls,
  49. );
  50. observeStep(view, {
  51. ctx,
  52. state,
  53. observer: (observation) => {
  54. observations.push(observation);
  55. },
  56. });
  57. }
  58. return {
  59. observations,
  60. summary: snapshotTurnSummary(ctx, state),
  61. metrics: replayMetrics(input.steps, observations),
  62. };
  63. }
  64. function replayMetrics(
  65. steps: readonly RunawayGuardReplayStep[],
  66. observations: readonly RunawayGuardObservation[],
  67. ): RunawayGuardReplayResult['metrics'] {
  68. const firstSignalStepIndex = observations.reduce<number | undefined>(
  69. (minimum, observation) =>
  70. minimum === undefined ? observation.stepIndex : Math.min(minimum, observation.stepIndex),
  71. undefined,
  72. );
  73. let toolCallCount = 0;
  74. let providerTokens = 0;
  75. let postSignalToolCallCount = 0;
  76. let postSignalProviderTokens = 0;
  77. for (const [index, step] of steps.entries()) {
  78. const stepIndex = index + 1;
  79. const calls = toolCallIdsFromMessage(step.message).length;
  80. const tokens = assistantMessageTokens(step.message);
  81. toolCallCount += calls;
  82. providerTokens += tokens;
  83. if (firstSignalStepIndex !== undefined && stepIndex > firstSignalStepIndex) {
  84. postSignalToolCallCount += calls;
  85. postSignalProviderTokens += tokens;
  86. }
  87. }
  88. return {
  89. toolCallCount,
  90. providerTokens,
  91. ...(firstSignalStepIndex === undefined ? {} : { firstSignalStepIndex }),
  92. postSignalStepCount:
  93. firstSignalStepIndex === undefined ? 0 : Math.max(0, steps.length - firstSignalStepIndex),
  94. postSignalToolCallCount,
  95. postSignalProviderTokens,
  96. };
  97. }
  98. function assistantMessageTokens(message: PiStepEndHookInput['message']): number {
  99. if (message.role !== 'assistant') return 0;
  100. const tokens = message.usage?.totalTokens;
  101. return typeof tokens === 'number' && Number.isFinite(tokens) && tokens >= 0 ? tokens : 0;
  102. }