@stigmer/runner 3.15.3-dev.20260914121148 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (592) hide show
  1. package/README.md +2 -1
  2. package/dist/.build-fingerprint +1 -1
  3. package/dist/__test-utils__/approval-contract/types.d.ts +1 -1
  4. package/dist/__test-utils__/hermetic-activity.d.ts +61 -7
  5. package/dist/__test-utils__/hermetic-activity.js +100 -9
  6. package/dist/__test-utils__/hermetic-activity.js.map +1 -1
  7. package/dist/__test-utils__/model-registry-fixture.d.ts +22 -3
  8. package/dist/__test-utils__/model-registry-fixture.js +22 -7
  9. package/dist/__test-utils__/model-registry-fixture.js.map +1 -1
  10. package/dist/activities/execute-cursor/__test-utils__/contract-subject.d.ts +2 -2
  11. package/dist/activities/execute-cursor/__test-utils__/contract-subject.js +2 -2
  12. package/dist/activities/execute-cursor/__test-utils__/fold.d.ts +61 -0
  13. package/dist/activities/execute-cursor/__test-utils__/fold.js +94 -0
  14. package/dist/activities/execute-cursor/__test-utils__/fold.js.map +1 -0
  15. package/dist/activities/execute-cursor/__test-utils__/gateway-substrate.js +1 -1
  16. package/dist/activities/execute-cursor/__test-utils__/gateway-substrate.js.map +1 -1
  17. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.d.ts +47 -12
  18. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js +41 -10
  19. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js.map +1 -1
  20. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.d.ts +15 -6
  21. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js +17 -4
  22. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js.map +1 -1
  23. package/dist/activities/execute-cursor/adapter.d.ts +4 -4
  24. package/dist/activities/execute-cursor/adapter.js +4 -4
  25. package/dist/activities/execute-cursor/approval-policy.d.ts +10 -10
  26. package/dist/activities/execute-cursor/approval-policy.js +12 -23
  27. package/dist/activities/execute-cursor/approval-policy.js.map +1 -1
  28. package/dist/activities/execute-cursor/approval-state.d.ts +35 -1
  29. package/dist/activities/execute-cursor/approval-state.js +65 -0
  30. package/dist/activities/execute-cursor/approval-state.js.map +1 -1
  31. package/dist/activities/execute-cursor/{message-translator.d.ts → boundary-rows.d.ts} +45 -341
  32. package/dist/activities/execute-cursor/boundary-rows.js +1018 -0
  33. package/dist/activities/execute-cursor/boundary-rows.js.map +1 -0
  34. package/dist/activities/execute-cursor/cursor-capabilities.d.ts +1 -1
  35. package/dist/activities/execute-cursor/cursor-capabilities.js +1 -1
  36. package/dist/activities/execute-cursor/cursor-event-recorder.d.ts +33 -14
  37. package/dist/activities/execute-cursor/cursor-event-recorder.js +43 -21
  38. package/dist/activities/execute-cursor/cursor-event-recorder.js.map +1 -1
  39. package/dist/activities/execute-cursor/prompt-builder.d.ts +3 -3
  40. package/dist/activities/execute-cursor/prompt-builder.js +4 -4
  41. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  42. package/dist/activities/execute-cursor/service-tier.js +1 -2
  43. package/dist/activities/execute-cursor/service-tier.js.map +1 -1
  44. package/dist/activities/execute-cursor/sub-agent-steps.d.ts +79 -0
  45. package/dist/activities/execute-cursor/sub-agent-steps.js +180 -0
  46. package/dist/activities/execute-cursor/sub-agent-steps.js.map +1 -0
  47. package/dist/activities/execute-cursor/tool-result.d.ts +49 -0
  48. package/dist/activities/execute-cursor/tool-result.js +130 -0
  49. package/dist/activities/execute-cursor/tool-result.js.map +1 -0
  50. package/dist/activities/execute-cursor/translator.d.ts +178 -0
  51. package/dist/activities/execute-cursor/translator.js +485 -0
  52. package/dist/activities/execute-cursor/translator.js.map +1 -0
  53. package/dist/activities/execute-cursor/turn-boundary.d.ts +15 -5
  54. package/dist/activities/execute-cursor/turn-boundary.js +10 -14
  55. package/dist/activities/execute-cursor/turn-boundary.js.map +1 -1
  56. package/dist/activities/execute-cursor/turn-settle.d.ts +11 -7
  57. package/dist/activities/execute-cursor/turn-settle.js +47 -34
  58. package/dist/activities/execute-cursor/turn-settle.js.map +1 -1
  59. package/dist/activities/execute-cursor/turn-setup.d.ts +2 -2
  60. package/dist/activities/execute-cursor/turn-setup.js +5 -5
  61. package/dist/activities/execute-cursor/turn-setup.js.map +1 -1
  62. package/dist/activities/execute-cursor/turn-stream.d.ts +23 -14
  63. package/dist/activities/execute-cursor/turn-stream.js +41 -28
  64. package/dist/activities/execute-cursor/turn-stream.js.map +1 -1
  65. package/dist/activities/execute-cursor/turn.d.ts +4 -4
  66. package/dist/activities/execute-cursor/turn.js +5 -5
  67. package/dist/activities/execute-cursor/usage-pricing.d.ts +2 -2
  68. package/dist/activities/execute-cursor/usage-pricing.js +2 -2
  69. package/dist/activities/execute-deep-agent/__test-utils__/contract-subject.d.ts +2 -2
  70. package/dist/activities/execute-deep-agent/__test-utils__/contract-subject.js +2 -2
  71. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.d.ts +16 -11
  72. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.js +22 -10
  73. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.js.map +1 -1
  74. package/dist/activities/execute-deep-agent/__test-utils__/hitl-script.js +1 -1
  75. package/dist/activities/execute-deep-agent/__test-utils__/hitl-script.js.map +1 -1
  76. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.d.ts +2 -3
  77. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.js +2 -3
  78. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.js.map +1 -1
  79. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.d.ts +12 -3
  80. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.js +18 -4
  81. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.js.map +1 -1
  82. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.d.ts +10 -1
  83. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.js +24 -11
  84. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.js.map +1 -1
  85. package/dist/activities/execute-deep-agent/adapter.d.ts +1 -1
  86. package/dist/activities/execute-deep-agent/adapter.js +1 -1
  87. package/dist/activities/execute-deep-agent/approval-file-change.d.ts +19 -19
  88. package/dist/activities/execute-deep-agent/approval-file-change.js +16 -15
  89. package/dist/activities/execute-deep-agent/approval-file-change.js.map +1 -1
  90. package/dist/activities/execute-deep-agent/deep-agent-capabilities.d.ts +2 -2
  91. package/dist/activities/execute-deep-agent/deep-agent-capabilities.js +2 -2
  92. package/dist/activities/execute-deep-agent/hitl.d.ts +2 -2
  93. package/dist/activities/execute-deep-agent/hitl.js +2 -2
  94. package/dist/activities/execute-deep-agent/inline-publisher.d.ts +13 -3
  95. package/dist/activities/execute-deep-agent/inline-publisher.js +3 -3
  96. package/dist/activities/execute-deep-agent/inline-publisher.js.map +1 -1
  97. package/dist/activities/execute-deep-agent/prompt-builder.d.ts +3 -3
  98. package/dist/activities/execute-deep-agent/prompt-builder.js +6 -7
  99. package/dist/activities/execute-deep-agent/prompt-builder.js.map +1 -1
  100. package/dist/activities/execute-deep-agent/streaming-side-effects.d.ts +16 -8
  101. package/dist/activities/execute-deep-agent/streaming-side-effects.js +20 -33
  102. package/dist/activities/execute-deep-agent/streaming-side-effects.js.map +1 -1
  103. package/dist/activities/execute-deep-agent/subagent-transformer.d.ts +3 -3
  104. package/dist/activities/execute-deep-agent/subagent-transformer.js +1 -1
  105. package/dist/activities/execute-deep-agent/translator.d.ts +134 -0
  106. package/dist/activities/execute-deep-agent/translator.js +418 -0
  107. package/dist/activities/execute-deep-agent/translator.js.map +1 -0
  108. package/dist/activities/execute-deep-agent/turn-settle.d.ts +13 -7
  109. package/dist/activities/execute-deep-agent/turn-settle.js +34 -45
  110. package/dist/activities/execute-deep-agent/turn-settle.js.map +1 -1
  111. package/dist/activities/execute-deep-agent/turn-setup.d.ts +8 -8
  112. package/dist/activities/execute-deep-agent/turn-setup.js +7 -7
  113. package/dist/activities/execute-deep-agent/turn-stream.d.ts +13 -10
  114. package/dist/activities/execute-deep-agent/turn-stream.js +44 -41
  115. package/dist/activities/execute-deep-agent/turn-stream.js.map +1 -1
  116. package/dist/activities/execute-deep-agent/turn.d.ts +3 -3
  117. package/dist/activities/execute-deep-agent/turn.js +3 -3
  118. package/dist/activities/generate-session-subject.d.ts +25 -4
  119. package/dist/activities/generate-session-subject.js +17 -7
  120. package/dist/activities/generate-session-subject.js.map +1 -1
  121. package/dist/client/stigmer-client.d.ts +17 -6
  122. package/dist/client/stigmer-client.js +47 -14
  123. package/dist/client/stigmer-client.js.map +1 -1
  124. package/dist/config.d.ts +6 -3
  125. package/dist/config.js +4 -1
  126. package/dist/config.js.map +1 -1
  127. package/dist/harness/approval-decisions.d.ts +1 -1
  128. package/dist/harness/approval-decisions.js +1 -1
  129. package/dist/harness/capabilities.d.ts +21 -11
  130. package/dist/harness/capabilities.js +2 -2
  131. package/dist/harness/capture.d.ts +4 -4
  132. package/dist/harness/capture.js +4 -4
  133. package/dist/harness/persist-chokepoint.d.ts +3 -3
  134. package/dist/harness/persist-chokepoint.js +3 -3
  135. package/dist/harness/registry.d.ts +2 -2
  136. package/dist/harness/registry.js +2 -2
  137. package/dist/harness/run-turn.d.ts +6 -4
  138. package/dist/harness/run-turn.js +31 -9
  139. package/dist/harness/run-turn.js.map +1 -1
  140. package/dist/harness/stop-controller.d.ts +1 -1
  141. package/dist/harness/stop-controller.js +1 -1
  142. package/dist/harness/terminal-table.d.ts +7 -7
  143. package/dist/harness/terminal-table.js +7 -7
  144. package/dist/harness/transcript/builder.d.ts +182 -0
  145. package/dist/harness/transcript/builder.js +693 -0
  146. package/dist/harness/transcript/builder.js.map +1 -0
  147. package/dist/harness/transcript/events.d.ts +218 -0
  148. package/dist/harness/transcript/events.js +50 -0
  149. package/dist/harness/transcript/events.js.map +1 -0
  150. package/dist/harness/transcript/state.d.ts +110 -0
  151. package/dist/harness/transcript/state.js +148 -0
  152. package/dist/harness/transcript/state.js.map +1 -0
  153. package/dist/harness/turn-context.d.ts +54 -38
  154. package/dist/harness/turn-context.js +42 -43
  155. package/dist/harness/turn-context.js.map +1 -1
  156. package/dist/harness/types.d.ts +63 -22
  157. package/dist/harness/types.js +12 -11
  158. package/dist/harness/types.js.map +1 -1
  159. package/dist/harness/usage-accumulator.d.ts +2 -2
  160. package/dist/harness/usage-accumulator.js +2 -2
  161. package/dist/harness-adapters.d.ts +5 -4
  162. package/dist/harness-adapters.js +5 -4
  163. package/dist/harness-adapters.js.map +1 -1
  164. package/dist/interceptors/run-credential-activity.d.ts +28 -0
  165. package/dist/interceptors/run-credential-activity.js +56 -0
  166. package/dist/interceptors/run-credential-activity.js.map +1 -0
  167. package/dist/middleware/approval-gate.d.ts +6 -0
  168. package/dist/middleware/approval-gate.js +7 -57
  169. package/dist/middleware/approval-gate.js.map +1 -1
  170. package/dist/middleware/cost-advisory.d.ts +3 -3
  171. package/dist/middleware/cost-advisory.js +3 -3
  172. package/dist/middleware/index.d.ts +1 -1
  173. package/dist/middleware/index.js +1 -1
  174. package/dist/runner-manager.js +10 -4
  175. package/dist/runner-manager.js.map +1 -1
  176. package/dist/shared/activity-input.d.ts +9 -0
  177. package/dist/shared/activity-input.js +17 -0
  178. package/dist/shared/activity-input.js.map +1 -1
  179. package/dist/shared/approval-policy.d.ts +53 -0
  180. package/dist/shared/approval-policy.js +76 -0
  181. package/dist/shared/approval-policy.js.map +1 -1
  182. package/dist/shared/args-preview.d.ts +45 -22
  183. package/dist/shared/args-preview.js +51 -41
  184. package/dist/shared/args-preview.js.map +1 -1
  185. package/dist/shared/attachment-resolver.d.ts +4 -4
  186. package/dist/shared/attachment-resolver.js +4 -4
  187. package/dist/shared/attachment-zip.d.ts +2 -2
  188. package/dist/shared/attachment-zip.js +2 -2
  189. package/dist/shared/channel-attachment.d.ts +8 -5
  190. package/dist/shared/channel-attachment.js +10 -6
  191. package/dist/shared/channel-attachment.js.map +1 -1
  192. package/dist/shared/cost-guard.d.ts +2 -2
  193. package/dist/shared/cost-guard.js +2 -2
  194. package/dist/shared/exact-apply.d.ts +1 -1
  195. package/dist/shared/exact-apply.js +1 -1
  196. package/dist/shared/execution-context.d.ts +2 -2
  197. package/dist/shared/execution-context.js +2 -2
  198. package/dist/shared/extract-structured-output.d.ts +2 -2
  199. package/dist/shared/extract-structured-output.js +2 -2
  200. package/dist/shared/filereview/cas-touched.d.ts +2 -2
  201. package/dist/shared/filereview/cas-touched.js +2 -2
  202. package/dist/shared/filereview/progress.d.ts +13 -0
  203. package/dist/shared/filereview/progress.js +13 -0
  204. package/dist/shared/filereview/progress.js.map +1 -1
  205. package/dist/shared/heartbeat.d.ts +1 -1
  206. package/dist/shared/heartbeat.js +1 -1
  207. package/dist/shared/llm-backend.d.ts +0 -4
  208. package/dist/shared/llm-backend.js +0 -4
  209. package/dist/shared/llm-backend.js.map +1 -1
  210. package/dist/shared/memory-attachment.d.ts +16 -9
  211. package/dist/shared/memory-attachment.js +18 -10
  212. package/dist/shared/memory-attachment.js.map +1 -1
  213. package/dist/shared/model-error.d.ts +1 -2
  214. package/dist/shared/model-error.js +1 -2
  215. package/dist/shared/model-error.js.map +1 -1
  216. package/dist/shared/persist-decision.d.ts +18 -24
  217. package/dist/shared/persist-decision.js +19 -11
  218. package/dist/shared/persist-decision.js.map +1 -1
  219. package/dist/shared/prompt-sections.d.ts +4 -4
  220. package/dist/shared/prompt-sections.js +4 -4
  221. package/dist/shared/run-credential-store.d.ts +32 -0
  222. package/dist/shared/run-credential-store.js +39 -0
  223. package/dist/shared/run-credential-store.js.map +1 -0
  224. package/dist/shared/run-credential.d.ts +61 -0
  225. package/dist/shared/run-credential.js +68 -0
  226. package/dist/shared/run-credential.js.map +1 -0
  227. package/dist/shared/skill-resolver.d.ts +3 -3
  228. package/dist/shared/skill-resolver.js +3 -3
  229. package/dist/shared/status-offload.d.ts +1 -1
  230. package/dist/shared/status-offload.js +2 -2
  231. package/dist/shared/status-offload.js.map +1 -1
  232. package/dist/shared/streaming-scheduler.d.ts +2 -7
  233. package/dist/shared/streaming-scheduler.js +6 -14
  234. package/dist/shared/streaming-scheduler.js.map +1 -1
  235. package/dist/shared/subagent-rows.d.ts +2 -2
  236. package/dist/shared/subagent-rows.js +2 -2
  237. package/dist/shared/synthesized-attachment.d.ts +30 -3
  238. package/dist/shared/synthesized-attachment.js +26 -0
  239. package/dist/shared/synthesized-attachment.js.map +1 -1
  240. package/dist/shared/todos.d.ts +3 -3
  241. package/dist/shared/todos.js +3 -3
  242. package/dist/shared/tool-row.d.ts +19 -1
  243. package/dist/shared/tool-row.js +36 -2
  244. package/dist/shared/tool-row.js.map +1 -1
  245. package/dist/shared/worker-shutdown.d.ts +1 -1
  246. package/dist/shared/worker-shutdown.js +1 -1
  247. package/dist/shared/workspace/session-provision.d.ts +1 -1
  248. package/dist/shared/workspace/session-provision.js +1 -1
  249. package/dist/shared/workspace/sources/empty.d.ts +1 -1
  250. package/dist/shared/workspace/sources/empty.js +1 -2
  251. package/dist/shared/workspace/sources/empty.js.map +1 -1
  252. package/dist/shared/workspace/sources/git.js +4 -4
  253. package/dist/shared/workspace/sources/git.js.map +1 -1
  254. package/dist/shared/workspace/sources/local-path.js +6 -6
  255. package/dist/shared/workspace/sources/local-path.js.map +1 -1
  256. package/dist/shared/workspace/stigmer-link.d.ts +1 -1
  257. package/dist/shared/workspace/stigmer-link.js +1 -1
  258. package/dist/shared/workspace/types.d.ts +2 -5
  259. package/dist/shared/workspace/types.js +0 -6
  260. package/dist/shared/workspace/types.js.map +1 -1
  261. package/dist/shared/workspace/writeback-coordinator.d.ts +17 -4
  262. package/dist/shared/workspace/writeback-coordinator.js +7 -9
  263. package/dist/shared/workspace/writeback-coordinator.js.map +1 -1
  264. package/dist/worker.js +10 -3
  265. package/dist/worker.js.map +1 -1
  266. package/dist/workflow-source.d.ts +10 -0
  267. package/dist/workflow-source.js +12 -0
  268. package/dist/workflow-source.js.map +1 -1
  269. package/dist/workflows/execute-from-execution.d.ts +15 -0
  270. package/dist/workflows/execute-from-execution.js +11 -0
  271. package/dist/workflows/execute-from-execution.js.map +1 -1
  272. package/dist/workflows/index.d.ts +5 -3
  273. package/dist/workflows/index.js +5 -3
  274. package/dist/workflows/index.js.map +1 -1
  275. package/dist/workflows/interceptors/run-credential.d.ts +34 -0
  276. package/dist/workflows/interceptors/run-credential.js +71 -0
  277. package/dist/workflows/interceptors/run-credential.js.map +1 -0
  278. package/package.json +4 -4
  279. package/src/__test-utils__/__tests__/execution-record-barrier.test.ts +70 -0
  280. package/src/__test-utils__/__tests__/harness-contract-self-check.test.ts +35 -1
  281. package/src/__test-utils__/approval-contract/contract.ts +1 -1
  282. package/src/__test-utils__/approval-contract/types.ts +1 -1
  283. package/src/__test-utils__/harness-boot-order-child.ts +1 -1
  284. package/src/__test-utils__/harness-contract/contract.ts +8 -8
  285. package/src/__test-utils__/harness-contract/recording-sink.ts +11 -1
  286. package/src/__test-utils__/harness-contract/runtime-contract.ts +52 -16
  287. package/src/__test-utils__/harness-contract/scripted-adapter.ts +47 -43
  288. package/src/__test-utils__/hermetic-activity.ts +113 -9
  289. package/src/__test-utils__/model-registry-fixture.ts +31 -7
  290. package/src/__test-utils__/module-specifiers.ts +32 -3
  291. package/src/__tests__/harness-boot-order.test.ts +1 -1
  292. package/src/__tests__/harness-contract.test.ts +1 -1
  293. package/src/__tests__/run-credential-e2e.test.ts +233 -0
  294. package/src/__tests__/run-credential-registration.test.ts +80 -0
  295. package/src/__tests__/runner-manager.test.ts +1 -1
  296. package/src/activities/__tests__/generate-session-subject-wire.test.ts +119 -0
  297. package/src/activities/execute-cursor/__test-utils__/__tests__/scripted-double.test.ts +1 -1
  298. package/src/activities/execute-cursor/__test-utils__/contract-subject.ts +2 -2
  299. package/src/activities/execute-cursor/__test-utils__/fold.ts +116 -0
  300. package/src/activities/execute-cursor/__test-utils__/gateway-substrate.ts +1 -1
  301. package/src/activities/execute-cursor/__test-utils__/hermetic-cursor.ts +67 -17
  302. package/src/activities/execute-cursor/__test-utils__/scripted-agent.ts +19 -5
  303. package/src/activities/execute-cursor/__tests__/approval-gate.test.ts +2 -1
  304. package/src/activities/execute-cursor/__tests__/approval-state.test.ts +14 -21
  305. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +3 -3
  306. package/src/activities/execute-cursor/__tests__/coarse-fingerprint.test.ts +2 -1
  307. package/src/activities/execute-cursor/__tests__/cursor-event-recorder.test.ts +142 -0
  308. package/src/activities/execute-cursor/__tests__/cursor-fetch-interceptor-bypass.test.ts +19 -8
  309. package/src/activities/execute-cursor/__tests__/cursor-sdk-auth-smoke.test.ts +10 -8
  310. package/src/activities/execute-cursor/__tests__/cursor-transcript-live.test.ts +298 -0
  311. package/src/activities/execute-cursor/__tests__/deny-gate-exact-apply.test.ts +4 -2
  312. package/src/activities/execute-cursor/__tests__/fetch-interceptor.test.ts +1 -1
  313. package/src/activities/execute-cursor/__tests__/hermetic/deny-and-retry.test.ts +1 -1
  314. package/src/activities/execute-cursor/__tests__/hermetic/file-review-capture.test.ts +1 -1
  315. package/src/activities/execute-cursor/__tests__/hermetic/goldens/mcp-tool-call.status.json +71 -0
  316. package/src/activities/execute-cursor/__tests__/hermetic/goldens/sdk-task-note.status.json +73 -0
  317. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.error-delta.status.json +78 -0
  318. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.output-first.status.json +72 -0
  319. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.status.json +72 -0
  320. package/src/activities/execute-cursor/__tests__/hermetic/goldens/sub-agent-delegation.status.json +109 -0
  321. package/src/activities/execute-cursor/__tests__/hermetic/goldens/thinking-turn.status.json +78 -0
  322. package/src/activities/execute-cursor/__tests__/hermetic/goldens/todo-write.status.json +119 -0
  323. package/src/activities/execute-cursor/__tests__/hermetic/goldens/tool-error.status.json +68 -0
  324. package/src/activities/execute-cursor/__tests__/hermetic/goldens/tool-only-step.status.json +67 -0
  325. package/src/activities/execute-cursor/__tests__/hermetic/goldens/unattributed-hook-block.status.json +1 -1
  326. package/src/activities/execute-cursor/__tests__/hermetic/harness-contract.test.ts +7 -7
  327. package/src/activities/execute-cursor/__tests__/hermetic/mcp-tool-call.test.ts +146 -0
  328. package/src/activities/execute-cursor/__tests__/hermetic/pause-vs-shutdown.test.ts +5 -5
  329. package/src/activities/execute-cursor/__tests__/hermetic/plain-turn.test.ts +2 -1
  330. package/src/activities/execute-cursor/__tests__/hermetic/run-wait-arms.test.ts +2 -1
  331. package/src/activities/execute-cursor/__tests__/hermetic/sdk-task-note.test.ts +122 -0
  332. package/src/activities/execute-cursor/__tests__/hermetic/shell-output-delta.test.ts +276 -0
  333. package/src/activities/execute-cursor/__tests__/hermetic/stream-self-stop-arms.test.ts +8 -8
  334. package/src/activities/execute-cursor/__tests__/hermetic/sub-agent-delegation.test.ts +196 -0
  335. package/src/activities/execute-cursor/__tests__/hermetic/thinking-turn.test.ts +145 -0
  336. package/src/activities/execute-cursor/__tests__/hermetic/thrown-error-arms.test.ts +1 -1
  337. package/src/activities/execute-cursor/__tests__/hermetic/todo-write.test.ts +165 -0
  338. package/src/activities/execute-cursor/__tests__/hermetic/tool-call.test.ts +3 -3
  339. package/src/activities/execute-cursor/__tests__/hermetic/tool-error.test.ts +138 -0
  340. package/src/activities/execute-cursor/__tests__/hermetic/tool-only-step.test.ts +130 -0
  341. package/src/activities/execute-cursor/__tests__/hermetic/unattributed-hook-block.test.ts +13 -1
  342. package/src/activities/execute-cursor/__tests__/hermetic/workspace-lock-timeout.test.ts +2 -2
  343. package/src/activities/execute-cursor/__tests__/hitl-ledger.test.ts +43 -60
  344. package/src/activities/execute-cursor/__tests__/hitl-resume-history.test.ts +23 -28
  345. package/src/activities/execute-cursor/__tests__/hook-script.test.ts +2 -1
  346. package/src/activities/execute-cursor/__tests__/http2-interceptor.test.ts +1 -1
  347. package/src/activities/execute-cursor/__tests__/prompt-goldens.test.ts +5 -5
  348. package/src/activities/execute-cursor/__tests__/same-identity-reproposal.test.ts +11 -13
  349. package/src/activities/execute-cursor/__tests__/sequential-gate-resume.test.ts +8 -11
  350. package/src/activities/execute-cursor/__tests__/tool-result-image.test.ts +8 -22
  351. package/src/activities/execute-cursor/__tests__/translator.test.ts +594 -0
  352. package/src/activities/execute-cursor/__tests__/turn-boundary.test.ts +8 -5
  353. package/src/activities/execute-cursor/__tests__/turn-stream.test.ts +87 -63
  354. package/src/activities/execute-cursor/adapter.ts +4 -4
  355. package/src/activities/execute-cursor/approval-policy.ts +12 -24
  356. package/src/activities/execute-cursor/approval-state.ts +66 -1
  357. package/src/activities/execute-cursor/boundary-rows.ts +1132 -0
  358. package/src/activities/execute-cursor/cursor-capabilities.ts +1 -1
  359. package/src/activities/execute-cursor/cursor-event-recorder.ts +57 -28
  360. package/src/activities/execute-cursor/fetch-interceptor.ts +1 -1
  361. package/src/activities/execute-cursor/http2-interceptor.ts +1 -1
  362. package/src/activities/execute-cursor/prompt-builder.ts +6 -6
  363. package/src/activities/execute-cursor/service-tier.ts +1 -2
  364. package/src/activities/execute-cursor/sub-agent-steps.ts +188 -0
  365. package/src/activities/execute-cursor/tool-result.ts +128 -0
  366. package/src/activities/execute-cursor/translator.ts +541 -0
  367. package/src/activities/execute-cursor/turn-boundary.ts +21 -14
  368. package/src/activities/execute-cursor/turn-settle.ts +46 -34
  369. package/src/activities/execute-cursor/turn-setup.ts +5 -5
  370. package/src/activities/execute-cursor/turn-stream.ts +49 -46
  371. package/src/activities/execute-cursor/turn.ts +5 -5
  372. package/src/activities/execute-cursor/usage-pricing.ts +2 -2
  373. package/src/activities/execute-deep-agent/__test-utils__/contract-subject.ts +2 -2
  374. package/src/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.ts +23 -11
  375. package/src/activities/execute-deep-agent/__test-utils__/hitl-script.ts +1 -1
  376. package/src/activities/execute-deep-agent/__test-utils__/scripted-model-module.ts +2 -3
  377. package/src/activities/execute-deep-agent/__test-utils__/scripted-model.ts +25 -4
  378. package/src/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.ts +25 -11
  379. package/src/activities/execute-deep-agent/__tests__/adapter-graph-is-sdk-free.test.ts +1 -1
  380. package/src/activities/execute-deep-agent/__tests__/adapter-is-temporal-free.test.ts +1 -1
  381. package/src/activities/execute-deep-agent/__tests__/approval-file-change.test.ts +6 -17
  382. package/src/activities/execute-deep-agent/__tests__/hermetic/file-review-capture.test.ts +25 -8
  383. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve-all-lease.turn1.status.json +2 -7
  384. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve-all-lease.turn2.status.json +4 -14
  385. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve.turn2.status.json +1 -5
  386. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/file-review-capture.status.json +4 -7
  387. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/gate.turn1.status.json +1 -5
  388. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/inline-artifact.turn1.status.json +2 -9
  389. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/inline-artifact.turn2.status.json +2 -9
  390. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/pause.loop.after-tool.status.json +1 -4
  391. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/pause.loop.mid-tool.status.json +1 -4
  392. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/platform-stop.status.json +1 -4
  393. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/recursion-limit.persisted.status.json +109 -76
  394. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/reject.turn2.status.json +1 -5
  395. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sequential-gates.turn2.status.json +2 -10
  396. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sequential-gates.turn3.status.json +2 -10
  397. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/skip.turn2.status.json +1 -5
  398. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sub-agent-delegation.status.json +3 -6
  399. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/tool-call.status.json +1 -4
  400. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/worker-shutdown.status.json +1 -4
  401. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/write-todos.status.json +92 -0
  402. package/src/activities/execute-deep-agent/__tests__/hermetic/harness-contract.test.ts +3 -3
  403. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-approve-all-lease.test.ts +9 -5
  404. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-round-trips.test.ts +3 -3
  405. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-sequential-gates.test.ts +3 -3
  406. package/src/activities/execute-deep-agent/__tests__/hermetic/inline-artifact-across-gate.test.ts +7 -6
  407. package/src/activities/execute-deep-agent/__tests__/hermetic/pause-vs-shutdown.test.ts +10 -11
  408. package/src/activities/execute-deep-agent/__tests__/hermetic/plain-turn.test.ts +4 -4
  409. package/src/activities/execute-deep-agent/__tests__/hermetic/platform-stop.test.ts +9 -8
  410. package/src/activities/execute-deep-agent/__tests__/hermetic/recursion-limit.test.ts +21 -13
  411. package/src/activities/execute-deep-agent/__tests__/hermetic/resolution-error.test.ts +2 -2
  412. package/src/activities/execute-deep-agent/__tests__/hermetic/structured-output.test.ts +7 -7
  413. package/src/activities/execute-deep-agent/__tests__/hermetic/sub-agent-delegation.test.ts +28 -12
  414. package/src/activities/execute-deep-agent/__tests__/hermetic/tool-call.test.ts +21 -21
  415. package/src/activities/execute-deep-agent/__tests__/hermetic/workspace-lock-timeout.test.ts +5 -5
  416. package/src/activities/execute-deep-agent/__tests__/hermetic/write-todos.test.ts +160 -0
  417. package/src/activities/execute-deep-agent/__tests__/inline-publisher.test.ts +35 -30
  418. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +3 -4
  419. package/src/activities/execute-deep-agent/__tests__/prompt-goldens.test.ts +12 -10
  420. package/src/activities/execute-deep-agent/__tests__/scripted-model.test.ts +13 -3
  421. package/src/activities/execute-deep-agent/__tests__/streaming-side-effects.test.ts +26 -18
  422. package/src/activities/execute-deep-agent/__tests__/subagent-wiring.test.ts +1 -1
  423. package/src/activities/execute-deep-agent/__tests__/{subagent-tracker.test.ts → translator-subagents.test.ts} +76 -57
  424. package/src/activities/execute-deep-agent/__tests__/{v3-status-builder.test.ts → translator-through-builder.test.ts} +213 -299
  425. package/src/activities/execute-deep-agent/__tests__/translator.test.ts +505 -0
  426. package/src/activities/execute-deep-agent/__tests__/turn-stream.test.ts +11 -29
  427. package/src/activities/execute-deep-agent/adapter.ts +1 -1
  428. package/src/activities/execute-deep-agent/approval-file-change.ts +20 -22
  429. package/src/activities/execute-deep-agent/deep-agent-capabilities.ts +2 -2
  430. package/src/activities/execute-deep-agent/hitl.ts +2 -2
  431. package/src/activities/execute-deep-agent/inline-publisher.ts +16 -5
  432. package/src/activities/execute-deep-agent/prompt-builder.ts +6 -7
  433. package/src/activities/execute-deep-agent/streaming-side-effects.ts +22 -31
  434. package/src/activities/execute-deep-agent/subagent-transformer.ts +3 -3
  435. package/src/activities/execute-deep-agent/translator.ts +463 -0
  436. package/src/activities/execute-deep-agent/turn-settle.ts +35 -43
  437. package/src/activities/execute-deep-agent/turn-setup.ts +8 -8
  438. package/src/activities/execute-deep-agent/turn-stream.ts +53 -51
  439. package/src/activities/execute-deep-agent/turn.ts +3 -3
  440. package/src/activities/generate-session-subject.ts +29 -4
  441. package/src/client/__tests__/stigmer-client.test.ts +92 -0
  442. package/src/client/stigmer-client.ts +48 -14
  443. package/src/config.ts +6 -3
  444. package/src/harness/README.md +335 -0
  445. package/src/harness/__tests__/approval-decisions.test.ts +2 -2
  446. package/src/harness/__tests__/capture.test.ts +3 -3
  447. package/src/harness/__tests__/import-direction.test.ts +3 -2
  448. package/src/harness/__tests__/mount-skills.test.ts +4 -1
  449. package/src/harness/__tests__/readme-index.test.ts +339 -0
  450. package/src/harness/__tests__/run-turn.test.ts +131 -6
  451. package/src/harness/__tests__/transcript-is-engine-free.test.ts +83 -0
  452. package/src/harness/__tests__/transcript-writers.test.ts +191 -0
  453. package/src/harness/__tests__/turn-attachments-vision.test.ts +5 -2
  454. package/src/harness/__tests__/turn-context.test.ts +5 -5
  455. package/src/harness/approval-decisions.ts +1 -1
  456. package/src/harness/capabilities.ts +21 -11
  457. package/src/harness/capture.ts +4 -4
  458. package/src/harness/persist-chokepoint.ts +3 -3
  459. package/src/harness/registry.ts +2 -2
  460. package/src/harness/run-turn.ts +33 -9
  461. package/src/harness/stop-controller.ts +1 -1
  462. package/src/harness/terminal-table.ts +7 -7
  463. package/src/harness/transcript/__tests__/builder.test.ts +975 -0
  464. package/src/harness/transcript/__tests__/state.test.ts +143 -0
  465. package/src/harness/transcript/builder.ts +755 -0
  466. package/src/harness/transcript/events.ts +262 -0
  467. package/src/harness/transcript/state.ts +167 -0
  468. package/src/harness/turn-context.ts +61 -46
  469. package/src/harness/types.ts +64 -22
  470. package/src/harness/usage-accumulator.ts +2 -2
  471. package/src/harness-adapters.ts +5 -4
  472. package/src/interceptors/__tests__/run-credential-activity.test.ts +133 -0
  473. package/src/interceptors/run-credential-activity.ts +67 -0
  474. package/src/middleware/__tests__/cost-advisory.test.ts +2 -2
  475. package/src/middleware/approval-gate.ts +7 -74
  476. package/src/middleware/cost-advisory.ts +3 -3
  477. package/src/middleware/index.ts +1 -1
  478. package/src/runner-manager.ts +14 -4
  479. package/src/shared/__tests__/approval-policy.test.ts +45 -0
  480. package/src/shared/__tests__/args-preview.test.ts +40 -20
  481. package/src/shared/__tests__/attachment-naming.test.ts +1 -1
  482. package/src/shared/__tests__/attachment-resolver.test.ts +5 -5
  483. package/src/shared/__tests__/attachment-zip.test.ts +1 -1
  484. package/src/shared/__tests__/blueprint-resolver.test.ts +1 -1
  485. package/src/shared/__tests__/channel-attachment.test.ts +12 -0
  486. package/src/shared/__tests__/cost-guard.test.ts +1 -1
  487. package/src/shared/__tests__/exact-apply.test.ts +2 -1
  488. package/src/shared/__tests__/memory-attachment.test.ts +17 -0
  489. package/src/shared/__tests__/persist-decision.test.ts +19 -33
  490. package/src/shared/__tests__/prompt-sections.test.ts +1 -1
  491. package/src/shared/__tests__/run-credential.test.ts +111 -0
  492. package/src/shared/__tests__/stamp-flowed-rows.test.ts +1 -1
  493. package/src/shared/__tests__/status-offload.test.ts +1 -1
  494. package/src/shared/__tests__/streaming-scheduler.test.ts +8 -9
  495. package/src/shared/__tests__/todos.test.ts +1 -1
  496. package/src/shared/__tests__/tool-row.test.ts +1 -1
  497. package/src/shared/activity-input.ts +21 -0
  498. package/src/shared/approval-policy.ts +95 -0
  499. package/src/shared/args-preview.ts +51 -42
  500. package/src/shared/attachment-resolver.ts +4 -4
  501. package/src/shared/attachment-zip.ts +2 -2
  502. package/src/shared/channel-attachment.ts +14 -6
  503. package/src/shared/cost-guard.ts +2 -2
  504. package/src/shared/exact-apply.ts +1 -1
  505. package/src/shared/execution-context.ts +2 -2
  506. package/src/shared/extract-structured-output.ts +2 -2
  507. package/src/shared/filereview/__tests__/capture.test.ts +9 -5
  508. package/src/shared/filereview/__tests__/git-substrate.test.ts +4 -1
  509. package/src/shared/filereview/__tests__/proxy-reconcile.test.ts +3 -3
  510. package/src/shared/filereview/cas-touched.ts +2 -2
  511. package/src/shared/filereview/progress.ts +13 -0
  512. package/src/shared/heartbeat.ts +1 -1
  513. package/src/shared/llm-backend.ts +0 -4
  514. package/src/shared/memory-attachment.ts +22 -10
  515. package/src/shared/model-error.ts +1 -2
  516. package/src/shared/persist-decision.ts +19 -28
  517. package/src/shared/prompt-sections.ts +4 -4
  518. package/src/shared/run-credential-store.ts +45 -0
  519. package/src/shared/run-credential.ts +70 -0
  520. package/src/shared/skill-resolver.ts +3 -3
  521. package/src/shared/status-offload.ts +2 -2
  522. package/src/shared/streaming-scheduler.ts +8 -13
  523. package/src/shared/subagent-rows.ts +2 -2
  524. package/src/shared/synthesized-attachment.ts +38 -3
  525. package/src/shared/todos.ts +3 -3
  526. package/src/shared/tool-row.ts +38 -2
  527. package/src/shared/worker-shutdown.ts +1 -1
  528. package/src/shared/workspace/__tests__/git-source.test.ts +3 -3
  529. package/src/shared/workspace/__tests__/provisioner.test.ts +5 -5
  530. package/src/shared/workspace/__tests__/session-provision.test.ts +2 -2
  531. package/src/shared/workspace/__tests__/writeback-coordinator.integration.test.ts +8 -9
  532. package/src/shared/workspace/__tests__/writeback-coordinator.test.ts +25 -25
  533. package/src/shared/workspace/provisioner.ts +1 -1
  534. package/src/shared/workspace/session-provision.ts +1 -1
  535. package/src/shared/workspace/sources/empty.ts +2 -2
  536. package/src/shared/workspace/sources/git.ts +3 -4
  537. package/src/shared/workspace/sources/local-path.ts +5 -6
  538. package/src/shared/workspace/stigmer-link.ts +1 -1
  539. package/src/shared/workspace/types.ts +2 -5
  540. package/src/shared/workspace/writeback-coordinator.ts +23 -12
  541. package/src/worker.ts +15 -3
  542. package/src/workflow-source.ts +15 -0
  543. package/src/workflows/__tests__/run-credential-interceptor.test.ts +178 -0
  544. package/src/workflows/execute-from-execution.ts +17 -0
  545. package/src/workflows/index.ts +5 -3
  546. package/src/workflows/interceptors/run-credential.ts +101 -0
  547. package/dist/activities/execute-cursor/delta-enricher.d.ts +0 -87
  548. package/dist/activities/execute-cursor/delta-enricher.js +0 -265
  549. package/dist/activities/execute-cursor/delta-enricher.js.map +0 -1
  550. package/dist/activities/execute-cursor/message-translator.js +0 -2040
  551. package/dist/activities/execute-cursor/message-translator.js.map +0 -1
  552. package/dist/activities/execute-cursor/todo-tracker.d.ts +0 -40
  553. package/dist/activities/execute-cursor/todo-tracker.js +0 -80
  554. package/dist/activities/execute-cursor/todo-tracker.js.map +0 -1
  555. package/dist/activities/execute-deep-agent/execution-state.d.ts +0 -54
  556. package/dist/activities/execute-deep-agent/execution-state.js +0 -68
  557. package/dist/activities/execute-deep-agent/execution-state.js.map +0 -1
  558. package/dist/activities/execute-deep-agent/status-builder-shared.d.ts +0 -65
  559. package/dist/activities/execute-deep-agent/status-builder-shared.js +0 -90
  560. package/dist/activities/execute-deep-agent/status-builder-shared.js.map +0 -1
  561. package/dist/activities/execute-deep-agent/subagent-tracker.d.ts +0 -113
  562. package/dist/activities/execute-deep-agent/subagent-tracker.js +0 -400
  563. package/dist/activities/execute-deep-agent/subagent-tracker.js.map +0 -1
  564. package/dist/activities/execute-deep-agent/v3-events.d.ts +0 -102
  565. package/dist/activities/execute-deep-agent/v3-events.js +0 -35
  566. package/dist/activities/execute-deep-agent/v3-events.js.map +0 -1
  567. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.d.ts +0 -15
  568. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.js +0 -235
  569. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.js.map +0 -1
  570. package/dist/activities/execute-deep-agent/v3-status-builder.d.ts +0 -111
  571. package/dist/activities/execute-deep-agent/v3-status-builder.js +0 -457
  572. package/dist/activities/execute-deep-agent/v3-status-builder.js.map +0 -1
  573. package/dist/shared/execution-status-writer.d.ts +0 -31
  574. package/dist/shared/execution-status-writer.js +0 -43
  575. package/dist/shared/execution-status-writer.js.map +0 -1
  576. package/src/activities/execute-cursor/__tests__/delta-enricher.test.ts +0 -310
  577. package/src/activities/execute-cursor/__tests__/message-translator.test.ts +0 -1033
  578. package/src/activities/execute-cursor/__tests__/todo-tracker.test.ts +0 -498
  579. package/src/activities/execute-cursor/delta-enricher.ts +0 -307
  580. package/src/activities/execute-cursor/message-translator.ts +0 -2319
  581. package/src/activities/execute-cursor/todo-tracker.ts +0 -91
  582. package/src/activities/execute-deep-agent/__tests__/execution-state-extended.test.ts +0 -148
  583. package/src/activities/execute-deep-agent/__tests__/execution-state.test.ts +0 -154
  584. package/src/activities/execute-deep-agent/__tests__/status-builder-shared.test.ts +0 -47
  585. package/src/activities/execute-deep-agent/__tests__/v3-protocol-normalizer.test.ts +0 -324
  586. package/src/activities/execute-deep-agent/execution-state.ts +0 -78
  587. package/src/activities/execute-deep-agent/status-builder-shared.ts +0 -142
  588. package/src/activities/execute-deep-agent/subagent-tracker.ts +0 -479
  589. package/src/activities/execute-deep-agent/v3-events.ts +0 -153
  590. package/src/activities/execute-deep-agent/v3-protocol-normalizer.ts +0 -264
  591. package/src/activities/execute-deep-agent/v3-status-builder.ts +0 -565
  592. package/src/shared/execution-status-writer.ts +0 -56
@@ -1,2040 +0,0 @@
1
- /**
2
- * Translates Cursor SDK streaming events into Stigmer AgentMessage protos.
3
- *
4
- * The Cursor SDK emits SDKMessage events during a Run. This module provides
5
- * both stateless translation (translateEvent) and stateful accumulation
6
- * (MessageAccumulator) for building coherent messages from token-level
7
- * streaming events.
8
- *
9
- * The Cursor SDK emits one SDKAssistantMessage per token chunk — a single
10
- * LLM turn produces dozens of events. MessageAccumulator merges them into
11
- * a single AgentMessage per turn, matching the Python agent-runner's
12
- * proven pattern (see chat_model.py handle_chat_model_stream).
13
- *
14
- * Tool calls are attached to the most recent MESSAGE_AI message rather
15
- * than emitted as standalone MESSAGE_TOOL messages. This matches:
16
- * - The proto model (AgentMessage.tool_calls repeated field)
17
- * - The Python agent-runner's StatusBuilder pattern
18
- * - The UI's MessageThread expectation (tool calls on AI messages)
19
- *
20
- * Task (sub-agent) tool calls additionally produce SubAgentExecution
21
- * protos accessible via MessageAccumulator.subAgentExecutions.
22
- *
23
- * MCP tool enrichment:
24
- * Cursor reports MCP tool calls with name="mcp" and the actual details
25
- * (providerIdentifier, toolName, args) inside event.args. This module
26
- * extracts those details to populate the ToolCall proto with:
27
- * - name: the actual MCP tool name (e.g., "search_services")
28
- * - mcpServerSlug: the MCP server identifier (e.g., "planton")
29
- * - requiresApproval: from the merged policy chain
30
- * - approvalMessage: from the policy, with placeholder resolution
31
- */
32
- import { create } from "@bufbuild/protobuf";
33
- import { AgentMessageSchema, ToolCallSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/message_pb";
34
- import { SubAgentExecutionSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/subagent_pb";
35
- import { ApprovalAction, ApprovalPolicySource, MessageType, ToolCallStatus, SubAgentStatus } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
36
- import { lookupMcpToolPolicy, resolveApprovalMessage, builtInRequiresApproval, getBuiltInApprovalMessage, SALIENT_ARG_FIELDS } from "./approval-policy.js";
37
- import { POLICY_ENGINE_VERSION, resolveApprovalProvenance, toProtoPolicySource, unattendedSkipMessage, } from "../../shared/approval-policy.js";
38
- import { approvalDenials, denialKindOf, grantToken, primaryToken, toolIdentity, } from "./approval-state.js";
39
- import { utcTimestamp } from "../../shared/status.js";
40
- import { cancelInProgressSubAgentProtos } from "../../shared/subagent-rows.js";
41
- import { hideToolCallRow, isToolCallRowHidden } from "../../shared/tool-row.js";
42
- import { classifyTool, toolApprovalCategory } from "../../shared/tool-kind.js";
43
- import { resolveWorkspacePath } from "../../shared/file-change.js";
44
- import { contentDigest, extractFilePath } from "../../shared/file-tools.js";
45
- import { isSecretLikePath } from "../../shared/filereview/secret-paths.js";
46
- import { buildElidedArgsPreview } from "../../shared/args-preview.js";
47
- export { utcTimestamp };
48
- const SUPPRESSED_TOOL_NAMES = new Set(["TodoWrite", "updateTodos"]);
49
- /**
50
- * Try to extract MCP tool details from a tool_call event.
51
- * Returns undefined if the event is not an MCP tool call.
52
- */
53
- export function extractMcpToolDetails(event) {
54
- if (event.name !== "mcp")
55
- return undefined;
56
- const args = event.args;
57
- if (args == null || typeof args !== "object")
58
- return undefined;
59
- const obj = args;
60
- const providerIdentifier = typeof obj.providerIdentifier === "string" ? obj.providerIdentifier : "";
61
- const toolName = typeof obj.toolName === "string" ? obj.toolName : "";
62
- if (!toolName)
63
- return undefined;
64
- const innerArgs = (typeof obj.args === "object" && obj.args !== null)
65
- ? obj.args
66
- : {};
67
- return { providerIdentifier, toolName, innerArgs };
68
- }
69
- /**
70
- * Translate a single Cursor SDKMessage into zero or more Stigmer AgentMessages.
71
- *
72
- * Most events produce exactly one message. Some (like system init) are
73
- * informational and produce none.
74
- *
75
- * Note: for production streaming, use MessageAccumulator instead — it
76
- * merges token-level events and attaches tool calls to their parent AI
77
- * messages. This stateless function is retained for unit testing and
78
- * simple single-event translation.
79
- */
80
- export function translateEvent(event) {
81
- switch (event.type) {
82
- case "assistant":
83
- return [translateAssistant(event)];
84
- case "thinking":
85
- return [translateThinking(event)];
86
- case "tool_call":
87
- return [translateToolCall(event)];
88
- case "task":
89
- return event.text ? [translateTask(event)] : [];
90
- case "system":
91
- case "status":
92
- case "user":
93
- case "request":
94
- return [];
95
- default:
96
- return [];
97
- }
98
- }
99
- function translateAssistant(event) {
100
- const textBlocks = event.message.content
101
- .filter((b) => b.type === "text")
102
- .map((b) => b.text);
103
- return create(AgentMessageSchema, {
104
- type: MessageType.MESSAGE_AI,
105
- content: textBlocks.join(""),
106
- timestamp: utcTimestamp(),
107
- });
108
- }
109
- function translateThinking(event) {
110
- return create(AgentMessageSchema, {
111
- type: MessageType.MESSAGE_THINKING,
112
- content: event.text,
113
- timestamp: utcTimestamp(),
114
- });
115
- }
116
- /**
117
- * Stateless translation of a tool_call event into a standalone MESSAGE_TOOL
118
- * message. Retained for backward compatibility with translateEvent() and
119
- * tests that use the stateless API.
120
- */
121
- function translateToolCall(event) {
122
- const toolCall = buildToolCallProto(event);
123
- const displayName = toolCall.mcpServerSlug
124
- ? `${toolCall.mcpServerSlug}/${toolCall.name}`
125
- : toolCall.name;
126
- return create(AgentMessageSchema, {
127
- type: MessageType.MESSAGE_TOOL,
128
- content: `Tool: ${displayName} [${event.status}]`,
129
- timestamp: utcTimestamp(),
130
- toolCalls: [toolCall],
131
- });
132
- }
133
- /**
134
- * Build a ToolCall proto from a Cursor SDK tool_call event.
135
- *
136
- * For MCP tools (event.name === "mcp"), extracts the actual tool name
137
- * and server slug from event.args. For built-in tools, uses the event
138
- * name directly.
139
- *
140
- * Approval fields are populated when mergedPolicies are provided.
141
- * Without policies, only basic fields are set (backward compatible).
142
- *
143
- * When mergedPolicies are provided, the tool call also carries its authorization
144
- * provenance (approval_policy_source) — which policy layer gated or cleared it —
145
- * derived from the same merged policy chain the gate uses, so the Cursor
146
- * reconstruction is as auditable as the native harness. `provenance` supplies the
147
- * run-scoped context (global bypass, active leases) the per-tool map cannot.
148
- */
149
- export function buildToolCallProto(event, mergedPolicies, provenance) {
150
- const status = mapToolCallStatus(event.status);
151
- const mcpDetails = extractMcpToolDetails(event);
152
- const actualName = mcpDetails?.toolName ?? event.name;
153
- const mcpServerSlug = mcpDetails?.providerIdentifier ?? "";
154
- const toolCall = create(ToolCallSchema, {
155
- id: event.call_id,
156
- name: actualName,
157
- status,
158
- startedAt: status === ToolCallStatus.TOOL_CALL_RUNNING ? utcTimestamp() : "",
159
- completedAt: isTerminalToolStatus(status) ? utcTimestamp() : "",
160
- result: toResultString(event.result),
161
- error: status === ToolCallStatus.TOOL_CALL_FAILED
162
- ? (typeof event.result === "string" ? event.result : "Tool call failed")
163
- : "",
164
- mcpServerSlug,
165
- toolKind: classifyTool(actualName, mcpServerSlug),
166
- });
167
- if (event.args != null) {
168
- toolCall.argsPreview = typeof event.args === "string"
169
- ? event.args
170
- : JSON.stringify(event.args);
171
- }
172
- const argsObj = mcpDetails?.innerArgs ?? (typeof event.args === "object" && event.args !== null
173
- ? event.args
174
- : undefined);
175
- if (argsObj && typeof argsObj === "object") {
176
- toolCall.args = argsObj;
177
- }
178
- // Populate approval fields from the merged policy chain
179
- if (mergedPolicies && mcpDetails) {
180
- const policy = lookupMcpToolPolicy(actualName, mcpServerSlug, mergedPolicies);
181
- if (policy) {
182
- toolCall.requiresApproval = true;
183
- toolCall.approvalMessage = resolveApprovalMessage(policy.approvalMessage, actualName, mcpDetails.innerArgs);
184
- if (status === ToolCallStatus.TOOL_CALL_FAILED) {
185
- toolCall.approvalRequestedAt = utcTimestamp();
186
- }
187
- }
188
- }
189
- else if (mergedPolicies && !mcpDetails) {
190
- const requires = builtInRequiresApproval(actualName);
191
- toolCall.requiresApproval = requires;
192
- if (requires) {
193
- const template = getBuiltInApprovalMessage(actualName);
194
- if (template) {
195
- toolCall.approvalMessage = resolveApprovalMessage(template, actualName, argsObj ?? {});
196
- if (status === ToolCallStatus.TOOL_CALL_FAILED) {
197
- toolCall.approvalRequestedAt = utcTimestamp();
198
- }
199
- }
200
- }
201
- }
202
- // Stamp authorization provenance from the same merged policy chain the gate
203
- // (the deny-oracle hook + this map) uses, so the persisted record explains WHY
204
- // each tool was gated or cleared. Only when policies are present — the stateless
205
- // path leaves it UNSPECIFIED, like an unclassified tool_kind.
206
- if (mergedPolicies) {
207
- const source = resolveApprovalProvenance(actualName, mcpServerSlug, mergedPolicies, provenance?.leasedCategories ?? NO_LEASED_CATEGORIES, provenance?.globalBypass ?? false);
208
- toolCall.approvalPolicySource = toProtoPolicySource(source);
209
- if (source)
210
- toolCall.policyEngineVersion = POLICY_ENGINE_VERSION;
211
- }
212
- return toolCall;
213
- }
214
- /** Shared empty set so a reconstruction without leases allocates nothing. */
215
- const NO_LEASED_CATEGORIES = new Set();
216
- function translateTask(event) {
217
- return create(AgentMessageSchema, {
218
- type: MessageType.MESSAGE_SYSTEM,
219
- content: event.text ?? "",
220
- timestamp: utcTimestamp(),
221
- });
222
- }
223
- function mapToolCallStatus(cursorStatus) {
224
- switch (cursorStatus) {
225
- case "running":
226
- return ToolCallStatus.TOOL_CALL_RUNNING;
227
- case "completed":
228
- return ToolCallStatus.TOOL_CALL_COMPLETED;
229
- case "error":
230
- return ToolCallStatus.TOOL_CALL_FAILED;
231
- default:
232
- return ToolCallStatus.TOOL_CALL_STATUS_UNSPECIFIED;
233
- }
234
- }
235
- function mapSubAgentStatus(cursorStatus) {
236
- switch (cursorStatus) {
237
- case "running":
238
- return SubAgentStatus.SUB_AGENT_IN_PROGRESS;
239
- case "completed":
240
- return SubAgentStatus.SUB_AGENT_COMPLETED;
241
- case "error":
242
- return SubAgentStatus.SUB_AGENT_FAILED;
243
- default:
244
- return SubAgentStatus.SUB_AGENT_PENDING;
245
- }
246
- }
247
- /**
248
- * Terminal for the MONOTONIC status guard in {@link mergeToolCallEvent}: once a
249
- * row reaches one of these, a later event re-emit must not regress it.
250
- *
251
- * TOOL_CALL_INTERRUPTED is deliberately NOT here, even though it is terminal
252
- * everywhere else (server, clients, provenance scoping — see the shared
253
- * TERMINAL_TOOL_CALL_STATUSES in tool-row.ts). INTERRUPTED is server-authored
254
- * when an execution terminalizes with the call in flight; if that FAILED
255
- * execution is later RECOVERED, the harness checkpoint can re-execute the call
256
- * under its original call id — and live execution evidence outranks the
257
- * interruption marker, so the replayed event must advance the row to its true
258
- * outcome (the enum's documented recovery supersede rule).
259
- */
260
- function isTerminalToolStatus(status) {
261
- return (status === ToolCallStatus.TOOL_CALL_COMPLETED ||
262
- status === ToolCallStatus.TOOL_CALL_FAILED ||
263
- status === ToolCallStatus.TOOL_CALL_SKIPPED);
264
- }
265
- /**
266
- * Extract sub-agent name from task tool args, handling both the
267
- * legacy string format (`"generalPurpose"`) and the current SDK
268
- * object format (`{ kind: "generalPurpose", name?: "..." }`).
269
- *
270
- * Falls back to `description` (always populated by the SDK) before
271
- * returning the generic `"task"`. The `kind` value `"unspecified"`
272
- * is treated as absent since the Cursor SDK uses it as a default
273
- * when the sub-agent type is not specified in the blueprint.
274
- */
275
- function extractSubagentName(args) {
276
- if (args == null || typeof args !== "object")
277
- return "task";
278
- const obj = args;
279
- const subagentType = obj.subagentType ?? obj.subagent_type;
280
- if (typeof subagentType === "string" && subagentType)
281
- return subagentType;
282
- if (subagentType != null && typeof subagentType === "object") {
283
- const typed = subagentType;
284
- if (typeof typed.name === "string" && typed.name)
285
- return typed.name;
286
- if (typeof typed.kind === "string" && typed.kind && typed.kind !== "unspecified") {
287
- return typed.kind;
288
- }
289
- }
290
- if (typeof obj.description === "string" && obj.description)
291
- return obj.description;
292
- return "task";
293
- }
294
- function safeString(obj, key) {
295
- if (obj != null && typeof obj === "object" && key in obj) {
296
- const val = obj[key];
297
- return typeof val === "string" ? val : "";
298
- }
299
- return "";
300
- }
301
- /**
302
- * Normalize a tool_call event result into a string for the ToolCall proto.
303
- * Returns "" for an absent result so callers can treat "no result yet" and
304
- * "empty result" uniformly (e.g. to avoid clobbering a captured result).
305
- *
306
- * The one non-passthrough case is a multimodal MCP result (e.g. a computer-use
307
- * screenshot): see {@link canonicalizeImageResult}. Everything else is the
308
- * string as-is, or a whole-value JSON.stringify — byte-identical to before.
309
- */
310
- export function toResultString(result) {
311
- if (result == null)
312
- return "";
313
- if (typeof result === "string")
314
- return result;
315
- const canonical = canonicalizeImageResult(result);
316
- if (canonical !== undefined)
317
- return canonical;
318
- return JSON.stringify(result);
319
- }
320
- /**
321
- * Re-emit a Cursor MCP result that carries an image block as the canonical
322
- * top-level content-block array the persist-time offload understands.
323
- *
324
- * The Cursor SDK wraps an MCP tool result as `{ status, value: { content: [...] } }`
325
- * (or a bare `{ content: [...] }`), where an image block is
326
- * `{ image: { data, mimeType } }` and `data` is a Node Buffer-JSON
327
- * (`{ type:"Buffer", data:number[] }`). Persisting that envelope verbatim buries
328
- * the image where `detectImagePayload`/`contentBlocks` (shared/status-offload.ts)
329
- * cannot see it, so the screenshot lands as `text/plain` instead of a renderable
330
- * `ToolCallOutputRef`.
331
- *
332
- * This mirrors `serializeToolContent` in the deep-agent path
333
- * (execute-deep-agent/status-builder-shared.ts): the harness adapter normalizes
334
- * its own wire shape into the canonical array
335
- * `[{ type:"text", text }, { type:"image", data:<base64>, mimeType }]`
336
- * so the shared offload stays harness-agnostic (its envelope handling is
337
- * documented there as insurance, not the primary path). Buffer-JSON is decoded
338
- * to base64 here so the bloated byte-array never propagates into the status.
339
- *
340
- * Returns undefined when there is no content array or no image block, so the
341
- * caller falls back to its existing serialization (no change for text/error
342
- * results).
343
- */
344
- export function canonicalizeImageResult(result) {
345
- if (result == null || typeof result !== "object")
346
- return undefined;
347
- const blocks = resultContentBlocks(result);
348
- if (!blocks)
349
- return undefined;
350
- const canonical = [];
351
- let sawImage = false;
352
- for (const block of blocks) {
353
- if (!block || typeof block !== "object")
354
- continue;
355
- const b = block;
356
- if (b.image && typeof b.image === "object") {
357
- const img = b.image;
358
- const base64 = imageDataToBase64(img.data);
359
- if (base64) {
360
- const mimeType = typeof img.mimeType === "string" ? img.mimeType : "image/png";
361
- canonical.push({ type: "image", data: base64, mimeType });
362
- sawImage = true;
363
- continue;
364
- }
365
- }
366
- const text = blockText(b);
367
- if (text !== undefined)
368
- canonical.push({ type: "text", text });
369
- }
370
- return sawImage ? JSON.stringify(canonical) : undefined;
371
- }
372
- /** Extract the content-block array from a Cursor result envelope or a bare one. */
373
- function resultContentBlocks(obj) {
374
- const value = obj.value;
375
- if (value && typeof value === "object" && Array.isArray(value.content)) {
376
- return value.content;
377
- }
378
- if (Array.isArray(obj.content))
379
- return obj.content;
380
- return undefined;
381
- }
382
- /**
383
- * Decode an image block's `data` to plain base64. Accepts a Node Buffer-JSON
384
- * (`{ type:"Buffer", data:number[] }`, how the Cursor SDK serializes bytes), a
385
- * `data:` URL, or an already-base64 string. Returns undefined for anything else.
386
- */
387
- function imageDataToBase64(data) {
388
- if (data && typeof data === "object") {
389
- const d = data;
390
- if (d.type === "Buffer" && Array.isArray(d.data)) {
391
- try {
392
- return Buffer.from(d.data).toString("base64");
393
- }
394
- catch {
395
- return undefined;
396
- }
397
- }
398
- return undefined;
399
- }
400
- if (typeof data === "string" && data) {
401
- const dataUrl = data.match(/^data:image\/[a-zA-Z0-9.+-]+;base64,([\s\S]+)$/);
402
- return (dataUrl ? dataUrl[1] : data).replace(/\s+/g, "");
403
- }
404
- return undefined;
405
- }
406
- /** Extract the text from a Cursor content block: `{ text:{text} }` or `{ text }`. */
407
- function blockText(b) {
408
- const t = b.text;
409
- if (typeof t === "string")
410
- return t;
411
- if (t && typeof t === "object" && typeof t.text === "string") {
412
- return t.text;
413
- }
414
- return undefined;
415
- }
416
- /**
417
- * Parse the task tool's completed result into AgentMessages.
418
- *
419
- * The Cursor SDK returns sub-agent work as a blob in the task tool's
420
- * completed event (not as streaming events with a distinct agent_id).
421
- * Re-verified 2026-08-23 on the pinned SDK (1.0.13) AND the latest (1.0.28),
422
- * this time including the write side (stigmer/stigmer#839): an injected
423
- * platform.eventStore/eventNotifier receives parent events only on 1.0.13 and
424
- * is bypassed entirely on 1.0.28 (persistence moved into the executor daemon's
425
- * own state dir); zero events reach the parent's run.stream() mid-task; the
426
- * agentId in the task args is not a platform-store agent id at all, so it can
427
- * never be addressable via Agent.listRuns / Agent.getRun (this is WHY the
428
- * 2026-07-02 read-side polls all returned not-found). On 1.0.28 the child
429
- * transcript lands at a deterministic path knowable at spawn
430
- * (~/.cursor/projects/<slug>/agent-transcripts/<parentId>/subagents/<argsAgentId>.jsonl)
431
- * but is flushed only at completion — verified with 200ms sampling across a
432
- * full sub-agent run. Live nested visibility is therefore still an upstream
433
- * SDK limitation — do not try to fake it here; the UI shows an elapsed-time
434
- * affordance instead (SubAgentSection). Probe scripts and recordings:
435
- * stigmer-cloud _projects/2026-08/20260823.03.cursor-subagent-live-progress.
436
- * The result shape is:
437
- *
438
- * { status: "success", value: { conversationSteps: ConversationStep[] } }
439
- *
440
- * where each ConversationStep is a protobuf-oneof object keyed DIRECTLY by its
441
- * kind (there is NO `{ type, message }` envelope — verified against production
442
- * sub-agent blobs; see the `buildSubAgentToolCall` note):
443
- * - { thinkingMessage: { text, thinkingDurationMs? } }
444
- * - { assistantMessage: { text } }
445
- * - { toolCall: { toolCallId, <kind>ToolCall: { args, result } } }
446
- *
447
- * This function defensively parses whatever steps are present and
448
- * appends corresponding AgentMessage protos to the output array.
449
- * Unknown step types are silently skipped for forward compatibility.
450
- */
451
- export function extractConversationSteps(result, out) {
452
- if (result == null || typeof result !== "object")
453
- return;
454
- const r = result;
455
- const value = r.value ?? r;
456
- if (value == null || typeof value !== "object")
457
- return;
458
- const v = value;
459
- const steps = v.conversationSteps;
460
- if (!Array.isArray(steps))
461
- return;
462
- for (const step of steps) {
463
- if (step == null || typeof step !== "object")
464
- continue;
465
- const s = step;
466
- const type = s.type;
467
- if (type === "thinkingMessage" || s.thinkingMessage != null) {
468
- const msg = (type === "thinkingMessage" ? s.message : s.thinkingMessage);
469
- const text = typeof msg?.text === "string" ? msg.text : "";
470
- if (text) {
471
- out.push(create(AgentMessageSchema, {
472
- type: MessageType.MESSAGE_THINKING,
473
- content: text,
474
- timestamp: utcTimestamp(),
475
- }));
476
- }
477
- }
478
- else if (type === "assistantMessage" || s.assistantMessage != null) {
479
- const msg = (type === "assistantMessage" ? s.message : s.assistantMessage);
480
- const text = typeof msg?.text === "string" ? msg.text : "";
481
- if (text) {
482
- out.push(create(AgentMessageSchema, {
483
- type: MessageType.MESSAGE_AI,
484
- content: text,
485
- timestamp: utcTimestamp(),
486
- }));
487
- }
488
- }
489
- else if (s.toolCall != null) {
490
- const tc = buildSubAgentToolCall(s.toolCall, out.length);
491
- if (tc) {
492
- out.push(create(AgentMessageSchema, {
493
- type: MessageType.MESSAGE_AI,
494
- content: "",
495
- timestamp: utcTimestamp(),
496
- toolCalls: [tc],
497
- }));
498
- }
499
- }
500
- }
501
- }
502
- /**
503
- * The failure branches of a sub-agent tool call's `result` oneof. A completion
504
- * is `{ success: ... }`; every other branch is a non-completion the UI must show
505
- * as failed — an errored read/glob/grep (`error`), or a shell the approval gate
506
- * stopped (`permissionDenied` / `rejected`).
507
- */
508
- const SUBAGENT_TOOL_RESULT_FAILURE_KEYS = new Set([
509
- "error",
510
- "permissionDenied",
511
- "rejected",
512
- ]);
513
- /**
514
- * Build a ToolCall proto from one sub-agent `toolCall` conversation step.
515
- *
516
- * The Cursor SDK serializes a sub-agent's tool call as protobuf-oneof JSON:
517
- *
518
- * { toolCallId, <kind>ToolCall: { args, result } }
519
- *
520
- * The tool family is the lone `<kind>ToolCall` sibling of `toolCallId` (e.g.
521
- * `readToolCall`, `globToolCall`, `grepToolCall`, `shellToolCall`); the bare
522
- * tool name (`read`) is the suffix-stripped key, which feeds the shared
523
- * {@link classifyTool} exactly like a top-level call. `result` is itself a oneof
524
- * `{ success | error | permissionDenied | rejected }` (see
525
- * {@link interpretSubAgentToolResult}).
526
- *
527
- * This is deliberately key-driven rather than an enumerated switch, so a new
528
- * tool family the SDK adds surfaces automatically instead of being dropped.
529
- * Returns undefined when no `<kind>ToolCall` key is present (a malformed or
530
- * forward-incompatible step), so the caller skips it rather than emitting a
531
- * blank, nameless tool call.
532
- *
533
- * History: an earlier revision parsed a `{ type: "toolCall", message: { type,
534
- * args, result: { status, value } } }` envelope. That shape never appears in the
535
- * real task-result blob (confirmed against production sub-agent outputs and the
536
- * WA03 capture), so every sub-agent tool call was silently discarded and the UI
537
- * showed a sub-agent that "did nothing".
538
- */
539
- function buildSubAgentToolCall(toolCall, seq) {
540
- if (toolCall == null || typeof toolCall !== "object")
541
- return undefined;
542
- const obj = toolCall;
543
- const kindKey = Object.keys(obj).find((k) => k !== "toolCallId" && k.endsWith("ToolCall"));
544
- if (!kindKey)
545
- return undefined;
546
- const name = kindKey.slice(0, -"ToolCall".length);
547
- const inner = obj[kindKey] != null && typeof obj[kindKey] === "object"
548
- ? obj[kindKey]
549
- : {};
550
- // Prefer the SDK's real call id so the row is stable across resumes and never
551
- // collides with a sibling; fall back to a per-step synthetic id only when the
552
- // SDK omits one.
553
- const id = typeof obj.toolCallId === "string" && obj.toolCallId
554
- ? obj.toolCallId
555
- : `sub-${name}-${seq}`;
556
- const { status, result, error } = interpretSubAgentToolResult(inner.result);
557
- const tc = create(ToolCallSchema, {
558
- id,
559
- name,
560
- status,
561
- result,
562
- error,
563
- startedAt: utcTimestamp(),
564
- completedAt: utcTimestamp(),
565
- toolKind: classifyTool(name),
566
- });
567
- if (inner.args != null && typeof inner.args === "object") {
568
- tc.args = inner.args;
569
- tc.argsPreview = JSON.stringify(inner.args);
570
- }
571
- return tc;
572
- }
573
- /**
574
- * Map a sub-agent tool call's `result` oneof to a (status, result, error)
575
- * triple. `success` → COMPLETED with the serialized payload (a screenshot is
576
- * canonicalized the same way as a top-level result); any failure branch (see
577
- * {@link SUBAGENT_TOOL_RESULT_FAILURE_KEYS}) → FAILED with the serialized
578
- * detail. An absent result is a COMPLETED call with no output — the SDK omits
579
- * `result` for a call that reports nothing.
580
- */
581
- function interpretSubAgentToolResult(result) {
582
- if (result == null || typeof result !== "object") {
583
- return { status: ToolCallStatus.TOOL_CALL_COMPLETED, result: "", error: "" };
584
- }
585
- const r = result;
586
- if ("success" in r) {
587
- const val = r.success;
588
- const str = canonicalizeImageResult(val) ??
589
- (typeof val === "string" ? val : JSON.stringify(val));
590
- return { status: ToolCallStatus.TOOL_CALL_COMPLETED, result: str, error: "" };
591
- }
592
- const failKey = Object.keys(r).find((k) => SUBAGENT_TOOL_RESULT_FAILURE_KEYS.has(k));
593
- if (failKey) {
594
- const val = r[failKey];
595
- const detail = typeof val === "string" ? val : JSON.stringify(val);
596
- return { status: ToolCallStatus.TOOL_CALL_FAILED, result: "", error: detail };
597
- }
598
- // Unknown oneof branch — surface it as a completed result rather than drop it.
599
- return {
600
- status: ToolCallStatus.TOOL_CALL_COMPLETED,
601
- result: JSON.stringify(r),
602
- error: "",
603
- };
604
- }
605
- /**
606
- * Stateful accumulator that merges per-token SDK events into coherent
607
- * AgentMessages.
608
- *
609
- * The Cursor SDK emits one `assistant` event per token chunk (validated:
610
- * a 2-sentence response produces ~41 events). Without accumulation each
611
- * chunk becomes a separate AgentMessage, causing the UI to render each
612
- * word on its own line.
613
- *
614
- * MessageAccumulator tracks the active AI and thinking messages per
615
- * run_id. Consecutive assistant events for the same run_id append to
616
- * the existing message's content instead of creating new ones.
617
- *
618
- * Tool calls are attached to the most recent MESSAGE_AI message's
619
- * toolCalls array — matching the Python agent-runner's StatusBuilder
620
- * pattern and the UI's MessageThread expectations.
621
- *
622
- * Tool call lifecycle is tracked via a `toolCallIndex` map (keyed by
623
- * call_id), mirroring the native harness's `ExecutionState.toolCalls`.
624
- * This ensures completion events always find the correct ToolCall proto
625
- * regardless of which AI message it was originally attached to — the
626
- * index stores the same object reference that lives in the message's
627
- * `toolCalls[]` array, so mutations propagate directly to the proto.
628
- *
629
- * Task (sub-agent) tool calls additionally produce SubAgentExecution
630
- * protos, accessible via the subAgentExecutions getter.
631
- */
632
- export class MessageAccumulator {
633
- messages;
634
- activeAiByRunId = new Map();
635
- activeThinkingByRunId = new Map();
636
- _subAgentExecutions;
637
- subAgentMap = new Map();
638
- mergedPolicies;
639
- provenance;
640
- workspaceRoot;
641
- toolCallIndex = new Map();
642
- _dirty = false;
643
- constructor(messages, options) {
644
- this.messages = messages;
645
- this._subAgentExecutions = options?.subAgentExecutions ?? [];
646
- this.mergedPolicies = options?.mergedPolicies;
647
- this.provenance = options?.provenance;
648
- this.workspaceRoot = options?.workspaceRoot;
649
- // Resume seeding. When constructed over a pre-seeded status (the runtime's
650
- // `seedFromPersistedStatus` on a resume), rebuild the by-id indexes so a
651
- // cross-message completion for a seeded call resolves onto the existing
652
- // proto and a resumed sub-agent's lifecycle updates merge onto its seeded
653
- // row. A first run carries an empty status, so both are no-ops.
654
- this.rebuildToolCallIndex();
655
- this.rebuildSubAgentIndex();
656
- }
657
- /** Index every sub-agent row already present in the (seeded) array by its id, so upserts land on it. */
658
- rebuildSubAgentIndex() {
659
- for (const sub of this._subAgentExecutions) {
660
- if (sub.id)
661
- this.subAgentMap.set(sub.id, sub);
662
- }
663
- }
664
- /**
665
- * Index every tool call already present in the (seeded) transcript by its
666
- * call_id. Called once at construction: on a first run the transcript is empty
667
- * (no-op); on a resume it lets re-emitted lifecycle events for a previously
668
- * committed call_id reconcile onto the existing proto instead of duplicating.
669
- */
670
- rebuildToolCallIndex() {
671
- this.toolCallIndex.clear();
672
- for (const message of this.messages) {
673
- for (const tc of message.toolCalls) {
674
- if (tc.id)
675
- this.toolCallIndex.set(tc.id, tc);
676
- }
677
- }
678
- }
679
- get subAgentExecutions() {
680
- return this._subAgentExecutions;
681
- }
682
- /**
683
- * True when a discrete, user-visible state change has accumulated since the
684
- * last markPersisted(): a tool call created or transitioned to a terminal
685
- * status, or a sub-agent execution created or updated. The streaming loop
686
- * treats this as a force-flush signal so the live UI surfaces a tool call the
687
- * instant it starts and completes, and a sub-agent's IN_PROGRESS state the
688
- * instant delegation begins — instead of waiting for the scheduler's time
689
- * cadence or the parent finalizing.
690
- *
691
- * High-frequency token deltas (assistant text, model thinking) deliberately do
692
- * NOT set this flag; they ride the StreamingUpdateScheduler's time cadence so
693
- * we avoid a per-token persist storm — matching the native harness, which only
694
- * force-flushes on discrete tool start/end events.
695
- */
696
- get isDirty() {
697
- return this._dirty;
698
- }
699
- /** Clears the dirty flag after the latest status has been persisted. */
700
- markPersisted() {
701
- this._dirty = false;
702
- }
703
- /**
704
- * Transition any non-terminal sub-agent (IN_PROGRESS or PENDING) to CANCELLED.
705
- *
706
- * Called when the parent run is aborted (pause / cancel / worker shutdown):
707
- * the Cursor SDK run stops, so a delegated sub-agent is no longer executing.
708
- * Without this, the final snapshot would show a permanent "Running" zombie
709
- * sub-agent. Mirrors the native harness's cancelSubAgents().
710
- */
711
- cancelInProgressSubAgents() {
712
- if (cancelInProgressSubAgentProtos(this._subAgentExecutions)) {
713
- this._dirty = true;
714
- }
715
- }
716
- processEvent(event) {
717
- switch (event.type) {
718
- case "assistant":
719
- this.accumulateAssistant(event);
720
- break;
721
- case "thinking":
722
- this.accumulateThinking(event);
723
- break;
724
- case "tool_call":
725
- this.finalizeStreaming(event.run_id);
726
- this.attachToolCallToLastAi(event);
727
- break;
728
- case "task":
729
- if (event.text) {
730
- this.messages.push(translateTask(event));
731
- }
732
- break;
733
- }
734
- }
735
- finalize() {
736
- for (const msg of this.activeAiByRunId.values()) {
737
- msg.isStreaming = false;
738
- }
739
- for (const msg of this.activeThinkingByRunId.values()) {
740
- msg.isStreaming = false;
741
- }
742
- this.activeAiByRunId.clear();
743
- this.activeThinkingByRunId.clear();
744
- }
745
- /**
746
- * Attach a tool call to the current AI message, upserting by `call_id` so a
747
- * single call maps to at most ONE ToolCall across all messages.
748
- *
749
- * The Cursor SDK can emit the lifecycle for one `call_id` more than once —
750
- * observed in production as two "running" events ~0.5s apart for task/edit
751
- * tools, which previously appended a duplicate ToolCall (the same call
752
- * rendered two or three times in the UI). We therefore index by `call_id`
753
- * and merge subsequent events into the existing proto, mirroring how
754
- * trackSubAgentExecution() upserts via subAgentMap. The first event for a
755
- * `call_id` (running or terminal) creates the proto on the last AI message;
756
- * the index keeps pointing at it even after later assistant text starts a
757
- * new AI message, so cross-message completions still land on the original.
758
- */
759
- attachToolCallToLastAi(event) {
760
- if (SUPPRESSED_TOOL_NAMES.has(event.name))
761
- return;
762
- const existing = this.toolCallIndex.get(event.call_id);
763
- if (existing) {
764
- this.mergeToolCallEvent(existing, event);
765
- return;
766
- }
767
- const tc = buildToolCallProto(event, this.mergedPolicies, this.provenance);
768
- // Resume reconciliation. A resumed Cursor agent re-runs a previously
769
- // approved tool with a BRAND-NEW call_id, so it misses the by-id index
770
- // above. Reconcile it onto the seeded WAITING_APPROVAL call with the same
771
- // canonical identity (the (category, salient)/MCP-name space the hook and
772
- // grants already use — see toolCallIdentityToken) and keep the original id.
773
- // Without this the seeded approved call and the re-run would both appear (a
774
- // duplicate row) and dropping the seeded id would trip the backend's
775
- // append-only-at-identity guard, stalling the run. This generalizes what
776
- // the native builder does by exact tool_call_id (`V3StatusBuilder`'s resume
777
- // reconciliation; its v2 predecessor matched by tool name) to the full
778
- // Cursor identity, reusing the single existing identity definition rather
779
- // than introducing a parallel one.
780
- const seeded = this.findResumableSeededToolCall(tc);
781
- if (seeded) {
782
- // Re-key the fresh call_id onto the seeded proto so this call_id's later
783
- // lifecycle events resolve here, then merge in place. mergeToolCallEvent
784
- // advances WAITING_APPROVAL (non-terminal) toward the event's status.
785
- this.toolCallIndex.set(event.call_id, seeded);
786
- this.mergeToolCallEvent(seeded, event);
787
- return;
788
- }
789
- this.findOrCreateLastAiMessage().toolCalls.push(tc);
790
- this.toolCallIndex.set(event.call_id, tc);
791
- // A new tool call is a discrete, user-visible event — force a prompt
792
- // flush so the live UI surfaces it the instant it starts.
793
- this._dirty = true;
794
- }
795
- /**
796
- * Find a seeded, still-gated tool call this resumed event should reconcile
797
- * onto: the first tool call in the index that is still WAITING_APPROVAL and
798
- * shares the candidate's canonical identity token. "First" (Map iteration =
799
- * transcript order) mirrors the v2 deep-agent's ordered first-unreconciled
800
- * match — once reconciled a call leaves WAITING_APPROVAL, so a second co-
801
- * pending call with the same identity naturally reconciles onto the next one.
802
- * Tool calls created during this turn are not WAITING_APPROVAL until the
803
- * post-stream denial reconciliation runs, so they can never be matched here.
804
- *
805
- * Only a row whose decision EXECUTES is resumable: the re-issue after an
806
- * APPROVE is the approved act itself, landing on its row. A row the user
807
- * declined (SKIP / REJECT) is a closed gate — a later same-identity call is a
808
- * NEW act the model was told not to perform, and it gets its own row so the
809
- * hook's denial gates it afresh instead of landing on the declined row and
810
- * inheriting its decision (S2 M4 finding F9, the accumulator's half; the
811
- * denial overlay's half is {@link isAdjudicatedRow}).
812
- */
813
- findResumableSeededToolCall(candidate) {
814
- const wanted = toolCallIdentityToken(candidate);
815
- for (const tc of this.toolCallIndex.values()) {
816
- if (tc.status === ToolCallStatus.TOOL_CALL_WAITING_APPROVAL &&
817
- !isDeclinedRow(tc) &&
818
- toolCallIdentityToken(tc) === wanted) {
819
- return tc;
820
- }
821
- }
822
- return undefined;
823
- }
824
- /**
825
- * Merge a repeated tool_call event into the ToolCall already tracked for this
826
- * `call_id`. The merge is defensive because a re-emitted event may carry less
827
- * information than an earlier one (a late "running" after "completed", or a
828
- * completion with an empty result): status only advances toward terminal,
829
- * timestamps are stamped once, and a populated result/args is never clobbered
830
- * by an empty one.
831
- */
832
- mergeToolCallEvent(existing, event) {
833
- const status = mapToolCallStatus(event.status);
834
- const wasTerminal = isTerminalToolStatus(existing.status);
835
- // Status advances monotonically: once terminal (completed/failed/skipped)
836
- // a later "running" re-emit must not regress it back to RUNNING.
837
- if (!isTerminalToolStatus(existing.status)) {
838
- existing.status = status;
839
- }
840
- if (isTerminalToolStatus(status) && !existing.completedAt) {
841
- existing.completedAt = utcTimestamp();
842
- }
843
- // The running -> terminal transition is the user-visible "tool finished"
844
- // moment — force a prompt flush so the result appears live rather than at
845
- // the next scheduler tick. Repeated terminal re-emits (already terminal) do
846
- // not re-flag: that would be noise, not a state change.
847
- if (!wasTerminal && isTerminalToolStatus(status)) {
848
- this._dirty = true;
849
- }
850
- if (!existing.startedAt && status === ToolCallStatus.TOOL_CALL_RUNNING) {
851
- existing.startedAt = utcTimestamp();
852
- }
853
- // Only a non-empty incoming result overwrites; a result-less "running"
854
- // re-emit must not wipe a result captured on completion (or vice versa).
855
- const incomingResult = toResultString(event.result);
856
- if (incomingResult) {
857
- existing.result = incomingResult;
858
- }
859
- if (status === ToolCallStatus.TOOL_CALL_FAILED) {
860
- if (!existing.error) {
861
- existing.error = typeof event.result === "string"
862
- ? event.result
863
- : "Tool call failed";
864
- }
865
- if (existing.requiresApproval && !existing.approvalRequestedAt) {
866
- existing.approvalRequestedAt = utcTimestamp();
867
- }
868
- }
869
- if (event.args != null && !existing.argsPreview) {
870
- existing.argsPreview = typeof event.args === "string"
871
- ? event.args
872
- : JSON.stringify(event.args);
873
- }
874
- }
875
- findOrCreateLastAiMessage() {
876
- for (let i = this.messages.length - 1; i >= 0; i--) {
877
- if (this.messages[i].type === MessageType.MESSAGE_AI) {
878
- return this.messages[i];
879
- }
880
- }
881
- const msg = create(AgentMessageSchema, {
882
- type: MessageType.MESSAGE_AI,
883
- content: "",
884
- timestamp: utcTimestamp(),
885
- });
886
- this.messages.push(msg);
887
- return msg;
888
- }
889
- trackSubAgentExecution(event) {
890
- const existing = this.subAgentMap.get(event.call_id);
891
- if (existing) {
892
- existing.status = mapSubAgentStatus(event.status);
893
- if (event.status === "completed" || event.status === "error") {
894
- existing.completedAt = utcTimestamp();
895
- }
896
- if (event.status === "completed" && event.result != null) {
897
- existing.output = typeof event.result === "string"
898
- ? event.result
899
- : JSON.stringify(event.result);
900
- extractConversationSteps(event.result, existing.messages);
901
- }
902
- if (event.status === "error") {
903
- existing.error = typeof event.result === "string"
904
- ? event.result
905
- : "Sub-agent failed";
906
- }
907
- this._dirty = true;
908
- return existing;
909
- }
910
- const sub = create(SubAgentExecutionSchema, {
911
- id: event.call_id,
912
- name: extractSubagentName(event.args),
913
- subject: safeString(event.args, "description"),
914
- input: safeString(event.args, "prompt"),
915
- status: mapSubAgentStatus(event.status),
916
- startedAt: utcTimestamp(),
917
- });
918
- this._subAgentExecutions.push(sub);
919
- this.subAgentMap.set(event.call_id, sub);
920
- this._dirty = true;
921
- return sub;
922
- }
923
- accumulateAssistant(event) {
924
- const text = event.message.content
925
- .filter((b) => b.type === "text")
926
- .map((b) => b.text)
927
- .join("");
928
- if (!text)
929
- return;
930
- const existing = this.activeAiByRunId.get(event.run_id);
931
- if (existing) {
932
- existing.content += text;
933
- return;
934
- }
935
- const msg = create(AgentMessageSchema, {
936
- type: MessageType.MESSAGE_AI,
937
- content: text,
938
- timestamp: utcTimestamp(),
939
- isStreaming: true,
940
- });
941
- this.messages.push(msg);
942
- this.activeAiByRunId.set(event.run_id, msg);
943
- }
944
- accumulateThinking(event) {
945
- if (!event.text)
946
- return;
947
- const existing = this.activeThinkingByRunId.get(event.run_id);
948
- if (existing) {
949
- existing.content += event.text;
950
- return;
951
- }
952
- const msg = create(AgentMessageSchema, {
953
- type: MessageType.MESSAGE_THINKING,
954
- content: event.text,
955
- timestamp: utcTimestamp(),
956
- isStreaming: true,
957
- });
958
- this.messages.push(msg);
959
- this.activeThinkingByRunId.set(event.run_id, msg);
960
- }
961
- finalizeStreaming(runId) {
962
- const ai = this.activeAiByRunId.get(runId);
963
- if (ai) {
964
- ai.isStreaming = false;
965
- this.activeAiByRunId.delete(runId);
966
- }
967
- const thinking = this.activeThinkingByRunId.get(runId);
968
- if (thinking) {
969
- thinking.isStreaming = false;
970
- this.activeThinkingByRunId.delete(runId);
971
- }
972
- }
973
- }
974
- /**
975
- * Reconcile the denial ledger written by the preToolUse hook against the tool
976
- * calls accumulated from the stream, marking each denied call as
977
- * WAITING_APPROVAL.
978
- *
979
- * This is the cursor analog of the native harness synthesizing WAITING_APPROVAL
980
- * tool calls from LangGraph interrupts (execute-deep-agent/turn-settle.ts). The hook
981
- * ledger — not the SDK-reported tool status — is the authoritative record of
982
- * what was gated, because the hook is the only component that makes the per-call
983
- * allow/deny decision. The backend then projects pending_approvals from these
984
- * WAITING_APPROVAL tool calls (PendingApprovalComputer), so the approval surface
985
- * is driven entirely by tool-call status, exactly like the native harness.
986
- *
987
- * Correlation is by tool identity token (the same space as approvedGrantTokens),
988
- * not by call id: a denied tool's identity is stable, and a single resource
989
- * approved once should produce one approval regardless of how many times the
990
- * agent re-attempted it within the turn.
991
- *
992
- * ONE GATE PER TURN (deny-only clean pause). The Cursor harness can only gate by
993
- * the hook returning `deny`, which Cursor surfaces to the model as a tool
994
- * *failure* — so a blocked model frequently improvises a workaround (the
995
- * canonical case: a denied `edit notes.md` followed ~2.5s later by a
996
- * `shell: cat > notes.md`, in the SAME assistant message with no narration
997
- * between them — observed in production, exec aex_01kw4p0cqgk0j8vvxbs5t8gv59).
998
- * The first-denial stop (index.ts) tries to cancel the turn at that first
999
- * denial, but `run.cancel()` is async and races the SDK's auto-execution, so the
1000
- * workaround can still stream and land a SECOND denial in the ledger. Two
1001
- * denials of distinct identity would otherwise surface two approval cards for
1002
- * one logical intent. Their identities differ (`write\nnotes.md` vs
1003
- * `shell\ncat > notes.md`), so no same-identity twin collapse can join them, and
1004
- * they share one message, so no positional rule can separate them; the only
1005
- * honest signal that the second is a reaction is CAUSALITY — it was emitted
1006
- * after the model saw the first denial. We therefore ANCHOR on the FIRST ledger
1007
- * denial of the turn (the ledger is reset per turn and appended in denial order,
1008
- * so ledger[0] is the original intent) and surface ONLY that identity. Every
1009
- * other denied identity in the turn — a post-denial workaround, or a genuine
1010
- * co-pending sibling the deny-only harness defers — is blanked in place to a
1011
- * hidden SKIPPED row ({@link collapseNonAnchorDenials}). A deferred sibling is
1012
- * not lost: on resume it re-attempts and gates again next turn (sequential
1013
- * gating). The native (LangGraph) harness pauses BEFORE the model can react, so
1014
- * it keeps full in-turn co-pending and is untouched by this rule. This is the
1015
- * near-term, invariant-preserving stepping stone to the Tool Execution Gateway,
1016
- * where an un-leased workaround is refused by construction.
1017
- *
1018
- * Correlation runs in two passes. The first matches the streamed token to a
1019
- * ledger token byte-for-byte (the common case). The hook, however, records its
1020
- * token from the RAW path Cursor hands it — a bash script cannot normalize a
1021
- * path against the workspace root — so an ABSOLUTE hook `file_path` against a
1022
- * RELATIVE stream `path` (or vice versa) yields two different raw tokens for one
1023
- * edit and the exact pass misses. The runner CAN normalize, so a second pass
1024
- * matches any still-unmatched FILE denial to a streamed call by (category,
1025
- * workspace-normalized path) and overlays the REAL streamed call, never appending
1026
- * a content-less placeholder beside it. This is the difference between one honest
1027
- * gate and two cards, one of which reads "No preview available". It reuses the
1028
- * single tool-identity definition + `resolveWorkspacePath`; it introduces no
1029
- * parallel identity.
1030
- *
1031
- * Only after BOTH passes miss is a placeholder WAITING_APPROVAL tool call
1032
- * synthesized (rare — Cursor normally emits a tool_call event for every
1033
- * attempt), so the gate still surfaces and never renders as a silent success.
1034
- * Critically, every match overlays a call IN PLACE (the committed id is
1035
- * preserved): the backend's append-only-at-identity transcript guard rejects a
1036
- * finalize that drops a previously-committed tool-call id, so reconciliation may
1037
- * only reconcile entries in place, never remove them.
1038
- *
1039
- * Every matched/synthesized call is enriched with the hook-captured authoritative
1040
- * input (`ledger.input`) via {@link applyGateInput}: the full proposed args, a
1041
- * compact `args_preview`, and the content digest — so the approval card renders
1042
- * the proposed write/edit content from `args` and a resume re-gates a diverging
1043
- * sibling edit. A missing capture (the hook's grep fallback) degrades to the
1044
- * prior behavior.
1045
- *
1046
- * Returns the tool calls now marked WAITING_APPROVAL — the single anchor gate
1047
- * for the turn (overlaid or, rarely, synthesized).
1048
- */
1049
- export async function reconcileDeniedToolCalls(messages, ledger, mergedPolicies, workspaceBackend) {
1050
- // Defense-in-depth: only APPROVAL-kind denials may become approval gates.
1051
- // The turn boundary already passes the filtered subset; re-filtering here
1052
- // makes it structurally impossible for a secret/capture-error/fail-closed
1053
- // entry to manufacture a pause the user cannot meaningfully grant, no matter
1054
- // what a future caller passes (an absent kind is the pre-kind format and
1055
- // counts as approval).
1056
- ledger = approvalDenials(ledger);
1057
- if (ledger.length === 0)
1058
- return [];
1059
- // The workspace the gated files live in; its rootDir normalizes paths for the
1060
- // abs-vs-rel correlation fallback (normalizedFileSalient).
1061
- const workspaceRoot = workspaceBackend?.rootDir;
1062
- // One gate per turn: anchor on the FIRST ledger denial. The ledger is reset
1063
- // per turn and appended in denial order, so ledger[0] is the model's original
1064
- // intent; any later denial of a DIFFERENT identity is a post-denial workaround
1065
- // or a deferred co-pending sibling (see the doc comment). We surface ONLY the
1066
- // anchor identity below and blank every other denied identity to a hidden
1067
- // SKIPPED row. `deniedTokens` still carries every denied identity — it is the
1068
- // scope for that collapse, never an additional gate.
1069
- const anchorToken = ledger[0].token;
1070
- const deniedTokens = new Set(ledger.map((e) => e.token));
1071
- // The authoritative pre-execution args the hook captured for the anchor. A
1072
- // resource re-attempted within the turn shares a token; last write wins (the
1073
- // attempts carry the same proposed change).
1074
- let anchorInput;
1075
- for (const e of ledger) {
1076
- if (e.token === anchorToken && e.input)
1077
- anchorInput = e.input;
1078
- }
1079
- const matchedCalls = new Set();
1080
- const result = [];
1081
- let anchorMatched = false;
1082
- // 1. Exact overlay: a streamed call whose token equals the anchor denial token
1083
- // byte-for-byte (the path form agreed on both sides). The anchor resource
1084
- // re-attempted within the turn shares one token and collapses to a single
1085
- // approval (the first match is the keeper; same-identity twins are blanked
1086
- // by collapseRedundantToolCallTwins below). A row an earlier invocation's
1087
- // gate already settled is never the home of THIS turn's denial
1088
- // (isAdjudicatedRow) — the search moves past it to this turn's attempt.
1089
- for (const msg of messages) {
1090
- if (anchorMatched)
1091
- break;
1092
- for (const tc of msg.toolCalls) {
1093
- if (isAdjudicatedRow(tc))
1094
- continue;
1095
- if (toolCallIdentityToken(tc) !== anchorToken)
1096
- continue;
1097
- overlayDeniedStreamCall(tc, anchorInput, mergedPolicies);
1098
- matchedCalls.add(tc);
1099
- result.push(tc);
1100
- anchorMatched = true;
1101
- break;
1102
- }
1103
- }
1104
- // 2. Normalized-path fallback (the abs-vs-rel drift fix): if the anchor is a
1105
- // FILE denial the exact pass missed, match a streamed call by (category,
1106
- // workspace-normalized path) and overlay the REAL call — never a content-
1107
- // less placeholder beside it. Requires the workspace root to normalize;
1108
- // shell/MCP denials (no path) and resumes without a root fall through to
1109
- // synthesis.
1110
- if (!anchorMatched && workspaceRoot) {
1111
- const decoded = decodeIdentityToken(anchorToken);
1112
- const wanted = decoded
1113
- ? normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot)
1114
- : undefined;
1115
- if (wanted) {
1116
- const tc = findUnmatchedStreamCallByNormalizedSalient(messages, matchedCalls, wanted, workspaceRoot);
1117
- if (tc) {
1118
- overlayDeniedStreamCall(tc, anchorInput, mergedPolicies);
1119
- matchedCalls.add(tc);
1120
- result.push(tc);
1121
- anchorMatched = true;
1122
- }
1123
- }
1124
- }
1125
- // 2a. One gate per turn: blank every denied identity OTHER than the anchor to a
1126
- // hidden SKIPPED row (the workaround shell, or a deferred co-pending
1127
- // sibling). Runs BEFORE the WAITING_FOR_APPROVAL persist so a reaction is
1128
- // never persisted as WAITING_APPROVAL — the backend authors an approval
1129
- // REQUESTED event only from a WAITING_APPROVAL tool call, so collapsing
1130
- // here keeps the append-only approval-event stream free of an orphan
1131
- // REQUESTED that would need retraction.
1132
- const nonAnchorCollapsed = collapseNonAnchorDenials(messages, deniedTokens, anchorToken);
1133
- if (nonAnchorCollapsed > 0) {
1134
- console.log(`ExecuteCursor reconcile collapsed ${nonAnchorCollapsed} non-anchor denied ` +
1135
- `tool call(s) to hidden SKIPPED (one gate per turn; anchor is the first ` +
1136
- `denial of the turn)`);
1137
- }
1138
- // 2b. Collapse same-turn duplicate edits. When the model emitted the SAME
1139
- // resource twice in one turn (two call ids, one identity token), only the
1140
- // FIRST same-token stream call was overlaid into the gate above; any OTHER
1141
- // same-token call stays a committed row (RUNNING zombie, or a
1142
- // denied-reported-as-success COMPLETED) that would render as a second,
1143
- // content-less card beside the gate (the reported "No preview available"
1144
- // duplicate). The overlaid gate is now WAITING_APPROVAL, so the shared
1145
- // routine recognizes it as the keeper and blanks the twins IN PLACE to
1146
- // hidden SKIPPED rows — we cannot drop them, since the backend's
1147
- // append-only-at-identity guard rejects removing a previously-committed
1148
- // tool-call id, but the id is preserved so the finalize stays append-only.
1149
- const collapsed = collapseRedundantToolCallTwins(messages);
1150
- if (collapsed > 0) {
1151
- console.log(`ExecuteCursor reconcile collapsed ${collapsed} redundant tool-call twin(s) ` +
1152
- `superseded by the approval gate (kept in place as hidden SKIPPED rows)`);
1153
- }
1154
- // 2c. Finalize interrupted rows. The first-denial stop cancelled the run, so
1155
- // a tool call still PENDING/RUNNING here can never complete — no event
1156
- // will ever deliver its result, and left alone it persists as a spinner
1157
- // forever. The canonical victim is a post-denial workaround whose own
1158
- // hook denial raced (or never reached) the final ledger read, so the
1159
- // token-scoped collapse in 2a could not see it (production case
1160
- // aex_01kwj07f7g23c3wp9sn8496z5g: a python-write shell reaction persisted
1161
- // as RUNNING with requiresApproval=true). Whatever the cause, a
1162
- // non-terminal row on a turn that is pausing is an interrupted attempt
1163
- // with no output: collapse it to the same hidden SKIPPED shape as every
1164
- // other superseded row (in place — the append-only-at-identity guard
1165
- // forbids dropping a committed id). Runs AFTER the anchor overlay, so the
1166
- // gate itself (now WAITING_APPROVAL) is never touched.
1167
- const interrupted = finalizeInterruptedToolCalls(messages);
1168
- if (interrupted > 0) {
1169
- console.log(`ExecuteCursor reconcile collapsed ${interrupted} interrupted non-terminal ` +
1170
- `tool call(s) that can never complete (run cancelled at first denial)`);
1171
- }
1172
- // 3. Synthesize the anchor gate if it matched NO streamed call in either pass
1173
- // (rare — Cursor emits a tool_call event for every attempt), so the gate
1174
- // still surfaces rather than rendering as a silent success. After the
1175
- // normalized fallback this should be ~0; the caller logs a divergence when
1176
- // it is not (a synthesized id is prefixed `approval:`). Only the anchor is
1177
- // ever synthesized: non-anchor denials are deliberately collapsed, never
1178
- // surfaced (one gate per turn).
1179
- if (!anchorMatched) {
1180
- const anchorEntry = ledger.find((e) => e.token === anchorToken) ?? ledger[0];
1181
- const decoded = decodeIdentityToken(anchorToken);
1182
- // Display the hook's raw tool name; carry the decoded salient so the grant
1183
- // rebuilt from this tool call on reinvocation keys on the same resource.
1184
- const displayName = anchorEntry.toolName || decoded?.key || "tool";
1185
- const salient = decoded?.salient ?? "";
1186
- const tc = synthesizeWaitingApprovalToolCall(displayName, salient, decoded?.digest ?? "", anchorToken, mergedPolicies);
1187
- // The hook-captured input upgrades the placeholder from a bare {path} to the
1188
- // full proposed args, so even a synthesized gate shows the proposed change.
1189
- applyGateInput(tc, anchorInput ?? anchorEntry.input);
1190
- appendToolCallToLastAiMessage(messages, tc);
1191
- result.push(tc);
1192
- }
1193
- return result;
1194
- }
1195
- /**
1196
- * Overlay WAITING_APPROVAL onto a streamed tool call the hook denied. Mutates
1197
- * `tc` in place — the call keeps its committed id, so the backend's
1198
- * append-only-at-identity transcript guard accepts the finalize (an in-place
1199
- * status change is a reconcile, not a drop). The single overlay routine for both
1200
- * the exact and the normalized correlation passes, so the gate diff can never
1201
- * diverge between them. The hook-captured `input` (when present) is the
1202
- * authoritative, complete proposed args — the stream may have carried only
1203
- * partial args before the first-denial cancel — so it supplies the args preview
1204
- * and the content digest (see {@link applyGateInput}).
1205
- */
1206
- function overlayDeniedStreamCall(tc, input, mergedPolicies) {
1207
- markWaitingApproval(tc, mergedPolicies);
1208
- applyGateInput(tc, input);
1209
- }
1210
- /**
1211
- * Collapse every tool call still in a non-terminal state (PENDING / RUNNING)
1212
- * to the hidden SKIPPED row shape, returning how many were collapsed.
1213
- *
1214
- * Called only on the pause-for-approval path, after the anchor gate has been
1215
- * overlaid to WAITING_APPROVAL: the run was cancelled, so nothing will ever
1216
- * complete these calls, and a permanently-RUNNING row would render as an
1217
- * eternal spinner beside the approval card. This is the causality sibling of
1218
- * {@link collapseNonAnchorDenials}: that collapse is token-scoped (it needs the
1219
- * denial in the ledger), while this one catches the attempt whose hook denial
1220
- * raced the final ledger read or whose execution the cancel interrupted
1221
- * outright — either way an attempt with no output that the turn's end orphaned.
1222
- */
1223
- function finalizeInterruptedToolCalls(messages) {
1224
- let finalized = 0;
1225
- for (const msg of messages) {
1226
- for (const tc of msg.toolCalls) {
1227
- if (tc.status !== ToolCallStatus.TOOL_CALL_PENDING &&
1228
- tc.status !== ToolCallStatus.TOOL_CALL_RUNNING) {
1229
- continue;
1230
- }
1231
- hideToolCallRow(tc);
1232
- finalized++;
1233
- }
1234
- }
1235
- return finalized;
1236
- }
1237
- /**
1238
- * Recognizes a tool call already blanked to a hidden collapsed row, so a second
1239
- * pass never re-collapses it (and never miscounts). Mirrors the SDK's
1240
- * `isCollapsedToolCall` shape without importing across the runner/SDK seam.
1241
- */
1242
- function isAlreadyCollapsed(tc) {
1243
- return (tc.status === ToolCallStatus.TOOL_CALL_SKIPPED &&
1244
- !tc.requiresApproval &&
1245
- !tc.result &&
1246
- !tc.error &&
1247
- !tc.argsPreview);
1248
- }
1249
- /**
1250
- * Whether the server has already adjudicated this row — the user decided its
1251
- * gate (`approval_action`, the server's field; the runner never writes it).
1252
- *
1253
- * Such a row belongs to a gate that is CLOSED: approved and executed, or
1254
- * declined, in an earlier invocation of this execution. No reconciliation of
1255
- * the CURRENT turn may rewrite it — not the denial overlay (a new denial of the
1256
- * same identity is a NEW act and gets its own row), not the twin collapse (the
1257
- * executed row is the transcript's record). Before this rule the overlay matched
1258
- * a denial to the FIRST same-identity row in the whole transcript, flipped a
1259
- * completed, approved row back to WAITING_APPROVAL with its APPROVE still on
1260
- * it, and the next invocation read that as the decision for the new, undecided
1261
- * proposal — an approval bleeding to a later identical act (S2 M4 finding F9,
1262
- * found by the harness contract kit's invariant 3 against this adapter).
1263
- */
1264
- function isAdjudicatedRow(tc) {
1265
- return tc.approvalAction !== ApprovalAction.UNSPECIFIED;
1266
- }
1267
- /** Adjudicated with a decision that does NOT execute: the user declined this gate. */
1268
- function isDeclinedRow(tc) {
1269
- switch (tc.approvalAction) {
1270
- case ApprovalAction.SKIP:
1271
- case ApprovalAction.REJECT:
1272
- return true;
1273
- case ApprovalAction.UNSPECIFIED:
1274
- case ApprovalAction.APPROVE:
1275
- case ApprovalAction.APPROVE_ALL:
1276
- return false;
1277
- default: {
1278
- const exhaustive = tc.approvalAction;
1279
- throw new Error(`isDeclinedRow: unknown approval action ${String(exhaustive)}`);
1280
- }
1281
- }
1282
- }
1283
- /**
1284
- * Whether a tool call carries a change/output of its own — the signal that it is
1285
- * authoritative for its resource rather than a redundant denial/cancel twin.
1286
- *
1287
- * The notion of "change" is category-aware on purpose:
1288
- * - A file mutation (`write`/`delete`) never carries an authoritative change on
1289
- * the tool-call ROW: under apply-then-review its review lives in the
1290
- * `FileChangeSet` ledger (capture mode), and under the no-storage deny-gate it
1291
- * is the WAITING_APPROVAL gate itself (kept explicitly by the caller). So a
1292
- * file row is authoritative only as that gate, never on its own — hence
1293
- * `false` here. (Before Phase 5 Slice 4 this read `file_changes.length > 0`;
1294
- * that field is gone, and the row was never the review surface.)
1295
- * - Every other gated tool (shell, MCP) has no ledger; its "change" is its
1296
- * execution output, so a genuine run carries a non-empty `result` while a
1297
- * denied/cancelled attempt that never executed does not. This keeps two
1298
- * distinct shell runs (each with output) both visible while still collapsing a
1299
- * same-command denial twin.
1300
- */
1301
- function carriesOwnChange(tc) {
1302
- const category = toolApprovalCategory(tc.name);
1303
- if (category === "write" || category === "delete") {
1304
- return false;
1305
- }
1306
- return !!tc.result;
1307
- }
1308
- /**
1309
- * Collapse redundant same-identity tool-call twins to a single visible row.
1310
- *
1311
- * The model frequently emits the SAME gated action twice in one turn (two
1312
- * tool-call ids, one identity). When the first attempt is gated and the run is
1313
- * cancelled mid-flight, the extra attempt never receives a terminal event and
1314
- * persists as a stuck `RUNNING` row ("No preview available"); other variants are
1315
- * a denied-reported-as-success `COMPLETED` with an empty result, two no-change
1316
- * `COMPLETED` attempts where neither carries a change, or — on the denial path —
1317
- * a `FAILED` twin beside the overlaid gate. All render as a duplicate card beside
1318
- * the real action (or the approval gate). This is the recurring duplicate-card
1319
- * defect, most visible for file edits but shared by every gated tool family.
1320
- *
1321
- * The routine is harness-agnostic and a pure function of `messages`:
1322
- *
1323
- * 1. Scope to GATED identities — file mutations (`write`/`delete`) and shell key
1324
- * on their cross-taxonomy category; MCP tools are recognized by their server
1325
- * slug. A same-turn duplicate of a gated tool is a denial/cancel artifact, not
1326
- * meaningful repetition. The category is name-derived (via {@link toolIdentity}
1327
- * -> approvalCategory), so a twin cancelled before classification (empty
1328
- * `toolKind`) is still scoped via its name (`edit` -> `write`). Ungated
1329
- * read-only tools are left untouched.
1330
- * 2. Group those calls by `toolCallIdentityToken` — the SAME `toolIdentity` used
1331
- * for denial correlation and resume grants, so scope and grouping cannot drift.
1332
- * 3. In each group the keepers carry authoritative state — a change/output of
1333
- * their own (see {@link carriesOwnChange}) or the approval gate itself
1334
- * (`WAITING_APPROVAL`). For a file mutation the gate is the sole authoritative
1335
- * row: the row carries no diff (review lives in the `FileChangeSet` ledger, or
1336
- * is the no-storage deny-gate itself), so a denied write's same-identity
1337
- * siblings — a denied/zombie row or a stale snapshot from a second attempt —
1338
- * collapse onto the gate. A shell/MCP twin keeps every distinct run with
1339
- * output. If NO member qualifies (every attempt produced no change), keep
1340
- * exactly ONE representative — preferring a terminal attempt over a stuck
1341
- * `RUNNING` zombie — so the resource still shows a single card. Every
1342
- * non-keeper is blanked in place to a hidden `SKIPPED` row (see
1343
- * {@link collapseDenialTwin}).
1344
- *
1345
- * It is deliberately subtractive — it only ever HIDES a row, never invents a
1346
- * terminal state. The committed `id` is preserved on every collapse, so the
1347
- * finalize stays append-only by construction and the backend's
1348
- * append-only-at-identity guard accepts it. Returns the number collapsed, for
1349
- * observability.
1350
- */
1351
- export function collapseRedundantToolCallTwins(messages) {
1352
- const groups = new Map();
1353
- for (const msg of messages) {
1354
- for (const tc of msg.toolCalls) {
1355
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1356
- const gated = tc.mcpServerSlug
1357
- ? true
1358
- : id.key === "write" || id.key === "delete" || id.key === "shell";
1359
- if (!gated)
1360
- continue;
1361
- const token = grantToken(id.key, id.salient);
1362
- const bucket = groups.get(token);
1363
- if (bucket)
1364
- bucket.push(tc);
1365
- else
1366
- groups.set(token, [tc]);
1367
- }
1368
- }
1369
- let collapsed = 0;
1370
- for (const group of groups.values()) {
1371
- if (group.length < 2)
1372
- continue; // a lone call is never a twin
1373
- // Keepers carry authoritative state: a change/output of their own
1374
- // (carriesOwnChange), the approval gate itself, or a gate an earlier
1375
- // invocation already settled (isAdjudicatedRow — the transcript's record of
1376
- // what the user decided and what ran; a same-identity act in a later turn
1377
- // is a new act, never this row's twin). For a file mutation the gate is the
1378
- // sole authoritative row (the row carries no diff — review lives in the
1379
- // ledger, or the row IS the no-storage deny-gate), so a denied write's
1380
- // same-identity siblings collapse onto it; a shell/MCP twin keeps every
1381
- // distinct run with output.
1382
- const keepers = new Set(group.filter((tc) => carriesOwnChange(tc) ||
1383
- isAdjudicatedRow(tc) ||
1384
- tc.status === ToolCallStatus.TOOL_CALL_WAITING_APPROVAL));
1385
- // All attempts produced no change (e.g. denied-reported-as-success): keep one
1386
- // representative, preferring a settled outcome over a stuck RUNNING zombie.
1387
- if (keepers.size === 0) {
1388
- const terminal = [...group].reverse().find((tc) => isTerminalToolStatus(tc.status));
1389
- keepers.add(terminal ?? group[0]);
1390
- }
1391
- for (const tc of group) {
1392
- if (keepers.has(tc))
1393
- continue;
1394
- if (isAlreadyCollapsed(tc))
1395
- continue;
1396
- collapseDenialTwin(tc);
1397
- collapsed++;
1398
- }
1399
- }
1400
- return collapsed;
1401
- }
1402
- /**
1403
- * One gate per turn: blank every DENIED tool call whose identity differs from
1404
- * the anchor (the first denial of the turn) to a hidden SKIPPED row.
1405
- *
1406
- * This is the cross-identity complement of {@link collapseRedundantToolCallTwins}
1407
- * (which only joins SAME-identity duplicates). The canonical target is the
1408
- * deny-only workaround — a denied `edit notes.md` followed by a `shell:
1409
- * cat > notes.md` whose identity (`shell\n…`) differs from the edit's
1410
- * (`write\nnotes.md`), so no twin collapse can join them and (since they share
1411
- * one assistant message) no positional rule can separate them. The honest signal
1412
- * that the shell is redundant is that it is a DIFFERENT denied identity in the
1413
- * same turn as the anchor; under the one-gate-per-turn contract every such
1414
- * identity is either a post-denial reaction or a co-pending sibling the harness
1415
- * defers to the next turn, so it is hidden, not surfaced.
1416
- *
1417
- * Scoped strictly to identities present in `deniedTokens`: a non-denied tool
1418
- * (an earlier read/glob, or an already-granted call that ran) is never touched.
1419
- * Subtractive and id-preserving (via {@link collapseDenialTwin}), so the finalize
1420
- * stays append-only. Returns the number collapsed, for observability.
1421
- */
1422
- function collapseNonAnchorDenials(messages, deniedTokens, anchorToken) {
1423
- let collapsed = 0;
1424
- for (const msg of messages) {
1425
- for (const tc of msg.toolCalls) {
1426
- if (isAdjudicatedRow(tc))
1427
- continue;
1428
- const token = toolCallIdentityToken(tc);
1429
- if (token === anchorToken)
1430
- continue;
1431
- if (!deniedTokens.has(token))
1432
- continue;
1433
- if (isAlreadyCollapsed(tc))
1434
- continue;
1435
- collapseDenialTwin(tc);
1436
- collapsed++;
1437
- }
1438
- }
1439
- return collapsed;
1440
- }
1441
- /**
1442
- * Blank a superseded denial twin in place to a hidden SKIPPED row. Keeps the
1443
- * committed `id` (append-only), `name`, and `toolKind`; clears every renderable
1444
- * surface and the approval flags so the SDK's `isCollapsedToolCall` predicate
1445
- * recognizes it and renders nothing. The structured `args` are left as the honest
1446
- * stored record of the redundant attempt (never rendered, since the row is
1447
- * hidden; the gate carries the authoritative proposed change).
1448
- */
1449
- function collapseDenialTwin(tc) {
1450
- hideToolCallRow(tc);
1451
- }
1452
- // `hideToolCallRow` (the "hidden row" shape, shared by the denial-twin collapse
1453
- // and the capture flow) lives in shared/tool-row.ts so both harnesses collapse
1454
- // rows identically; imported at the top of this module.
1455
- /**
1456
- * Overlay the hook-captured authoritative tool input onto a gated tool call so
1457
- * the approval card can show the proposed change before the user approves.
1458
- *
1459
- * When `input` is present it becomes the single source for the preview: the full
1460
- * structured `args` (the approval card renders the proposed write/edit content
1461
- * from these), a compact-but-always-valid `args_preview` (the field a resumed
1462
- * turn parses to rebuild the grant salient — so salient fields are never elided),
1463
- * and the content digest.
1464
- *
1465
- * The digest is the resume identity: it binds the grant to (category, path,
1466
- * content) so a sibling edit to the same file re-gates rather than riding an
1467
- * earlier approval through. It is also the identity the Cursor deny-gate's
1468
- * exact-apply reads on resume — together with the whole-file bytes in `args` — to
1469
- * write exactly what was approved (see exact-apply.ts). There is no separate
1470
- * captured `file_changes` mirror; `args` is the single source for both the
1471
- * preview and the applied bytes.
1472
- *
1473
- * With no `input` (the hook's grep fallback) there is nothing authoritative to
1474
- * stamp and the call keeps its existing args.
1475
- */
1476
- function applyGateInput(tc, input) {
1477
- if (!input)
1478
- return;
1479
- // Defense-in-depth (DD-26 #2): never overlay a secret-like write's content into
1480
- // the persisted approval preview. Normally unreachable — the hook hard-blocks a
1481
- // secret write and records no ledger input — but if a hook classify failure fell
1482
- // one through, its content must still never reach args/args_preview. The
1483
- // Invariant-A backstop is the final net; this closes the path at the source.
1484
- const gatePath = extractFilePath(input);
1485
- if (gatePath !== null && isSecretLikePath(gatePath))
1486
- return;
1487
- tc.args = input;
1488
- tc.argsPreview = buildElidedArgsPreview(input, SALIENT_ARG_FIELDS);
1489
- // Stamp the content digest from the AUTHORITATIVE captured input, so the
1490
- // approved edit's exact content survives to resume on a small, never-elided
1491
- // field — the grant then binds to (category, path, content) and a sibling
1492
- // edit to the same file re-gates. Empty for a non-content tool. This is the
1493
- // one place the digest is authored; everything downstream reads the field.
1494
- tc.approvalContentDigest = contentDigest(input);
1495
- }
1496
- /**
1497
- * The workspace-normalized identity of a FILE approval category's salient, or
1498
- * undefined for a non-file category (shell, whose salient is a command, not a
1499
- * path) or an empty salient. Both the hook-decoded denial salient and a streamed
1500
- * call's salient pass through this, so an absolute-vs-relative path difference
1501
- * collapses to one comparable key (`category + "\n" + relPath`). Restricting to
1502
- * write/delete keeps a shell command from being mangled by path normalization.
1503
- */
1504
- function normalizedFileSalient(category, salient, workspaceRoot) {
1505
- if ((category !== "write" && category !== "delete") || !salient)
1506
- return undefined;
1507
- const { path } = resolveWorkspacePath(salient, workspaceRoot, /* virtualRoot */ false);
1508
- return `${category}\n${path}`;
1509
- }
1510
- /**
1511
- * Find the first not-yet-overlaid streamed tool call whose workspace-normalized
1512
- * (category, path) equals `wanted`. Skips calls already claimed by an earlier
1513
- * denial so several concurrent file denials each overlay a distinct stream call.
1514
- */
1515
- function findUnmatchedStreamCallByNormalizedSalient(messages, matchedCalls, wanted, workspaceRoot) {
1516
- for (const msg of messages) {
1517
- for (const tc of msg.toolCalls) {
1518
- if (matchedCalls.has(tc) || isAdjudicatedRow(tc))
1519
- continue;
1520
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1521
- if (normalizedFileSalient(id.key, id.salient, workspaceRoot) === wanted) {
1522
- return tc;
1523
- }
1524
- }
1525
- }
1526
- return undefined;
1527
- }
1528
- /**
1529
- * Redact provisional post-denial narration when a Cursor turn pauses for approval.
1530
- *
1531
- * THE PROBLEM. Unlike the native harness — which gates with a LangGraph
1532
- * `interrupt()` *before* the tool runs, so the model never sees a denial — the
1533
- * Cursor harness can only gate via the file-based `beforeMCPExecution`/
1534
- * `preToolUse` hook returning `deny`. Cursor surfaces that deny to the model as
1535
- * a tool *failure* (often its own generic "blocked by a hook" text; see the
1536
- * Phase 0 ground-truth capture in cursor_hitl_test.go), and there is no
1537
- * non-leaky SDK approval primitive to use instead (the `request` event is
1538
- * opaque and carries no responder). So a well-behaved model frequently reacts by
1539
- * narrating defeat — "I couldn't do this; enable the hook in your Cursor
1540
- * settings" — which would otherwise be persisted as the assistant's verdict and
1541
- * rendered right next to the approval card that is, in fact, asking the user to
1542
- * approve. Contradictory and alarming.
1543
- *
1544
- * THE GUARANTEE. The runner's job is to simplify this data, not mirror its
1545
- * complexity: a turn that pauses for approval must read the SAME shape the
1546
- * native harness produces — `[pre-tool text][tool calls WAITING_APPROVAL]`, with
1547
- * no post-denial verdict. We therefore BLANK (clear the `content` of, and mark
1548
- * non-streaming) the trailing assistant/thinking messages that (a) appear
1549
- * positionally AFTER the last message bearing a WAITING_APPROVAL tool call and
1550
- * (b) carry no tool calls of their own. The approval card (projected from the
1551
- * WAITING_APPROVAL tool-call status) becomes the single, unambiguous source of
1552
- * truth. The blanked messages are already invisible on every surface via the
1553
- * existing empty-message handling (`buildThreadItems` skips empty `MESSAGE_AI`;
1554
- * `MessageEntry` renders nothing for empty `MESSAGE_THINKING`), so the shared
1555
- * `@stigmer/react`/Ink components stay harness-agnostic with zero per-harness UI
1556
- * special-casing — the cleanliness lives in the data, not in each consumer.
1557
- *
1558
- * WHY BLANK INSTEAD OF REMOVE. Removing the messages would make the persisted
1559
- * WAITING_FOR_APPROVAL transcript SHORTER than the in-progress transcript the
1560
- * runner already streamed. The backend's append-only message guard rejects a
1561
- * shrink for a non-terminal execution (it protects against regressed/partial
1562
- * writes). Blanking keeps the message COUNT identical, so the finalize is
1563
- * append-only BY CONSTRUCTION and the guard accepts it with no special case —
1564
- * which is why this phase deletes the backend's former `isApprovalFinalize`
1565
- * shrink exception in both editions. The transcript is the authoritative *raw*
1566
- * record; the verbatim narration text remains recoverable from the runner logs
1567
- * and the recorded cursor-event stream.
1568
- *
1569
- * WHY THIS IS DETERMINISTIC. `attachToolCallToLastAi` calls
1570
- * `finalizeStreaming(run_id)` before attaching a tool call, so any assistant
1571
- * text the model emits *after* the denied tool call always starts a NEW message
1572
- * — post-denial narration is never merged into the message that holds the gated
1573
- * call. We stop at the first non-narration message — one bearing a VISIBLE tool
1574
- * call — so legitimately-executed tools after the gate and any text around them
1575
- * are never touched; only the contiguous trailing reaction block is blanked. A
1576
- * message whose every tool call was collapsed to the hidden SKIPPED row (a
1577
- * post-denial workaround or an interrupted attempt — see
1578
- * collapseNonAnchorDenials / finalizeInterruptedToolCalls, which run first) IS
1579
- * trailing narration: its rows render as absent, so only its text remains, and
1580
- * that text is precisely the reaction this redaction exists to blank. Treating
1581
- * it as a stop would strand every reaction message behind it (the production
1582
- * shape in aex_01kwj07f7g23c3wp9sn8496z5g: [gate][thinking][narration+workaround
1583
- * row] — the old walk stopped at the workaround message and redacted nothing).
1584
- * The first-denial stop in index.ts is the primary mechanism that keeps this
1585
- * block small (it ends the turn before the model produces inter-tool
1586
- * narration); this redaction is the backstop for any token that streamed before
1587
- * the cancel landed.
1588
- *
1589
- * Returns the blanked messages (for diagnostics); mutates `messages` in place.
1590
- */
1591
- export function clearProvisionalPostDenialNarration(messages, deniedToolCalls) {
1592
- if (deniedToolCalls.length === 0)
1593
- return [];
1594
- // reconcileDeniedToolCalls returns the very ToolCall protos held inside
1595
- // messages[].toolCalls (overlaid) or appended to the last AI message
1596
- // (synthesized), so object identity is a stable, exact match.
1597
- const denied = new Set(deniedToolCalls);
1598
- let lastGatedIdx = -1;
1599
- for (let i = 0; i < messages.length; i++) {
1600
- if (messages[i].toolCalls.some((tc) => denied.has(tc))) {
1601
- lastGatedIdx = i;
1602
- }
1603
- }
1604
- if (lastGatedIdx < 0)
1605
- return [];
1606
- const redacted = [];
1607
- for (let i = messages.length - 1; i > lastGatedIdx; i--) {
1608
- const msg = messages[i];
1609
- const isProvisionalNarration = (msg.type === MessageType.MESSAGE_AI || msg.type === MessageType.MESSAGE_THINKING) &&
1610
- msg.toolCalls.every((tc) => isToolCallRowHidden(tc));
1611
- // Stop at the first message that is NOT trailing narration: a message
1612
- // bearing a visible (non-collapsed) tool call marks real activity we must
1613
- // preserve, and anything before it is no longer "trailing".
1614
- if (!isProvisionalNarration)
1615
- break;
1616
- // Blank in place — keep the message so the transcript count never shrinks,
1617
- // but drop its provisional content so no consumer renders the defeatist
1618
- // verdict. Empty AI/THINKING messages are hidden by the SDK already; hidden
1619
- // SKIPPED rows already render as absent.
1620
- msg.content = "";
1621
- msg.isStreaming = false;
1622
- redacted.unshift(msg);
1623
- }
1624
- return redacted;
1625
- }
1626
- /**
1627
- * Substrings of the error text Cursor stamps onto a tool call blocked by a
1628
- * `preToolUse`/`beforeMCPExecution` hook (its generic replacement for the
1629
- * hook's own agent_message — confirmed by the Phase 0 ground-truth capture in
1630
- * cursor_hitl_test.go). The SDK has NO structured "denied by hook" signal, so
1631
- * this marker family is the only stream-side trace of a hook block and is
1632
- * single-sourced here for every consumer (the issue #205 attribution detector
1633
- * below; tests). Matched case-insensitively against the FAILED call's error.
1634
- */
1635
- export const HOOK_BLOCK_ERROR_MARKERS = ["blocked by a hook"];
1636
- /** True when a tool call's error text reads as a hook block. */
1637
- function isHookBlockError(errorText) {
1638
- if (!errorText)
1639
- return false;
1640
- const lowered = errorText.toLowerCase();
1641
- return HOOK_BLOCK_ERROR_MARKERS.some((marker) => lowered.includes(marker));
1642
- }
1643
- /**
1644
- * Detect tool calls blocked by a hook that STIGMER'S OWN hook did not deny —
1645
- * the issue #205 invariant check "a blocked tool must never silently complete".
1646
- *
1647
- * Cursor runs EVERY hook registered in the workspace's `.cursor/hooks.json`
1648
- * and a deny from any of them blocks the tool. Our hook records every deny it
1649
- * issues to the denial ledger (all kinds — see {@link DeniedLedgerEntry}), so a
1650
- * FAILED tool call carrying Cursor's hook-block error text with NO matching
1651
- * ledger entry was blocked by a FOREIGN hook (a user/team `preToolUse` policy
1652
- * hook the merge deliberately preserves) — or, equally fatally, by our own
1653
- * hook whose best-effort ledger append failed. Either way the runner cannot
1654
- * pause for approval (an approval grants a token only OUR hook reads; the
1655
- * foreign hook would deny the re-attempt forever), so the caller surfaces an
1656
- * explicit failure instead of completing with the work silently undone.
1657
- *
1658
- * Attribution, in order:
1659
- * 1. Any `fail-closed` ledger entry → the gate itself was broken this turn and
1660
- * denied EVERYTHING it saw; per-call correlation is meaningless, so every
1661
- * hook block is attributed to our own (broken) gate. Nothing is reported.
1662
- * 2. Exact identity: the call's {@link toolCallIdentityToken} appears in the
1663
- * ledger (any kind — approval gates were overlaid to WAITING_APPROVAL or
1664
- * collapsed by the reconcile that runs first, so a still-FAILED row here is
1665
- * typically a secret/capture-error deny, correctly attributed as ours).
1666
- * 3. Normalized-path fallback: the same abs-vs-rel drift the reconcile's
1667
- * second pass handles — a FILE call matches a ledger entry by (category,
1668
- * workspace-normalized path) even when the raw tokens differ.
1669
- *
1670
- * Scoped to THIS turn's messages (from `turnStartMessageIndex`): seeded
1671
- * prior-turn rows were already adjudicated and must never re-trigger.
1672
- * Deliberately conservative: an ordinary tool failure (no hook-block text)
1673
- * is never reported, and a foreign hook denying with fully custom text evades
1674
- * the marker match (the documented residual — the install-time
1675
- * foreignGatingHooks warning still fires for diagnosability).
1676
- */
1677
- export function detectUnattributedHookBlocks(messages, turnStartMessageIndex, ledger, workspaceRoot) {
1678
- if (ledger.some((e) => denialKindOf(e) === "fail-closed"))
1679
- return [];
1680
- const ledgerTokens = new Set(ledger.map((e) => e.token));
1681
- const ledgerNormalizedSalients = new Set();
1682
- if (workspaceRoot) {
1683
- for (const entry of ledger) {
1684
- const decoded = decodeIdentityToken(entry.token);
1685
- if (!decoded)
1686
- continue;
1687
- const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
1688
- if (normalized)
1689
- ledgerNormalizedSalients.add(normalized);
1690
- }
1691
- }
1692
- const blocks = [];
1693
- for (const msg of messages.slice(Math.max(0, turnStartMessageIndex))) {
1694
- for (const tc of msg.toolCalls) {
1695
- if (tc.status !== ToolCallStatus.TOOL_CALL_FAILED)
1696
- continue;
1697
- if (!isHookBlockError(tc.error))
1698
- continue;
1699
- if (ledgerTokens.has(toolCallIdentityToken(tc)))
1700
- continue;
1701
- if (workspaceRoot) {
1702
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1703
- const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
1704
- if (normalized && ledgerNormalizedSalients.has(normalized))
1705
- continue;
1706
- }
1707
- blocks.push({ toolCallId: tc.id, toolName: tc.name, error: tc.error });
1708
- }
1709
- }
1710
- return blocks;
1711
- }
1712
- /**
1713
- * The honest terminal error stamped on a tool call that never resolved (issue
1714
- * #965). Deliberately states all three negatives — not executed, not approved,
1715
- * not denied — because the incident's harm was the model claiming an approval
1716
- * was pending: this text is what the transcript shows INSTEAD of a spinner or
1717
- * a silent after-the-fact interruption, and it must leave no room for an
1718
- * approval-is-coming reading.
1719
- */
1720
- export const UNRESOLVED_TOOL_CALL_ERROR = "The tool did not return a result before the turn ended. It was never " +
1721
- "executed, approved, or denied — no approval is pending for it.";
1722
- /**
1723
- * Settle this-turn tool calls that are still NON-TERMINAL when a turn
1724
- * completes without pausing — the issue #965 invariant, the sibling of
1725
- * {@link detectUnattributedHookBlocks}' #205 invariant ("a blocked tool must
1726
- * never silently complete" → "an unresolved tool must never silently
1727
- * complete").
1728
- *
1729
- * THE SHAPE THIS CATCHES. A tool that hangs INSIDE the Cursor agent runtime —
1730
- * the production case is `generateImage`, which rides the SDK's
1731
- * interaction-query channel rather than the ordinary tool path — streams a
1732
- * tool_call start, never streams a result, and is invisible to every Stigmer
1733
- * seam: the hook never denied it (no ledger entry), so the reconcile never
1734
- * gated it, and the turn completes with the row still PENDING/RUNNING. Before
1735
- * this sweep, the server's terminal settle (issue #207) stamped such rows
1736
- * TOOL_CALL_INTERRUPTED silently AFTER the runner reported completion — the
1737
- * transcript's last word stayed whatever the model claimed, which in
1738
- * aex_01m1a6ww3nmp4952ar5v0g4g85 was a promise that an approval was pending
1739
- * when none existed.
1740
- *
1741
- * Settling here instead makes the runner the author of the honest record: the
1742
- * row gets TOOL_CALL_INTERRUPTED with {@link UNRESOLVED_TOOL_CALL_ERROR}, and
1743
- * the caller (turn-boundary.ts) appends a system disclosure naming what never
1744
- * ran.
1745
- *
1746
- * WHY INTERRUPTED AND NEVER FAILED. TOOL_CALL_INTERRUPTED is deliberately the
1747
- * one settled status the monotonic merge guard lets live execution evidence
1748
- * supersede (see the guard's note in this file, ~line 331): if this FAILED
1749
- * execution is later RECOVERED, the harness checkpoint may re-execute the call
1750
- * under its original id, and the replayed events must be able to advance the
1751
- * row to its true outcome. A boundary-stamped FAILED would freeze it forever.
1752
- *
1753
- * WHY IT NEVER FAILS THE RUN (unlike #205). A foreign hook block is provably
1754
- * adversarial — approval semantics are permanently broken, so completing would
1755
- * always be a lie. An unresolved row can also be benign stream event-loss
1756
- * where the tool actually ran; failing the run would convert those into
1757
- * regressions. Disclosure restores honesty at zero regression risk.
1758
- *
1759
- * Scope and exclusions, in order:
1760
- * - THIS turn's parent-transcript rows only (from `turnStartMessageIndex`):
1761
- * seeded prior-turn rows were adjudicated by their own execution's settle,
1762
- * and sub-agent inner rows are the server settle's concern — the parent row
1763
- * (e.g. the Task call) is what the user sees. Mirrors #205's scoping.
1764
- * - Only PENDING/RUNNING rows: every terminal row was adjudicated, and
1765
- * WAITING_APPROVAL rows belong to the pause machinery (the caller only runs
1766
- * this sweep on a NON-pausing turn, so none should exist here anyway).
1767
- * - Only rows with NO denial-ledger entry of ANY kind (exact token, then the
1768
- * normalized-path fallback — the same two identities every sweep in this
1769
- * file uses): a ledger-attributed row is the unattended/secret/fail-closed
1770
- * machinery's to settle, not ours.
1771
- *
1772
- * Returns the settled calls so the boundary can disclose and log them.
1773
- */
1774
- export function settleUnresolvedToolCalls(messages, turnStartMessageIndex, ledger, workspaceRoot) {
1775
- const ledgerTokens = new Set(ledger.map((e) => e.token));
1776
- const ledgerNormalizedSalients = new Set();
1777
- if (workspaceRoot) {
1778
- for (const entry of ledger) {
1779
- const decoded = decodeIdentityToken(entry.token);
1780
- if (!decoded)
1781
- continue;
1782
- const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
1783
- if (normalized)
1784
- ledgerNormalizedSalients.add(normalized);
1785
- }
1786
- }
1787
- const matchesLedger = (tc) => {
1788
- if (ledgerTokens.has(toolCallIdentityToken(tc)))
1789
- return true;
1790
- if (!workspaceRoot)
1791
- return false;
1792
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1793
- const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
1794
- return !!normalized && ledgerNormalizedSalients.has(normalized);
1795
- };
1796
- const settled = [];
1797
- for (const msg of messages.slice(Math.max(0, turnStartMessageIndex))) {
1798
- for (const tc of msg.toolCalls) {
1799
- if (tc.status !== ToolCallStatus.TOOL_CALL_PENDING &&
1800
- tc.status !== ToolCallStatus.TOOL_CALL_RUNNING) {
1801
- continue;
1802
- }
1803
- if (matchesLedger(tc))
1804
- continue;
1805
- tc.status = ToolCallStatus.TOOL_CALL_INTERRUPTED;
1806
- tc.error = UNRESOLVED_TOOL_CALL_ERROR;
1807
- tc.isStreaming = false;
1808
- if (!tc.completedAt)
1809
- tc.completedAt = utcTimestamp();
1810
- settled.push({ toolCallId: tc.id, toolName: tc.name });
1811
- }
1812
- }
1813
- return settled;
1814
- }
1815
- /**
1816
- * Stamp the tool calls the hook denied under UNATTENDED approval mode
1817
- * (DD-014) as terminal TOOL_CALL_SKIPPED rows with UNATTENDED_SKIP
1818
- * provenance — the Cursor twin of the native harness's
1819
- * `reconcileUnattendedSkips`, so both harnesses persist the same honest
1820
- * shape for a platform-resolved skip.
1821
- *
1822
- * An unattended denial never pauses the run (its ledger kind is excluded
1823
- * from {@link approvalDenials}), so the stream leaves the denied call as a
1824
- * FAILED row carrying Cursor's generic hook-block error — dishonest ("the
1825
- * tool broke") and alarming in a transcript an org admin reviews. This pass
1826
- * correlates the unattended ledger entries to their streamed calls with the
1827
- * SAME two identities the rest of the file uses — exact token, then
1828
- * (category, workspace-normalized path) for the abs-vs-rel drift — and
1829
- * settles each match to SKIPPED with a result explaining the skip.
1830
- *
1831
- * Scope: hook-blocked FAILED rows and still-non-terminal (PENDING/RUNNING)
1832
- * rows only — a COMPLETED row is a real execution and is never rewritten
1833
- * (an unattended deny cannot produce one). `approval_action`/`approved_by`
1834
- * stay untouched: server-owned, human-decision-only fields (DD-014 D-e).
1835
- * Unmatched ledger entries need no synthesis — there is no pause to
1836
- * surface; the model already saw the deny and adapted in-turn.
1837
- *
1838
- * Returns how many tool calls were stamped.
1839
- */
1840
- export function stampUnattendedSkippedToolCalls(messages, subAgentExecutions, unattendedLedger, workspaceRoot) {
1841
- if (unattendedLedger.length === 0)
1842
- return 0;
1843
- const ledgerTokens = new Set(unattendedLedger.map((e) => e.token));
1844
- const ledgerNormalizedSalients = new Set();
1845
- if (workspaceRoot) {
1846
- for (const entry of unattendedLedger) {
1847
- const decoded = decodeIdentityToken(entry.token);
1848
- if (!decoded)
1849
- continue;
1850
- const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
1851
- if (normalized)
1852
- ledgerNormalizedSalients.add(normalized);
1853
- }
1854
- }
1855
- const matchesLedger = (tc) => {
1856
- if (ledgerTokens.has(toolCallIdentityToken(tc)))
1857
- return true;
1858
- if (!workspaceRoot)
1859
- return false;
1860
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1861
- const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
1862
- return !!normalized && ledgerNormalizedSalients.has(normalized);
1863
- };
1864
- let stamped = 0;
1865
- const apply = (msgs) => {
1866
- for (const msg of msgs) {
1867
- for (const tc of msg.toolCalls) {
1868
- const deniedShape = (tc.status === ToolCallStatus.TOOL_CALL_FAILED && isHookBlockError(tc.error)) ||
1869
- tc.status === ToolCallStatus.TOOL_CALL_PENDING ||
1870
- tc.status === ToolCallStatus.TOOL_CALL_RUNNING;
1871
- if (!deniedShape || !matchesLedger(tc))
1872
- continue;
1873
- tc.status = ToolCallStatus.TOOL_CALL_SKIPPED;
1874
- tc.approvalPolicySource = ApprovalPolicySource.UNATTENDED_SKIP;
1875
- tc.policyEngineVersion = POLICY_ENGINE_VERSION;
1876
- tc.error = "";
1877
- tc.result = unattendedSkipMessage(tc.name);
1878
- tc.isStreaming = false;
1879
- if (!tc.completedAt)
1880
- tc.completedAt = utcTimestamp();
1881
- stamped++;
1882
- }
1883
- }
1884
- };
1885
- apply(messages);
1886
- for (const subAgent of subAgentExecutions) {
1887
- apply(subAgent.messages);
1888
- }
1889
- return stamped;
1890
- }
1891
- /**
1892
- * Compute a streamed tool call's identity token in the same canonical space the
1893
- * preToolUse hook records denials in (see {@link toolIdentity} / primaryToken).
1894
- * The token keys on the cross-taxonomy category + salient resource PLUS, for a
1895
- * file edit/write, the {@link contentDigest} of the edit content — so a stream
1896
- * `edit` correlates to the hook's `Write` deny for the same path AND content,
1897
- * and an approval of one edit does not match a DIFFERENT edit to the same file.
1898
- *
1899
- * The digest is read from the persisted `approval_content_digest` field when
1900
- * present (a seeded gate carries it, stable even if `args` was elided), and is
1901
- * recomputed from the call's args otherwise (a freshly-streamed call). For a
1902
- * shell/delete/MCP call (no content) it falls back to the coarse token, exactly
1903
- * as before — so those identities are unchanged.
1904
- *
1905
- * Exported so the resume-grant round-trip can be locked against it: the grant a
1906
- * resume mints for an approved tool (buildApprovalGrants -> primaryToken) must
1907
- * equal THIS denial/overlay identity, or the re-issued call is re-gated forever
1908
- * (the dual-path drift the approval-state round-trip suite guards against).
1909
- */
1910
- export function toolCallIdentityToken(tc) {
1911
- const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
1912
- const digest = tc.approvalContentDigest || contentDigest(toolCallArgs(tc));
1913
- return primaryToken(id.key, id.salient, digest);
1914
- }
1915
- /**
1916
- * Decode a primary token back into its (key, salient, digest) for the synthesis
1917
- * fallback. The token is `base64(key \n salient)` (coarse) or
1918
- * `base64(key \n salient \n digest)` (content-exact); the digest is the optional
1919
- * third segment. salient never contains a newline (a path or shell command), so
1920
- * splitting on the first two newlines is unambiguous.
1921
- */
1922
- function decodeIdentityToken(token) {
1923
- try {
1924
- const decoded = Buffer.from(token, "base64").toString("utf-8");
1925
- const first = decoded.indexOf("\n");
1926
- if (first < 0)
1927
- return undefined;
1928
- const key = decoded.slice(0, first);
1929
- const rest = decoded.slice(first + 1);
1930
- const second = rest.indexOf("\n");
1931
- if (second < 0)
1932
- return { key, salient: rest, digest: "" };
1933
- return { key, salient: rest.slice(0, second), digest: rest.slice(second + 1) };
1934
- }
1935
- catch {
1936
- return undefined;
1937
- }
1938
- }
1939
- /** Best-effort args record for a tool call (proto struct, else parsed preview). */
1940
- function toolCallArgs(tc) {
1941
- if (tc.args && typeof tc.args === "object") {
1942
- return tc.args;
1943
- }
1944
- if (tc.argsPreview) {
1945
- try {
1946
- const parsed = JSON.parse(tc.argsPreview);
1947
- if (parsed && typeof parsed === "object")
1948
- return parsed;
1949
- }
1950
- catch {
1951
- // fall through
1952
- }
1953
- }
1954
- return {};
1955
- }
1956
- /**
1957
- * Mark a denied tool call as awaiting approval, clearing the result/terminal
1958
- * fields the stream may have set (the tool never actually ran — it was gated).
1959
- */
1960
- function markWaitingApproval(tc, mergedPolicies) {
1961
- tc.status = ToolCallStatus.TOOL_CALL_WAITING_APPROVAL;
1962
- tc.requiresApproval = true;
1963
- if (!tc.approvalMessage) {
1964
- tc.approvalMessage = resolveDeniedApprovalMessage(tc.name, tc.mcpServerSlug, toolCallArgs(tc), mergedPolicies);
1965
- }
1966
- if (!tc.approvalRequestedAt)
1967
- tc.approvalRequestedAt = utcTimestamp();
1968
- tc.completedAt = "";
1969
- tc.error = "";
1970
- tc.result = "";
1971
- }
1972
- function synthesizeWaitingApprovalToolCall(displayName, salient, digest, token, mergedPolicies) {
1973
- const tc = create(ToolCallSchema, {
1974
- id: `approval:${token}`,
1975
- name: displayName,
1976
- status: ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,
1977
- requiresApproval: true,
1978
- startedAt: utcTimestamp(),
1979
- approvalRequestedAt: utcTimestamp(),
1980
- toolKind: classifyTool(displayName),
1981
- // Carry the decoded digest so this placeholder's identity (and the grant
1982
- // rebuilt from it on resume) equals the anchor's content token. applyGateInput
1983
- // overwrites it from the authoritative input when one was captured.
1984
- approvalContentDigest: digest,
1985
- });
1986
- // Carry the salient resource so reconstructAdjudicatedApprovals -> the grant
1987
- // builder keys on the same resource the hook will see on the re-attempt.
1988
- if (salient) {
1989
- tc.argsPreview = JSON.stringify({ path: salient });
1990
- }
1991
- tc.approvalMessage = salient
1992
- ? `Tool requires approval: ${displayName} (${salient})`
1993
- : resolveDeniedApprovalMessage(displayName, "", {}, mergedPolicies);
1994
- // A synthesized call is a ledger denial — it was gated, so it has a governing
1995
- // layer. A denied call never occurs under a global bypass or a matching lease,
1996
- // so empty leases + no bypass faithfully attribute it (a built-in resolves to
1997
- // builtin_category; an MCP placeholder lacks a reconstructed slug and stays
1998
- // UNSPECIFIED rather than be mislabeled).
1999
- if (mergedPolicies) {
2000
- const source = resolveApprovalProvenance(displayName, "", mergedPolicies, NO_LEASED_CATEGORIES, false);
2001
- tc.approvalPolicySource = toProtoPolicySource(source);
2002
- if (source)
2003
- tc.policyEngineVersion = POLICY_ENGINE_VERSION;
2004
- }
2005
- return tc;
2006
- }
2007
- /**
2008
- * Resolve a human-readable approval message for a denied tool, preferring the
2009
- * MCP policy template, then the built-in template, then a generic fallback.
2010
- */
2011
- function resolveDeniedApprovalMessage(name, mcpServerSlug, args, mergedPolicies) {
2012
- if (mergedPolicies && mcpServerSlug) {
2013
- const policy = lookupMcpToolPolicy(name, mcpServerSlug, mergedPolicies);
2014
- if (policy)
2015
- return resolveApprovalMessage(policy.approvalMessage, name, args);
2016
- }
2017
- if (!mcpServerSlug) {
2018
- const template = getBuiltInApprovalMessage(name);
2019
- if (template)
2020
- return resolveApprovalMessage(template, name, args);
2021
- }
2022
- return `Tool requires approval: ${name}`;
2023
- }
2024
- /** Append a tool call to the last AI message, creating one if none exists. */
2025
- function appendToolCallToLastAiMessage(messages, tc) {
2026
- for (let i = messages.length - 1; i >= 0; i--) {
2027
- if (messages[i].type === MessageType.MESSAGE_AI) {
2028
- messages[i].toolCalls.push(tc);
2029
- return;
2030
- }
2031
- }
2032
- const msg = create(AgentMessageSchema, {
2033
- type: MessageType.MESSAGE_AI,
2034
- content: "",
2035
- timestamp: utcTimestamp(),
2036
- toolCalls: [tc],
2037
- });
2038
- messages.push(msg);
2039
- }
2040
- //# sourceMappingURL=message-translator.js.map