signals.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import type {
  2. ReminderCandidates,
  3. RunawayGuardObservation,
  4. RunawayGuardOptions,
  5. RunawayGuardReminderSignalKind,
  6. RunawayGuardRunIdentity,
  7. RunawayGuardSignalKind,
  8. } from './contracts.js';
  9. import type { ProgressView, StepView } from './step-view.js';
  10. import { recordMaxOccurrences, type ProgressStreak, type ShadowState } from './state.js';
  11. import { isReminderSignalKind } from './reminder.js';
  12. interface DetectionSinks {
  13. readonly ctx: RunawayGuardRunIdentity;
  14. readonly state: ShadowState;
  15. readonly observer: RunawayGuardOptions['onSignal'];
  16. }
  17. export function observeStep(
  18. view: StepView,
  19. sinks: DetectionSinks,
  20. remindAfterOccurrences?: number,
  21. ): ReminderCandidates {
  22. const reminderCandidates = new Set<RunawayGuardReminderSignalKind>();
  23. sinks.state.detectActionStreaks = observeRepeatedKeys(
  24. sinks.state.detectActionStreaks,
  25. view.detectActionKeys,
  26. 'exact_action_repeat',
  27. sinks,
  28. remindAfterOccurrences,
  29. true,
  30. reminderCandidates,
  31. );
  32. sinks.state.pollingActionStreaks = observeRepeatedKeys(
  33. sinks.state.pollingActionStreaks,
  34. view.pollingActionKeys,
  35. 'polling_repeat',
  36. sinks,
  37. remindAfterOccurrences,
  38. false,
  39. reminderCandidates,
  40. );
  41. sinks.state.detectResultStreaks = observeRepeatedKeys(
  42. sinks.state.detectResultStreaks,
  43. view.detectResultKeys,
  44. 'exact_result_repeat',
  45. sinks,
  46. remindAfterOccurrences,
  47. false,
  48. reminderCandidates,
  49. );
  50. sinks.state.errorFamilyStreaks = observeRepeatedKeys(
  51. sinks.state.errorFamilyStreaks,
  52. view.errorFamilyKeys,
  53. 'same_error_family',
  54. sinks,
  55. remindAfterOccurrences,
  56. view.remindableErrorFamilyKeys,
  57. reminderCandidates,
  58. );
  59. sinks.state.progressStreaks = observeProgress(
  60. view.progress,
  61. sinks,
  62. remindAfterOccurrences,
  63. reminderCandidates,
  64. );
  65. observeAbab(view.detectActionBatchKey, sinks);
  66. return reminderCandidates;
  67. }
  68. function observeProgress(
  69. current: readonly ProgressView[],
  70. sinks: DetectionSinks,
  71. remindAfterOccurrences: number | undefined,
  72. reminderCandidates: Set<RunawayGuardReminderSignalKind>,
  73. ): Map<string, ProgressStreak> {
  74. const previous = sinks.state.progressStreaks;
  75. const next = new Map<string, ProgressStreak>(
  76. [...previous].filter(([, streak]) => streak.continuousPolling === true),
  77. );
  78. const pollingCandidates = new Set<string>();
  79. for (const view of current) {
  80. if (view.type === 'interrupt') {
  81. for (const [loopKey, streak] of next) {
  82. if (streak.continuousPolling) next.delete(loopKey);
  83. }
  84. pollingCandidates.clear();
  85. continue;
  86. }
  87. if (view.type === 'reset') {
  88. next.delete(view.loopKey);
  89. pollingCandidates.delete(view.loopKey);
  90. continue;
  91. }
  92. let prior = previous.get(view.loopKey);
  93. if (view.continuousPolling) {
  94. const continuous = next.get(view.loopKey);
  95. prior = continuous?.continuousPolling === true ? continuous : undefined;
  96. }
  97. if (view.verifiedProgress) {
  98. next.set(view.loopKey, {
  99. progressKey: view.progressKey,
  100. occurrences: 0,
  101. ...(view.continuousPolling ? { continuousPolling: true } : {}),
  102. ...(view.reminderEligible ? { reminderEligible: true } : {}),
  103. });
  104. pollingCandidates.delete(view.loopKey);
  105. continue;
  106. }
  107. const occurrences = prior?.progressKey === view.progressKey ? prior.occurrences + 1 : 1;
  108. next.set(view.loopKey, {
  109. progressKey: view.progressKey,
  110. occurrences,
  111. ...(view.continuousPolling ? { continuousPolling: true } : {}),
  112. ...(view.reminderEligible ? { reminderEligible: true } : {}),
  113. });
  114. if (prior?.progressKey !== view.progressKey) pollingCandidates.delete(view.loopKey);
  115. const signalKind: RunawayGuardSignalKind =
  116. view.kind === 'polling' ? 'polling_repeat' : 'unchanged_progress_repeat';
  117. recordMaxOccurrences(sinks.state, signalKind, occurrences);
  118. if ((prior?.occurrences ?? 0) < 2 && occurrences >= 2) {
  119. emitObservation(sinks.observer, sinks.ctx, sinks.state, signalKind, 2);
  120. }
  121. if (
  122. remindAfterOccurrences !== undefined &&
  123. view.kind === 'detect' &&
  124. (prior?.occurrences ?? 0) < remindAfterOccurrences &&
  125. occurrences >= remindAfterOccurrences
  126. ) {
  127. addReminderCandidate(reminderCandidates, 'unchanged_progress_repeat');
  128. }
  129. if (
  130. remindAfterOccurrences !== undefined &&
  131. view.continuousPolling &&
  132. view.reminderEligible &&
  133. (prior?.occurrences ?? 0) < remindAfterOccurrences &&
  134. occurrences >= remindAfterOccurrences
  135. ) {
  136. pollingCandidates.add(view.loopKey);
  137. }
  138. }
  139. if (
  140. remindAfterOccurrences !== undefined &&
  141. [...pollingCandidates].some((loopKey) => {
  142. const streak = next.get(loopKey);
  143. return (
  144. streak?.continuousPolling === true &&
  145. streak.reminderEligible === true &&
  146. streak.occurrences >= remindAfterOccurrences
  147. );
  148. })
  149. ) {
  150. addReminderCandidate(reminderCandidates, 'polling_repeat');
  151. }
  152. return next;
  153. }
  154. function observeRepeatedKeys(
  155. previous: ReadonlyMap<string, number>,
  156. current: readonly string[],
  157. signalKind: RunawayGuardSignalKind,
  158. sinks: DetectionSinks,
  159. remindAfterOccurrences: number | undefined,
  160. reminderEligibility: boolean | ReadonlySet<string>,
  161. reminderCandidates: Set<RunawayGuardReminderSignalKind>,
  162. ): Map<string, number> {
  163. const counts = occurrenceCounts(current);
  164. const next = new Map<string, number>();
  165. for (const [key, count] of counts) {
  166. const prior = previous.get(key) ?? 0;
  167. const occurrences = prior + count;
  168. next.set(key, occurrences);
  169. recordMaxOccurrences(sinks.state, signalKind, occurrences);
  170. if (prior < 2 && occurrences >= 2) {
  171. emitObservation(sinks.observer, sinks.ctx, sinks.state, signalKind, 2);
  172. }
  173. if (
  174. remindAfterOccurrences !== undefined &&
  175. (reminderEligibility === true ||
  176. (reminderEligibility !== false && reminderEligibility.has(key))) &&
  177. prior < remindAfterOccurrences &&
  178. occurrences >= remindAfterOccurrences
  179. ) {
  180. if (isReminderSignalKind(signalKind)) {
  181. addReminderCandidate(reminderCandidates, signalKind);
  182. }
  183. }
  184. }
  185. return next;
  186. }
  187. function addReminderCandidate(
  188. candidates: Set<RunawayGuardReminderSignalKind>,
  189. signalKind: RunawayGuardReminderSignalKind,
  190. ): void {
  191. candidates.add(signalKind);
  192. }
  193. function observeAbab(current: string | undefined, sinks: DetectionSinks): void {
  194. if (!current) {
  195. sinks.state.recentActionBatches = [];
  196. sinks.state.activeAbabKey = undefined;
  197. return;
  198. }
  199. sinks.state.recentActionBatches.push(current);
  200. if (sinks.state.recentActionBatches.length > 4) sinks.state.recentActionBatches.shift();
  201. if (sinks.state.recentActionBatches.length < 4) return;
  202. const [a, b, c, d] = sinks.state.recentActionBatches;
  203. if (!a || !b || a === b || a !== c || b !== d) {
  204. sinks.state.activeAbabKey = undefined;
  205. return;
  206. }
  207. const episode = `${a}\u0000${b}`;
  208. if (sinks.state.activeAbabKey === episode) return;
  209. sinks.state.activeAbabKey = episode;
  210. emitObservation(sinks.observer, sinks.ctx, sinks.state, 'abab_action_cycle', 2);
  211. }
  212. function emitObservation(
  213. observer: RunawayGuardOptions['onSignal'],
  214. ctx: RunawayGuardRunIdentity,
  215. state: ShadowState,
  216. signalKind: RunawayGuardSignalKind,
  217. occurrences: number,
  218. ): void {
  219. const stats = state.signalStats[signalKind];
  220. stats.episodeCount += 1;
  221. stats.firstStepIndex ??= state.stepIndex;
  222. stats.lastStepIndex = state.stepIndex;
  223. recordMaxOccurrences(state, signalKind, occurrences);
  224. if (!observer) return;
  225. const observation: RunawayGuardObservation = {
  226. schemaVersion: 1,
  227. sessionId: ctx.sessionId,
  228. turnId: ctx.turnId,
  229. agentName: ctx.agentName,
  230. signalKind,
  231. stepIndex: state.stepIndex,
  232. occurrences,
  233. };
  234. notifyBestEffort(observer, observation);
  235. }
  236. function notifyBestEffort<T>(
  237. observer: ((observation: T) => void | Promise<void>) | undefined,
  238. observation: T,
  239. ): void {
  240. if (!observer) return;
  241. try {
  242. Promise.resolve(observer(observation)).catch(() => undefined);
  243. } catch {
  244. // Observer failures are intentionally disconnected from Turn execution.
  245. }
  246. }
  247. function occurrenceCounts(values: readonly string[]): Map<string, number> {
  248. const counts = new Map<string, number>();
  249. for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1);
  250. return counts;
  251. }