@agent-native/core 0.221.0-same-host-mcp-20261027-20261027081850 → 0.221.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 (327) hide show
  1. package/dist/a2a/server.js +4 -4
  2. package/dist/a2a/task-lifecycle.d.ts +12 -12
  3. package/dist/a2a/task-lifecycle.js +10 -12
  4. package/dist/a2a/task-store.js +81 -228
  5. package/dist/action-caller.d.ts +3 -0
  6. package/dist/action-caller.js +8 -0
  7. package/dist/action.d.ts +1 -0
  8. package/dist/agent/engine/ai-sdk-engine.js +3 -3
  9. package/dist/agent/engine/anthropic-engine.js +3 -3
  10. package/dist/agent/engine/credential-owner.d.ts +3 -0
  11. package/dist/agent/engine/credential-owner.js +9 -0
  12. package/dist/agent/engine/registry.js +28 -2
  13. package/dist/agent/harness/acp-adapter.d.ts +1 -0
  14. package/dist/agent/harness/acp-adapter.js +36 -5
  15. package/dist/agent/harness/background.d.ts +5 -1
  16. package/dist/agent/harness/background.js +4 -3
  17. package/dist/agent/harness/lifecycle.d.ts +2 -0
  18. package/dist/agent/harness/lifecycle.js +452 -84
  19. package/dist/agent/harness/run-policy.d.ts +5 -0
  20. package/dist/agent/harness/run-policy.js +70 -0
  21. package/dist/agent/harness/runner.js +89 -73
  22. package/dist/agent/harness/store.d.ts +10 -1
  23. package/dist/agent/harness/store.js +91 -12
  24. package/dist/agent/harness/turn-driver.d.ts +12 -0
  25. package/dist/agent/harness/turn-driver.js +42 -0
  26. package/dist/agent/harness/types.d.ts +11 -0
  27. package/dist/agent/production-agent.d.ts +9 -0
  28. package/dist/agent/production-agent.js +153 -41
  29. package/dist/agent/run-manager.d.ts +4 -0
  30. package/dist/agent/run-manager.js +23 -7
  31. package/dist/agent/run-store.d.ts +3 -1
  32. package/dist/agent/run-store.fencing.native-harness.fixture.test.support.js +34 -0
  33. package/dist/agent/run-store.fencing.worker.test.support.d.ts +1 -0
  34. package/dist/agent/{run-store.fencing.worker.js → run-store.fencing.worker.test.support.js} +337 -4
  35. package/dist/agent/run-store.js +89 -17
  36. package/dist/app-config/clips.d.ts +10 -0
  37. package/dist/app-config/clips.js +24 -0
  38. package/dist/app-config/index.d.ts +1 -1
  39. package/dist/app-config/index.js +1 -1
  40. package/dist/app-config/schema.d.ts +1 -0
  41. package/dist/appearance/actions/set-theme-family.js +16 -2
  42. package/dist/appearance/theme-family.d.ts +11 -1
  43. package/dist/appearance/theme-family.js +21 -2
  44. package/dist/automations/outside-origin.d.ts +13 -0
  45. package/dist/automations/outside-origin.js +23 -0
  46. package/dist/automations/service.d.ts +4 -2
  47. package/dist/automations/service.js +11 -8
  48. package/dist/cli/code-agent-executor.js +5 -16
  49. package/dist/cli/create.d.ts +11 -2
  50. package/dist/cli/create.js +121 -32
  51. package/dist/cli/skills-content/turn-into-app-skill.d.ts +4 -3
  52. package/dist/cli/skills-content/turn-into-app-skill.js +143 -36
  53. package/dist/cli/skills.d.ts +3 -0
  54. package/dist/cli/skills.js +4 -1
  55. package/dist/cli/template-sync.js +4 -4
  56. package/dist/cli/upgrade.d.ts +1 -0
  57. package/dist/cli/upgrade.js +207 -2
  58. package/dist/client/chat/agentkit-agent-native.js +23 -3
  59. package/dist/client/mcp-approval.d.ts +53 -0
  60. package/dist/client/mcp-approval.js +81 -0
  61. package/dist/client/onboarding/use-onboarding.js +6 -4
  62. package/dist/client/resources/mcp-integration-catalog.js +19 -0
  63. package/dist/client/theme-family.d.ts +2 -1
  64. package/dist/client/theme-family.js +271 -32
  65. package/dist/client/theme.js +3 -2
  66. package/dist/code-agents/background-controller.js +1 -13
  67. package/dist/code-agents/prompt-attachments.d.ts +11 -0
  68. package/dist/code-agents/prompt-attachments.js +103 -6
  69. package/dist/collab/awareness-store.d.ts +8 -0
  70. package/dist/collab/awareness-store.js +9 -1
  71. package/dist/collab/index.d.ts +1 -1
  72. package/dist/collab/index.js +1 -1
  73. package/dist/collab/routes.d.ts +1 -1
  74. package/dist/collab/struct-routes.d.ts +1 -1
  75. package/dist/config.d.ts +13 -3
  76. package/dist/config.js +64 -1
  77. package/dist/db/client.d.ts +8 -6
  78. package/dist/db/client.js +56 -17
  79. package/dist/db/create-get-db.js +6 -1
  80. package/dist/db/index.d.ts +2 -1
  81. package/dist/db/index.js +1 -0
  82. package/dist/db/schema-snapshot.generated.js +9 -2
  83. package/dist/db/sql.d.ts +28 -0
  84. package/dist/db/sql.js +186 -0
  85. package/dist/decisions/actions/decide.d.ts +4 -0
  86. package/dist/decisions/actions/decide.js +7 -0
  87. package/dist/decisions/decide.d.ts +1 -0
  88. package/dist/decisions/decide.js +21 -9
  89. package/dist/decisions/index.d.ts +4 -1
  90. package/dist/decisions/index.js +3 -0
  91. package/dist/decisions/response.d.ts +1 -0
  92. package/dist/decisions/response.js +36 -11
  93. package/dist/decisions/types.d.ts +5 -0
  94. package/dist/decisions/validation.js +6 -3
  95. package/dist/deploy/build.js +11 -5
  96. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  97. package/dist/file-upload/attachment-text.d.ts +71 -0
  98. package/dist/file-upload/attachment-text.js +209 -0
  99. package/dist/file-upload/downscale-inline-image.d.ts +4 -0
  100. package/dist/file-upload/downscale-inline-image.js +27 -0
  101. package/dist/file-upload/inline-attachment-limits.d.ts +4 -0
  102. package/dist/file-upload/inline-attachment-limits.js +20 -1
  103. package/dist/file-upload/owned-attachment.d.ts +13 -1
  104. package/dist/file-upload/owned-attachment.js +52 -15
  105. package/dist/file-upload/pre-upload-attachments.js +74 -12
  106. package/dist/file-upload/registry.d.ts +1 -0
  107. package/dist/file-upload/registry.js +15 -7
  108. package/dist/file-upload/status.d.ts +19 -0
  109. package/dist/file-upload/status.js +49 -0
  110. package/dist/file-upload/thread-image-history.js +10 -2
  111. package/dist/index.browser.d.ts +1 -0
  112. package/dist/index.browser.js +1 -0
  113. package/dist/index.d.ts +1 -0
  114. package/dist/index.js +1 -0
  115. package/dist/ingestion/media.js +11 -5
  116. package/dist/jobs/actions/run-automation-now.js +2 -2
  117. package/dist/jobs/background-automation-runner.js +4 -4
  118. package/dist/jobs/frontmatter.d.ts +1 -1
  119. package/dist/jobs/frontmatter.js +5 -2
  120. package/dist/jobs/run-now.d.ts +2 -0
  121. package/dist/jobs/run-now.js +1 -1
  122. package/dist/jobs/scheduler.d.ts +2 -0
  123. package/dist/jobs/scheduler.js +1 -1
  124. package/dist/localization/automation-outcome-messages.js +22 -22
  125. package/dist/localization/core-messages/supplemental/ar-SA.js +1 -0
  126. package/dist/localization/core-messages/supplemental/de-DE.js +1 -0
  127. package/dist/localization/core-messages/supplemental/en-US.js +1 -0
  128. package/dist/localization/core-messages/supplemental/es-ES.js +1 -0
  129. package/dist/localization/core-messages/supplemental/fr-FR.js +1 -0
  130. package/dist/localization/core-messages/supplemental/hi-IN.js +1 -0
  131. package/dist/localization/core-messages/supplemental/ja-JP.js +1 -0
  132. package/dist/localization/core-messages/supplemental/ko-KR.js +1 -0
  133. package/dist/localization/core-messages/supplemental/pt-BR.js +1 -0
  134. package/dist/localization/core-messages/supplemental/zh-CN.js +1 -0
  135. package/dist/localization/core-messages/supplemental/zh-TW.js +1 -0
  136. package/dist/localization/mcp-approval-messages.d.ts +7 -1
  137. package/dist/localization/mcp-approval-messages.js +66 -0
  138. package/dist/localization/mcp-settings-messages.d.ts +1 -0
  139. package/dist/mcp/action-eligibility.d.ts +1 -0
  140. package/dist/mcp/action-eligibility.js +10 -5
  141. package/dist/mcp/analytics.d.ts +2 -0
  142. package/dist/mcp/analytics.js +10 -2
  143. package/dist/mcp/approval-route.d.ts +7 -0
  144. package/dist/mcp/approval-route.js +41 -16
  145. package/dist/mcp/approval-summary.d.ts +12 -2
  146. package/dist/mcp/approval-summary.js +128 -23
  147. package/dist/mcp/approval-time.d.ts +13 -3
  148. package/dist/mcp/approval-time.js +49 -5
  149. package/dist/mcp/build-server.d.ts +12 -1
  150. package/dist/mcp/build-server.js +157 -155
  151. package/dist/mcp/builtin-tools.d.ts +1 -0
  152. package/dist/mcp/builtin-tools.js +30 -14
  153. package/dist/mcp/direct-action-call.js +72 -27
  154. package/dist/mcp/embed-app.js +11 -6
  155. package/dist/mcp/embed-redaction.d.ts +10 -13
  156. package/dist/mcp/embed-redaction.js +227 -40
  157. package/dist/mcp/execute-action-call.d.ts +3 -2
  158. package/dist/mcp/execute-action-call.js +1 -4
  159. package/dist/mcp/framework-tools.d.ts +2 -2
  160. package/dist/mcp/oauth-route.js +102 -6
  161. package/dist/mcp/screen-memory-stdio.d.ts +3 -3
  162. package/dist/mcp/server.js +6 -0
  163. package/dist/mcp-client/oauth-routes.js +12 -2
  164. package/dist/notifications/routes.d.ts +3 -3
  165. package/dist/observability/failure-context.js +1 -0
  166. package/dist/observability/traces.js +11 -1
  167. package/dist/onboarding/first-run-builder-credits-experiment.d.ts +12 -0
  168. package/dist/onboarding/first-run-builder-credits-experiment.js +91 -0
  169. package/dist/org/index.d.ts +1 -1
  170. package/dist/provider-api/actions/custom-provider-registration.d.ts +11 -11
  171. package/dist/provider-api/actions/provider-api.d.ts +12 -12
  172. package/dist/server/action-approval.d.ts +2 -2
  173. package/dist/server/action-approval.js +17 -10
  174. package/dist/server/action-discovery.js +2 -122
  175. package/dist/server/action-routes.d.ts +0 -1
  176. package/dist/server/action-routes.js +138 -58
  177. package/dist/server/agent-chat/action-filters-a2a.d.ts +1 -0
  178. package/dist/server/agent-chat/action-filters-a2a.js +11 -1
  179. package/dist/server/agent-chat/framework-prompts.d.ts +1 -0
  180. package/dist/server/agent-chat/framework-prompts.js +22 -1
  181. package/dist/server/agent-chat/mcp-options.d.ts +7 -0
  182. package/dist/server/agent-chat/mcp-options.js +1 -0
  183. package/dist/server/agent-chat/plugin-options.d.ts +23 -0
  184. package/dist/server/agent-chat/prompt-resources.d.ts +4 -2
  185. package/dist/server/agent-chat/prompt-resources.js +78 -32
  186. package/dist/server/agent-chat-plugin.js +214 -125
  187. package/dist/server/agent-engine-api-key-route.d.ts +2 -2
  188. package/dist/server/agent-engine-ollama-models-route.d.ts +1 -1
  189. package/dist/server/agent-run-context.js +4 -0
  190. package/dist/server/attachment-actions.d.ts +14 -7
  191. package/dist/server/attachment-actions.js +310 -65
  192. package/dist/server/attribution.d.ts +2 -0
  193. package/dist/server/auth.d.ts +2 -1
  194. package/dist/server/auth.js +84 -17
  195. package/dist/server/better-auth-instance.js +46 -12
  196. package/dist/server/builder-api-auth.d.ts +1 -0
  197. package/dist/server/builder-api-auth.js +8 -0
  198. package/dist/server/builder-browser.d.ts +5 -1
  199. package/dist/server/builder-browser.js +80 -4
  200. package/dist/server/cli-wrapper-flags.d.ts +27 -0
  201. package/dist/server/cli-wrapper-flags.js +500 -0
  202. package/dist/server/consent-route.d.ts +3 -0
  203. package/dist/server/consent-route.js +29 -10
  204. package/dist/server/core-routes-plugin.js +72 -60
  205. package/dist/server/credential-provider.js +26 -11
  206. package/dist/server/edge.d.ts +3 -2
  207. package/dist/server/edge.js +3 -2
  208. package/dist/server/embed-request-origin.d.ts +4 -0
  209. package/dist/server/embed-request-origin.js +28 -0
  210. package/dist/server/embed-route.js +4 -2
  211. package/dist/server/embed-session.d.ts +16 -4
  212. package/dist/server/embed-session.js +253 -145
  213. package/dist/server/embedded.d.ts +2 -1
  214. package/dist/server/embedded.js +9 -5
  215. package/dist/server/filesystem-action-entry.d.ts +15 -1
  216. package/dist/server/filesystem-action-entry.js +153 -23
  217. package/dist/server/first-touch-route.d.ts +1 -1
  218. package/dist/server/google-oauth.d.ts +7 -0
  219. package/dist/server/google-oauth.js +33 -6
  220. package/dist/server/index.d.ts +11 -6
  221. package/dist/server/index.js +8 -3
  222. package/dist/server/magic-link-attribution.d.ts +2 -0
  223. package/dist/server/magic-link-attribution.js +8 -2
  224. package/dist/server/mcp-signup-attribution.d.ts +23 -0
  225. package/dist/server/mcp-signup-attribution.js +135 -0
  226. package/dist/server/prompts/framework-core.js +2 -1
  227. package/dist/server/prompts/shared-rules.d.ts +2 -0
  228. package/dist/server/prompts/shared-rules.js +2 -0
  229. package/dist/server/realtime-voice.d.ts +65 -2
  230. package/dist/server/realtime-voice.js +235 -36
  231. package/dist/server/release-migrations.js +37 -10
  232. package/dist/server/request-context.d.ts +17 -0
  233. package/dist/server/request-context.js +4 -0
  234. package/dist/server/request-origin.d.ts +4 -6
  235. package/dist/server/request-origin.js +26 -28
  236. package/dist/server/session-resolution-unavailable.d.ts +22 -0
  237. package/dist/server/session-resolution-unavailable.js +65 -0
  238. package/dist/server/short-lived-token.d.ts +10 -2
  239. package/dist/server/short-lived-token.js +12 -4
  240. package/dist/server/ui-action-capability.js +18 -4
  241. package/dist/shared/first-run-builder-credits-experiment.d.ts +13 -0
  242. package/dist/shared/first-run-builder-credits-experiment.js +22 -0
  243. package/dist/shared/index.d.ts +1 -0
  244. package/dist/shared/index.js +1 -0
  245. package/dist/shared/mcp-approval-review.d.ts +19 -0
  246. package/dist/shared/mcp-approval-review.js +29 -0
  247. package/dist/shared/reasoning-effort.d.ts +4 -0
  248. package/dist/shared/reasoning-effort.js +20 -0
  249. package/dist/sharing/access.d.ts +11 -2
  250. package/dist/sharing/access.js +12 -7
  251. package/dist/state-machine/index.d.ts +5 -8
  252. package/dist/state-machine/index.js +6 -2
  253. package/dist/templates/builder-code-starter/app/components/layout/Layout.tsx.patch +48 -18
  254. package/dist/templates/builder-code-starter/server/plugins/agent-chat.ts.patch +7 -6
  255. package/dist/templates/builder-code-starter/template-layer.json +1 -0
  256. package/dist/templates/chat/.agents/skills/storing-data/SKILL.md +18 -0
  257. package/dist/templates/chat/app/components/chat/ChatRouteContent.tsx +18 -4
  258. package/dist/templates/chat/app/components/home/HomePage.tsx +28 -69
  259. package/dist/templates/chat/app/components/layout/Layout.tsx +46 -14
  260. package/dist/templates/chat/app/i18n/ar-SA.ts +0 -4
  261. package/dist/templates/chat/app/i18n/de-DE.ts +0 -5
  262. package/dist/templates/chat/app/i18n/en-US.ts +0 -4
  263. package/dist/templates/chat/app/i18n/es-ES.ts +0 -5
  264. package/dist/templates/chat/app/i18n/fr-FR.ts +0 -5
  265. package/dist/templates/chat/app/i18n/hi-IN.ts +0 -5
  266. package/dist/templates/chat/app/i18n/ja-JP.ts +0 -5
  267. package/dist/templates/chat/app/i18n/ko-KR.ts +0 -5
  268. package/dist/templates/chat/app/i18n/pt-BR.ts +0 -5
  269. package/dist/templates/chat/app/i18n/zh-CN.ts +0 -4
  270. package/dist/templates/chat/app/i18n/zh-TW.ts +0 -4
  271. package/dist/templates/chat/app/lib/chat-paths.ts +36 -13
  272. package/dist/templates/chat/package.json +1 -0
  273. package/dist/templates/chat/server/plugins/agent-chat.ts +2 -1
  274. package/dist/templates/default/.agents/skills/storing-data/SKILL.md +18 -0
  275. package/dist/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +123 -33
  276. package/dist/templates/headless/.agents/skills/storing-data/SKILL.md +18 -0
  277. package/dist/templates/workspace-core/.agents/skills/storing-data/SKILL.md +18 -0
  278. package/dist/templates/workspace-core/.agents/skills/turn-into-app/SKILL.md +34 -29
  279. package/dist/templates/workspace-core/.agents/skills/turn-into-app/references/fresh-project.md +12 -5
  280. package/dist/templates/workspace-core/.agents/skills/turn-into-app/references/review-loop.md +3 -2
  281. package/dist/templates/workspace-core/.agents/skills/turn-into-app/references/where-it-runs.md +93 -0
  282. package/dist/tracking/registry.js +25 -0
  283. package/dist/triggers/actions/manage-automation.js +6 -2
  284. package/dist/triggers/actions.js +14 -2
  285. package/dist/triggers/index.d.ts +1 -0
  286. package/dist/triggers/index.js +1 -0
  287. package/dist/vite/client.js +5 -4
  288. package/docs/content/authentication.mdx +2 -0
  289. package/docs/content/components.mdx +1 -1
  290. package/docs/content/decisions.mdx +1 -1
  291. package/docs/content/recurring-jobs.mdx +15 -0
  292. package/docs/content/template-chat-developers.mdx +1 -1
  293. package/docs/content/template-chat-features.mdx +4 -4
  294. package/docs/content/turn-into-app.mdx +18 -10
  295. package/package.json +6 -4
  296. package/src/templates/builder-code-starter/app/components/layout/Layout.tsx.patch +48 -18
  297. package/src/templates/builder-code-starter/server/plugins/agent-chat.ts.patch +7 -6
  298. package/src/templates/builder-code-starter/template-layer.json +1 -0
  299. package/src/templates/chat/.agents/skills/storing-data/SKILL.md +18 -0
  300. package/src/templates/chat/app/components/chat/ChatRouteContent.tsx +18 -4
  301. package/src/templates/chat/app/components/home/HomePage.tsx +28 -69
  302. package/src/templates/chat/app/components/layout/Layout.tsx +46 -14
  303. package/src/templates/chat/app/i18n/ar-SA.ts +0 -4
  304. package/src/templates/chat/app/i18n/de-DE.ts +0 -5
  305. package/src/templates/chat/app/i18n/en-US.ts +0 -4
  306. package/src/templates/chat/app/i18n/es-ES.ts +0 -5
  307. package/src/templates/chat/app/i18n/fr-FR.ts +0 -5
  308. package/src/templates/chat/app/i18n/hi-IN.ts +0 -5
  309. package/src/templates/chat/app/i18n/ja-JP.ts +0 -5
  310. package/src/templates/chat/app/i18n/ko-KR.ts +0 -5
  311. package/src/templates/chat/app/i18n/pt-BR.ts +0 -5
  312. package/src/templates/chat/app/i18n/zh-CN.ts +0 -4
  313. package/src/templates/chat/app/i18n/zh-TW.ts +0 -4
  314. package/src/templates/chat/app/lib/chat-paths.ts +36 -13
  315. package/src/templates/chat/package.json +1 -0
  316. package/src/templates/chat/server/plugins/agent-chat.ts +2 -1
  317. package/src/templates/default/.agents/skills/storing-data/SKILL.md +18 -0
  318. package/src/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +123 -33
  319. package/src/templates/headless/.agents/skills/storing-data/SKILL.md +18 -0
  320. package/src/templates/workspace-core/.agents/skills/storing-data/SKILL.md +18 -0
  321. package/src/templates/workspace-core/.agents/skills/turn-into-app/SKILL.md +34 -29
  322. package/src/templates/workspace-core/.agents/skills/turn-into-app/references/fresh-project.md +12 -5
  323. package/src/templates/workspace-core/.agents/skills/turn-into-app/references/review-loop.md +3 -2
  324. package/src/templates/workspace-core/.agents/skills/turn-into-app/references/where-it-runs.md +93 -0
  325. package/dist/automations/mcp-origin.d.ts +0 -2
  326. package/dist/automations/mcp-origin.js +0 -10
  327. /package/dist/agent/{run-store.fencing.worker.d.ts → run-store.fencing.native-harness.fixture.test.support.d.ts} +0 -0
@@ -1,8 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { performance } from "node:perf_hooks";
3
+ import { startRun, tryClaimRunSlot } from "../run-manager.js";
4
+ import { ensureAgentToolApprovalTable, hasPendingCurrentTurnApproval, } from "../tool-approval-store.js";
3
5
  import { resolveAgentHarness } from "./registry.js";
6
+ import { agentHarnessFollowUpRunOptions } from "./run-policy.js";
4
7
  import { APPROVAL_RESOLUTION_CLAIM_LEASE_MS, AgentHarnessSessionConflictError, claimAgentHarnessSessionFollowUp, claimAgentHarnessSessionApprovalResolution, failAgentHarnessSessionApprovalResolution, failAgentHarnessSessionFollowUp, finalizeAgentHarnessSessionApprovalResolution, finalizeAgentHarnessSessionFollowUp, finishAgentHarnessSessionExpiryCleanup, getAgentHarnessSession, getAgentHarnessSessionByRunId, isAgentHarnessSessionConflictError, listExpiredAgentHarnessApprovalResolutions, listExpiredAgentHarnessFollowUps, markAgentHarnessSessionStopped, markAgentHarnessSessionStoppedIfUnclaimed, markAgentHarnessSessionFollowUpDispatched, persistAgentHarnessApprovalEvent, persistAgentHarnessFollowUpEvent, reconcileExpiredAgentHarnessFollowUp, reconcileExpiredAgentHarnessApprovalResolution, renewAgentHarnessSessionApprovalResolutionClaim, renewAgentHarnessSessionFollowUpClaim, releaseAgentHarnessSessionApprovalResolutionBeforeDispatch, startAgentHarnessSessionApprovalDispatch, startAgentHarnessSessionExpiryCleanup, startAgentHarnessSessionFollowUpDispatch, updateAgentHarnessSession, updateAgentHarnessSessionAtGeneration, updateAgentHarnessSessionIfFollowUpClaim, RESOLVED_APPROVAL_LIMIT, } from "./store.js";
5
8
  import { agentHarnessEventToAgentChatEvents } from "./translate.js";
9
+ import { driveAgentHarnessTurnChunks } from "./turn-driver.js";
6
10
  const LIVE_SESSION_TTL_MS = 24 * 60 * 60 * 1_000;
7
11
  const APPROVAL_CLAIM_POLL_INTERVAL_MS = 500;
8
12
  const APPROVAL_CLAIM_RENEW_INTERVAL_MS = Math.floor(APPROVAL_RESOLUTION_CLAIM_LEASE_MS / 3);
@@ -11,6 +15,12 @@ const FOLLOW_UP_CLAIM_LEASE_MS = 60_000;
11
15
  const FOLLOW_UP_CLAIM_RENEW_INTERVAL_MS = 20_000;
12
16
  const FOLLOW_UP_DEADLINE_MS = LIVE_SESSION_TTL_MS;
13
17
  const MAX_FOLLOW_UP_FINALIZATION_ATTEMPTS = 3;
18
+ function isAbortRequested(signal) {
19
+ return signal.aborted;
20
+ }
21
+ function isApprovalResolutionInProgress(live) {
22
+ return live.approvalResolutionInProgress;
23
+ }
14
24
  const liveSessions = new Map();
15
25
  const sessionOperations = new Map();
16
26
  const activeFollowUps = new Set();
@@ -82,25 +92,32 @@ export async function resolveAgentHarnessApproval(input) {
82
92
  ? `Approval ${input.approval.id} does not match pending approval ${pending.id}.`
83
93
  : "This harness session has no pending approval.");
84
94
  }
85
- const live = ownedLiveSession(session.id, input.scope);
86
- if (!live) {
87
- return failure(input.runId, session, "unavailable", "The pending approval belongs to a harness process that is no longer live and cannot be reconstructed safely.");
88
- }
89
- if (!live.session.approve && !live.session.continueTurn) {
95
+ let live = ownedLiveSession(session.id, input.scope);
96
+ if (live && !live.session.approve && !live.session.continueTurn) {
90
97
  return failure(input.runId, session, "unavailable", `Harness ${session.harnessName} does not expose approval continuation.`);
91
98
  }
92
- if (live.expiryCleanupInProgress) {
99
+ if (live?.expiryCleanupInProgress) {
93
100
  return failure(input.runId, session, "unavailable", "The live harness session is being cleaned up and cannot resolve approval.");
94
101
  }
95
- live.approvalResolutionInProgress = true;
96
102
  const approvalAbort = new AbortController();
97
103
  let finalizing = false;
98
104
  let stopWatchingApprovalClaim;
99
105
  let approvalClaimAcquired = false;
100
106
  let approvalResolutionStarted = null;
107
+ let rehydratedSession;
108
+ let rehydratedSessionCleanupAttempted = false;
101
109
  let providerDispatchStarted = false;
110
+ const hasApprovalProviderDispatchStarted = () => providerDispatchStarted;
111
+ const stopRehydratedSession = async () => {
112
+ if (!rehydratedSession || rehydratedSessionCleanupAttempted)
113
+ return;
114
+ rehydratedSessionCleanupAttempted = true;
115
+ await stopAcquiredHarnessSession(session.id, rehydratedSession);
116
+ };
117
+ if (live)
118
+ live.approvalResolutionInProgress = true;
102
119
  try {
103
- const resolutionStarted = await beginApprovalResolution(input.runId, input.approval.id, live.session);
120
+ const resolutionStarted = await beginApprovalResolution(input.runId, input.approval.id, live?.session);
104
121
  if (!resolutionStarted) {
105
122
  const latest = await getAgentHarnessSessionByRunId(input.runId);
106
123
  return failure(input.runId, latest ?? session, "unavailable", "The harness session changed before approval dispatch; its latest state was preserved.");
@@ -108,19 +125,79 @@ export async function resolveAgentHarnessApproval(input) {
108
125
  approvalResolutionStarted = resolutionStarted;
109
126
  approvalClaimAcquired = true;
110
127
  stopWatchingApprovalClaim = watchApprovalResolutionClaim(session.id, input.approval.id, approvalAbort, () => finalizing);
128
+ if (!live) {
129
+ const acquired = await acquireSession(resolutionStarted, input.scope);
130
+ if (!acquired.ok) {
131
+ const latest = await releaseUndispatchedApprovalResolution({
132
+ runId: input.runId,
133
+ session: resolutionStarted,
134
+ approvalId: input.approval.id,
135
+ });
136
+ return failure(input.runId, latest ?? acquired.result.session ?? session, acquired.result.errorCode ?? "unavailable", acquired.result.error ?? "Harness session could not be resumed.");
137
+ }
138
+ live = acquired.live;
139
+ live.approvalResolutionInProgress = true;
140
+ if (acquired.rehydrated) {
141
+ rehydratedSession = acquired.live.session;
142
+ }
143
+ }
144
+ const activeLive = live;
145
+ if (!activeLive.session.approve && !activeLive.session.continueTurn) {
146
+ const latest = await releaseUndispatchedApprovalResolution({
147
+ runId: input.runId,
148
+ session: resolutionStarted,
149
+ approvalId: input.approval.id,
150
+ liveSession: activeLive.session,
151
+ });
152
+ await stopRehydratedSession();
153
+ return failure(input.runId, latest ?? session, "unavailable", `Harness ${session.harnessName} does not expose approval continuation.`);
154
+ }
155
+ if (activeLive.expiryCleanupInProgress) {
156
+ const latest = await releaseUndispatchedApprovalResolution({
157
+ runId: input.runId,
158
+ session: resolutionStarted,
159
+ approvalId: input.approval.id,
160
+ liveSession: activeLive.session,
161
+ });
162
+ return failure(input.runId, latest ?? session, "unavailable", "The live harness session is being cleaned up and cannot resolve approval.");
163
+ }
164
+ if (activeLive.session.canResolveApproval &&
165
+ !(await activeLive.session.canResolveApproval(input.approval))) {
166
+ const failed = await failAgentHarnessSessionApprovalResolution({
167
+ sessionId: session.id,
168
+ approvalId: input.approval.id,
169
+ recordResolvedId: false,
170
+ errorEvent: {
171
+ type: "error",
172
+ error: "The provider session resumed without its pending approval request. The approval was not sent and cannot be retried on this session.",
173
+ errorCode: "harness_approval_not_resumable",
174
+ },
175
+ });
176
+ if (failed) {
177
+ refreshLiveAgentHarnessSessionGeneration(session.id, activeLive.session, failed.generation);
178
+ }
179
+ await stopRehydratedSession();
180
+ const latest = failed ?? (await getAgentHarnessSessionByRunId(input.runId));
181
+ return failure(input.runId, latest ?? session, "unavailable", "The provider session resumed without the pending approval request. The approval was not sent and the session cannot resume it.");
182
+ }
111
183
  const dispatch = await startAgentHarnessSessionApprovalDispatch(session.id, resolutionStarted.status, resolutionStarted.generation, input.approval.id, () => {
112
- providerDispatchStarted = true;
113
- if (live.session.approve) {
114
- const result = live.session.approve(input.approval);
184
+ const liveSession = activeLive.session;
185
+ if (liveSession.approve) {
186
+ const result = liveSession.approve(input.approval);
187
+ providerDispatchStarted = true;
115
188
  void result.catch(() => { });
116
189
  return {
117
190
  kind: "approve",
118
191
  result,
119
192
  };
120
193
  }
121
- const stream = live.session.continueTurn({
194
+ const stream = liveSession.continueTurn?.({
122
195
  approval: input.approval,
123
196
  });
197
+ if (!stream) {
198
+ throw new Error("Harness session cannot continue an approval.");
199
+ }
200
+ providerDispatchStarted = true;
124
201
  const iterator = stream[Symbol.asyncIterator]();
125
202
  const firstNext = nextHarnessEvent(iterator, approvalAbort.signal);
126
203
  void firstNext.catch(() => { });
@@ -136,11 +213,12 @@ export async function resolveAgentHarnessApproval(input) {
136
213
  runId: input.runId,
137
214
  session: resolutionStarted,
138
215
  approvalId: input.approval.id,
139
- liveSession: live.session,
216
+ liveSession: activeLive.session,
140
217
  });
218
+ await stopRehydratedSession();
141
219
  return failure(input.runId, latest ?? session, "unavailable", "The harness session changed before approval dispatch; its latest state was preserved.");
142
220
  }
143
- refreshLiveAgentHarnessSessionGeneration(session.id, live.session, dispatch.session.generation);
221
+ refreshLiveAgentHarnessSessionGeneration(session.id, activeLive.session, dispatch.session.generation);
144
222
  const events = [];
145
223
  const continued = dispatch.started.kind === "continue";
146
224
  if (dispatch.started.kind === "approve") {
@@ -156,7 +234,7 @@ export async function resolveAgentHarnessApproval(input) {
156
234
  approvalResolutionStatus: dispatch.session.status,
157
235
  firstNext: dispatch.started.firstNext,
158
236
  iterator: dispatch.started.iterator,
159
- liveSession: live.session,
237
+ liveSession: activeLive.session,
160
238
  abortSignal: approvalAbort.signal,
161
239
  persistEvent: async (event) => {
162
240
  if (event.type === "done")
@@ -170,8 +248,8 @@ export async function resolveAgentHarnessApproval(input) {
170
248
  }
171
249
  approvalAbort.signal.throwIfAborted();
172
250
  const nextPending = events.find((event) => event.type === "approval-request");
173
- const detachResumeState = continued && !nextPending && live.session.detach
174
- ? () => live.session.detach()
251
+ const detachResumeState = continued && !nextPending && activeLive.session.detach
252
+ ? async () => activeLive.session.detach?.()
175
253
  : undefined;
176
254
  let updated;
177
255
  finalizing = true;
@@ -181,7 +259,7 @@ export async function resolveAgentHarnessApproval(input) {
181
259
  approvalId: input.approval.id,
182
260
  nextPending,
183
261
  detachResumeState,
184
- liveSession: live.session,
262
+ liveSession: activeLive.session,
185
263
  });
186
264
  }
187
265
  catch (error) {
@@ -205,7 +283,7 @@ export async function resolveAgentHarnessApproval(input) {
205
283
  if (continued &&
206
284
  !asPendingApproval(updated.pendingApproval) &&
207
285
  !updated.followUpClaimId) {
208
- releaseLiveAgentHarnessSession(session.id, live.session);
286
+ releaseLiveAgentHarnessSession(session.id, activeLive.session);
209
287
  }
210
288
  if (continued && events.some((event) => event.type === "done")) {
211
289
  await input.onHarnessEvent?.({ type: "done" });
@@ -213,16 +291,18 @@ export async function resolveAgentHarnessApproval(input) {
213
291
  return {
214
292
  ok: true,
215
293
  runId: input.runId,
216
- session: updated ?? session,
294
+ session: updated,
217
295
  events,
218
296
  };
219
297
  }
220
298
  catch (error) {
299
+ const cleanupErrors = [error];
221
300
  if (approvalClaimAcquired &&
222
301
  !finalizing &&
223
- (!providerDispatchStarted || !isAgentHarnessSessionConflictError(error))) {
302
+ (!hasApprovalProviderDispatchStarted() ||
303
+ !isAgentHarnessSessionConflictError(error))) {
224
304
  try {
225
- const recovered = providerDispatchStarted
305
+ const recovered = hasApprovalProviderDispatchStarted()
226
306
  ? await failAgentHarnessSessionApprovalResolution({
227
307
  sessionId: session.id,
228
308
  approvalId: input.approval.id,
@@ -232,22 +312,34 @@ export async function resolveAgentHarnessApproval(input) {
232
312
  runId: input.runId,
233
313
  session: approvalResolutionStarted,
234
314
  approvalId: input.approval.id,
235
- liveSession: live.session,
315
+ liveSession: live?.session,
236
316
  })
237
317
  : null;
238
- if (recovered) {
318
+ if (recovered && live) {
239
319
  refreshLiveAgentHarnessSessionGeneration(session.id, live.session, recovered.generation);
240
320
  }
241
321
  }
242
322
  catch (cleanupError) {
243
- throw new AggregateError([error, cleanupError], "Harness approval failed and its resolution claim could not be released.");
323
+ cleanupErrors.push(cleanupError);
244
324
  }
245
325
  }
326
+ if (!hasApprovalProviderDispatchStarted() && rehydratedSession) {
327
+ try {
328
+ await stopRehydratedSession();
329
+ }
330
+ catch (cleanupError) {
331
+ cleanupErrors.push(cleanupError);
332
+ }
333
+ }
334
+ if (cleanupErrors.length > 1) {
335
+ throw new AggregateError(cleanupErrors, "Harness approval failed and pre-dispatch cleanup was incomplete.");
336
+ }
246
337
  throw error;
247
338
  }
248
339
  finally {
249
340
  stopWatchingApprovalClaim?.();
250
- live.approvalResolutionInProgress = false;
341
+ if (live)
342
+ live.approvalResolutionInProgress = false;
251
343
  }
252
344
  });
253
345
  }
@@ -333,7 +425,9 @@ async function beginApprovalResolution(runId, approvalId, liveSession) {
333
425
  const updated = await claimAgentHarnessSessionApprovalResolution(latest.id, approvalId, latest.status, latest.generation, latest.followUpClaimId ?? null);
334
426
  if (!updated)
335
427
  return null;
336
- refreshLiveAgentHarnessSessionGeneration(latest.id, liveSession, updated.generation);
428
+ if (liveSession) {
429
+ refreshLiveAgentHarnessSessionGeneration(latest.id, liveSession, updated.generation);
430
+ }
337
431
  return updated;
338
432
  }
339
433
  catch (error) {
@@ -364,7 +458,9 @@ async function releaseUndispatchedApprovalResolution(input) {
364
458
  expectedFollowUpClaimId: latest.followUpClaimId ?? null,
365
459
  });
366
460
  if (released) {
367
- refreshLiveAgentHarnessSessionGeneration(latest.id, input.liveSession, released.generation);
461
+ if (input.liveSession) {
462
+ refreshLiveAgentHarnessSessionGeneration(latest.id, input.liveSession, released.generation);
463
+ }
368
464
  return released;
369
465
  }
370
466
  latest = await getAgentHarnessSessionByRunId(input.runId);
@@ -473,51 +569,309 @@ export async function sendAgentHarnessFollowUp(input) {
473
569
  const events = [];
474
570
  let iteratorClosePromise;
475
571
  let providerDispatchStarted = false;
572
+ const hasFollowUpProviderDispatchStarted = () => providerDispatchStarted;
573
+ let activeRun;
476
574
  try {
477
575
  const dispatchIntent = await markAgentHarnessSessionFollowUpDispatched(session.id, claimed.generation, claimId);
478
576
  if (!dispatchIntent) {
479
577
  throw new AgentHarnessSessionConflictError(session.id);
480
578
  }
481
579
  refreshLiveAgentHarnessSessionGeneration(session.id, acquired.live.session, dispatchIntent.generation);
482
- const dispatch = await startAgentHarnessSessionFollowUpDispatch(session.id, dispatchIntent.generation, claimId, () => {
483
- providerDispatchStarted = true;
484
- const stream = acquired.live.session.streamTurn({
485
- prompt,
486
- metadata: input.metadata,
487
- abortSignal: followUpAbort.signal,
580
+ let dispatchGeneration = dispatchIntent.generation;
581
+ let continuingNativeTurn = false;
582
+ let physicalRunId = followUpId;
583
+ let softTimeoutDeadlineAt;
584
+ const followUpRunOptions = agentHarnessFollowUpRunOptions(session.runPolicy);
585
+ const followUpSoftTimeoutMs = followUpRunOptions.softTimeoutMs ?? 0;
586
+ const assertFollowUpClaimCanDispatch = async () => {
587
+ const latest = await getAgentHarnessSession(session.id);
588
+ const now = Date.now();
589
+ if (!latest ||
590
+ latest.status !== "running" ||
591
+ latest.followUpClaimId !== claimId ||
592
+ latest.followUpId !== followUpId ||
593
+ (latest.followUpClaimExpiresAt ?? 0) <= now ||
594
+ (latest.followUpDeadlineAt ?? 0) <= now ||
595
+ latest.expiryCleanupId != null) {
596
+ throw new AgentHarnessSessionConflictError(session.id);
597
+ }
598
+ };
599
+ for (;;) {
600
+ if (isAbortRequested(followUpAbort.signal)) {
601
+ throw (followUpAbort.signal.reason ??
602
+ new AgentHarnessSessionConflictError(session.id));
603
+ }
604
+ let firstDispatchResolved = false;
605
+ const checkpointState = { attempted: false, available: false };
606
+ let runFailure;
607
+ let resolveFirstDispatch;
608
+ let rejectFirstDispatch;
609
+ const firstDispatch = new Promise((resolve, reject) => {
610
+ resolveFirstDispatch = resolve;
611
+ rejectFirstDispatch = reject;
488
612
  });
489
- const iterator = stream[Symbol.asyncIterator]();
490
- const firstNext = nextHarnessEvent(iterator, followUpAbort.signal);
491
- // The transaction may commit before consumeEvents can await it.
492
- void firstNext.catch(() => { });
493
- return {
494
- stream,
495
- iterator,
496
- firstNext,
613
+ void firstDispatch.catch(() => { });
614
+ const persistNativeCheckpoint = async () => {
615
+ if (checkpointState.attempted)
616
+ return checkpointState.available;
617
+ checkpointState.attempted = true;
618
+ const resumeState = await acquired.live.session.checkpoint?.();
619
+ if (resumeState === undefined)
620
+ return false;
621
+ const checkpointed = await updateAgentHarnessSessionIfFollowUpClaim(session.id, claimId, { resumeState }, { allowCurrentApprovalResolution: true });
622
+ if (!checkpointed) {
623
+ throw new AgentHarnessSessionConflictError(session.id);
624
+ }
625
+ refreshLiveAgentHarnessSessionGeneration(session.id, acquired.live.session, checkpointed.generation);
626
+ dispatchGeneration = checkpointed.generation;
627
+ checkpointState.available = true;
628
+ return true;
497
629
  };
498
- });
499
- if (!dispatch) {
500
- throw new AgentHarnessSessionConflictError(session.id);
501
- }
502
- refreshLiveAgentHarnessSessionGeneration(session.id, acquired.live.session, dispatch.session.generation);
503
- await consumeEvents(dispatch.started.stream, events, input.onHarnessEvent, session.id, {
504
- followUpClaimId: claimId,
505
- abortSignal: followUpAbort.signal,
506
- firstNext: dispatch.started.firstNext,
507
- iterator: dispatch.started.iterator,
508
- liveSession: acquired.live.session,
509
- allowCurrentApprovalResolution: true,
510
- persistEvent: async (event) => {
511
- for (const chatEvent of agentHarnessEventToAgentChatEvents(event)) {
512
- await persistAgentHarnessFollowUpEvent(session.id, followUpId, claimId, chatEvent);
630
+ const abortActiveRun = () => {
631
+ if (activeRun && !activeRun.abort.signal.aborted) {
632
+ activeRun.abort.abort(followUpAbort.signal.reason);
513
633
  }
514
- },
515
- onAbortIteratorClose: (closePromise) => {
516
- iteratorClosePromise = closePromise;
517
- void closePromise.catch(() => { });
518
- },
519
- });
520
- if (followUpAbort.signal.aborted) {
634
+ };
635
+ followUpAbort.signal.addEventListener("abort", abortActiveRun, {
636
+ once: true,
637
+ });
638
+ try {
639
+ const dispatch = await startAgentHarnessSessionFollowUpDispatch(session.id, dispatchGeneration, claimId, async (assertCurrent) => {
640
+ try {
641
+ if (softTimeoutDeadlineAt === undefined &&
642
+ followUpSoftTimeoutMs > 0) {
643
+ softTimeoutDeadlineAt = Date.now() + followUpSoftTimeoutMs;
644
+ }
645
+ const queuedSubmissionStore = continuingNativeTurn
646
+ ? undefined
647
+ : await import("../../chat-threads/store.js");
648
+ await queuedSubmissionStore?.ensureChatThreadTables();
649
+ if (session.ownerEmail) {
650
+ await ensureAgentToolApprovalTable();
651
+ }
652
+ const admission = await tryClaimRunSlot(session.threadId, physicalRunId, undefined, {
653
+ turnId: followUpId,
654
+ ...(queuedSubmissionStore
655
+ ? {
656
+ hasPendingQueuedSubmission: (tx) => queuedSubmissionStore.hasPendingQueuedSubmissionReceipt(tx, session.threadId),
657
+ }
658
+ : {}),
659
+ ...(session.ownerEmail
660
+ ? {
661
+ hasPendingApproval: (tx) => hasPendingCurrentTurnApproval(session.threadId, tx),
662
+ }
663
+ : {}),
664
+ afterInsert: (tx) => assertCurrent(tx),
665
+ });
666
+ if (!admission.claimed) {
667
+ throw new AgentHarnessSessionConflictError(session.id);
668
+ }
669
+ const started = startRun(physicalRunId, session.threadId, async (send, _signal, control) => {
670
+ const runControl = control;
671
+ try {
672
+ await driveAgentHarnessTurnChunks({
673
+ session: acquired.live.session,
674
+ ...(continuingNativeTurn
675
+ ? {}
676
+ : {
677
+ input: {
678
+ prompt,
679
+ ...(input.metadata === undefined
680
+ ? {}
681
+ : { metadata: input.metadata }),
682
+ },
683
+ }),
684
+ control: runControl,
685
+ beforeStream: assertFollowUpClaimCanDispatch,
686
+ onProviderDispatch: () => {
687
+ providerDispatchStarted = true;
688
+ },
689
+ consume: async (stream) => {
690
+ const iterator = stream[Symbol.asyncIterator]();
691
+ const firstNext = nextHarnessEvent(iterator, runControl.chunkSignal);
692
+ void firstNext.catch(() => { });
693
+ if (!firstDispatchResolved) {
694
+ firstDispatchResolved = true;
695
+ if (activeRun)
696
+ resolveFirstDispatch(activeRun);
697
+ }
698
+ try {
699
+ await consumeEvents(stream, events, input.onHarnessEvent, session.id, {
700
+ followUpClaimId: claimId,
701
+ abortSignal: runControl.chunkSignal,
702
+ firstNext,
703
+ iterator,
704
+ liveSession: acquired.live.session,
705
+ allowCurrentApprovalResolution: true,
706
+ persistFollowUpApprovalRequest: async (event) => {
707
+ const latest = await getAgentHarnessSession(session.id);
708
+ if (!latest)
709
+ return null;
710
+ const checkpoint = await acquired.live.session.checkpoint?.();
711
+ const resumeState = checkpoint === undefined
712
+ ? latest.resumeState
713
+ : checkpoint;
714
+ return updateAgentHarnessSessionIfFollowUpClaim(session.id, claimId, {
715
+ pendingApproval: event,
716
+ ...(resumeState === undefined
717
+ ? {}
718
+ : { resumeState }),
719
+ }, {
720
+ expectedApprovalResolutionId: latest.approvalResolutionId ?? null,
721
+ allowCurrentApprovalResolution: true,
722
+ });
723
+ },
724
+ persistEvent: async (event) => {
725
+ for (const chatEvent of agentHarnessEventToAgentChatEvents(event)) {
726
+ await persistAgentHarnessFollowUpEvent(session.id, followUpId, claimId, chatEvent);
727
+ await send(chatEvent);
728
+ }
729
+ },
730
+ onAbortIteratorClose: (closePromise) => {
731
+ iteratorClosePromise = closePromise;
732
+ void closePromise.catch(() => { });
733
+ },
734
+ });
735
+ return;
736
+ }
737
+ catch (error) {
738
+ if (followUpAbort.signal.aborted) {
739
+ runFailure = error;
740
+ throw error;
741
+ }
742
+ if (isAbortRequested(runControl.turnSignal)) {
743
+ await persistNativeCheckpoint();
744
+ return "stop";
745
+ }
746
+ if (!runControl.chunkBoundaryReason()) {
747
+ runFailure = error;
748
+ throw error;
749
+ }
750
+ }
751
+ if (isAbortRequested(runControl.turnSignal)) {
752
+ if (isAbortRequested(followUpAbort.signal)) {
753
+ throw (followUpAbort.signal.reason ??
754
+ new AgentHarnessSessionConflictError(session.id));
755
+ }
756
+ await persistNativeCheckpoint();
757
+ return "stop";
758
+ }
759
+ },
760
+ afterStream: async () => {
761
+ if (isAbortRequested(runControl.turnSignal)) {
762
+ if (isAbortRequested(followUpAbort.signal)) {
763
+ throw (followUpAbort.signal.reason ??
764
+ new AgentHarnessSessionConflictError(session.id));
765
+ }
766
+ await persistNativeCheckpoint();
767
+ return "stop";
768
+ }
769
+ const latest = await getAgentHarnessSessionByRunId(input.runId);
770
+ const pending = asPendingApproval(latest?.pendingApproval);
771
+ if (pending &&
772
+ !latest?.resolvedApprovalIds?.includes(pending.id)) {
773
+ return "stop";
774
+ }
775
+ if (runControl.chunkBoundaryReason() &&
776
+ acquired.live.session.continueTurn &&
777
+ iteratorClosePromise) {
778
+ await iteratorClosePromise;
779
+ iteratorClosePromise = undefined;
780
+ }
781
+ return;
782
+ },
783
+ });
784
+ }
785
+ catch (error) {
786
+ runFailure ??= error;
787
+ throw error;
788
+ }
789
+ }, input.onRunComplete, {
790
+ ...followUpRunOptions,
791
+ runRowAlreadyInserted: true,
792
+ ...(softTimeoutDeadlineAt === undefined
793
+ ? {}
794
+ : { softTimeoutDeadlineAt }),
795
+ turnId: followUpId,
796
+ parentId: input.runId,
797
+ });
798
+ activeRun = started;
799
+ void started.finalized.then(() => {
800
+ if (!firstDispatchResolved) {
801
+ rejectFirstDispatch(runFailure ??
802
+ new Error("The AgentHarness follow-up run ended before provider dispatch."));
803
+ }
804
+ }, rejectFirstDispatch);
805
+ if (followUpAbort.signal.aborted)
806
+ abortActiveRun();
807
+ return firstDispatch;
808
+ }
809
+ catch (error) {
810
+ rejectFirstDispatch(error);
811
+ throw error;
812
+ }
813
+ });
814
+ if (!dispatch) {
815
+ throw new AgentHarnessSessionConflictError(session.id);
816
+ }
817
+ activeRun = dispatch.started;
818
+ dispatchGeneration = dispatch.session.generation;
819
+ refreshLiveAgentHarnessSessionGeneration(session.id, acquired.live.session, dispatch.session.generation);
820
+ if (isAbortRequested(followUpAbort.signal))
821
+ abortActiveRun();
822
+ await activeRun.finalized;
823
+ }
824
+ finally {
825
+ followUpAbort.signal.removeEventListener("abort", abortActiveRun);
826
+ }
827
+ if (isAbortRequested(followUpAbort.signal)) {
828
+ throw (followUpAbort.signal.reason ??
829
+ new AgentHarnessSessionConflictError(session.id));
830
+ }
831
+ if (activeRun.status === "errored") {
832
+ if (runFailure instanceof Error)
833
+ throw runFailure;
834
+ throw new Error("The AgentHarness follow-up run failed.", {
835
+ cause: runFailure,
836
+ });
837
+ }
838
+ if (activeRun.status === "aborted") {
839
+ throw new Error(`The AgentHarness follow-up run was aborted${activeRun.abortReason ? `: ${activeRun.abortReason}` : "."}`);
840
+ }
841
+ if (activeRun.status !== "truncated")
842
+ break;
843
+ if (softTimeoutDeadlineAt !== undefined &&
844
+ Date.now() >= softTimeoutDeadlineAt) {
845
+ throw new Error("The AgentHarness follow-up reached its soft timeout before the truncated response completed.");
846
+ }
847
+ if (iteratorClosePromise) {
848
+ await iteratorClosePromise;
849
+ iteratorClosePromise = undefined;
850
+ }
851
+ if (!checkpointState.attempted && !(await persistNativeCheckpoint())) {
852
+ throw new Error("The AgentHarness follow-up was truncated without a resumable checkpoint.");
853
+ }
854
+ if (!checkpointState.available) {
855
+ throw new Error("The AgentHarness follow-up was truncated without a resumable checkpoint.");
856
+ }
857
+ const latest = await getAgentHarnessSessionByRunId(input.runId);
858
+ if (!latest ||
859
+ latest.status !== "running" ||
860
+ latest.followUpClaimId !== claimId) {
861
+ throw new AgentHarnessSessionConflictError(session.id);
862
+ }
863
+ const pending = asPendingApproval(latest.pendingApproval);
864
+ if (pending && !latest.resolvedApprovalIds?.includes(pending.id)) {
865
+ break;
866
+ }
867
+ if (!acquired.live.session.continueTurn) {
868
+ throw new Error("The AgentHarness follow-up was truncated and the provider cannot continue the turn.");
869
+ }
870
+ dispatchGeneration = latest.generation;
871
+ continuingNativeTurn = true;
872
+ physicalRunId = randomUUID();
873
+ }
874
+ if (isAbortRequested(followUpAbort.signal)) {
521
875
  throw (followUpAbort.signal.reason ??
522
876
  new AgentHarnessSessionConflictError(session.id));
523
877
  }
@@ -550,6 +904,11 @@ export async function sendAgentHarnessFollowUp(input) {
550
904
  ? persistedApproval
551
905
  : undefined);
552
906
  let resumeState = latest.resumeState ?? session.resumeState;
907
+ if (pending && acquired.live.session.checkpoint) {
908
+ const checkpoint = await acquired.live.session.checkpoint();
909
+ if (checkpoint !== undefined)
910
+ resumeState = checkpoint;
911
+ }
553
912
  if (!pending &&
554
913
  !latest.approvalResolutionId &&
555
914
  acquired.live.session.detach) {
@@ -619,9 +978,6 @@ export async function sendAgentHarnessFollowUp(input) {
619
978
  };
620
979
  });
621
980
  stopWatchingClaim();
622
- if (!updated) {
623
- return failure(input.runId, session, "unavailable", "The harness follow-up was interrupted before its final state could be saved.");
624
- }
625
981
  if (!updated.ok) {
626
982
  if (updated.session?.status === "idle" ||
627
983
  updated.session?.status === "stopped" ||
@@ -635,7 +991,7 @@ export async function sendAgentHarnessFollowUp(input) {
635
991
  }
636
992
  catch (error) {
637
993
  stopWatchingClaim();
638
- if (followUpAbort.signal.aborted) {
994
+ if (isAbortRequested(followUpAbort.signal)) {
639
995
  const reason = followUpAbort.signal.reason;
640
996
  if (isAgentHarnessSessionConflictError(reason)) {
641
997
  const latest = await getAgentHarnessSessionByRunId(input.runId);
@@ -661,19 +1017,19 @@ export async function sendAgentHarnessFollowUp(input) {
661
1017
  }
662
1018
  }
663
1019
  if (cleanupErrors.length > 0) {
664
- throw new AggregateError([reason ?? error, ...cleanupErrors], "Harness follow-up was interrupted and stream cleanup was incomplete.");
1020
+ throw new AggregateError([reason, ...cleanupErrors], "Harness follow-up was interrupted and stream cleanup was incomplete.");
665
1021
  }
666
1022
  return failure(input.runId, latest ?? session, "unavailable", "The harness follow-up was interrupted because its session claim changed or stopped.");
667
1023
  }
668
1024
  const failures = [reason ?? error];
669
1025
  let failedSession = null;
670
1026
  try {
671
- failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, providerDispatchStarted ? "unknown" : "not_dispatched");
1027
+ failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, hasFollowUpProviderDispatchStarted() ? "unknown" : "not_dispatched");
672
1028
  }
673
1029
  catch (persistError) {
674
1030
  failures.push(persistError);
675
1031
  }
676
- if (failedSession && providerDispatchStarted) {
1032
+ if (failedSession && hasFollowUpProviderDispatchStarted()) {
677
1033
  try {
678
1034
  await stopAcquiredHarnessSession(session.id, acquired.live.session);
679
1035
  }
@@ -702,14 +1058,16 @@ export async function sendAgentHarnessFollowUp(input) {
702
1058
  latest.followUpClaimId === claimId) {
703
1059
  let failedSession;
704
1060
  try {
705
- failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, providerDispatchStarted ? "unknown" : "not_dispatched");
706
- retryableAdmissionFailure = Boolean(failedSession && !providerDispatchStarted);
1061
+ failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, hasFollowUpProviderDispatchStarted()
1062
+ ? "unknown"
1063
+ : "not_dispatched");
1064
+ retryableAdmissionFailure = Boolean(failedSession && !hasFollowUpProviderDispatchStarted());
707
1065
  }
708
1066
  catch (cleanupError) {
709
1067
  const failures = [error, cleanupError];
710
1068
  throw new AggregateError(failures, "Harness follow-up conflict cleanup was incomplete.");
711
1069
  }
712
- if (failedSession && providerDispatchStarted) {
1070
+ if (failedSession && hasFollowUpProviderDispatchStarted()) {
713
1071
  try {
714
1072
  await stopAcquiredHarnessSession(session.id, acquired.live.session);
715
1073
  }
@@ -733,12 +1091,12 @@ export async function sendAgentHarnessFollowUp(input) {
733
1091
  const failures = [error];
734
1092
  let failedSession = null;
735
1093
  try {
736
- failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, providerDispatchStarted ? "unknown" : "not_dispatched");
1094
+ failedSession = await markOwnedFollowUpErrored(session.id, claimId, acquired.live.session, hasFollowUpProviderDispatchStarted() ? "unknown" : "not_dispatched");
737
1095
  }
738
1096
  catch (persistError) {
739
1097
  failures.push(persistError);
740
1098
  }
741
- if (failedSession && providerDispatchStarted) {
1099
+ if (failedSession && hasFollowUpProviderDispatchStarted()) {
742
1100
  try {
743
1101
  await stopAcquiredHarnessSession(session.id, acquired.live.session);
744
1102
  }
@@ -816,7 +1174,7 @@ export async function sweepExpiredAgentHarnessSessions(now = Date.now()) {
816
1174
  try {
817
1175
  const current = await getAgentHarnessSession(sessionId);
818
1176
  // Approval can claim this live session while the read is in flight.
819
- if (live.approvalResolutionInProgress)
1177
+ if (isApprovalResolutionInProgress(live))
820
1178
  continue;
821
1179
  if (!current) {
822
1180
  if (live.session.stop)
@@ -842,7 +1200,7 @@ export async function sweepExpiredAgentHarnessSessions(now = Date.now()) {
842
1200
  : "stopped");
843
1201
  if (!stopped) {
844
1202
  const latest = await getAgentHarnessSession(sessionId);
845
- if (live.approvalResolutionInProgress)
1203
+ if (isApprovalResolutionInProgress(live))
846
1204
  continue;
847
1205
  if (!latest) {
848
1206
  if (live.session.stop)
@@ -1018,7 +1376,7 @@ async function consumeEvents(stream, events, onHarnessEvent, sessionId, options)
1018
1376
  const iterator = options?.iterator ?? stream[Symbol.asyncIterator]();
1019
1377
  let firstNext = options?.firstNext;
1020
1378
  try {
1021
- while (true) {
1379
+ for (;;) {
1022
1380
  const next = await (firstNext ??
1023
1381
  nextHarnessEvent(iterator, options?.abortSignal));
1024
1382
  firstNext = undefined;
@@ -1028,10 +1386,20 @@ async function consumeEvents(stream, events, onHarnessEvent, sessionId, options)
1028
1386
  events.push(event);
1029
1387
  if (event.type === "approval-request") {
1030
1388
  const updated = options?.followUpClaimId
1031
- ? await updateAgentHarnessSessionIfFollowUpClaim(sessionId, options.followUpClaimId, { pendingApproval: event }, {
1032
- expectedApprovalResolutionId: options.approvalResolutionId,
1033
- allowCurrentApprovalResolution: options.allowCurrentApprovalResolution,
1034
- })
1389
+ ? options.persistFollowUpApprovalRequest
1390
+ ? await options.persistFollowUpApprovalRequest(event)
1391
+ : await updateAgentHarnessSessionIfFollowUpClaim(sessionId, options.followUpClaimId, { pendingApproval: event }, {
1392
+ ...(options.approvalResolutionId === undefined
1393
+ ? {}
1394
+ : {
1395
+ expectedApprovalResolutionId: options.approvalResolutionId,
1396
+ }),
1397
+ ...(options.allowCurrentApprovalResolution === undefined
1398
+ ? {}
1399
+ : {
1400
+ allowCurrentApprovalResolution: options.allowCurrentApprovalResolution,
1401
+ }),
1402
+ })
1035
1403
  : options?.approvalResolutionId !== undefined
1036
1404
  ? await updateApprovalContinuationPending(sessionId, options.approvalResolutionId, options.approvalResolutionStatus, options.liveSession, event)
1037
1405
  : await updateAgentHarnessSession(sessionId, {
@@ -1401,5 +1769,5 @@ function scheduleCleanup() {
1401
1769
  scheduleCleanup();
1402
1770
  });
1403
1771
  }, LIVE_SESSION_TTL_MS);
1404
- cleanupTimer.unref?.();
1772
+ cleanupTimer.unref();
1405
1773
  }