step-view.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import type { PiStepEndHookInput } from '@mavis/agent-core/pi-turn-runner';
  2. import type {
  3. RunawayGuardProgressProjection,
  4. RunawayGuardToolPolicy,
  5. RunawayGuardToolPolicyKind,
  6. RunawayGuardToolStep,
  7. RunawayGuardTrustedToolProvenance,
  8. RunawayGuardVerifiedToolProgress,
  9. } from './contracts.js';
  10. import type { ShadowState } from './state.js';
  11. import { fingerprint, fingerprintWithinBudget, isRecord } from './fingerprint.js';
  12. export interface StepView {
  13. readonly detectActionKeys: readonly string[];
  14. readonly pollingActionKeys: readonly string[];
  15. readonly detectResultKeys: readonly string[];
  16. readonly errorFamilyKeys: readonly string[];
  17. readonly remindableErrorFamilyKeys: ReadonlySet<string>;
  18. readonly progress: readonly ProgressView[];
  19. readonly detectActionBatchKey?: string;
  20. }
  21. export type ProgressView = ProgressObservationView | ProgressResetView | ProgressInterruptView;
  22. interface ProgressObservationView {
  23. readonly type: 'observation';
  24. readonly kind: Exclude<RunawayGuardToolPolicyKind, 'exempt'>;
  25. readonly loopKey: string;
  26. readonly progressKey: string;
  27. readonly verifiedProgress: boolean;
  28. readonly continuousPolling: boolean;
  29. readonly reminderEligible: boolean;
  30. }
  31. interface ProgressResetView {
  32. readonly type: 'reset';
  33. readonly loopKey: string;
  34. }
  35. interface ProgressInterruptView {
  36. readonly type: 'interrupt';
  37. }
  38. interface ToolResultProjection {
  39. readonly toolName: string;
  40. readonly content: unknown;
  41. readonly details?: unknown;
  42. readonly isError: boolean;
  43. }
  44. export function projectStep(
  45. message: PiStepEndHookInput['message'],
  46. toolResults: PiStepEndHookInput['toolResults'],
  47. state: ShadowState,
  48. policies: ReadonlyMap<string, RunawayGuardToolPolicy>,
  49. maxBytes: number,
  50. verifiedProgressByCallId: ReadonlyMap<string, RunawayGuardVerifiedToolProgress>,
  51. trustedToolProvenanceByCallId: ReadonlyMap<string, RunawayGuardTrustedToolProvenance>,
  52. blockedToolCalls: PiStepEndHookInput['blockedToolCalls'] = [],
  53. ): StepView {
  54. const excludedCallIds = new Set(
  55. blockedToolCalls
  56. .filter((call) => call.blockedBy === 'permission')
  57. .map((call) => call.toolCallId),
  58. );
  59. const detectActionKeys: string[] = [];
  60. const pollingActionKeys: string[] = [];
  61. const detectResultKeys: string[] = [];
  62. const errorFamilyKeys: string[] = [];
  63. const remindableErrorFamilyKeys = new Set<string>();
  64. const progress: ProgressView[] = [];
  65. const resultsByCallId = new Map(toolResults.map((result) => [result.toolCallId, result]));
  66. const actionKeysByCallId = new Map<string, string>();
  67. const expectedResultCallIds = new Set<string>();
  68. if (message.role === 'assistant') {
  69. for (const block of message.content) {
  70. if (block.type !== 'toolCall') continue;
  71. const excluded = excludedCallIds.has(block.id);
  72. const configuredPolicy = policies.get(block.name);
  73. const policy = configuredPolicy?.kind ?? 'detect';
  74. const result = resultsByCallId.get(block.id);
  75. const projectedResult = excluded ? undefined : result;
  76. const verifiedProgress = excluded ? undefined : verifiedProgressByCallId.get(block.id);
  77. const trustedToolProvenance = trustedToolProvenanceByCallId.get(block.id);
  78. const toolStep: RunawayGuardToolStep = {
  79. toolCallId: block.id,
  80. toolName: block.name,
  81. arguments: block.arguments,
  82. ...(projectedResult
  83. ? {
  84. result: {
  85. toolName: projectedResult.toolName,
  86. content: projectedResult.content,
  87. ...(projectedResult.details === undefined
  88. ? {}
  89. : { details: projectedResult.details }),
  90. isError: projectedResult.isError,
  91. },
  92. }
  93. : {}),
  94. ...(verifiedProgress ? { verifiedProgress } : {}),
  95. ...(trustedToolProvenance ? { trustedToolProvenance } : {}),
  96. };
  97. const progressProjection = projectProgressBestEffort(configuredPolicy, toolStep);
  98. const pollingControl = policy === 'polling' ? progressProjection?.polling : undefined;
  99. appendPollingControl(
  100. progress,
  101. pollingControl,
  102. progressProjection,
  103. block.name,
  104. state,
  105. maxBytes,
  106. );
  107. if (!pollingControl) progress.push({ type: 'interrupt' });
  108. // Permission rejection stays excluded from the old detectors, but its
  109. // trusted task identity must still reset the new polling continuity.
  110. if (excluded || policy === 'exempt') continue;
  111. if (result?.isError && isExpectedResultBestEffort(configuredPolicy, toolStep)) {
  112. expectedResultCallIds.add(block.id);
  113. }
  114. let observedChange = false;
  115. if (progressProjection && pollingControl?.mode !== 'reset') {
  116. const loopKey = fingerprintWithinBudget(
  117. state.secret,
  118. { toolName: block.name, loopKey: progressProjection.loopKey },
  119. maxBytes,
  120. );
  121. const progressKey = fingerprintWithinBudget(
  122. state.secret,
  123. { toolName: block.name, progressKey: progressProjection.progressKey },
  124. maxBytes,
  125. );
  126. if (loopKey && progressKey) {
  127. observedChange =
  128. hasPositiveProgress(progressProjection) ||
  129. (pollingControl?.mode === 'continuous' && hasPositiveProgress(verifiedProgress));
  130. progress.push({
  131. type: 'observation',
  132. kind: policy,
  133. loopKey,
  134. progressKey,
  135. verifiedProgress: observedChange,
  136. continuousPolling: pollingControl?.mode === 'continuous',
  137. reminderEligible:
  138. pollingControl?.mode === 'continuous' && pollingControl.reminderEligible === true,
  139. });
  140. } else {
  141. state.fingerprintSkippedCount += Number(!loopKey) + Number(!progressKey);
  142. if (pollingControl?.mode === 'continuous') progress.push({ type: 'interrupt' });
  143. }
  144. }
  145. const actionValue = projectActionKeyBestEffort(configuredPolicy, block.arguments);
  146. const actionKey = fingerprintWithinBudget(
  147. state.secret,
  148. { toolName: block.name, actionKey: actionValue },
  149. maxBytes,
  150. );
  151. if (!actionKey) {
  152. state.fingerprintSkippedCount += 1;
  153. continue;
  154. }
  155. actionKeysByCallId.set(block.id, actionKey);
  156. if (observedChange) {
  157. // A real change invalidates a mechanical no-change hypothesis for this call only.
  158. expectedResultCallIds.add(block.id);
  159. } else if (policy === 'polling') {
  160. if (!progressProjection) pollingActionKeys.push(actionKey);
  161. } else {
  162. detectActionKeys.push(actionKey);
  163. }
  164. }
  165. }
  166. for (const result of toolResults) {
  167. if (excludedCallIds.has(result.toolCallId)) continue;
  168. const policy = policies.get(result.toolName)?.kind ?? 'detect';
  169. const projected: ToolResultProjection = {
  170. toolName: result.toolName,
  171. content: result.content,
  172. isError: result.isError,
  173. ...(result.details === undefined ? {} : { details: result.details }),
  174. };
  175. if (policy === 'detect') {
  176. const resultKey = fingerprintWithinBudget(state.secret, projected, maxBytes);
  177. if (resultKey) detectResultKeys.push(resultKey);
  178. else state.fingerprintSkippedCount += 1;
  179. }
  180. if (result.isError && policy !== 'exempt' && !expectedResultCallIds.has(result.toolCallId)) {
  181. const family = errorFamily(result.toolName, result.details, result.content);
  182. if (family) {
  183. const actionKey = actionKeysByCallId.get(result.toolCallId);
  184. const key = fingerprintWithinBudget(
  185. state.secret,
  186. { family, actionKey: actionKey ?? null },
  187. maxBytes,
  188. );
  189. if (!key) {
  190. state.fingerprintSkippedCount += 1;
  191. continue;
  192. }
  193. errorFamilyKeys.push(key);
  194. if (policy === 'detect' && actionKey) {
  195. remindableErrorFamilyKeys.add(key);
  196. }
  197. }
  198. }
  199. }
  200. detectActionKeys.sort();
  201. pollingActionKeys.sort();
  202. detectResultKeys.sort();
  203. errorFamilyKeys.sort();
  204. return {
  205. detectActionKeys,
  206. pollingActionKeys,
  207. detectResultKeys,
  208. errorFamilyKeys,
  209. remindableErrorFamilyKeys,
  210. progress,
  211. detectActionBatchKey:
  212. detectActionKeys.length > 0
  213. ? fingerprint(state.secret, `action-batch\u0000${detectActionKeys.join('\u0000')}`)
  214. : undefined,
  215. };
  216. }
  217. function appendPollingControl(
  218. progress: ProgressView[],
  219. control: RunawayGuardProgressProjection['polling'] | undefined,
  220. projection: RunawayGuardProgressProjection | undefined,
  221. toolName: string,
  222. state: ShadowState,
  223. maxBytes: number,
  224. ): void {
  225. if (control?.mode !== 'reset' || !projection) return;
  226. const loopKey = fingerprintWithinBudget(
  227. state.secret,
  228. { toolName, loopKey: projection.loopKey },
  229. maxBytes,
  230. );
  231. if (!loopKey) {
  232. state.fingerprintSkippedCount += 1;
  233. progress.push({ type: 'interrupt' });
  234. return;
  235. }
  236. progress.push({ type: 'reset', loopKey });
  237. }
  238. function hasPositiveProgress(projection: RunawayGuardProgressProjection | undefined): boolean {
  239. return (
  240. projection?.stateChanged === true ||
  241. projection?.artifactChanged === true ||
  242. (projection?.newFacts ?? 0) > 0
  243. );
  244. }
  245. function projectActionKeyBestEffort(
  246. policy: RunawayGuardToolPolicy | undefined,
  247. argumentsValue: unknown,
  248. ): unknown {
  249. if (!policy?.projectActionKey) return argumentsValue;
  250. try {
  251. return policy.projectActionKey(argumentsValue) ?? argumentsValue;
  252. } catch {
  253. return argumentsValue;
  254. }
  255. }
  256. function projectProgressBestEffort(
  257. policy: RunawayGuardToolPolicy | undefined,
  258. step: RunawayGuardToolStep,
  259. ): RunawayGuardProgressProjection | undefined {
  260. if (policy?.projectProgress) {
  261. try {
  262. const projection = policy.projectProgress(step);
  263. if (projection && validProgressProjection(projection)) return projection;
  264. } catch {
  265. // Fall through to independently verified host progress.
  266. }
  267. }
  268. if (!step.verifiedProgress || !validProgressProjection(step.verifiedProgress)) return undefined;
  269. // Host facts may veto a trusted polling observation, but cannot independently
  270. // create one: only the configured tool policy may opt into polling continuity.
  271. const { loopKey, progressKey, newFacts, stateChanged, artifactChanged } = step.verifiedProgress;
  272. return {
  273. loopKey,
  274. progressKey,
  275. ...(newFacts === undefined ? {} : { newFacts }),
  276. ...(stateChanged === undefined ? {} : { stateChanged }),
  277. ...(artifactChanged === undefined ? {} : { artifactChanged }),
  278. };
  279. }
  280. function isExpectedResultBestEffort(
  281. policy: RunawayGuardToolPolicy | undefined,
  282. step: RunawayGuardToolStep,
  283. ): boolean {
  284. if (!policy?.isExpectedResult) return false;
  285. try {
  286. return policy.isExpectedResult(step) === true;
  287. } catch {
  288. return false;
  289. }
  290. }
  291. export function toolCallIdsFromMessage(message: PiStepEndHookInput['message']): readonly string[] {
  292. if (message.role !== 'assistant') return [];
  293. return message.content.flatMap((block) => (block.type === 'toolCall' ? [block.id] : []));
  294. }
  295. export function verifiedProgressMap(
  296. values: readonly RunawayGuardVerifiedToolProgress[],
  297. expected: ReadonlySet<string>,
  298. ): ReadonlyMap<string, RunawayGuardVerifiedToolProgress> {
  299. const valid = values.filter(
  300. (value) =>
  301. isRecord(value) &&
  302. expected.has(value.toolCallId) &&
  303. typeof value.toolCallId === 'string' &&
  304. validProgressProjection(value),
  305. );
  306. return new Map(valid.map((value) => [value.toolCallId, value]));
  307. }
  308. export function verifiedProgressMapBestEffort(
  309. values: readonly RunawayGuardVerifiedToolProgress[],
  310. expected: ReadonlySet<string>,
  311. ): ReadonlyMap<string, RunawayGuardVerifiedToolProgress> {
  312. try {
  313. return verifiedProgressMap(values, expected);
  314. } catch {
  315. return new Map();
  316. }
  317. }
  318. export function trustedToolProvenanceMap(
  319. values: readonly RunawayGuardTrustedToolProvenance[],
  320. expected: ReadonlySet<string>,
  321. ): ReadonlyMap<string, RunawayGuardTrustedToolProvenance> {
  322. const valid = values.filter(
  323. (value) =>
  324. isRecord(value) &&
  325. expected.has(value.toolCallId) &&
  326. typeof value.toolCallId === 'string' &&
  327. typeof value.toolName === 'string' &&
  328. value.toolName.length > 0 &&
  329. (value.source === 'builtin' || value.source === 'captured-compatibility'),
  330. );
  331. return new Map(valid.map((value) => [value.toolCallId, value]));
  332. }
  333. export function trustedToolProvenanceMapBestEffort(
  334. values: readonly RunawayGuardTrustedToolProvenance[],
  335. expected: ReadonlySet<string>,
  336. ): ReadonlyMap<string, RunawayGuardTrustedToolProvenance> {
  337. try {
  338. return trustedToolProvenanceMap(values, expected);
  339. } catch {
  340. return new Map();
  341. }
  342. }
  343. function validProgressProjection(projection: RunawayGuardProgressProjection): boolean {
  344. return (
  345. isRecord(projection) &&
  346. projection.loopKey !== undefined &&
  347. projection.loopKey !== null &&
  348. projection.progressKey !== undefined &&
  349. projection.progressKey !== null &&
  350. (projection.newFacts === undefined ||
  351. (Number.isSafeInteger(projection.newFacts) && projection.newFacts >= 0)) &&
  352. (projection.stateChanged === undefined || typeof projection.stateChanged === 'boolean') &&
  353. (projection.artifactChanged === undefined || typeof projection.artifactChanged === 'boolean') &&
  354. validPollingControl(projection.polling)
  355. );
  356. }
  357. function validPollingControl(value: unknown): boolean {
  358. return (
  359. value === undefined ||
  360. (isRecord(value) &&
  361. (value.mode === 'continuous' || value.mode === 'reset') &&
  362. (value.reminderEligible === undefined || typeof value.reminderEligible === 'boolean'))
  363. );
  364. }
  365. function errorFamily(toolName: string, details: unknown, content: unknown): string | undefined {
  366. const structured = structuredErrorCode(details);
  367. if (structured) return `${toolName}\u0000code:${structured}`;
  368. const text = firstText(content);
  369. if (!text) return undefined;
  370. const normalized = text.toLowerCase();
  371. const category = ERROR_CATEGORIES.find(({ pattern }) => pattern.test(normalized))?.name;
  372. if (category) return `${toolName}\u0000category:${category}`;
  373. const bounded = normalized.replace(/\s+/g, ' ').trim().slice(0, 1_024);
  374. return bounded ? `${toolName}\u0000text:${bounded}` : undefined;
  375. }
  376. const ERROR_CATEGORIES: readonly { readonly name: string; readonly pattern: RegExp }[] = [
  377. { name: 'timeout', pattern: /timeout|timed out|deadline exceeded/ },
  378. { name: 'rate_limit', pattern: /rate.?limit|too many requests|\b429\b/ },
  379. { name: 'network', pattern: /network|econn|socket|dns|connection reset/ },
  380. { name: 'auth', pattern: /unauth|invalid api key|\b401\b/ },
  381. { name: 'permission', pattern: /permission|forbidden|access denied|\b403\b/ },
  382. { name: 'not_found', pattern: /not found|enoent|\b404\b/ },
  383. { name: 'invalid_argument', pattern: /invalid argument|validation failed|bad request|\b400\b/ },
  384. { name: 'process_exit', pattern: /exit code|non-zero|process failed/ },
  385. ];
  386. function structuredErrorCode(details: unknown): string | undefined {
  387. if (!isRecord(details)) return undefined;
  388. for (const key of ['error_code', 'errorCode', 'code', 'status']) {
  389. const value = details[key];
  390. if (typeof value === 'string' && value.length > 0 && value.length <= 128) return value;
  391. if (typeof value === 'number' && Number.isFinite(value)) return String(value);
  392. }
  393. return undefined;
  394. }
  395. function firstText(content: unknown): string | undefined {
  396. if (!Array.isArray(content)) return undefined;
  397. for (const block of content) {
  398. if (!isRecord(block) || block['type'] !== 'text') continue;
  399. const text = block['text'];
  400. if (typeof text === 'string' && text.length > 0 && text.length <= 4_096) return text;
  401. }
  402. return undefined;
  403. }