eve 0.71.2 → 0.72.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 (470) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +22 -6
  3. package/dist/src/acp/adapter.js +1 -1
  4. package/dist/src/ai/decide.d.ts +7 -0
  5. package/dist/src/ai/decide.js +1 -0
  6. package/dist/src/channel/conversation-context.d.ts +4 -1
  7. package/dist/src/channel/invoke-tool.d.ts +41 -0
  8. package/dist/src/channel/invoke-tool.js +1 -0
  9. package/dist/src/channel/routes.d.ts +3 -0
  10. package/dist/src/chunks/{use-eve-agent-CFCaYnrI.js → use-eve-agent-C1GYGCtb.js} +698 -388
  11. package/dist/src/chunks/{use-eve-agent-DcDhXNv1.js → use-eve-agent-hZJ7CB8t.js} +698 -388
  12. package/dist/src/cli/commands/integration-setup.js +1 -1
  13. package/dist/src/cli/commands/registry.js +1 -1
  14. package/dist/src/cli/commands/trace-detail.d.ts +1 -1
  15. package/dist/src/cli/commands/trace-detail.js +1 -1
  16. package/dist/src/cli/dev/tui/runner.js +1 -1
  17. package/dist/src/cli/dev/tui/setup-flow.d.ts +1 -0
  18. package/dist/src/cli/dev/tui/setup-panel.d.ts +1 -0
  19. package/dist/src/cli/dev/tui/setup-panel.js +2 -1
  20. package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +2 -2
  21. package/dist/src/cli/dev/tui/traces/trace-conversation.js +2 -2
  22. package/dist/src/cli/dev/tui/transcript-parts.d.ts +2 -1
  23. package/dist/src/cli/dev/tui/transcript-parts.js +1 -1
  24. package/dist/src/cli/dev/tui/transcript.js +1 -1
  25. package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
  26. package/dist/src/client/conversation-projection.d.ts +4 -0
  27. package/dist/src/client/conversation-projection.js +1 -0
  28. package/dist/src/client/conversation-reducer.js +1 -1
  29. package/dist/src/client/conversation-state.d.ts +5 -26
  30. package/dist/src/client/conversation-state.js +1 -1
  31. package/dist/src/client/index.d.ts +1 -0
  32. package/dist/src/client/index.js +1 -1
  33. package/dist/src/client/message-action-parts.d.ts +1 -11
  34. package/dist/src/client/message-action-parts.js +1 -1
  35. package/dist/src/client/message-reducer.d.ts +3 -1
  36. package/dist/src/client/message-reducer.js +1 -1
  37. package/dist/src/client/session-utils.js +1 -1
  38. package/dist/src/client/session.js +1 -1
  39. package/dist/src/client/tool-call-state.d.ts +23 -0
  40. package/dist/src/client/tool-call-state.js +1 -0
  41. package/dist/src/client/tool-part-state.d.ts +7 -0
  42. package/dist/src/client/tool-part-state.js +1 -0
  43. package/dist/src/compiled/.vendor-stamp.json +10 -10
  44. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +1453 -1358
  45. package/dist/src/compiled/@ai-sdk/anthropic/index.js +1 -2
  46. package/dist/src/compiled/@ai-sdk/code-mode/index.d.ts +172 -163
  47. package/dist/src/compiled/@ai-sdk/code-mode/index.js +15 -20
  48. package/dist/src/compiled/@ai-sdk/google/index.d.ts +772 -733
  49. package/dist/src/compiled/@ai-sdk/google/index.js +6 -8
  50. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +887 -790
  51. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  52. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +1722 -1691
  53. package/dist/src/compiled/@ai-sdk/openai/index.js +3 -14
  54. package/dist/src/compiled/@ai-sdk/otel/index.d.ts +216 -159
  55. package/dist/src/compiled/@ai-sdk/otel/index.js +3 -3
  56. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +7542 -7271
  57. package/dist/src/compiled/@ai-sdk/provider/index.js +1 -3
  58. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +1799 -1600
  59. package/dist/src/compiled/@eve/catalog/index.js +1 -1
  60. package/dist/src/compiled/_chunks/workflow/dist-DXLdlucM.js +15 -0
  61. package/dist/src/compiled/_chunks/workflow/experimental-decision-BrfWf6-n.js +3 -0
  62. package/dist/src/compiler/extension-compatibility.d.ts +36 -20
  63. package/dist/src/compiler/extension-compatibility.js +1 -1
  64. package/dist/src/compiler/manifest.js +1 -1
  65. package/dist/src/context/build-dynamic-tools.js +1 -1
  66. package/dist/src/context/caller-scope.d.ts +7 -0
  67. package/dist/src/context/caller-scope.js +1 -0
  68. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  69. package/dist/src/context/dynamic-tool-metadata.d.ts +1 -0
  70. package/dist/src/context/providers/session.js +1 -1
  71. package/dist/src/evals/define-eval.d.ts +1 -1
  72. package/dist/src/evals/judge.d.ts +1 -1
  73. package/dist/src/evals/judge.js +2 -2
  74. package/dist/src/evals/types.d.ts +8 -8
  75. package/dist/src/execution/cancel-descendant-turns-step.d.ts +1 -0
  76. package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
  77. package/dist/src/execution/cancelled-model-call-batch.js +1 -1
  78. package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -1
  79. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  80. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  81. package/dist/src/execution/durable-session-read.d.ts +5 -0
  82. package/dist/src/execution/durable-session-read.js +1 -0
  83. package/dist/src/execution/durable-session-store.d.ts +4 -10
  84. package/dist/src/execution/durable-session-store.js +1 -1
  85. package/dist/src/execution/dynamic-connections.d.ts +3 -3
  86. package/dist/src/execution/dynamic-connections.js +1 -1
  87. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  88. package/dist/src/execution/invoke-tool.d.ts +35 -0
  89. package/dist/src/execution/invoke-tool.js +1 -0
  90. package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
  91. package/dist/src/execution/legacy-session/snapshot.d.ts +3 -0
  92. package/dist/src/execution/legacy-session/snapshot.js +1 -1
  93. package/dist/src/execution/model-call-batching.js +1 -1
  94. package/dist/src/execution/node-step.d.ts +2 -0
  95. package/dist/src/execution/node-step.js +1 -1
  96. package/dist/src/execution/proxied-deliver-step.js +1 -1
  97. package/dist/src/execution/publish-session-events.d.ts +8 -0
  98. package/dist/src/execution/publish-session-events.js +1 -1
  99. package/dist/src/execution/sandbox/active-handles.d.ts +6 -0
  100. package/dist/src/execution/sandbox/active-handles.js +1 -1
  101. package/dist/src/execution/sandbox/ensure.js +1 -1
  102. package/dist/src/execution/session/active-turn.js +1 -1
  103. package/dist/src/execution/session/answer-caller.d.ts +15 -0
  104. package/dist/src/execution/session/answer-caller.js +1 -0
  105. package/dist/src/execution/session/checkpoint-migrations.js +1 -1
  106. package/dist/src/execution/session/finalization.js +1 -1
  107. package/dist/src/execution/session/handoff-steps.d.ts +3 -1
  108. package/dist/src/execution/session/handoff-steps.js +1 -1
  109. package/dist/src/execution/session/handoff.d.ts +1 -1
  110. package/dist/src/execution/session/handoff.js +1 -1
  111. package/dist/src/execution/session/pending-turn-state.d.ts +8 -3
  112. package/dist/src/execution/session/pending-turn-state.js +1 -1
  113. package/dist/src/execution/session/task-tool-tracing-step.d.ts +5 -0
  114. package/dist/src/execution/session/task-tool-tracing-step.js +1 -0
  115. package/dist/src/execution/session/turn-step-result.js +1 -1
  116. package/dist/src/execution/session/turn-step.js +1 -1
  117. package/dist/src/execution/session/turn-waiting-step.js +1 -1
  118. package/dist/src/execution/session/turn.d.ts +1 -0
  119. package/dist/src/execution/session/turn.js +1 -1
  120. package/dist/src/execution/settle-cancelled-turn-step.d.ts +4 -6
  121. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  122. package/dist/src/execution/tasks/start.d.ts +3 -3
  123. package/dist/src/execution/tasks/start.js +1 -1
  124. package/dist/src/execution/tasks/steps.d.ts +1 -1
  125. package/dist/src/execution/tasks/steps.js +1 -1
  126. package/dist/src/execution/terminal-session-completion-step.d.ts +7 -0
  127. package/dist/src/execution/terminal-session-completion-step.js +1 -1
  128. package/dist/src/execution/terminal-session-failure-step.js +1 -1
  129. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  130. package/dist/src/execution/tools/connection-tools.js +1 -1
  131. package/dist/src/execution/tools/workflow/authorization-completion.js +1 -1
  132. package/dist/src/execution/tools/workflow/harness-definition.js +1 -1
  133. package/dist/src/execution/tools/workflow/step-execution.js +1 -1
  134. package/dist/src/execution/tools/workflow/step.js +1 -1
  135. package/dist/src/execution/tools/workflow/withdraw-step.d.ts +7 -9
  136. package/dist/src/execution/tools/workflow/withdraw-step.js +1 -1
  137. package/dist/src/execution/workflow-runtime.js +1 -1
  138. package/dist/src/execution/workflow-trace-context.d.ts +2 -2
  139. package/dist/src/harness/authorization.d.ts +4 -2
  140. package/dist/src/harness/authorization.js +1 -1
  141. package/dist/src/harness/{compaction.js → compaction/engine.js} +1 -1
  142. package/dist/src/harness/compaction/step.d.ts +46 -0
  143. package/dist/src/harness/compaction/step.js +1 -0
  144. package/dist/src/harness/coordination.d.ts +32 -64
  145. package/dist/src/harness/coordination.js +1 -1
  146. package/dist/src/harness/current-messages.d.ts +1 -3
  147. package/dist/src/harness/current-messages.js +1 -1
  148. package/dist/src/harness/emission.d.ts +4 -52
  149. package/dist/src/harness/emission.js +1 -1
  150. package/dist/src/harness/execute-tool.d.ts +1 -0
  151. package/dist/src/harness/final-output.d.ts +5 -0
  152. package/dist/src/harness/final-output.js +1 -1
  153. package/dist/src/harness/hitl/approvals.d.ts +115 -0
  154. package/dist/src/harness/hitl/approvals.js +1 -0
  155. package/dist/src/harness/hitl/approved-call-callers.d.ts +14 -0
  156. package/dist/src/harness/hitl/approved-call-callers.js +1 -0
  157. package/dist/src/harness/hitl/approved-calls.d.ts +37 -0
  158. package/dist/src/harness/hitl/approved-calls.js +1 -0
  159. package/dist/src/harness/{session-limit-continuation.d.ts → hitl/budget-request.d.ts} +3 -1
  160. package/dist/src/harness/hitl/budget-request.js +1 -0
  161. package/dist/src/harness/hitl/budget.d.ts +21 -0
  162. package/dist/src/harness/hitl/budget.js +1 -0
  163. package/dist/src/harness/{approval-candidates.d.ts → hitl/candidates.d.ts} +13 -18
  164. package/dist/src/harness/hitl/candidates.js +1 -0
  165. package/dist/src/harness/hitl/coordinator.js +1 -0
  166. package/dist/src/harness/hitl/delivery.d.ts +37 -0
  167. package/dist/src/harness/hitl/delivery.js +1 -0
  168. package/dist/src/harness/hitl/index.d.ts +49 -0
  169. package/dist/src/harness/hitl/index.js +1 -0
  170. package/dist/src/harness/hitl/intake.d.ts +67 -0
  171. package/dist/src/harness/hitl/intake.js +1 -0
  172. package/dist/src/harness/{stale-input-responses.d.ts → hitl/stale-responses.d.ts} +5 -3
  173. package/dist/src/harness/hitl/stale-responses.js +3 -0
  174. package/dist/src/harness/inline-tool-authorization.d.ts +4 -0
  175. package/dist/src/harness/inline-tool-authorization.js +1 -1
  176. package/dist/src/harness/input-extraction.d.ts +1 -10
  177. package/dist/src/harness/input-extraction.js +1 -1
  178. package/dist/src/harness/input-request-resolution.d.ts +1 -5
  179. package/dist/src/harness/input-request-resolution.js +1 -1
  180. package/dist/src/harness/messages.js +1 -1
  181. package/dist/src/harness/model-call/call.d.ts +78 -0
  182. package/dist/src/harness/model-call/call.js +1 -0
  183. package/dist/src/harness/{model-call-error.d.ts → model-call/errors.d.ts} +1 -1
  184. package/dist/src/harness/model-call/failure.d.ts +52 -0
  185. package/dist/src/harness/model-call/failure.js +1 -0
  186. package/dist/src/harness/model-call/model.d.ts +18 -0
  187. package/dist/src/harness/model-call/model.js +1 -0
  188. package/dist/src/harness/model-call/recovery.d.ts +52 -0
  189. package/dist/src/harness/model-call/recovery.js +1 -0
  190. package/dist/src/harness/model-call/request.d.ts +30 -0
  191. package/dist/src/harness/model-call/request.js +3 -0
  192. package/dist/src/harness/model-call/response.d.ts +39 -0
  193. package/dist/src/harness/model-call/response.js +1 -0
  194. package/dist/src/harness/model-call/retry.d.ts +11 -0
  195. package/dist/src/harness/model-call/retry.js +1 -0
  196. package/dist/src/harness/model-call/run.d.ts +38 -0
  197. package/dist/src/harness/model-call/run.js +1 -0
  198. package/dist/src/harness/model-call/tools.d.ts +48 -0
  199. package/dist/src/harness/model-call/tools.js +1 -0
  200. package/dist/src/harness/model-call/usage.d.ts +23 -0
  201. package/dist/src/harness/model-call/usage.js +1 -0
  202. package/dist/src/harness/nested-actions.d.ts +2 -2
  203. package/dist/src/harness/provider-tools.d.ts +7 -3
  204. package/dist/src/harness/provider-tools.js +1 -1
  205. package/dist/src/harness/proxy-input-requests.d.ts +4 -12
  206. package/dist/src/harness/proxy-input-requests.js +1 -1
  207. package/dist/src/harness/session-machine/commit.d.ts +28 -0
  208. package/dist/src/harness/session-machine/commit.js +1 -0
  209. package/dist/src/harness/session-machine/current.d.ts +29 -0
  210. package/dist/src/harness/session-machine/current.js +1 -0
  211. package/dist/src/harness/session-machine/events.d.ts +6 -0
  212. package/dist/src/harness/session-machine/events.js +1 -0
  213. package/dist/src/harness/session-machine/resolver-events.d.ts +12 -0
  214. package/dist/src/harness/session-machine/resolver-events.js +1 -0
  215. package/dist/src/harness/session-machine/state.d.ts +47 -0
  216. package/dist/src/harness/session-machine/state.js +1 -0
  217. package/dist/src/harness/session-machine/transitions.d.ts +188 -0
  218. package/dist/src/harness/session-machine/transitions.js +1 -0
  219. package/dist/src/harness/session-machine/view.d.ts +58 -0
  220. package/dist/src/harness/session-machine/view.js +1 -0
  221. package/dist/src/harness/step/after-model.d.ts +7 -0
  222. package/dist/src/harness/step/after-model.js +1 -0
  223. package/dist/src/harness/step/context.d.ts +59 -0
  224. package/dist/src/harness/step/context.js +1 -0
  225. package/dist/src/harness/step/intake.d.ts +34 -0
  226. package/dist/src/harness/step/intake.js +1 -0
  227. package/dist/src/harness/step/prompt.d.ts +37 -0
  228. package/dist/src/harness/step/prompt.js +1 -0
  229. package/dist/src/harness/step-hooks.d.ts +8 -13
  230. package/dist/src/harness/step-hooks.js +1 -1
  231. package/dist/src/harness/tool-call-io.d.ts +25 -0
  232. package/dist/src/harness/tool-call-io.js +1 -0
  233. package/dist/src/harness/tool-loop.d.ts +7 -22
  234. package/dist/src/harness/tool-loop.js +1 -3
  235. package/dist/src/harness/tool-model-output.d.ts +1 -2
  236. package/dist/src/harness/tools.d.ts +14 -0
  237. package/dist/src/harness/tools.js +1 -1
  238. package/dist/src/harness/turn-tag-state.d.ts +1 -1
  239. package/dist/src/harness/types.d.ts +6 -0
  240. package/dist/src/instrumentation/ai-sdk-hook-bridge.d.ts +1 -1
  241. package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -1
  242. package/dist/src/instrumentation/content.js +1 -1
  243. package/dist/src/instrumentation/dispatch.js +1 -1
  244. package/dist/src/instrumentation/lifecycle.d.ts +28 -52
  245. package/dist/src/instrumentation/native-events.d.ts +2 -1
  246. package/dist/src/instrumentation/native-events.js +1 -1
  247. package/dist/src/instrumentation/provider.d.ts +1 -1
  248. package/dist/src/instrumentation/runtime-context.d.ts +2 -3
  249. package/dist/src/instrumentation/runtime-context.js +1 -1
  250. package/dist/src/instrumentation/runtime.d.ts +11 -1
  251. package/dist/src/instrumentation/runtime.js +1 -1
  252. package/dist/src/instrumentation/state.d.ts +6 -1
  253. package/dist/src/instrumentation/state.js +1 -1
  254. package/dist/src/internal/application/package.js +1 -1
  255. package/dist/src/internal/attachments/limited-read.d.ts +16 -0
  256. package/dist/src/internal/attachments/limited-read.js +1 -0
  257. package/dist/src/internal/authored-definition/schema-backed.d.ts +2 -1
  258. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  259. package/dist/src/internal/gateway.d.ts +2 -0
  260. package/dist/src/internal/gateway.js +1 -1
  261. package/dist/src/internal/mcp/published-tools.d.ts +13 -0
  262. package/dist/src/internal/mcp/published-tools.js +1 -0
  263. package/dist/src/internal/mcp/request-trace-context.d.ts +12 -0
  264. package/dist/src/internal/mcp/request-trace-context.js +1 -0
  265. package/dist/src/internal/mcp/streamable-http-server.d.ts +7 -3
  266. package/dist/src/internal/mcp/streamable-http-server.js +1 -1
  267. package/dist/src/internal/model-auth/transport.d.ts +3 -3
  268. package/dist/src/internal/model-auth/transport.js +1 -1
  269. package/dist/src/internal/nitro/host/instrumentation-entry.js +2 -2
  270. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  271. package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
  272. package/dist/src/internal/nitro/routes/route-invoke-tool.d.ts +24 -0
  273. package/dist/src/internal/nitro/routes/route-invoke-tool.js +1 -0
  274. package/dist/src/models/auto.d.ts +5 -5
  275. package/dist/src/models/auto.js +2 -2
  276. package/dist/src/protocol/message.d.ts +7 -0
  277. package/dist/src/protocol/message.js +1 -1
  278. package/dist/src/protocol/session-projection.d.ts +159 -0
  279. package/dist/src/protocol/session-projection.js +1 -0
  280. package/dist/src/public/ai/index.d.ts +1 -1
  281. package/dist/src/public/ai/index.js +1 -1
  282. package/dist/src/public/channels/chat-sdk/attachment-refs.d.ts +15 -0
  283. package/dist/src/public/channels/chat-sdk/attachment-refs.js +1 -0
  284. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  285. package/dist/src/public/channels/chat-sdk/messageToUserContent.d.ts +11 -5
  286. package/dist/src/public/channels/chat-sdk/messageToUserContent.js +1 -1
  287. package/dist/src/public/channels/discord/attachments.d.ts +15 -0
  288. package/dist/src/public/channels/discord/attachments.js +1 -0
  289. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  290. package/dist/src/public/channels/discord/inbound.d.ts +13 -0
  291. package/dist/src/public/channels/discord/inbound.js +1 -1
  292. package/dist/src/public/channels/index.d.ts +1 -1
  293. package/dist/src/public/channels/linear/inbound-uploads.d.ts +21 -0
  294. package/dist/src/public/channels/linear/inbound-uploads.js +1 -0
  295. package/dist/src/public/channels/linear/linearChannel.js +1 -1
  296. package/dist/src/public/channels/linq/inboundContent.d.ts +7 -1
  297. package/dist/src/public/channels/linq/inboundContent.js +1 -1
  298. package/dist/src/public/channels/linq/linqChannel.js +1 -1
  299. package/dist/src/public/channels/mcp.d.ts +17 -2
  300. package/dist/src/public/channels/mcp.js +1 -1
  301. package/dist/src/public/channels/photon/attachments.d.ts +21 -0
  302. package/dist/src/public/channels/photon/attachments.js +1 -0
  303. package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
  304. package/dist/src/public/channels/slack/attachments.d.ts +3 -1
  305. package/dist/src/public/channels/slack/attachments.js +1 -1
  306. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  307. package/dist/src/public/channels/teams/attachments.d.ts +4 -4
  308. package/dist/src/public/channels/teams/attachments.js +1 -1
  309. package/dist/src/public/channels/telegram/attachments.js +1 -1
  310. package/dist/src/public/channels/twilio/api.d.ts +7 -0
  311. package/dist/src/public/channels/twilio/api.js +1 -1
  312. package/dist/src/public/channels/twilio/inbound.d.ts +7 -0
  313. package/dist/src/public/channels/twilio/inbound.js +2 -2
  314. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  315. package/dist/src/public/definitions/channel.d.ts +1 -0
  316. package/dist/src/public/definitions/connections/mcp.d.ts +1 -1
  317. package/dist/src/public/definitions/connections/openapi.d.ts +1 -1
  318. package/dist/src/public/models/openai/chatgpt/model.js +1 -1
  319. package/dist/src/react/index.d.ts +1 -0
  320. package/dist/src/react/index.js +1 -1
  321. package/dist/src/runtime/agent/mock-model-adapter.js +2 -2
  322. package/dist/src/runtime/connections/mcp-client.js +1 -1
  323. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  324. package/dist/src/runtime/resolve-tool.js +1 -1
  325. package/dist/src/setup/boxes/resolve-provisioning.d.ts +2 -0
  326. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  327. package/dist/src/setup/cli/prompt-ui.d.ts +3 -0
  328. package/dist/src/setup/cli/prompt-ui.js +3 -1
  329. package/dist/src/setup/cli/select-component.d.ts +1 -0
  330. package/dist/src/setup/cli/select-component.js +1 -1
  331. package/dist/src/setup/flows/ensure-vercel-project.d.ts +2 -0
  332. package/dist/src/setup/flows/ensure-vercel-project.js +1 -1
  333. package/dist/src/setup/integrations/discord/api.js +1 -1
  334. package/dist/src/setup/integrations/web/auth-options.d.ts +4 -0
  335. package/dist/src/setup/integrations/web/auth-options.js +1 -0
  336. package/dist/src/setup/integrations/web/auth-scaffold.d.ts +7 -0
  337. package/dist/src/setup/integrations/web/auth-scaffold.js +1 -0
  338. package/dist/src/setup/integrations/web/provision-auth.d.ts +3 -0
  339. package/dist/src/setup/integrations/web/provision-auth.js +1 -0
  340. package/dist/src/setup/integrations/web/setup.d.ts +11 -6
  341. package/dist/src/setup/integrations/web/setup.js +3 -3
  342. package/dist/src/setup/prompter.d.ts +2 -0
  343. package/dist/src/setup/prompter.js +1 -1
  344. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  345. package/dist/src/setup/scaffold/create/project.js +2 -2
  346. package/dist/src/setup/scaffold/create/web-template.d.ts +3 -3
  347. package/dist/src/setup/scaffold/create/web-template.js +26 -8
  348. package/dist/src/setup/scaffold/update/web-options.js +1 -1
  349. package/dist/src/setup/vercel-project-api.d.ts +9 -0
  350. package/dist/src/setup/vercel-project-api.js +1 -1
  351. package/dist/src/setup/vercel-project.d.ts +4 -2
  352. package/dist/src/setup/vercel-project.js +0 -0
  353. package/dist/src/shared/web-search.d.ts +1 -1
  354. package/dist/src/subagents/adapter.js +1 -1
  355. package/dist/src/subagents/event-proxy-step.js +1 -1
  356. package/dist/src/subagents/hitl-proxy.d.ts +4 -28
  357. package/dist/src/subagents/hitl-proxy.js +1 -1
  358. package/dist/src/svelte/index.d.ts +2 -0
  359. package/dist/src/svelte/index.js +39 -2
  360. package/dist/src/svelte/use-eve-agent.js +1 -1
  361. package/dist/src/tools/approval/policies.d.ts +5 -5
  362. package/dist/src/tools/approval/policies.js +1 -1
  363. package/dist/src/tools/framework/agent.js +1 -1
  364. package/dist/src/tools/provided/agent-router.js +1 -1
  365. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  366. package/dist/src/tools/provided/ask-question.js +2 -2
  367. package/dist/src/tools/provided/bash.js +1 -1
  368. package/dist/src/tools/provided/framework-tool.d.ts +3 -0
  369. package/dist/src/tools/provided/framework-tool.js +1 -0
  370. package/dist/src/tools/provided/glob.js +2 -2
  371. package/dist/src/tools/provided/grep.js +2 -2
  372. package/dist/src/tools/provided/load-skill.js +1 -1
  373. package/dist/src/tools/provided/no-reply.js +1 -1
  374. package/dist/src/tools/provided/read-file.js +2 -2
  375. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  376. package/dist/src/tools/provided/sleep.js +1 -1
  377. package/dist/src/tools/provided/task-cancel.js +1 -1
  378. package/dist/src/tools/provided/task-wait.js +1 -1
  379. package/dist/src/tools/provided/web-fetch.js +2 -2
  380. package/dist/src/tools/provided/web-search.js +1 -1
  381. package/dist/src/tools/provided/workflow.js +1 -1
  382. package/dist/src/tools/provided/write-file.js +2 -2
  383. package/dist/src/tracing/agent-approval-instrumentation.d.ts +2 -2
  384. package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
  385. package/dist/src/tracing/agent-otel-provider.js +2 -2
  386. package/dist/src/tracing/agent-otel-usage.d.ts +1 -1
  387. package/dist/src/tracing/agent-otel-usage.js +1 -1
  388. package/dist/src/tracing/agent-span-contract.d.ts +8 -1
  389. package/dist/src/tracing/agent-span-contract.js +1 -1
  390. package/dist/src/tracing/agent-tool-instrumentation.d.ts +16 -5
  391. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  392. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  393. package/dist/src/tracing/agent-trace-span-processor.js +1 -1
  394. package/dist/src/tracing/agent-trace-state.d.ts +8 -3
  395. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  396. package/dist/src/tracing/invoke-tool-span.d.ts +61 -0
  397. package/dist/src/tracing/invoke-tool-span.js +1 -0
  398. package/dist/src/tracing/local-trace-analysis.js +1 -1
  399. package/dist/src/vue/index.d.ts +2 -0
  400. package/dist/src/vue/index.js +39 -2
  401. package/dist/src/vue/use-eve-agent.js +1 -1
  402. package/docs/agent-config.md +2 -2
  403. package/docs/channels/chat-sdk.mdx +3 -1
  404. package/docs/channels/custom.mdx +3 -0
  405. package/docs/channels/discord.mdx +5 -4
  406. package/docs/channels/eve.mdx +65 -0
  407. package/docs/channels/linear.mdx +1 -1
  408. package/docs/channels/linq.mdx +2 -0
  409. package/docs/channels/mcp.mdx +39 -1
  410. package/docs/channels/photon.mdx +5 -0
  411. package/docs/channels/teams.mdx +4 -7
  412. package/docs/channels/twilio.mdx +1 -1
  413. package/docs/concepts/built-in-tools.md +12 -0
  414. package/docs/concepts/sessions-runs-and-streaming.md +3 -3
  415. package/docs/connections/overview.mdx +1 -1
  416. package/docs/dynamic-configuration/meta.json +1 -1
  417. package/docs/evals/judge.mdx +16 -16
  418. package/docs/evals/overview.mdx +1 -1
  419. package/docs/guides/{evaluate.md → decide.md} +35 -35
  420. package/docs/guides/dynamic-capabilities.md +1 -1
  421. package/docs/guides/frontend/overview.mdx +3 -1
  422. package/docs/guides/hooks.md +1 -1
  423. package/docs/guides/instrumentation/instrumentation.mdx +23 -22
  424. package/docs/guides/instrumentation/otel.mdx +13 -2
  425. package/docs/reference/cli.md +4 -2
  426. package/docs/reference/typescript-api.md +4 -2
  427. package/docs/tools/human-in-the-loop.md +8 -4
  428. package/docs/tools/workflows.mdx +4 -4
  429. package/package.json +13 -11
  430. package/dist/src/ai/evaluate.d.ts +0 -7
  431. package/dist/src/ai/evaluate.js +0 -1
  432. package/dist/src/client/message-task-parts.d.ts +0 -8
  433. package/dist/src/client/message-task-parts.js +0 -1
  434. package/dist/src/compiled/_chunks/workflow/dist-C3ZE62yI.js +0 -25
  435. package/dist/src/compiled/_chunks/workflow/experimental-evaluation-Dm32egEG.js +0 -5
  436. package/dist/src/harness/active-turn-id.d.ts +0 -11
  437. package/dist/src/harness/active-turn-id.js +0 -1
  438. package/dist/src/harness/approval-candidates.js +0 -1
  439. package/dist/src/harness/approval-delivery-coordinator.js +0 -1
  440. package/dist/src/harness/cancelled-turn-emission.d.ts +0 -12
  441. package/dist/src/harness/cancelled-turn-emission.js +0 -1
  442. package/dist/src/harness/emission-state.d.ts +0 -26
  443. package/dist/src/harness/emission-state.js +0 -1
  444. package/dist/src/harness/held-requests.d.ts +0 -18
  445. package/dist/src/harness/held-requests.js +0 -1
  446. package/dist/src/harness/hitl/approval-input-requests.d.ts +0 -27
  447. package/dist/src/harness/hitl/approval-input-requests.js +0 -1
  448. package/dist/src/harness/hitl/pending-input-resolution.d.ts +0 -54
  449. package/dist/src/harness/hitl/pending-input-resolution.js +0 -1
  450. package/dist/src/harness/hitl/session-limit-input-requests.d.ts +0 -12
  451. package/dist/src/harness/hitl/session-limit-input-requests.js +0 -1
  452. package/dist/src/harness/input-requests.d.ts +0 -31
  453. package/dist/src/harness/input-requests.js +0 -1
  454. package/dist/src/harness/pending-input-batches.d.ts +0 -81
  455. package/dist/src/harness/pending-input-batches.js +0 -1
  456. package/dist/src/harness/session-limit-continuation.js +0 -1
  457. package/dist/src/harness/session-limit-enforcement.d.ts +0 -45
  458. package/dist/src/harness/session-limit-enforcement.js +0 -1
  459. package/dist/src/harness/stale-input-responses.js +0 -3
  460. package/dist/src/harness/workflow-dispatch.d.ts +0 -30
  461. package/dist/src/harness/workflow-dispatch.js +0 -1
  462. package/dist/src/public/channels/linear/inbound-images.d.ts +0 -19
  463. package/dist/src/public/channels/linear/inbound-images.js +0 -1
  464. package/dist/src/tracing/agent-action-instrumentation.d.ts +0 -25
  465. package/dist/src/tracing/agent-action-instrumentation.js +0 -1
  466. /package/dist/src/harness/{compaction.d.ts → compaction/engine.d.ts} +0 -0
  467. /package/dist/src/harness/{compaction-prompt.d.ts → compaction/prompt.d.ts} +0 -0
  468. /package/dist/src/harness/{compaction-prompt.js → compaction/prompt.js} +0 -0
  469. /package/dist/src/harness/{approval-delivery-coordinator.d.ts → hitl/coordinator.d.ts} +0 -0
  470. /package/dist/src/harness/{model-call-error.js → model-call/errors.js} +0 -0
@@ -0,0 +1,188 @@
1
+ import type { ModelMessage, UserContent } from "ai";
2
+ import type { SubagentAuthorizationEventHookPayload, SubagentInputRequestHookPayload } from "#channel/types.js";
3
+ import type { AuthorizationChallenge } from "#harness/authorization.js";
4
+ import { type TurnWaitingOn, createSessionCompletedEvent, createSessionFailedEvent, type InputResolution, type RuntimeIdentity, type RuntimeTraceContext, type TaskCancelReason, type TaskStartedStreamEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
5
+ import type { RuntimeActionResult } from "#shared/action-types.js";
6
+ import type { InputRequest } from "#shared/input.js";
7
+ import type { JsonObject, JsonValue } from "#shared/json.js";
8
+ import type { TokenUsage } from "#shared/token-usage.js";
9
+ import type { Transition } from "./commit.js";
10
+ import type { StepCoordinates, SuspendedStep, TurnState } from "./state.js";
11
+ import { type SessionView } from "./view.js";
12
+ type ToolResponsePart = Extract<ModelMessage, {
13
+ role: "tool";
14
+ }>["content"][number];
15
+ export type ToolResultPart = Extract<ToolResponsePart, {
16
+ type: "tool-result";
17
+ }>;
18
+ /**
19
+ * Input arrives: the session starts once, a turn opens unless one is open (steering joins it),
20
+ * and a message is received.
21
+ */
22
+ export declare function receive(view: SessionView, input: {
23
+ readonly message?: string | UserContent;
24
+ readonly runtime?: RuntimeIdentity;
25
+ readonly trace?: RuntimeTraceContext;
26
+ }): Transition;
27
+ /** The open turn calls the model. */
28
+ export declare function startStep(view: SessionView, input: {
29
+ readonly modelId: string;
30
+ }): Transition;
31
+ /**
32
+ * The open turn parks: on `"tasks"` while work it started runs, on `"input"` while a person must
33
+ * act on a sign-in, approval, or question. It resumes in the same turn.
34
+ */
35
+ export declare function hold(view: SessionView, input: {
36
+ readonly on: TurnWaitingOn;
37
+ }): Transition;
38
+ /** Nothing is left to run: the turn completes, with its structured result when it has one. */
39
+ export declare function finishTurn(view: SessionView, input?: {
40
+ readonly result?: JsonValue;
41
+ }): Transition;
42
+ /**
43
+ * The step failed. A recoverable failure parks the session for the user to retry; a terminal
44
+ * one ends it.
45
+ */
46
+ export declare function fail(view: SessionView, failure: {
47
+ readonly code: string;
48
+ readonly details?: JsonObject;
49
+ readonly message: string;
50
+ readonly terminal?: {
51
+ readonly sessionId: string;
52
+ };
53
+ }): Transition;
54
+ /** The session waits for its next delivery. */
55
+ export declare function idle(view: SessionView): Transition;
56
+ export declare function sessionCompleted(usage: TokenUsage | undefined): ReturnType<typeof createSessionCompletedEvent>;
57
+ export declare function sessionFailed(input: {
58
+ readonly code: string;
59
+ readonly details?: JsonObject;
60
+ readonly message: string;
61
+ readonly sessionId: string;
62
+ readonly usage: TokenUsage | undefined;
63
+ }): ReturnType<typeof createSessionFailedEvent>;
64
+ /** One call's result, ready for its step's transcript. */
65
+ export interface SettledCall {
66
+ readonly part: ToolResultPart;
67
+ /** A runtime result, reported at the coordinates of the step that made the call. */
68
+ readonly result?: RuntimeActionResult;
69
+ }
70
+ /**
71
+ * Results reach the steps that made their calls. A step whose every call now has a result
72
+ * commits to history, where the model reads it.
73
+ */
74
+ export declare function settle(view: SessionView, input: {
75
+ readonly results: readonly SettledCall[];
76
+ }): {
77
+ commit: ModelMessage[];
78
+ events: UnstampedMessageStreamEvent[];
79
+ turn: {
80
+ queued?: import("../types.ts").StepInput;
81
+ grants: readonly string[];
82
+ suspended: SuspendedStep[];
83
+ };
84
+ };
85
+ /**
86
+ * A model response made calls the runtime runs. The response waits in a suspended step until
87
+ * every call it made has a result, so a call never reaches the model without its result.
88
+ */
89
+ export declare function suspendStep(view: SessionView, step: Pick<SuspendedStep, "event" | "messages" | "tasks">): Transition;
90
+ /** The step without the approved calls in `callIds`, which have run or joined the runtime. */
91
+ export declare function withoutApproved(step: SuspendedStep, callIds: ReadonlySet<string>): SuspendedStep;
92
+ /** Approved calls of suspended steps that haven't run. */
93
+ export declare function approvedCalls(turn: TurnState): readonly InputRequest[];
94
+ export declare function suspend(turn: TurnState, step: SuspendedStep): TurnState;
95
+ /** The ids of the calls a step's response made, except provider-executed ones. */
96
+ export declare function stepCallIds(step: Pick<SuspendedStep, "messages">): ReadonlySet<string>;
97
+ /** Places a result right after the message that made its call. */
98
+ export declare function withResult(messages: readonly ModelMessage[], part: ToolResultPart): ModelMessage[];
99
+ /** A call started or reached a task. */
100
+ export declare function startTask(view: SessionView, task: TaskStartedStreamEvent["data"]): Transition;
101
+ export type TaskCallOutcome = {
102
+ readonly status: "completed";
103
+ readonly output?: JsonValue;
104
+ } | {
105
+ readonly status: "failed";
106
+ readonly error: string;
107
+ } | {
108
+ readonly status: "cancelled";
109
+ readonly reason?: TaskCancelReason;
110
+ };
111
+ /** A task's run settled calls: each reports its outcome, naming the task as it started. */
112
+ export declare function settleTask(view: SessionView, input: {
113
+ readonly task: {
114
+ readonly id: string;
115
+ readonly kind?: TaskStartedStreamEvent["data"]["kind"];
116
+ readonly name?: string;
117
+ };
118
+ readonly calls: readonly {
119
+ readonly callId: string;
120
+ readonly turnId: string;
121
+ }[];
122
+ readonly outcome: TaskCallOutcome;
123
+ }): Transition;
124
+ /**
125
+ * A task or workflow run ended, on its own or cancelled: nobody can answer what it relayed, so
126
+ * each request still open is withdrawn.
127
+ */
128
+ export declare function finishRun(view: SessionView, run: {
129
+ readonly taskId?: string;
130
+ readonly requestIds?: Iterable<string>;
131
+ }): Transition;
132
+ /**
133
+ * A child session or workflow run asks a question or for a sign-in. The session passes it up
134
+ * with its original coordinates, and the open turn waits on the call it serves.
135
+ * A child's fresh batch replaces its earlier one, whose open requests are withdrawn.
136
+ */
137
+ export declare function relay(view: SessionView, input: {
138
+ readonly payload: SubagentInputRequestHookPayload | SubagentAuthorizationEventHookPayload;
139
+ readonly replacedRequestIds?: Iterable<string>;
140
+ }): Transition;
141
+ /**
142
+ * Answers to relayed requests are on their way to the asker: each request resolves here.
143
+ */
144
+ export declare function receiveRelayedAnswer(input: {
145
+ readonly message: string | UserContent;
146
+ readonly sequence: number;
147
+ readonly turnId: string;
148
+ }): import("#protocol/message.js").MessageReceivedStreamEvent;
149
+ export declare function routeAnswer(view: SessionView, input: {
150
+ readonly children: readonly {
151
+ readonly event: StepCoordinates;
152
+ readonly resolutions: readonly InputResolution[];
153
+ }[];
154
+ }): Transition;
155
+ /**
156
+ * A workflow run's sign-in, reported to the session that owns the run, which relays it. Built
157
+ * where the run asks, at the coordinates of the call it serves.
158
+ */
159
+ export declare function runSignIn(from: {
160
+ readonly sequence: number;
161
+ readonly stepIndex: number;
162
+ readonly taskId?: string;
163
+ readonly turnId: string;
164
+ }, challenge: AuthorizationChallenge, outcome?: "authorized" | "failed"): import("#protocol/message.js").AuthorizationCompletedStreamEvent | import("#protocol/message.js").AuthorizationRequiredStreamEvent;
165
+ /** Sign-in callbacks arrived: each completion is reported at the coordinates of the turn that asked. */
166
+ export declare function completeSignIn(view: SessionView, input: {
167
+ readonly completions: readonly AuthorizationChallenge[];
168
+ }): Transition;
169
+ /** Requests this session asked itself and still awaits; relayed requests answer elsewhere. */
170
+ export declare function ownOpenRequestIds(view: Omit<SessionView, "turn">): ReadonlySet<string>;
171
+ /** What the model reads for a call its turn's cancellation stopped before the call settled. */
172
+ export declare const CANCELLED_CALL_RESULT = "The turn was cancelled before this call finished.";
173
+ /**
174
+ * `session.cancel()`: the open turn ends cancelled. Its requests, its sign-ins, and every
175
+ * relayed request are withdrawn, since the cancel stops the work that asked them; its unsettled
176
+ * calls are stopped. The steps it ran commit to history, each unfinished call answered as
177
+ * cancelled, so the model sees that the work started and stopped.
178
+ */
179
+ export declare function cancel(view: SessionView): Transition;
180
+ /**
181
+ * `session.clear()`: everything the cleared history asked for is withdrawn, its approvals and
182
+ * the session-limit prompt and every sign-in, and the calls awaiting them stop. Requests relayed
183
+ * from live tasks stay: clearing doesn't stop the work that asked them.
184
+ */
185
+ export declare function clear(view: SessionView, input: {
186
+ readonly sessionId: string;
187
+ }): Transition;
188
+ export {};
@@ -0,0 +1 @@
1
+ import{activeTurnId,answeredCallIds,nextStepIndex,turnPosition}from"./view.js";import{inputWithdrawn,signInWithdrawn}from"./events.js";import{openInputs,openSignIns,turnCoordinates}from"#protocol/session-projection.js";import{createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTaskSettledEvent,createTaskStartedEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,createTurnWaitingEvent}from"#protocol/message.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";const unchanged=(e,t)=>({events:t,turn:e.turn});function at(e){let t=turnPosition(e);return{sequence:t.sequence,stepIndex:t.stepIndex,turnId:activeTurnId(t)}}function receive(e,t){let n=turnPosition(e.projection),r=activeTurnId(n),i=[];return n.sessionStarted||i.push(createSessionStartedEvent({runtime:t.runtime,trace:t.trace})),n.turnId===``&&i.push(createTurnStartedEvent({sequence:n.sequence,trace:t.trace,turnId:r})),t.message!==void 0&&i.push(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:r})),unchanged(e,i)}function startStep(e,t){let{sequence:n,turnId:r}=at(e.projection);return unchanged(e,[createStepStartedEvent({modelId:t.modelId,sequence:n,stepIndex:nextStepIndex(e.projection),turnId:r})])}function hold(e,t){let{sequence:n,turnId:r}=turnPosition(e.projection);return r===``?unchanged(e,[]):unchanged(e,[createTurnWaitingEvent({on:t.on,sequence:n,turnId:r,usage:e.usage})])}function finishTurn(e,t={}){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=[];return t.result!==void 0&&a.push(createResultCompletedEvent({result:t.result,sequence:n,stepIndex:r,turnId:i})),e.projection.activeTurnId!==void 0&&a.push(createTurnCompletedEvent({sequence:n,turnId:i})),a.push(createSessionWaitingEvent(e.usage)),unchanged(e,a)}function fail(e,t){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=e.turn.suspended.filter(e=>(e.approved?.length??0)>0);return{commit:a.flatMap(cancelledTranscript),events:failedEvents(e,t,{sequence:n,stepIndex:r,turnId:i}),turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!a.includes(e))}}}function failedEvents(e,t,n){let{sequence:r,stepIndex:i,turnId:a}=n,{code:o,details:s,message:c}=t;return[createStepFailedEvent({code:o,details:s,message:c,sequence:r,stepIndex:i,turnId:a}),createTurnFailedEvent({code:o,details:s,message:c,sequence:r,turnId:a}),t.terminal===void 0?createSessionWaitingEvent(e.usage):createSessionFailedEvent({code:o,details:s,message:c,sessionId:t.terminal.sessionId,usage:e.usage})]}function idle(e){return unchanged(e,[createSessionWaitingEvent(e.usage)])}function sessionCompleted(e){return createSessionCompletedEvent(e)}function sessionFailed(e){return createSessionFailedEvent(e)}function settle(e,t){let n=[],r=[...e.turn.suspended];for(let{part:e,result:i}of t.results){let t=r.findIndex(t=>stepCallIds(t).has(e.toolCallId)),a=r[t];a!==void 0&&(r[t]=withoutApproved({...a,messages:withResult(a.messages,e)},new Set([e.toolCallId])),i!==void 0&&n.push(createActionResultEvent({result:i,...a.event})))}let i=r.filter(isComplete);return{commit:i.flatMap(e=>e.messages),events:n,turn:{...e.turn,suspended:r.filter(e=>!i.includes(e))}}}function suspendStep(e,t){return{events:[],turn:suspend(e.turn,{...t,requests:[]})}}function withoutApproved(e,t){if(e.approved===void 0)return e;let n=e.approved.filter(e=>!t.has(e.action.callId));if(n.length===e.approved.length)return e;let{approved:r,...i}=e;return n.length===0?i:{...i,approved:n}}function approvedCalls(e){return e.suspended.flatMap(e=>e.approved??[])}function suspend(e,t){return{...e,suspended:[...e.suspended,t]}}function stepCallIds(e){let t=new Set;for(let n of e.messages)if(n.role===`assistant`&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-call`&&e.providerExecuted!==!0&&t.add(e.toolCallId);return t}function isComplete(e){if(e.requests.length>0)return!1;let t=answeredCallIds(e.messages);return[...stepCallIds(e)].every(e=>t.has(e))}function withResult(e,t){let n=[...e],r=n.findIndex(e=>e.role===`assistant`&&Array.isArray(e.content)&&e.content.some(e=>e.type===`tool-call`&&e.toolCallId===t.toolCallId)),i=n[r+1];return r>=0&&i?.role===`tool`?n[r+1]={...i,content:[...i.content,t]}:n.splice(r>=0?r+1:n.length,0,{content:[t],role:`tool`}),n}function startTask(e,t){return unchanged(e,[createTaskStartedEvent(t)])}function settleTask(e,t){let{outcome:n,task:r}=t;return unchanged(e,t.calls.map(e=>{let t={callId:e.callId,kind:r.kind,name:r.name,taskId:r.id,turnId:e.turnId};switch(n.status){case`completed`:return createTaskSettledEvent({...t,output:n.output,status:`completed`});case`failed`:return createTaskSettledEvent({...t,error:{message:n.error},status:`failed`});case`cancelled`:return createTaskSettledEvent(n.reason===void 0?{...t,status:`cancelled`}:{...t,cancel:{reason:n.reason},status:`cancelled`})}}))}function finishRun(e,t){let n=new Set(t.requestIds);return unchanged(e,openInputs(e.projection).filter(e=>n.has(e.request.requestId)||t.taskId!==void 0&&e.taskId===t.taskId).map(inputWithdrawn))}function relay(e,t){let{payload:n}=t,r=[...finishRun(e,{requestIds:t.replacedRequestIds}).events];if(n.kind===`subagent-input-request`){let{event:e}=n;r.push(createInputRequestedEvent({callId:n.callId,requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId}))}else{let{event:t}=n;if(r.push(t),t.type!==`authorization.required`)return unchanged(e,r)}return r.push(...hold(e,{on:`input`}).events),unchanged(e,r)}function receiveRelayedAnswer(e){return createMessageReceivedEvent(e)}function routeAnswer(e,t){let n=t.children.filter(e=>e.resolutions.length>0).map(e=>createInputResolvedEvent({resolutions:e.resolutions,...e.event}));return unchanged(e,n)}function runSignIn(e,t,n){let r={...authorizationEventFields(t),sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId};return n===void 0?createAuthorizationRequiredEvent({...r,description:`Sign in to ${t.name} to continue.`,webhookUrl:t.hookUrl}):createAuthorizationCompletedEvent({...r,outcome:n})}function completeSignIn(e,t){let n=at(e.projection);return unchanged(e,t.completions.map(t=>{let r=t.attemptId===void 0?void 0:e.projection.authorizations[t.attemptId];return createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:r?.sequence??n.sequence,stepIndex:r?.stepIndex??n.stepIndex,turnId:r?.turnId??n.turnId})}))}function ownOpenRequestIds(e){return new Set(openInputs(e.projection).filter(t=>t.callId===void 0&&t.taskId===void 0&&!e.relayedRequestIds.has(t.request.requestId)).map(e=>e.request.requestId))}const CANCELLED_CALL_RESULT=`The turn was cancelled before this call finished.`;function cancel(e){let{projection:t}=e,n=t.activeTurnId,r=e.turn.suspended.filter(e=>n!==void 0&&e.event.turnId===n||e.tasks.some(t=>!answeredCallIds(e.messages).has(t.callId))||(e.approved?.length??0)>0),i=new Set(r.flatMap(e=>e.requests.map(e=>e.requestId))),a=[...openInputs(t).filter(t=>t.turnId===n||i.has(t.request.requestId)||e.relayedRequestIds.has(t.request.requestId)||t.request.kind===`session-limit`).map(inputWithdrawn),...openSignIns(t).filter(e=>e.turnId===n).map(e=>signInWithdrawn(e,`Cancelled.`))];if(n!==void 0){let{sequence:e}=turnCoordinates(t);a.push(createTurnCancelledEvent({sequence:e,turnId:n}))}return a.push(createSessionWaitingEvent(e.usage)),{commit:r.flatMap(cancelledTranscript),events:a,signIns:[],turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!r.includes(e))}}}function cancelledTranscript(e){let t=answeredCallIds(e.messages),n=[...e.messages];for(let r of e.messages)if(r.role===`assistant`&&typeof r.content!=`string`)for(let e of r.content)e.type===`tool-call`&&e.providerExecuted!==!0&&(t.has(e.toolCallId)||(n=withResult(n,{output:{type:`text`,value:CANCELLED_CALL_RESULT},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})));return n}function clear(e,t){let{projection:n}=e,{sequence:r,turnId:i}=turnCoordinates(n);return{clearsHistory:!0,events:[...openInputs(n).filter(t=>!e.relayedRequestIds.has(t.request.requestId)).map(inputWithdrawn),...openSignIns(n).map(e=>signInWithdrawn(e,`The context was cleared.`)),createContextClearedEvent({sequence:r,sessionId:t.sessionId,turnId:i}),createSessionWaitingEvent(e.usage)],turn:{grants:e.turn.grants,suspended:[]}}}export{CANCELLED_CALL_RESULT,approvedCalls,cancel,clear,completeSignIn,fail,finishRun,finishTurn,hold,idle,ownOpenRequestIds,receive,receiveRelayedAnswer,relay,routeAnswer,runSignIn,sessionCompleted,sessionFailed,settle,settleTask,startStep,startTask,stepCallIds,suspend,suspendStep,withResult,withoutApproved};
@@ -0,0 +1,58 @@
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
+ import type { TokenUsage } from "#shared/token-usage.js";
3
+ import type { ModelMessage } from "ai";
4
+ import type { AuthorizationChallenge } from "#harness/authorization.js";
5
+ import { type TaskToolCall } from "#execution/tasks/calls.js";
6
+ import type { SessionStateMap, StepInput } from "#harness/types.js";
7
+ import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
8
+ import { type SessionProjection } from "#protocol/session-projection.js";
9
+ import { type StepCoordinates, type SuspendedStep, type TurnState } from "./state.js";
10
+ export type { StepCoordinates, SuspendedStep, TurnState } from "./state.js";
11
+ export declare const SESSION_PROJECTION_STATE_KEY = "eve.harness.sessionProjection";
12
+ /** What a transition sees. */
13
+ export interface SessionView {
14
+ readonly turn: TurnState;
15
+ readonly projection: SessionProjection;
16
+ /** Requests this session relays for a child session or a workflow run, by `requestId`. */
17
+ readonly relayedRequestIds: ReadonlySet<string>;
18
+ /** The sign-in attempts the session waits on, with what completing them needs. */
19
+ readonly signIns: readonly AuthorizationChallenge[];
20
+ /** The session's token usage so far, which its waiting and terminal events report. */
21
+ readonly usage: TokenUsage;
22
+ }
23
+ /** Reads the authoritative lifecycle facts saved alongside execution state. */
24
+ export declare function storedProjection(state: SessionStateMap | undefined): SessionProjection;
25
+ /** Coordinates the next lifecycle event carries, and whether a turn is open. */
26
+ export interface TurnPosition {
27
+ readonly sessionStarted: boolean;
28
+ readonly sequence: number;
29
+ readonly stepIndex: number;
30
+ /** The open turn's id, or `""` between turns. */
31
+ readonly turnId: string;
32
+ /** The open turn streamed assistant output, so steering can no longer restart it. */
33
+ readonly assistantOutputStarted?: boolean;
34
+ }
35
+ export declare function turnPosition(projection: SessionProjection): TurnPosition;
36
+ /** The open turn's id, or the id the next turn takes. */
37
+ export declare function activeTurnId(position: Pick<TurnPosition, "sequence" | "turnId">): string;
38
+ export declare function isBetweenTurns(projection: SessionProjection): boolean;
39
+ /** The index the open turn's next `step.started` takes. */
40
+ export declare function nextStepIndex(projection: SessionProjection): number;
41
+ /** Input the session holds until it can run. */
42
+ export declare function queuedInput(state: SessionStateMap | undefined): StepInput | undefined;
43
+ export declare function suspendedSteps(state: SessionStateMap | undefined): readonly SuspendedStep[];
44
+ /** The ids of calls that already have a result in `messages`. */
45
+ export declare function answeredCallIds(messages: readonly ModelMessage[]): ReadonlySet<string>;
46
+ /** Workflow and agent calls of `step` the runtime still runs. */
47
+ export declare function runningTasks(step: SuspendedStep): readonly RuntimeWorkflowTaskRequest[];
48
+ /** What the turn waits on the runtime for: dispatched runs and the task tool calls. */
49
+ export interface RuntimeWait {
50
+ readonly event: StepCoordinates;
51
+ readonly callIds: readonly string[];
52
+ readonly tasks: readonly RuntimeWorkflowTaskRequest[];
53
+ readonly taskToolCalls: readonly TaskToolCall[];
54
+ /** Who approved each task an approval started, by call id. */
55
+ readonly approvers: Readonly<Record<string, SessionAuthContext>>;
56
+ }
57
+ /** The calls suspended steps wait on the runtime for, or `undefined` when none do. */
58
+ export declare function runtimeWait(state: SessionStateMap | undefined): RuntimeWait | undefined;
@@ -0,0 +1 @@
1
+ import{readTurnState}from"./state.js";import{initialSessionProjection,turnCoordinates}from"#protocol/session-projection.js";import{pendingTaskToolCalls}from"#execution/tasks/calls.js";const SESSION_PROJECTION_STATE_KEY=`eve.harness.sessionProjection`;function storedProjection(e){return e?.[`eve.harness.sessionProjection`]??initialSessionProjection()}function turnPosition(e){let{sequence:t,stepIndex:n}=turnCoordinates(e),r=e.activeTurnId===void 0?void 0:e.turns[e.activeTurnId],i={sessionStarted:e.started===!0,sequence:t,stepIndex:n,turnId:r?.turnId??``};return r?.outputStarted===!0&&(i.assistantOutputStarted=!0),i}function activeTurnId(e){return e.turnId===``?`turn_${e.sequence}`:e.turnId}function isBetweenTurns(e){return e.activeTurnId===void 0}function nextStepIndex(e){let t=e.activeTurnId===void 0?void 0:e.turns[e.activeTurnId];return t?.stepIndex===void 0?0:t.stepIndex+1}function queuedInput(e){return readTurnState(e).queued}function suspendedSteps(e){return readTurnState(e).suspended}function answeredCallIds(e){let t=new Set;for(let n of e)if((n.role===`tool`||n.role===`assistant`)&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-result`&&t.add(e.toolCallId);return t}function runningTasks(e){let t=answeredCallIds(e.messages);return e.tasks.filter(e=>!t.has(e.callId))}function runtimeWait(e){let t=suspendedSteps(e).flatMap(e=>{let t=runningTasks(e),n=pendingTaskToolCalls(e.messages);return t.length===0&&n.length===0?[]:[{step:e,tasks:t,taskToolCalls:n}]}),n=t[0];if(n===void 0)return;let r=t.flatMap(e=>e.tasks),i=t.flatMap(e=>e.taskToolCalls);return{approvers:Object.assign({},...t.map(e=>e.step.approvers)),callIds:[...r.map(e=>e.callId),...i.map(e=>e.callId)],event:n.step.event,taskToolCalls:i,tasks:r}}export{SESSION_PROJECTION_STATE_KEY,activeTurnId,answeredCallIds,isBetweenTurns,nextStepIndex,queuedInput,runningTasks,runtimeWait,storedProjection,suspendedSteps,turnPosition};
@@ -0,0 +1,7 @@
1
+ import type { ModelMessage } from "ai";
2
+ import type { StepResult } from "#harness/types.js";
3
+ import type { ModelResponse } from "#harness/model-call/run.js";
4
+ import type { Step } from "#harness/step/context.js";
5
+ export declare function handleStepResult(step: Step, input: ModelResponse): Promise<StepResult>;
6
+ /** The SDK's approval parts: eve answers approvals itself, so history never holds them. */
7
+ export declare function withoutApprovalParts(messages: readonly ModelMessage[]): ModelMessage[];
@@ -0,0 +1 @@
1
+ import{createLogger}from"#internal/logging.js";import{resolveAssistantStepText,validateHarnessModelMessages}from"#harness/messages.js";import{renderFinalOutputWhileWorkingError}from"#execution/tasks/render.js";import{stageToolResultMedia}from"#harness/attachment-staging.js";import{collectDeferredCalls}from"#harness/coordination.js";import{fail,finishTurn,hold,suspendStep,withResult}from"#harness/session-machine/transitions.js";import{extractToolApprovalInputRequests,hasRunnableQueue,parkOnApprovals,stopForToolSignIn}from"#harness/hitl/index.js";import{createToolResultMessagePartFromToolError,isToolResultError}from"#harness/action-result-helpers.js";import{setRequestEnvelopeTokens}from"#harness/request-envelope.js";import{isTaskTool,workingTaskIds}from"#execution/tasks/model-step.js";import{getInvalidToolCallInputError,isInvalidToolCall}from"#harness/tool-call-input-errors.js";import{resolveInlineAuthorizationInterrupt}from"#harness/inline-tool-authorization.js";import{FINAL_OUTPUT_BESIDE_PENDING_CALLS,FINAL_OUTPUT_TOOL_NAME}from"#harness/final-output.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{appendMissingToolResultMessages,extractToolResultCallIds}from"#harness/model-call/response.js";import{clearTurnClientContextState}from"#harness/turn-client-context.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";const log=createLogger(`harness.tool-loop`);function getInvalidToolCallInputErrors(e){let t=[];for(let n of e.toolCalls){if(n.toolName===FINAL_OUTPUT_TOOL_NAME)continue;let e=getInvalidToolCallInputError({toolCall:n});e!==void 0&&t.push(e)}return t}async function handleStepResult(e,t){let{promptMessages:n,result:r}=t,i=resolveAssistantStepText(r.response.messages,r.text),a=getInvalidToolCallInputErrors({toolCalls:r.toolCalls}),o=new Set([...r.invalidInputToolCallIds??[],...r.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId),...a.map(e=>e.toolCallId)]),s=appendMissingToolResultMessages({append:a.map(e=>createToolResultMessagePartFromToolError(e)),responseMessages:r.response.messages}),c=new Set;for(let e of[...r.content??[],...r.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&c.add(e.toolCallId);let l=normalizeProviderToolHistory({messages:s,providerExecutedOutcomeIds:c}),u=await stageToolResultMedia(withoutApprovalParts(l.messages));e.session=setRequestEnvelopeTokens({...e.session,compaction:createNextCompactionConfig(e.session.compaction,t.durableModelPromptMessageCount,r)},r.usage?.inputTokens!==void 0&&t.durableModelPromptMessageCount!==void 0?t.requestEnvelopeTokens:void 0);let d=extractToolApprovalInputRequests({content:r.content??[],excludedCallIds:o}),f=getAdvertisedTools({session:e.session,tools:t.coordinationTools}),p=new Set([...d.map(e=>e.action.callId),...extractToolResultCallIds(u)]),m=[],h=(r.toolCalls??[]).filter(e=>!o.has(e.toolCallId)).filter(e=>!p.has(e.toolCallId)).filter(e=>isDeferredHarnessTool(t.coordinationTools.get(e.toolName))).filter(t=>isDeferredHarnessTool(f.get(t.toolName))?!0:(log.warn(`deferred tool call blocked because tool is not advertised`,{callId:t.toolCallId,sessionId:e.session.sessionId,toolName:t.toolName}),m.push(t),!1));if(h.length>0||d.length>0){let{sequence:t,stepIndex:i,turnId:a}=e.position(),o=collectDeferredCalls({session:e.session,toolCalls:h,tools:f,turnId:a});e.session={...o.session,history:validateHarnessModelMessages(n)};let s={event:{sequence:t,stepIndex:i,turnId:a},messages:answerCallsThatWontRun(u,r,m),tasks:o.workflowRequests};return d.length>0?parkOnApprovals(e,{...s,requests:d,waitsOnRuntime:h.length>0}):(await e.apply(suspendStep(e.view(),s)),{next:null,session:e.session})}let g=resolveInlineAuthorizationInterrupt({messages:[...n,...u],toolResults:r.toolResults});if(g)return stopForToolSignIn(e,g);e.session={...e.session,history:validateHarnessModelMessages([...n,...u])};let _=e.session.outputSchema!==void 0&&extractFinalOutput(r)!==void 0,v=workingTaskIds(e.session),y=_&&v.length>0,b=u;y&&(b=rejectFinalOutput(u,r,v),e.session={...e.session,history:validateHarnessModelMessages([...n,...b])});let x=await stepEndsTurn(r,u,t.endsTurnTools);return(!_||y)&&(b.at(-1)?.role===`tool`&&!x||l.outcomeEndsResponse||hasRunnableQueue(e.view()))?{next:e.runStep,session:e.session}:v.length>0?(await e.apply(hold(e.view(),{on:`tasks`})),{held:{kind:`tasks`,taskIds:v},next:null,session:e.session}):settleTurn(e,{history:n,result:r,stepOutput:x?null:i})}function answerCallsThatWontRun(e,t,n){let r=extractToolResultCallIds(e);return[...(t.toolCalls??[]).filter(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME).map(e=>({output:{type:`error-text`,value:FINAL_OUTPUT_BESIDE_PENDING_CALLS},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})),...n.map(e=>({output:{type:`error-text`,value:`The tool "${e.toolName}" isn't available in this step, so the call didn't run.`},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`}))].filter(e=>!r.has(e.toolCallId)).reduce((e,t)=>withResult(e,t),[...e])}function withoutApprovalParts(e){return e.flatMap(e=>{if(e.role!==`assistant`&&e.role!==`tool`||!Array.isArray(e.content))return[e];let t=e.content.filter(e=>e.type!==`tool-approval-request`&&e.type!==`tool-approval-response`);return t.length===0?[]:[{...e,content:t}]})}async function stepEndsTurn(e,t,n){let r=e.toolCalls??[];if(r.length===0)return!1;let i=new Map;for(let e of t)if(e.role===`tool`)for(let t of e.content)t.type===`tool-result`&&i.set(t.toolCallId,t.output);if(!r.every(e=>{let t=i.get(e.toolCallId);return n.has(e.toolName)&&t!==void 0&&!isToolResultError(t)}))return!1;let a=new Map((e.toolResults??[]).map(e=>[e.toolCallId,e.output]));for(let e of r){let t=n.get(e.toolName);if(typeof t==`function`&&!await callEndsTurn(t,a.get(e.toolCallId),e))return!1}return!0}async function callEndsTurn(e,t,n){try{return await e(t)===!0}catch(e){return log.warn(`endsTurn threw; continuing the turn`,{callId:n.toolCallId,error:e,toolName:n.toolName}),!1}}function isDeferredHarnessTool(e){return e?.workflowId!==void 0||isTaskTool(e)}function rejectFinalOutput(e,t,n){let r=(t.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME);if(r===void 0)return[...e];let i={output:{type:`error-text`,value:renderFinalOutputWhileWorkingError(n)},toolCallId:r.toolCallId,toolName:FINAL_OUTPUT_TOOL_NAME,type:`tool-result`};return[...e,{content:[i],role:`tool`}]}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME&&!isInvalidToolCall(e))?.input}async function settleTurn(e,t){let{history:n,result:r,stepOutput:i}=t,a=e.session.outputSchema;if(e.session=clearTurnClientContextState(e.session),a===void 0)return await e.apply(finishTurn(e.view()),e.session.history),{next:null,session:e.session,settledTurn:{output:i??``}};let o=extractFinalOutput(r);return o===void 0?(e.session={...e.session,outputSchema:void 0},await e.apply(fail(e.view(),OUTPUT_SCHEMA_NOT_FULFILLED)),{next:null,session:e.session,settledTurn:{isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message}}):(e.session={...e.session,history:[...n,{content:JSON.stringify(o),role:`assistant`}],outputSchema:void 0},await e.apply(finishTurn(e.view(),{result:o}),e.session.history),{next:null,session:e.session,settledTurn:{output:o}})}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold,thresholdPercent:e.thresholdPercent};return n.usage?.inputTokens!==void 0&&t!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t),r}export{handleStepResult,withoutApprovalParts};
@@ -0,0 +1,59 @@
1
+ import type { ModelMessage } from "ai";
2
+ import type { AlsContext } from "#context/container.js";
3
+ import { type HarnessModelMessage } from "#harness/messages.js";
4
+ import { type Publish, type Transition } from "#harness/session-machine/commit.js";
5
+ import type { StepProjection } from "#harness/session-machine/current.js";
6
+ import { type SessionView, type TurnPosition } from "#harness/session-machine/view.js";
7
+ import type { HarnessEmitFn, HarnessSession, StepFn, StepInput, StepResult, ToolLoopHarnessConfig } from "#harness/types.js";
8
+ import type { InstrumentationStepScope } from "#instrumentation/runtime.js";
9
+ import type { createHistoryViewPreparer } from "#shared/history-view.js";
10
+ type HistoryViewPreparer = ReturnType<typeof createHistoryViewPreparer>;
11
+ /**
12
+ * One harness step: the session it changes, and the machine it changes the session through.
13
+ * Every lifecycle change goes through `apply`, which publishes the transition's events and saves
14
+ * what it changed; `position` reads where those events left the session.
15
+ */
16
+ export interface Step {
17
+ session: HarnessSession;
18
+ frameworkToolNames: ReadonlySet<string>;
19
+ readonly config: ToolLoopHarnessConfig;
20
+ /** The step's context; direct harness tests may run without one. */
21
+ readonly ctx: AlsContext | undefined;
22
+ readonly runStep: StepFn;
23
+ readonly publish: Publish;
24
+ /** The caller's event handler. Without one, a failure throws instead of being reported. */
25
+ readonly emit: HarnessEmitFn | undefined;
26
+ readonly instrumentation: InstrumentationStepScope<HarnessSession> | undefined;
27
+ /** A child's caller or a schedule hears only the turn's real end. */
28
+ readonly hasDelegatedCaller: boolean;
29
+ view(): SessionView;
30
+ position(): TurnPosition;
31
+ apply(transition: Transition, messages?: readonly ModelMessage[]): Promise<void>;
32
+ /** History as the model and hooks see it, under `state`, the session's by default. */
33
+ projectHistory(messages: readonly ModelMessage[], state?: HarnessSession["state"]): readonly ModelMessage[];
34
+ }
35
+ export declare function createStep(input: {
36
+ readonly config: ToolLoopHarnessConfig;
37
+ readonly ctx: AlsContext | undefined;
38
+ readonly emit: HarnessEmitFn | undefined;
39
+ readonly instrumentation: InstrumentationStepScope<HarnessSession> | undefined;
40
+ readonly live: StepProjection;
41
+ readonly prepareHistory: HistoryViewPreparer;
42
+ readonly publish: Publish;
43
+ readonly runStep: StepFn;
44
+ readonly session: HarnessSession;
45
+ }): Step;
46
+ /**
47
+ * Opens the turn, or joins the open one, with the preamble its hooks prepare: memory recall and
48
+ * dynamic instructions join history ahead of the turn's input. Returns the step's result when the
49
+ * preamble failed the session.
50
+ */
51
+ export declare function openTurn(step: Step, opened: {
52
+ readonly input: readonly HarnessModelMessage[];
53
+ readonly message?: StepInput["message"];
54
+ }): Promise<StepResult | undefined>;
55
+ /** A lifecycle event failed to publish: only a dynamic model selection failure is reported. */
56
+ export declare function failBoundaryEvent(step: Step, error: unknown): Promise<StepResult>;
57
+ /** No model can serve the turn: the session fails. */
58
+ export declare function failModelSelection(step: Step, error: unknown): Promise<StepResult>;
59
+ export {};
@@ -0,0 +1 @@
1
+ import{createErrorId,createLogger}from"#internal/logging.js";import{ParentSessionKey,SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{applyTransition,sessionView}from"#harness/session-machine/commit.js";import{fail,receive}from"#harness/session-machine/transitions.js";import{isDynamicModelSelectionError}from"#context/dynamic-model-lifecycle.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";const log=createLogger(`harness.step`);function createStep(e){let{ctx:t,live:n}=e,r={session:e.session,frameworkToolNames:new Set,config:e.config,ctx:t,runStep:e.runStep,publish:e.publish,emit:e.emit,instrumentation:e.instrumentation,hasDelegatedCaller:t?.get(ParentSessionKey)!==void 0||t?.get(SessionCallbackKey)!==void 0,view:()=>sessionView(n.read(),r.session.state),position:()=>turnPosition(n.read()),async apply(t,n){r.session=await applyTransition(r.session,t,e.publish,n)},projectHistory:(t,n=r.session.state)=>e.prepareHistory(t,n).messages};return r}async function openTurn(e,t){let{config:n,ctx:r}=e;r!==void 0&&(prepareDynamicInstructionPreamble(r,e.projectHistory(e.session.history)),prepareMemoryPreamble(r,{history:e.session.history,input:[...t.input],projector:n.historyProjector,state:e.session.state}));let i;try{let r=e.position(),i=await e.instrumentation?.preparePreamble({sequence:r.sequence,sessionStarted:r.sessionStarted,traceContext:e.instrumentation?.traceContext,turnId:activeTurnId(r)});await e.apply(receive(e.view(),{message:t.message,runtime:n.runtimeIdentity,trace:i}),e.projectHistory([...e.session.history,...t.input]))}catch(e){i={error:e}}let a=r===void 0?[]:drainDynamicInstructionUserMessages(r),o=r===void 0?void 0:drainMemoryCommit(r);if(e.session={...e.session,history:validateHarnessModelMessages([...e.session.history,...o?.recalledMessages??[],...a]),state:o?.state??e.session.state},i!==void 0)return failBoundaryEvent(e,i.error);e.instrumentation?.setTurnId(e.position().turnId)}async function failBoundaryEvent(e,t){if(throwIfTurnAborted(e.config.abortSignal),isTurnCancellation(t))throw t;if(isDynamicModelSelectionError(t))return failModelSelection(e,t);throw t}async function failModelSelection(e,t){if(throwIfTurnAborted(e.config.abortSignal),e.instrumentation?.recordError(t),e.emit===void 0)throw t;let n=createErrorId(),r=toErrorMessage(t),{session:i}=e;return log.error(`model selection failed terminally`,{error:t,errorId:n,sessionId:i.sessionId,turnId:activeTurnId(e.position())}),await e.apply(fail(e.view(),{code:`MODEL_SELECTION_FAILED`,details:{errorId:n},message:r,terminal:{sessionId:i.sessionId}})),{next:e.hasDelegatedCaller?{done:!0,isError:!0,output:r}:{done:!0,output:``},session:e.session}}export{createStep,failBoundaryEvent,failModelSelection,openTurn};
@@ -0,0 +1,34 @@
1
+ import { type HarnessModelMessage, type UserModelMessage } from "#harness/messages.js";
2
+ import { getTurnClientContextState } from "#harness/turn-client-context.js";
3
+ import type { StepInput } from "#harness/types.js";
4
+ import type { Step } from "./context.js";
5
+ /**
6
+ * Settles the calls the runtime ran for parked steps. Returns `undefined` while some are still
7
+ * running: input queued behind them waits until they have. Otherwise returns the step's input
8
+ * without the results it settled, and whether the step waited on any.
9
+ */
10
+ export declare function settleRuntimeWork(step: Step, input: StepInput | undefined): Promise<{
11
+ readonly input: StepInput | undefined;
12
+ readonly waited: boolean;
13
+ } | undefined>;
14
+ /** The turn's input as the model reads it. */
15
+ export interface TurnInput {
16
+ readonly turnId: string;
17
+ /** Context the client sent for this turn, which never joins history. */
18
+ readonly clientContext: readonly string[] | undefined;
19
+ readonly storedClientContext: ReturnType<typeof getTurnClientContextState>;
20
+ readonly ephemeral: readonly UserModelMessage[];
21
+ /** The context entries and the message, in history order. */
22
+ readonly messages: readonly UserModelMessage[];
23
+ /** The input carries a user's message, which follows tool results across a boundary. */
24
+ readonly hasUserMessage: boolean;
25
+ }
26
+ /**
27
+ * Prepares the turn's input: client and context entries, and the message with its attachments
28
+ * staged to the sandbox. A message a plain-text answer consumed never reaches the model.
29
+ */
30
+ export declare function prepareTurnInput(step: Step, input: StepInput | undefined, options: {
31
+ readonly consumedMessage: boolean;
32
+ }): Promise<TurnInput>;
33
+ /** The turn's input as it follows tool results: a user message needs a boundary before it. */
34
+ export declare function followingToolResults(turn: TurnInput): HarnessModelMessage[];
@@ -0,0 +1 @@
1
+ import{readClientContext}from"#internal/client-context.js";import{TOOL_RESULT_BOUNDARY,createFrameworkUserMessage,createUserMessage,frameworkMessageKindForStepInput,normalizeUserContent}from"#harness/messages.js";import{activeTurnId,runtimeWait}from"#harness/session-machine/view.js";import{stageAttachmentsToSandbox,stageToolResultMedia}from"#harness/attachment-staging.js";import{forgetFinishedRuns,runtimeResultCalls}from"#harness/coordination.js";import{finishRun,settle}from"#harness/session-machine/transitions.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{getTurnClientContextState}from"#harness/turn-client-context.js";async function settleRuntimeWork(e,t){let n=runtimeWait(e.session.state);if(n===void 0)return{input:t,waited:!1};let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:n.callIds,results:t?.runtimeActionResults??[]});if(r===void 0)return;let i=forgetFinishedRuns(e.session,r,n.event.turnId);e.session=i.session,await e.apply(finishRun(e.view(),{requestIds:i.requestIds}));let a=await runtimeResultCalls(r,e.config.tools),o=(await stageToolResultMedia([{role:`tool`,content:a.map(({part:e})=>e)}])).flatMap(e=>e.role===`tool`?e.content.filter(e=>e.type===`tool-result`):[]);if(await e.apply(settle(e.view(),{results:a.map((e,t)=>({...e,part:o[t]}))})),t===void 0)return{input:t,waited:!0};let{runtimeActionResults:s,...c}=t;return{input:c,waited:!0}}async function prepareTurnInput(e,t,n){let r=activeTurnId(e.position()),i=getTurnClientContextState(e.session.state,r),a=readClientContext(t),o=(a??i?.messages)?.map(e=>createFrameworkUserMessage(`context.instruction`,e))??[],s=(t?.context??[]).map(e=>createFrameworkUserMessage(`context.instruction`,e)),c=frameworkMessageKindForStepInput(t),l=normalizeUserContent(t?.message),u=l!==void 0&&!n.consumedMessage?await stageAttachmentsToSandbox(l):void 0;return u!==void 0&&s.push(c===void 0?createUserMessage(`user`,u):createFrameworkUserMessage(c,u)),{clientContext:a,ephemeral:o,hasUserMessage:u!==void 0&&c===void 0,messages:s,storedClientContext:i,turnId:r}}function followingToolResults(e){return[...e.hasUserMessage?[{content:TOOL_RESULT_BOUNDARY,role:`assistant`}]:[],...e.messages]}export{followingToolResults,prepareTurnInput,settleRuntimeWork};
@@ -0,0 +1,37 @@
1
+ import { type HarnessModelMessage } from "#harness/messages.js";
2
+ import { getTurnClientContextState } from "#harness/turn-client-context.js";
3
+ import type { Step } from "./context.js";
4
+ import { type TurnInput } from "./intake.js";
5
+ type ClientContext = NonNullable<ReturnType<typeof getTurnClientContextState>>;
6
+ /**
7
+ * What the model reads this step: durable history, with the task results and notes the step
8
+ * delivers and the turn's input, and the client's context for the turn, which keeps one position
9
+ * across the turn's steps and never joins history.
10
+ */
11
+ export interface Prompt {
12
+ /** Durable messages. Compaction may rewrite them. */
13
+ messages: HarnessModelMessage[];
14
+ clientContext: ClientContext | undefined;
15
+ }
16
+ export declare function buildPrompt(step: Step, turn: TurnInput): Promise<Prompt>;
17
+ /**
18
+ * The prompt a step starts on while approved calls wait to run: history and the turn's input,
19
+ * without the task results and the client context's position a prompt settles, which wait for
20
+ * the prompt the model reads once the calls have run.
21
+ */
22
+ export declare function previewPrompt(step: Step, turn: TurnInput): Prompt;
23
+ /**
24
+ * The turn's input after `messages`, past a tool-result boundary when they end in tool results.
25
+ * The client's context takes its position here, and never joins the messages.
26
+ */
27
+ export declare function placeTurnInput(step: Step, messages: readonly HarnessModelMessage[], turn: TurnInput): HarnessModelMessage[];
28
+ /** `messages`, the prompt's by default, with the client's context at its position. */
29
+ export declare function withClientContext(prompt: Prompt, messages?: readonly HarnessModelMessage[]): HarnessModelMessage[];
30
+ /** The prompt as the model reads it: with the client's context, projected for its history view. */
31
+ export declare function projectPrompt(step: Step, prompt: Prompt): HarnessModelMessage[];
32
+ /**
33
+ * Compaction rewrote the durable messages: the client's context keeps its distance from the end,
34
+ * so it stays after the turn's input.
35
+ */
36
+ export declare function compactPrompt(step: Step, prompt: Prompt, messages: HarnessModelMessage[]): void;
37
+ export {};
@@ -0,0 +1 @@
1
+ import{followingToolResults}from"./intake.js";import{createFrameworkUserMessage,followsToolResults,normalizeModelMessages,validateHarnessModelMessages}from"#harness/messages.js";import{appendTaskContext}from"#execution/tasks/model-step.js";import{hasUnansweredToolCall}from"#harness/model-call/response.js";import{getTurnClientContextState,setTurnClientContextState}from"#harness/turn-client-context.js";async function buildPrompt(e,t){let n=validateHarnessModelMessages([...e.session.history]);if(!hasUnansweredToolCall(n)){let t=await appendTaskContext({messages:n,projectHistory:e.projectHistory,session:e.session,tools:e.config.tools});e.session=t.session,n.push(...t.messages)}let r=placeTurnInput(e,n,t);return{clientContext:getTurnClientContextState(e.session.state,t.turnId),messages:r}}function previewPrompt(e,t){let n=validateHarnessModelMessages([...e.session.history]);return{clientContext:turnClientContext(n,t),messages:withTurnInput(n,t)}}function placeTurnInput(e,t,n){let r=turnClientContext(t,n);return r!==void 0&&(e.session=setTurnClientContextState(e.session,r)),withTurnInput(t,n)}function turnClientContext(e,t){return t.clientContext===void 0?t.storedClientContext:{insertionIndex:t.storedClientContext?.insertionIndex??e.length,messages:t.clientContext,turnId:t.turnId}}function withTurnInput(e,t){return[...e,...followsToolResults(e)?followingToolResults(t):t.messages]}function withClientContext(e,t=e.messages){let{clientContext:n}=e;if(n===void 0||n.messages.length===0)return[...t];let r=Math.min(Math.max(0,n.insertionIndex),t.length);return[...t.slice(0,r),...n.messages.map(e=>createFrameworkUserMessage(`context.instruction`,e)),...t.slice(r)]}function projectPrompt(e,t){return validateHarnessModelMessages(normalizeModelMessages(e.projectHistory(withClientContext(t))))}function compactPrompt(e,t,n){let{clientContext:r}=t;if(r!==void 0){let i=Math.max(0,t.messages.length-r.insertionIndex);t.clientContext={...r,insertionIndex:Math.max(0,n.length-i)},e.session=setTurnClientContextState(e.session,t.clientContext)}t.messages=n}export{buildPrompt,compactPrompt,placeTurnInput,previewPrompt,projectPrompt,withClientContext};
@@ -1,5 +1,5 @@
1
- import type { GenerateTextOnStepStartCallback, PrepareStepFunction, ProviderMetadata, StepResult, ToolSet } from "ai";
2
- import type { HarnessEmissionState } from "#harness/emission.js";
1
+ import type { GenerateTextOnStepStartCallback, ModelMessage, PrepareStepFunction, ProviderMetadata, StepResult, ToolSet } from "ai";
2
+ import type { TurnPosition } from "#harness/session-machine/view.js";
3
3
  import { type AnthropicCacheMarker, type PromptCachePath } from "#harness/prompt-cache.js";
4
4
  import { type HarnessEmitFn, type HarnessSession, type ToolLoopHarnessConfig } from "#harness/types.js";
5
5
  /**
@@ -17,16 +17,11 @@ export type HarnessStepResult = Pick<StepResult<ToolSet>, "content" | "finishRea
17
17
  interface StepHooksInput {
18
18
  readonly auth?: import("#channel/types.js").SessionAuthContext | null;
19
19
  readonly cachePath: PromptCachePath;
20
- readonly emit?: HarnessEmitFn;
21
- readonly emissionState: HarnessEmissionState;
22
20
  /**
23
- * When `false`, `onStepStart` skips the `step.started` emission.
24
- * Used by the harness recovery path to avoid emitting `step.started`
25
- * twice when retrying the same step with a degraded toolset.
26
- *
27
- * Defaults to `true`.
21
+ * Starts the model step the SDK is about to run. Omitted when the step already started, as
22
+ * it has for a retry of the same step.
28
23
  */
29
- readonly emitStepStarted?: boolean;
24
+ readonly startStep?: (messages: readonly ModelMessage[]) => Promise<void>;
30
25
  readonly marker: AnthropicCacheMarker | undefined;
31
26
  readonly session: HarnessSession;
32
27
  }
@@ -37,7 +32,7 @@ interface StepHooks {
37
32
  /**
38
33
  * `ToolLoopAgent` `onStepStart` callback.
39
34
  *
40
- * Emits the `step.started` event from the prepared step input.
35
+ * Starts the step from the prepared step input.
41
36
  */
42
37
  readonly onStepStart: GenerateTextOnStepStartCallback<ToolSet>;
43
38
  /**
@@ -61,7 +56,7 @@ interface StepHooks {
61
56
  * have been emitted before proceeding to post-step handling.
62
57
  *
63
58
  * Resolves once per hooks instance: a retried model call must rebuild
64
- * hooks via a fresh `runOneModelCall` attempt. Re-running a call against
59
+ * hooks via a fresh `ModelCaller.call` attempt. Re-running a call against
65
60
  * hooks whose `stepResult` already resolved reads the previous attempt's
66
61
  * result, not the retry's.
67
62
  *
@@ -96,7 +91,7 @@ export declare function buildStepHooks(input: StepHooksInput): StepHooks;
96
91
  * `handledInlineToolResultCallIds` contains results emitted by
97
92
  * `emitStreamContent` or sent to authorization. Skip them here.
98
93
  */
99
- export declare function emitStepActions(emitFn: HarnessEmitFn, state: HarnessEmissionState, step: HarnessStepResult, options: {
94
+ export declare function emitStepActions(emitFn: HarnessEmitFn, state: TurnPosition, step: HarnessStepResult, options: {
100
95
  readonly emittedActionCallIds?: ReadonlySet<string>;
101
96
  readonly excludedActionCallIds?: ReadonlySet<string>;
102
97
  readonly excludedActionToolNames: ReadonlySet<string>;
@@ -1 +1 @@
1
- import{contextStorage}from"#context/container.js";import{AuthKey}from"#context/keys.js";import{createActionResultEvent,createActionsRequestedEvent,createStepCompletedEvent}from"#protocol/message.js";import{emitStepStarted}from"#harness/emission.js";import{resolveConversationId}from"#shared/conversation-identity.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError}from"#harness/action-result-helpers.js";import{emitNestedToolActions}from"#harness/nested-actions.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{isInvalidToolCall}from"#harness/tool-call-input-errors.js";import{collectActionPresentation,createPresentedRuntimeActionRequestFromToolCall}from"#harness/action-presentation.js";import{normalizeAssistantStepFinishReason}from"#harness/finish-reason.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{applyConversationCacheControl,mergeGatewayAutoCaching}from"#harness/prompt-cache.js";import{resolveCallProviderOptions}from"#harness/provider-safety.js";import{requireSessionModelReference}from"#harness/types.js";function buildStepHooks(e){let t=e.session,n=e.emit,r;return{onStepEnd:async e=>{r(e)},onStepStart:async({messages:r})=>{n&&e.emitStepStarted!==!1&&await emitStepStarted(n,e.emissionState,requireSessionModelReference(t).id,r)},prepareStep:async({messages:n,model:r})=>{let i=n;e.cachePath.kind===`anthropic-direct`&&e.marker&&(i=applyConversationCacheControl([...n],e.marker));let a={messages:i},o=requireSessionModelReference(t),s=resolveCallProviderOptions({auth:e.auth??contextStorage.getStore()?.get(AuthKey)??null,conversationId:resolveConversationId(t.rootSessionId??t.sessionId),model:r,modelReference:o,providerOptions:o.providerOptions});return e.cachePath.kind===`gateway-auto`?a.providerOptions=mergeGatewayAutoCaching(s):s!==void 0&&(a.providerOptions=s),a},stepResult:new Promise(e=>{r=e})}}async function emitStepActions(e,t,n,r){let i=new Set(n.toolCalls.filter(isProviderExecutedToolCall).map(e=>e.toolCallId)),a=new Set([...r.excludedActionCallIds??[],...i,...extractToolApprovalInputRequests({content:n.content??[],excludedCallIds:r.excludedActionCallIds}).map(e=>e.action.callId),...n.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId)]),isExcluded=(e,t)=>a.has(e)||r.excludedActionToolNames.has(t),o=n.toolCalls.filter(e=>!isExcluded(e.toolCallId,e.toolName)&&!r.emittedActionCallIds?.has(e.toolCallId)).map(e=>createPresentedRuntimeActionRequestFromToolCall({toolCall:e,tools:r.tools}));o.length>0&&await e(createActionsRequestedEvent({actions:o.map(({action:e})=>e),presentation:collectActionPresentation(o),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}));let s=r.handledInlineToolResultCallIds,c=new Map(n.toolResults.map(e=>[e.toolCallId,e.output]));for(let r of reconcileToolResults(n)){if(isExcluded(r.callId,r.toolName)||s?.has(r.callId))continue;let n=c.get(r.callId);shouldSkipAuthorizationActionResult(r.callId,n)||(await emitNestedToolActions(e,t,r.callId),await e(createActionResultEvent({result:r,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})))}await e(createStepCompletedEvent({finishReason:normalizeAssistantStepFinishReason(n.finishReason),providerMetadata:extractStepProviderMetadata(n.providerMetadata),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId,usage:extractStepUsage({costUsd:extractGatewayCostUsd(n.providerMetadata),usage:n.usage})}))}function isProviderExecutedToolCall(e){return e.providerExecuted===!0}function reconcileToolResults(e){let t=new Map;for(let n of e.toolResults)n.providerExecuted!==!0&&t.set(n.toolCallId,createRuntimeToolResultFromStepResult(n));for(let n of e.content??[])n.type===`tool-error`&&n.providerExecuted!==!0&&(t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromToolError(n)));for(let n of extractToolResultParts(e.response.messages))n.providerExecuted!==!0&&(t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromMessagePart(n)));return[...t.values()]}function shouldSkipAuthorizationActionResult(e,t){if(t!==void 0&&isPendingAuthorizationToolOutput(t))return!0;let n=contextStorage.getStore();if(n===void 0)return!1;let r=readToolInterrupt(n,e);return r!==void 0&&isAuthorizationSignal(r)}function extractToolResultParts(e){let t=[];for(let n of e)if(n.role===`tool`&&Array.isArray(n.content))for(let e of n.content)e.type===`tool-result`&&t.push(e);return t}function extractStepUsage(e){let t={};e.costUsd!==void 0&&(t.costUsd=e.costUsd);let n=e.usage;return n===void 0?Object.keys(t).length>0?t:void 0:(n.inputTokens!==void 0&&(t.inputTokens=n.inputTokens),n.outputTokens!==void 0&&(t.outputTokens=n.outputTokens),n.inputTokenDetails?.cacheReadTokens!==void 0&&(t.cacheReadTokens=n.inputTokenDetails.cacheReadTokens),n.inputTokenDetails?.cacheWriteTokens!==void 0&&(t.cacheWriteTokens=n.inputTokenDetails.cacheWriteTokens),Object.keys(t).length>0?t:void 0)}function extractStepProviderMetadata(e){let t=readGatewayGenerationId(e);return t===void 0?void 0:{gateway:{generationId:t}}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayGenerationId(e){let t=readGatewayMetadata(e)?.generationId;return typeof t==`string`&&t.length>0?t:void 0}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}export{buildStepHooks,emitStepActions,readGatewayGenerationId};
1
+ import{contextStorage}from"#context/container.js";import{AuthKey}from"#context/keys.js";import{createActionResultEvent,createActionsRequestedEvent,createStepCompletedEvent}from"#protocol/message.js";import{resolveConversationId}from"#shared/conversation-identity.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError}from"#harness/action-result-helpers.js";import{emitNestedToolActions}from"#harness/nested-actions.js";import{requireSessionModelReference}from"#harness/types.js";import{resolveCallProviderOptions}from"#harness/provider-safety.js";import{isInvalidToolCall}from"#harness/tool-call-input-errors.js";import{collectActionPresentation,createPresentedRuntimeActionRequestFromToolCall}from"#harness/action-presentation.js";import{normalizeAssistantStepFinishReason}from"#harness/finish-reason.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{applyConversationCacheControl,mergeGatewayAutoCaching}from"#harness/prompt-cache.js";function buildStepHooks(e){let t=e.session,n;return{onStepEnd:async e=>{n(e)},onStepStart:async({messages:t})=>{await e.startStep?.(t)},prepareStep:async({messages:n,model:r})=>{let i=n;e.cachePath.kind===`anthropic-direct`&&e.marker&&(i=applyConversationCacheControl([...n],e.marker));let a={messages:i},o=requireSessionModelReference(t),s=resolveCallProviderOptions({auth:e.auth??contextStorage.getStore()?.get(AuthKey)??null,conversationId:resolveConversationId(t.rootSessionId??t.sessionId),model:r,modelReference:o,providerOptions:o.providerOptions});return e.cachePath.kind===`gateway-auto`?a.providerOptions=mergeGatewayAutoCaching(s):s!==void 0&&(a.providerOptions=s),a},stepResult:new Promise(e=>{n=e})}}async function emitStepActions(e,t,n,r){let i=new Set(n.toolCalls.filter(isProviderExecutedToolCall).map(e=>e.toolCallId)),a=new Set([...r.excludedActionCallIds??[],...i,...extractToolApprovalInputRequests({content:n.content??[],excludedCallIds:r.excludedActionCallIds}).map(e=>e.action.callId),...n.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId)]),isExcluded=(e,t)=>a.has(e)||r.excludedActionToolNames.has(t),o=n.toolCalls.filter(e=>!isExcluded(e.toolCallId,e.toolName)&&!r.emittedActionCallIds?.has(e.toolCallId)).map(e=>createPresentedRuntimeActionRequestFromToolCall({toolCall:e,tools:r.tools}));o.length>0&&await e(createActionsRequestedEvent({actions:o.map(({action:e})=>e),presentation:collectActionPresentation(o),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}));let s=r.handledInlineToolResultCallIds,c=new Map(n.toolResults.map(e=>[e.toolCallId,e.output]));for(let r of reconcileToolResults(n)){if(isExcluded(r.callId,r.toolName)||s?.has(r.callId))continue;let n=c.get(r.callId);shouldSkipAuthorizationActionResult(r.callId,n)||(await emitNestedToolActions(e,t,r.callId),await e(createActionResultEvent({result:r,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})))}await e(createStepCompletedEvent({finishReason:normalizeAssistantStepFinishReason(n.finishReason),providerMetadata:extractStepProviderMetadata(n.providerMetadata),sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId,usage:extractStepUsage({costUsd:extractGatewayCostUsd(n.providerMetadata),usage:n.usage})}))}function isProviderExecutedToolCall(e){return e.providerExecuted===!0}function reconcileToolResults(e){let t=new Map;for(let n of e.toolResults)n.providerExecuted!==!0&&t.set(n.toolCallId,createRuntimeToolResultFromStepResult(n));for(let n of e.content??[])n.type===`tool-error`&&n.providerExecuted!==!0&&(t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromToolError(n)));for(let n of extractToolResultParts(e.response.messages))n.providerExecuted!==!0&&(t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromMessagePart(n)));return[...t.values()]}function shouldSkipAuthorizationActionResult(e,t){if(t!==void 0&&isPendingAuthorizationToolOutput(t))return!0;let n=contextStorage.getStore();if(n===void 0)return!1;let r=readToolInterrupt(n,e);return r!==void 0&&isAuthorizationSignal(r)}function extractToolResultParts(e){let t=[];for(let n of e)if(n.role===`tool`&&Array.isArray(n.content))for(let e of n.content)e.type===`tool-result`&&t.push(e);return t}function extractStepUsage(e){let t={};e.costUsd!==void 0&&(t.costUsd=e.costUsd);let n=e.usage;return n===void 0?Object.keys(t).length>0?t:void 0:(n.inputTokens!==void 0&&(t.inputTokens=n.inputTokens),n.outputTokens!==void 0&&(t.outputTokens=n.outputTokens),n.inputTokenDetails?.cacheReadTokens!==void 0&&(t.cacheReadTokens=n.inputTokenDetails.cacheReadTokens),n.inputTokenDetails?.cacheWriteTokens!==void 0&&(t.cacheWriteTokens=n.inputTokenDetails.cacheWriteTokens),Object.keys(t).length>0?t:void 0)}function extractStepProviderMetadata(e){let t=readGatewayGenerationId(e);return t===void 0?void 0:{gateway:{generationId:t}}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayGenerationId(e){let t=readGatewayMetadata(e)?.generationId;return typeof t==`string`&&t.length>0?t:void 0}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}export{buildStepHooks,emitStepActions,readGatewayGenerationId};
@@ -0,0 +1,25 @@
1
+ import type { HarnessToolDefinition } from "#harness/execute-tool.js";
2
+ import { type ToolModelOutputValue } from "#harness/tool-model-output.js";
3
+ import type { JsonObject } from "#shared/json.js";
4
+ /** The result of checking one tool call's input the way a model-issued call is checked. */
5
+ export type ToolCallInputCheck = {
6
+ readonly kind: "valid";
7
+ readonly value: JsonObject;
8
+ } | {
9
+ readonly kind: "invalid";
10
+ readonly message: string;
11
+ } | {
12
+ readonly kind: "threw";
13
+ readonly error: unknown;
14
+ };
15
+ /**
16
+ * Checks a tool call's input the way a conversation does: no input (or an
17
+ * empty string) is `{}`, anything else that is not a JSON object is
18
+ * rejected, and the rest must satisfy the schema the model was given.
19
+ */
20
+ export declare function checkToolCallInput(definition: Pick<HarnessToolDefinition, "inputSchema" | "name">, input: unknown, callId: string): Promise<ToolCallInputCheck>;
21
+ /**
22
+ * What the model sees for a tool's output: pending sign-in text, the
23
+ * author's `toModelOutput`, or the output as text or JSON.
24
+ */
25
+ export declare function toolCallModelOutput(definition: Pick<HarnessToolDefinition, "name" | "toModelOutput">, output: unknown, toolCallId: string | undefined): Promise<ToolModelOutputValue>;
@@ -0,0 +1 @@
1
+ import{asSchema}from"ai";import{toErrorMessage}from"#shared/errors.js";import{toModelSchema}from"#tools/schema.js";import{resolveToolCallInputObject}from"#harness/coordination.js";import{authorizationPendingModelText,isAuthorizationPendingModelOutput}from"#harness/authorization.js";import{normalizeToolModelOutput}from"#harness/tool-model-output.js";async function checkToolCallInput(e,t,n){let r;try{r=resolveToolCallInputObject(t,{callId:n,toolName:e.name})}catch(t){return{kind:`invalid`,message:`Invalid input for tool "${e.name}": ${toErrorMessage(t)}`}}let i;try{let t=asSchema(toModelSchema(e.inputSchema,`input`));if(t.validate===void 0)return{kind:`valid`,value:r};i=await t.validate(r)}catch(e){return{error:e,kind:`threw`}}return i.success?{kind:`valid`,value:i.value}:{kind:`invalid`,message:`Invalid input for tool "${e.name}": ${toErrorMessage(i.error)}`}}async function toolCallModelOutput(e,t,n){return isAuthorizationPendingModelOutput(t)?{type:`text`,value:authorizationPendingModelText(t.connections)}:e.toModelOutput===void 0?typeof t==`string`?{type:`text`,value:t}:normalizeToolModelOutput({output:{type:`json`,value:t??null},toolCallId:n,toolName:e.name}):normalizeToolModelOutput({output:await e.toModelOutput(t),toolCallId:n,toolName:e.name})}export{checkToolCallInput,toolCallModelOutput};
@@ -1,24 +1,9 @@
1
- import { type ModelMessage } from "ai";
2
- import { type HarnessStepResult } from "#harness/step-hooks.js";
3
- import { type StepFn, type ToolLoopHarnessConfig } from "#harness/types.js";
4
- export declare function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn;
5
- type ToolResponsePart = Extract<ModelMessage, {
6
- role: "tool";
7
- }>["content"][number];
8
- type ToolResultPart = Extract<ToolResponsePart, {
9
- type: "tool-result";
10
- }>;
11
- type StepResponseMessage = HarnessStepResult["response"]["messages"][number];
1
+ import type { StepFn, ToolLoopHarnessConfig } from "#harness/types.js";
12
2
  /**
13
- * Appends synthesized tool results for calls that have no result anywhere in
14
- * the step's response messages. Exported for its dedupe contract: a call
15
- * already answered — including provider-executed results the SDK keeps
16
- * inline in the assistant message — must never receive a second
17
- * `tool-result`, or the next Anthropic call rejects the history with
18
- * "each tool_use must have a single result".
3
+ * Creates the harness step: one step of a session, backed by the AI SDK's `ToolLoopAgent`.
4
+ *
5
+ * A step settles what earlier steps parked and takes its delivery's answers, opens or joins the
6
+ * turn, runs the work those answers approved, then makes one model step and acts on its response.
7
+ * Every lifecycle change goes through the session machine (`Step.apply`).
19
8
  */
20
- export declare function appendMissingToolResultMessages(input: {
21
- readonly append: readonly ToolResultPart[];
22
- readonly responseMessages: readonly StepResponseMessage[];
23
- }): StepResponseMessage[];
24
- export {};
9
+ export declare function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn;