tubeless 0.3.7 → 0.3.9

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 (412) hide show
  1. package/dist/agent/agent-session.d.ts +31 -0
  2. package/dist/agent/agent-session.js +67 -0
  3. package/dist/agent/agent-session.js.map +1 -0
  4. package/dist/agent/agent-types.d.ts +50 -10
  5. package/dist/agent/agent-types.js.map +1 -1
  6. package/dist/agent/agent.d.ts +7 -5
  7. package/dist/agent/agent.js +3 -2
  8. package/dist/agent/agent.js.map +1 -1
  9. package/dist/agent/anthropic.js +16 -5
  10. package/dist/agent/anthropic.js.map +1 -1
  11. package/dist/agent/checkpoint-format.d.ts +3 -0
  12. package/dist/agent/checkpoint-format.js +4 -0
  13. package/dist/agent/checkpoint-format.js.map +1 -1
  14. package/dist/agent/checkpoint-session.d.ts +3 -1
  15. package/dist/agent/checkpoint-session.js +2 -1
  16. package/dist/agent/checkpoint-session.js.map +1 -1
  17. package/dist/agent/codemode-declarations.d.ts +16 -0
  18. package/dist/agent/codemode-declarations.js +190 -0
  19. package/dist/agent/codemode-declarations.js.map +1 -0
  20. package/dist/agent/codemode-executor.d.ts +73 -0
  21. package/dist/agent/codemode-executor.js +144 -0
  22. package/dist/agent/codemode-executor.js.map +1 -0
  23. package/dist/agent/codemode-node.d.ts +7 -0
  24. package/dist/agent/codemode-node.js +76 -0
  25. package/dist/agent/codemode-node.js.map +1 -0
  26. package/dist/agent/codemode-protocol.d.ts +33 -0
  27. package/dist/agent/codemode-protocol.js +2 -0
  28. package/dist/agent/codemode-protocol.js.map +1 -0
  29. package/dist/agent/codemode-realm.d.ts +13 -0
  30. package/dist/agent/codemode-realm.js +96 -0
  31. package/dist/agent/codemode-realm.js.map +1 -0
  32. package/dist/agent/codemode-worker.d.ts +1 -0
  33. package/dist/agent/codemode-worker.js +62 -0
  34. package/dist/agent/codemode-worker.js.map +1 -0
  35. package/dist/agent/codemode.d.ts +10 -0
  36. package/dist/agent/codemode.js +240 -0
  37. package/dist/agent/codemode.js.map +1 -0
  38. package/dist/agent/compile-agent.d.ts +8 -3
  39. package/dist/agent/compile-agent.js +39 -3
  40. package/dist/agent/compile-agent.js.map +1 -1
  41. package/dist/agent/decision.d.ts +9 -1
  42. package/dist/agent/decision.js +14 -0
  43. package/dist/agent/decision.js.map +1 -1
  44. package/dist/agent/default-tool-schema.js +5 -1
  45. package/dist/agent/default-tool-schema.js.map +1 -1
  46. package/dist/agent/execution-scope.d.ts +2 -0
  47. package/dist/agent/execution-scope.js +5 -0
  48. package/dist/agent/execution-scope.js.map +1 -1
  49. package/dist/agent/invocation.d.ts +2 -1
  50. package/dist/agent/invocation.js +8 -1
  51. package/dist/agent/invocation.js.map +1 -1
  52. package/dist/agent/mcp-http.d.ts +9 -0
  53. package/dist/agent/mcp-http.js +131 -0
  54. package/dist/agent/mcp-http.js.map +1 -0
  55. package/dist/agent/mcp-schema.d.ts +15 -0
  56. package/dist/agent/mcp-schema.js +323 -0
  57. package/dist/agent/mcp-schema.js.map +1 -0
  58. package/dist/agent/mcp-session.d.ts +38 -0
  59. package/dist/agent/mcp-session.js +123 -0
  60. package/dist/agent/mcp-session.js.map +1 -0
  61. package/dist/agent/mcp-stdio.d.ts +11 -0
  62. package/dist/agent/mcp-stdio.js +97 -0
  63. package/dist/agent/mcp-stdio.js.map +1 -0
  64. package/dist/agent/mcp.d.ts +37 -0
  65. package/dist/agent/mcp.js +153 -0
  66. package/dist/agent/mcp.js.map +1 -0
  67. package/dist/agent/model-agent.d.ts +46 -18
  68. package/dist/agent/model-agent.js +64 -17
  69. package/dist/agent/model-agent.js.map +1 -1
  70. package/dist/agent/model-prompt.d.ts +1 -1
  71. package/dist/agent/model-prompt.js +19 -3
  72. package/dist/agent/model-prompt.js.map +1 -1
  73. package/dist/agent/model-types.d.ts +13 -3
  74. package/dist/agent/model-types.js.map +1 -1
  75. package/dist/agent/node.d.ts +1 -0
  76. package/dist/agent/node.js +1 -0
  77. package/dist/agent/node.js.map +1 -1
  78. package/dist/agent/openai-protocol.d.ts +1 -1
  79. package/dist/agent/openai.js +24 -17
  80. package/dist/agent/openai.js.map +1 -1
  81. package/dist/agent/provider-http.js +1 -0
  82. package/dist/agent/provider-http.js.map +1 -1
  83. package/dist/agent/tool-execution.d.ts +24 -0
  84. package/dist/agent/tool-execution.js +43 -0
  85. package/dist/agent/tool-execution.js.map +1 -0
  86. package/dist/agent/tools.d.ts +21 -23
  87. package/dist/agent/tools.js +21 -1
  88. package/dist/agent/tools.js.map +1 -1
  89. package/dist/agent/turn.d.ts +2 -2
  90. package/dist/agent/turn.js +12 -54
  91. package/dist/agent/turn.js.map +1 -1
  92. package/dist/cli/cli-command.js +19 -29
  93. package/dist/cli/cli-command.js.map +1 -1
  94. package/dist/cli/cli-exit.d.ts +5 -0
  95. package/dist/cli/cli-exit.js +13 -0
  96. package/dist/cli/cli-exit.js.map +1 -1
  97. package/dist/cli/cli-parser.d.ts +3 -1
  98. package/dist/cli/cli-parser.js +80 -37
  99. package/dist/cli/cli-parser.js.map +1 -1
  100. package/dist/cli/cli-pipeline-command.js +3 -9
  101. package/dist/cli/cli-pipeline-command.js.map +1 -1
  102. package/dist/cli/cli-schema.js +19 -2
  103. package/dist/cli/cli-schema.js.map +1 -1
  104. package/dist/cloudflare/cloudflare-access.js +1 -1
  105. package/dist/cloudflare/cloudflare-access.js.map +1 -1
  106. package/dist/cloudflare/cloudflare-codemode.d.ts +28 -0
  107. package/dist/cloudflare/cloudflare-codemode.js +118 -0
  108. package/dist/cloudflare/cloudflare-codemode.js.map +1 -0
  109. package/dist/cloudflare/cloudflare-studio-client.js +1 -1
  110. package/dist/cloudflare/cloudflare-studio.js.map +1 -1
  111. package/dist/cloudflare/cloudflare.d.ts +1 -0
  112. package/dist/cloudflare/cloudflare.js +2 -1
  113. package/dist/cloudflare/cloudflare.js.map +1 -1
  114. package/dist/core/pipeline-plan.js +36 -3
  115. package/dist/core/pipeline-plan.js.map +1 -1
  116. package/dist/core/pipeline-types.d.ts +4 -1
  117. package/dist/core/pipeline-types.js.map +1 -1
  118. package/dist/hosting/hosting-commands.d.ts +1 -1
  119. package/dist/hosting/hosting-commands.js +2 -5
  120. package/dist/hosting/hosting-commands.js.map +1 -1
  121. package/dist/hosting/hosting-studio.d.ts +1 -1
  122. package/dist/hosting/hosting-studio.js +3 -3
  123. package/dist/hosting/hosting-studio.js.map +1 -1
  124. package/dist/project/pipeline-project.js +5 -3
  125. package/dist/project/pipeline-project.js.map +1 -1
  126. package/dist/project/project-compiler.js +5 -4
  127. package/dist/project/project-compiler.js.map +1 -1
  128. package/dist/run-store/run-store-migrate.js +3 -2
  129. package/dist/run-store/run-store-migrate.js.map +1 -1
  130. package/dist/run-store/run-store-sql.js +1 -1
  131. package/dist/run-store/run-store-sql.js.map +1 -1
  132. package/dist/studio/browser/app.d.ts +32 -0
  133. package/dist/studio/browser/app.js +315 -0
  134. package/dist/studio/browser/app.js.map +1 -0
  135. package/dist/studio/{run-store-ui-artifacts.d.ts → browser/components/artifacts.d.ts} +1 -1
  136. package/dist/studio/{run-store-ui-artifacts.js → browser/components/artifacts.js} +2 -2
  137. package/dist/studio/browser/components/artifacts.js.map +1 -0
  138. package/dist/studio/{run-store-ui-common.d.ts → browser/components/common.d.ts} +1 -1
  139. package/dist/studio/{run-store-ui-common.js → browser/components/common.js} +1 -1
  140. package/dist/studio/browser/components/common.js.map +1 -0
  141. package/dist/studio/{run-store-ui-debugging.d.ts → browser/components/debugging.d.ts} +6 -1
  142. package/dist/studio/{run-store-ui-debugging.js → browser/components/debugging.js} +6 -2
  143. package/dist/studio/browser/components/debugging.js.map +1 -0
  144. package/dist/studio/{run-store-ui-definitions.d.ts → browser/components/definitions.d.ts} +4 -4
  145. package/dist/studio/{run-store-ui-definitions.js → browser/components/definitions.js} +5 -5
  146. package/dist/studio/browser/components/definitions.js.map +1 -0
  147. package/dist/studio/{run-store-ui-launch.d.ts → browser/components/launch.d.ts} +6 -5
  148. package/dist/studio/{run-store-ui-launch.js → browser/components/launch.js} +22 -13
  149. package/dist/studio/browser/components/launch.js.map +1 -0
  150. package/dist/studio/{run-store-ui-metadata.d.ts → browser/components/metadata.d.ts} +1 -1
  151. package/dist/studio/{run-store-ui-metadata.js → browser/components/metadata.js} +1 -1
  152. package/dist/studio/browser/components/metadata.js.map +1 -0
  153. package/dist/studio/browser/components/pipeline.d.ts +27 -0
  154. package/dist/studio/browser/components/pipeline.js +108 -0
  155. package/dist/studio/browser/components/pipeline.js.map +1 -0
  156. package/dist/studio/browser/components/pipelines.d.ts +4 -0
  157. package/dist/studio/{run-store-ui-pipelines.js → browser/components/pipelines.js} +3 -10
  158. package/dist/studio/browser/components/pipelines.js.map +1 -0
  159. package/dist/studio/browser/components/rail.d.ts +34 -0
  160. package/dist/studio/browser/components/rail.js +69 -0
  161. package/dist/studio/browser/components/rail.js.map +1 -0
  162. package/dist/studio/browser/components/runs.d.ts +92 -0
  163. package/dist/studio/browser/components/runs.js +246 -0
  164. package/dist/studio/browser/components/runs.js.map +1 -0
  165. package/dist/studio/{run-store-ui-steps.d.ts → browser/components/steps.d.ts} +5 -2
  166. package/dist/studio/{run-store-ui-steps.js → browser/components/steps.js} +10 -4
  167. package/dist/studio/browser/components/steps.js.map +1 -0
  168. package/dist/studio/{run-store-ui-data-controller.d.ts → browser/data-controller.d.ts} +8 -5
  169. package/dist/studio/{run-store-ui-data-controller.js → browser/data-controller.js} +38 -110
  170. package/dist/studio/browser/data-controller.js.map +1 -0
  171. package/dist/studio/browser/entry.js +2 -0
  172. package/dist/studio/browser/graph/dependencies.d.ts +15 -0
  173. package/dist/studio/browser/graph/dependencies.js +43 -0
  174. package/dist/studio/browser/graph/dependencies.js.map +1 -0
  175. package/dist/studio/browser/graph/graph.d.ts +16 -0
  176. package/dist/studio/browser/graph/graph.js +261 -0
  177. package/dist/studio/browser/graph/graph.js.map +1 -0
  178. package/dist/studio/browser/graph/inspector.d.ts +28 -0
  179. package/dist/studio/browser/graph/inspector.js +66 -0
  180. package/dist/studio/browser/graph/inspector.js.map +1 -0
  181. package/dist/studio/{run-store-ui-graph-layout.js → browser/graph/layout.js} +1 -1
  182. package/dist/studio/browser/graph/layout.js.map +1 -0
  183. package/dist/studio/browser/graph/scene.d.ts +87 -0
  184. package/dist/studio/browser/graph/scene.js +262 -0
  185. package/dist/studio/browser/graph/scene.js.map +1 -0
  186. package/dist/studio/{run-store-ui-resource.js → browser/resource.js} +1 -1
  187. package/dist/studio/browser/resource.js.map +1 -0
  188. package/dist/studio/browser/run-detail-loader.d.ts +16 -0
  189. package/dist/studio/browser/run-detail-loader.js +94 -0
  190. package/dist/studio/browser/run-detail-loader.js.map +1 -0
  191. package/dist/studio/{run-store-ui-client-transport.d.ts → browser/transport.d.ts} +7 -5
  192. package/dist/studio/{run-store-ui-client-transport.js → browser/transport.js} +5 -3
  193. package/dist/studio/browser/transport.js.map +1 -0
  194. package/dist/studio/{run-store-ui-api.d.ts → server/api.d.ts} +3 -3
  195. package/dist/studio/{run-store-ui-api.js → server/api.js} +8 -5
  196. package/dist/studio/server/api.js.map +1 -0
  197. package/dist/studio/{run-store-ui-children.d.ts → server/children.d.ts} +2 -2
  198. package/dist/studio/{run-store-ui-children.js → server/children.js} +2 -2
  199. package/dist/studio/server/children.js.map +1 -0
  200. package/dist/studio/{run-store-ui-page-node.js → server/client-script.js} +3 -3
  201. package/dist/studio/server/client-script.js.map +1 -0
  202. package/dist/studio/{run-store-ui-handler.d.ts → server/handler.d.ts} +1 -1
  203. package/dist/studio/{run-store-ui-handler.js → server/handler.js} +3 -3
  204. package/dist/studio/server/handler.js.map +1 -0
  205. package/dist/studio/server/history.d.ts +21 -0
  206. package/dist/studio/server/history.js +149 -0
  207. package/dist/studio/server/history.js.map +1 -0
  208. package/dist/studio/{run-store-ui-hosting.js → server/hosting.js} +2 -2
  209. package/dist/studio/server/hosting.js.map +1 -0
  210. package/dist/studio/{run-store-ui-http.js → server/http.js} +1 -1
  211. package/dist/studio/server/http.js.map +1 -0
  212. package/dist/studio/{run-store-ui.d.ts → server/listener.d.ts} +4 -4
  213. package/dist/studio/{run-store-ui.js → server/listener.js} +7 -7
  214. package/dist/studio/server/listener.js.map +1 -0
  215. package/dist/studio/{run-store-ui-node.js → server/node-http.js} +1 -1
  216. package/dist/studio/server/node-http.js.map +1 -0
  217. package/dist/studio/{run-store-ui-page.js → server/page.js} +103 -49
  218. package/dist/studio/server/page.js.map +1 -0
  219. package/dist/studio/server/run-details.d.ts +15 -0
  220. package/dist/studio/server/run-details.js +51 -0
  221. package/dist/studio/server/run-details.js.map +1 -0
  222. package/dist/studio/{run-store-ui-state.d.ts → server/state.d.ts} +3 -8
  223. package/dist/studio/server/state.js +96 -0
  224. package/dist/studio/server/state.js.map +1 -0
  225. package/dist/studio/shared/limits.d.ts +7 -0
  226. package/dist/studio/shared/limits.js +8 -0
  227. package/dist/studio/shared/limits.js.map +1 -0
  228. package/dist/studio/{run-store-ui-protocol.d.ts → shared/protocol.d.ts} +2 -2
  229. package/dist/studio/{run-store-ui-protocol.js → shared/protocol.js} +2 -2
  230. package/dist/studio/shared/protocol.js.map +1 -0
  231. package/dist/studio/shared/route.d.ts +21 -0
  232. package/dist/studio/shared/route.js +51 -0
  233. package/dist/studio/shared/route.js.map +1 -0
  234. package/dist/studio/{run-store-ui-schema.d.ts → shared/schema.d.ts} +37 -15
  235. package/dist/studio/{run-store-ui-schema.js → shared/schema.js} +17 -8
  236. package/dist/studio/shared/schema.js.map +1 -0
  237. package/dist/tracing/trace-exporter-error.d.ts +2 -0
  238. package/dist/tracing/trace-exporter-error.js +10 -0
  239. package/dist/tracing/trace-exporter-error.js.map +1 -1
  240. package/dist/tracing/tracing-internal.js +18 -11
  241. package/dist/tracing/tracing-internal.js.map +1 -1
  242. package/dist/tracing/tracing.js +2 -2
  243. package/dist/tracing/tracing.js.map +1 -1
  244. package/dist/tracing/wire-schema.d.ts +0 -1
  245. package/dist/tracing/wire-schema.js +3 -5
  246. package/dist/tracing/wire-schema.js.map +1 -1
  247. package/dist/utilities/suggest.d.ts +14 -0
  248. package/dist/utilities/suggest.js +74 -0
  249. package/dist/utilities/suggest.js.map +1 -0
  250. package/dist/workbench/{workbench-agent.d.ts → agent/command.d.ts} +1 -1
  251. package/dist/workbench/{workbench-agent.js → agent/command.js} +24 -40
  252. package/dist/workbench/agent/command.js.map +1 -0
  253. package/dist/workbench/{workbench-agent-commands.js → agent/commands.js} +1 -1
  254. package/dist/workbench/agent/commands.js.map +1 -0
  255. package/dist/workbench/{workbench-agent-environment.d.ts → agent/environment.d.ts} +1 -1
  256. package/dist/workbench/{workbench-agent-environment.js → agent/environment.js} +2 -2
  257. package/dist/workbench/agent/environment.js.map +1 -0
  258. package/dist/workbench/{workbench-agent-history.d.ts → agent/history.d.ts} +1 -1
  259. package/dist/workbench/{workbench-agent-history.js → agent/history.js} +2 -2
  260. package/dist/workbench/agent/history.js.map +1 -0
  261. package/dist/workbench/{workbench-agent-input.d.ts → agent/input.d.ts} +1 -1
  262. package/dist/workbench/{workbench-agent-input.js → agent/input.js} +3 -3
  263. package/dist/workbench/agent/input.js.map +1 -0
  264. package/dist/workbench/agent/prompt.d.ts +28 -0
  265. package/dist/workbench/{workbench-agent-prompt.js → agent/prompt.js} +36 -30
  266. package/dist/workbench/agent/prompt.js.map +1 -0
  267. package/dist/workbench/{workbench-agent-session.d.ts → agent/session.d.ts} +2 -2
  268. package/dist/workbench/{workbench-agent-session.js → agent/session.js} +10 -12
  269. package/dist/workbench/agent/session.js.map +1 -0
  270. package/dist/workbench/cloud/auth.d.ts +3 -0
  271. package/dist/workbench/{workbench-auth.js → cloud/auth.js} +13 -37
  272. package/dist/workbench/cloud/auth.js.map +1 -0
  273. package/dist/workbench/{cloud-client.d.ts → cloud/client.d.ts} +1 -1
  274. package/dist/workbench/{cloud-client.js → cloud/client.js} +4 -4
  275. package/dist/workbench/cloud/client.js.map +1 -0
  276. package/dist/workbench/cloud/command.d.ts +3 -0
  277. package/dist/workbench/{workbench-cloud.js → cloud/command.js} +14 -50
  278. package/dist/workbench/cloud/command.js.map +1 -0
  279. package/dist/workbench/{cloud-config.js → cloud/config.js} +1 -1
  280. package/dist/workbench/cloud/config.js.map +1 -0
  281. package/dist/workbench/{cloud-credentials.js → cloud/credentials.js} +3 -3
  282. package/dist/workbench/cloud/credentials.js.map +1 -0
  283. package/dist/workbench/{cloud-protocol.js → cloud/protocol.js} +1 -1
  284. package/dist/workbench/cloud/protocol.js.map +1 -0
  285. package/dist/workbench/{workbench-cloud-shared.d.ts → cloud/shared.d.ts} +2 -2
  286. package/dist/workbench/{workbench-cloud-shared.js → cloud/shared.js} +3 -3
  287. package/dist/workbench/cloud/shared.js.map +1 -0
  288. package/dist/workbench/workbench-command-execution.d.ts +1 -1
  289. package/dist/workbench/workbench-command-execution.js +18 -2
  290. package/dist/workbench/workbench-command-execution.js.map +1 -1
  291. package/dist/workbench/workbench-command-specs.d.ts +570 -0
  292. package/dist/workbench/workbench-command-specs.js +461 -0
  293. package/dist/workbench/workbench-command-specs.js.map +1 -0
  294. package/dist/workbench/workbench-commands.js +66 -104
  295. package/dist/workbench/workbench-commands.js.map +1 -1
  296. package/dist/workbench/workbench-completion.d.ts +13 -0
  297. package/dist/workbench/workbench-completion.js +366 -0
  298. package/dist/workbench/workbench-completion.js.map +1 -0
  299. package/dist/workbench/workbench-history.js +136 -65
  300. package/dist/workbench/workbench-history.js.map +1 -1
  301. package/dist/workbench/workbench-init-cloudflare.js +2 -2
  302. package/dist/workbench/workbench-init-cloudflare.js.map +1 -1
  303. package/dist/workbench/workbench-init.js +5 -14
  304. package/dist/workbench/workbench-init.js.map +1 -1
  305. package/dist/workbench/workbench-launch-session.d.ts +1 -1
  306. package/dist/workbench/workbench-launch-session.js.map +1 -1
  307. package/dist/workbench/workbench-project-loader.d.ts +0 -1
  308. package/dist/workbench/workbench-project-loader.js +14 -5
  309. package/dist/workbench/workbench-project-loader.js.map +1 -1
  310. package/dist/workbench/workbench-run.js +27 -45
  311. package/dist/workbench/workbench-run.js.map +1 -1
  312. package/dist/workbench/workbench-shared.d.ts +2 -0
  313. package/dist/workbench/workbench-shared.js +4 -0
  314. package/dist/workbench/workbench-shared.js.map +1 -1
  315. package/dist/workbench/workbench-studio-launcher.d.ts +1 -1
  316. package/dist/workbench/workbench-studio-launcher.js.map +1 -1
  317. package/dist/workbench/workbench-subcommand.d.ts +34 -41
  318. package/dist/workbench/workbench-subcommand.js +49 -22
  319. package/dist/workbench/workbench-subcommand.js.map +1 -1
  320. package/dist/workbench/workbench-ui.js +7 -28
  321. package/dist/workbench/workbench-ui.js.map +1 -1
  322. package/dist/workbench/workbench-upgrade.js +5 -20
  323. package/dist/workbench/workbench-upgrade.js.map +1 -1
  324. package/dist/workbench/workbench.js +75 -49
  325. package/dist/workbench/workbench.js.map +1 -1
  326. package/docs/agent-guide.md +63 -6
  327. package/docs/agents.md +355 -36
  328. package/docs/api-reference.md +122 -94
  329. package/docs/api-report.json +43 -14
  330. package/docs/cli.md +70 -16
  331. package/docs/deploy-cloudflare.md +31 -0
  332. package/docs/llms.txt +8 -3
  333. package/docs/recipes.md +9 -2
  334. package/docs/studio.md +59 -37
  335. package/examples/agent-codemode.ts +69 -0
  336. package/examples/agent-delegation.ts +2 -2
  337. package/examples/agent-durable.ts +2 -2
  338. package/examples/agent-environment.ts +2 -2
  339. package/examples/agent-extract.ts +152 -0
  340. package/examples/agent-mcp.ts +33 -0
  341. package/examples/agent-model-anthropic.ts +2 -2
  342. package/examples/agent-model.ts +2 -2
  343. package/examples/agent-openai.ts +2 -2
  344. package/examples/agent-workspace.ts +2 -2
  345. package/examples/agent.ts +2 -2
  346. package/examples/project/tubeless.project.ts +6 -0
  347. package/package.json +21 -16
  348. package/skills/tubeless/SKILL.md +29 -3
  349. package/dist/studio/run-store-ui-api.js.map +0 -1
  350. package/dist/studio/run-store-ui-artifacts.js.map +0 -1
  351. package/dist/studio/run-store-ui-children.js.map +0 -1
  352. package/dist/studio/run-store-ui-client-browser.js +0 -4
  353. package/dist/studio/run-store-ui-client-transport.js.map +0 -1
  354. package/dist/studio/run-store-ui-client.d.ts +0 -20
  355. package/dist/studio/run-store-ui-client.js +0 -284
  356. package/dist/studio/run-store-ui-client.js.map +0 -1
  357. package/dist/studio/run-store-ui-common.js.map +0 -1
  358. package/dist/studio/run-store-ui-data-controller.js.map +0 -1
  359. package/dist/studio/run-store-ui-debugging.js.map +0 -1
  360. package/dist/studio/run-store-ui-definitions.js.map +0 -1
  361. package/dist/studio/run-store-ui-graph-layout.js.map +0 -1
  362. package/dist/studio/run-store-ui-graph.d.ts +0 -26
  363. package/dist/studio/run-store-ui-graph.js +0 -594
  364. package/dist/studio/run-store-ui-graph.js.map +0 -1
  365. package/dist/studio/run-store-ui-handler.js.map +0 -1
  366. package/dist/studio/run-store-ui-hosting.js.map +0 -1
  367. package/dist/studio/run-store-ui-http.js.map +0 -1
  368. package/dist/studio/run-store-ui-launch.js.map +0 -1
  369. package/dist/studio/run-store-ui-metadata.js.map +0 -1
  370. package/dist/studio/run-store-ui-node.js.map +0 -1
  371. package/dist/studio/run-store-ui-page-node.js.map +0 -1
  372. package/dist/studio/run-store-ui-page.js.map +0 -1
  373. package/dist/studio/run-store-ui-pipelines.d.ts +0 -9
  374. package/dist/studio/run-store-ui-pipelines.js.map +0 -1
  375. package/dist/studio/run-store-ui-protocol.js.map +0 -1
  376. package/dist/studio/run-store-ui-resource.js.map +0 -1
  377. package/dist/studio/run-store-ui-runs.d.ts +0 -31
  378. package/dist/studio/run-store-ui-runs.js +0 -163
  379. package/dist/studio/run-store-ui-runs.js.map +0 -1
  380. package/dist/studio/run-store-ui-schema.js.map +0 -1
  381. package/dist/studio/run-store-ui-state.js +0 -207
  382. package/dist/studio/run-store-ui-state.js.map +0 -1
  383. package/dist/studio/run-store-ui-steps.js.map +0 -1
  384. package/dist/studio/run-store-ui.js.map +0 -1
  385. package/dist/workbench/cloud-client.js.map +0 -1
  386. package/dist/workbench/cloud-config.js.map +0 -1
  387. package/dist/workbench/cloud-credentials.js.map +0 -1
  388. package/dist/workbench/cloud-protocol.js.map +0 -1
  389. package/dist/workbench/workbench-agent-commands.js.map +0 -1
  390. package/dist/workbench/workbench-agent-environment.js.map +0 -1
  391. package/dist/workbench/workbench-agent-history.js.map +0 -1
  392. package/dist/workbench/workbench-agent-input.js.map +0 -1
  393. package/dist/workbench/workbench-agent-prompt.d.ts +0 -19
  394. package/dist/workbench/workbench-agent-prompt.js.map +0 -1
  395. package/dist/workbench/workbench-agent-session.js.map +0 -1
  396. package/dist/workbench/workbench-agent.js.map +0 -1
  397. package/dist/workbench/workbench-auth.d.ts +0 -3
  398. package/dist/workbench/workbench-auth.js.map +0 -1
  399. package/dist/workbench/workbench-cloud-shared.js.map +0 -1
  400. package/dist/workbench/workbench-cloud.d.ts +0 -3
  401. package/dist/workbench/workbench-cloud.js.map +0 -1
  402. /package/dist/studio/{run-store-ui-graph-layout.d.ts → browser/graph/layout.d.ts} +0 -0
  403. /package/dist/studio/{run-store-ui-resource.d.ts → browser/resource.d.ts} +0 -0
  404. /package/dist/studio/{run-store-ui-page-node.d.ts → server/client-script.d.ts} +0 -0
  405. /package/dist/studio/{run-store-ui-hosting.d.ts → server/hosting.d.ts} +0 -0
  406. /package/dist/studio/{run-store-ui-http.d.ts → server/http.d.ts} +0 -0
  407. /package/dist/studio/{run-store-ui-node.d.ts → server/node-http.d.ts} +0 -0
  408. /package/dist/studio/{run-store-ui-page.d.ts → server/page.d.ts} +0 -0
  409. /package/dist/workbench/{workbench-agent-commands.d.ts → agent/commands.d.ts} +0 -0
  410. /package/dist/workbench/{cloud-config.d.ts → cloud/config.d.ts} +0 -0
  411. /package/dist/workbench/{cloud-credentials.d.ts → cloud/credentials.d.ts} +0 -0
  412. /package/dist/workbench/{cloud-protocol.d.ts → cloud/protocol.d.ts} +0 -0
@@ -0,0 +1,31 @@
1
+ import type { Pipeline, PipelineContext, PipelineRun, PipelineRunControls } from "../core/pipeline-types.js";
2
+ /** Conversation hooks a session supplies to its own compiled copy of a model-backed agent. */
3
+ export interface SessionHooks {
4
+ /** The committed conversation that seeds a fresh run. */
5
+ seed(): unknown;
6
+ /** Record the latest owned conversation, including a finish decision's. */
7
+ observe(conversation: unknown): void;
8
+ }
9
+ type SessionAgent = Pipeline<object, unknown, "agent", "agent", string>;
10
+ /** Let `createAgentSession` recompile this model-backed agent with session hooks. */
11
+ export declare function registerSessionAgent(agent: object, build: (hooks: SessionHooks) => SessionAgent): void;
12
+ /** Sequential runs of one model-backed agent that continue a single conversation. */
13
+ export interface AgentSession<Input extends object, Result> {
14
+ /** Run one prompt; the conversation advances only when the run completes and finalizes. */
15
+ run(input: Input, controls?: PipelineRunControls<"agent", "agent">, context?: Partial<PipelineContext>): Promise<PipelineRun<Result>>;
16
+ /** Run one prompt and return its result, or throw the run's execution error. */
17
+ runOrThrow(input: Input, controls?: PipelineRunControls<"agent", "agent">, context?: Partial<PipelineContext>): Promise<Result>;
18
+ /** Provider-owned plain data to persist; null before the first completed run or after clear(). */
19
+ readonly conversation: unknown;
20
+ /** Start the next run with a fresh conversation. */
21
+ clear(): void;
22
+ }
23
+ /**
24
+ * Continue one conversation across sequential runs of a `defineAgent` agent, such as chat
25
+ * prompts. Failed and cancelled runs keep the previous conversation. Pass a persisted
26
+ * `conversation` to resume from storage; it must come from the same model provider.
27
+ */
28
+ export declare function createAgentSession<Input extends object, Result>(agent: Pipeline<Input, Result, "agent", "agent", string>, options?: {
29
+ readonly conversation?: unknown;
30
+ }): AgentSession<Input, Result>;
31
+ export {};
@@ -0,0 +1,67 @@
1
+ import { PipelineExecutionError } from "../core/pipeline-execution-error.js";
2
+ import { agentError, ownState } from "./agent-state.js";
3
+ const builders = new WeakMap();
4
+ /** Let `createAgentSession` recompile this model-backed agent with session hooks. */
5
+ export function registerSessionAgent(agent, build) {
6
+ builders.set(agent, build);
7
+ }
8
+ /**
9
+ * Continue one conversation across sequential runs of a `defineAgent` agent, such as chat
10
+ * prompts. Failed and cancelled runs keep the previous conversation. Pass a persisted
11
+ * `conversation` to resume from storage; it must come from the same model provider.
12
+ */
13
+ export function createAgentSession(agent, options = {}) {
14
+ const build = builders.get(agent);
15
+ if (!build)
16
+ throw agentError("TUBELESS_AGENT_INVALID_DEFINITION", "createAgentSession requires an agent from defineAgent");
17
+ let committed = ownState(options.conversation ?? null);
18
+ // Track observation separately: a provider may legitimately return an undefined conversation.
19
+ let latest;
20
+ let observed = false;
21
+ let running = false;
22
+ // clear() during a run discards that run's conversation instead of reviving it later.
23
+ let generation = 0;
24
+ // SAFETY: the builder recompiles the same definition, so its options and result types match.
25
+ const compiled = build({
26
+ seed: () => committed,
27
+ observe: (conversation) => {
28
+ latest = ownState(conversation);
29
+ observed = true;
30
+ },
31
+ });
32
+ const run = async (input, controls, context) => {
33
+ if (running)
34
+ throw agentError("TUBELESS_AGENT_SESSION_BUSY", "Agent session is already running");
35
+ running = true;
36
+ latest = undefined;
37
+ observed = false;
38
+ const started = generation;
39
+ try {
40
+ const result = await compiled.run(input, controls, context);
41
+ if (result.status === "completed" && result.finalized && observed && generation === started)
42
+ committed = latest ?? null;
43
+ return result;
44
+ }
45
+ finally {
46
+ running = false;
47
+ }
48
+ };
49
+ return Object.freeze({
50
+ run,
51
+ async runOrThrow(input, controls, context) {
52
+ const result = await run(input, controls, context);
53
+ if (result.status !== "completed")
54
+ throw new PipelineExecutionError(result);
55
+ // SAFETY: a completed run always carries its result value, as in Pipeline.runOrThrow.
56
+ return result.value;
57
+ },
58
+ get conversation() {
59
+ return committed;
60
+ },
61
+ clear() {
62
+ committed = null;
63
+ generation++;
64
+ },
65
+ });
66
+ }
67
+ //# sourceMappingURL=agent-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-session.js","sourceRoot":"","sources":["../../src/agent/agent-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAO7E,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAWxD,MA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AM,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,SAAS,IAAI,QAAQ,IAAI,UAAU,KAAK,OAAO;gBACzF,SAAS,GAAG,MAAM,IAAI,IAAI,CAAC;YAC7B,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,OAAO,GAAG,KAAK,CAAC;QAClB,CAAC;IACH,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG;QACH,KAAK,CAAC,UAAU,CACd,KAAY,EACZ,QAAgD,EAChD,OAAkC;YAElC,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YACnD,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW;gBAAE,MAAM,IAAI,sBAAsB,CAAC,MAAM,CAAC,CAAC;YAC5E,sFAAsF;YACtF,OAAO,MAAM,CAAC,KAAe,CAAC;QAChC,CAAC;QACD,IAAI,YAAY;YACd,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,KAAK;YACH,SAAS,GAAG,IAAI,CAAC;YACjB,UAAU,EAAE,CAAC;QACf,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { PipelineExecutionError } from \"../core/pipeline-execution-error.js\";\nimport type {\n Pipeline,\n PipelineContext,\n PipelineRun,\n PipelineRunControls,\n} from \"../core/pipeline-types.js\";\nimport { agentError, ownState } from \"./agent-state.js\";\n\n/** Conversation hooks a session supplies to its own compiled copy of a model-backed agent. */\nexport interface SessionHooks {\n /** The committed conversation that seeds a fresh run. */\n seed(): unknown;\n /** Record the latest owned conversation, including a finish decision's. */\n observe(conversation: unknown): void;\n}\n\ntype SessionAgent = Pipeline<object, unknown, \"agent\", \"agent\", string>;\nconst builders = new WeakMap<object, (hooks: SessionHooks) => SessionAgent>();\n\n/** Let `createAgentSession` recompile this model-backed agent with session hooks. */\nexport function registerSessionAgent(\n agent: object,\n build: (hooks: SessionHooks) => SessionAgent\n): void {\n builders.set(agent, build);\n}\n\n/** Sequential runs of one model-backed agent that continue a single conversation. */\nexport interface AgentSession<Input extends object, Result> {\n /** Run one prompt; the conversation advances only when the run completes and finalizes. */\n run(\n input: Input,\n controls?: PipelineRunControls<\"agent\", \"agent\">,\n context?: Partial<PipelineContext>\n ): Promise<PipelineRun<Result>>;\n /** Run one prompt and return its result, or throw the run's execution error. */\n runOrThrow(\n input: Input,\n controls?: PipelineRunControls<\"agent\", \"agent\">,\n context?: Partial<PipelineContext>\n ): Promise<Result>;\n /** Provider-owned plain data to persist; null before the first completed run or after clear(). */\n readonly conversation: unknown;\n /** Start the next run with a fresh conversation. */\n clear(): void;\n}\n\n/**\n * Continue one conversation across sequential runs of a `defineAgent` agent, such as chat\n * prompts. Failed and cancelled runs keep the previous conversation. Pass a persisted\n * `conversation` to resume from storage; it must come from the same model provider.\n */\nexport function createAgentSession<Input extends object, Result>(\n agent: Pipeline<Input, Result, \"agent\", \"agent\", string>,\n options: { readonly conversation?: unknown } = {}\n): AgentSession<Input, Result> {\n const build = builders.get(agent);\n if (!build)\n throw agentError(\n \"TUBELESS_AGENT_INVALID_DEFINITION\",\n \"createAgentSession requires an agent from defineAgent\"\n );\n let committed: unknown = ownState(options.conversation ?? null);\n // Track observation separately: a provider may legitimately return an undefined conversation.\n let latest: unknown;\n let observed = false;\n let running = false;\n // clear() during a run discards that run's conversation instead of reviving it later.\n let generation = 0;\n // SAFETY: the builder recompiles the same definition, so its options and result types match.\n const compiled = build({\n seed: () => committed,\n observe: (conversation) => {\n latest = ownState(conversation);\n observed = true;\n },\n }) as unknown as Pipeline<Input, Result, \"agent\", \"agent\", string>;\n const run: AgentSession<Input, Result>[\"run\"] = async (input, controls, context) => {\n if (running)\n throw agentError(\"TUBELESS_AGENT_SESSION_BUSY\", \"Agent session is already running\");\n running = true;\n latest = undefined;\n observed = false;\n const started = generation;\n try {\n const result = await compiled.run(input, controls, context);\n if (result.status === \"completed\" && result.finalized && observed && generation === started)\n committed = latest ?? null;\n return result;\n } finally {\n running = false;\n }\n };\n return Object.freeze({\n run,\n async runOrThrow(\n input: Input,\n controls?: PipelineRunControls<\"agent\", \"agent\">,\n context?: Partial<PipelineContext>\n ) {\n const result = await run(input, controls, context);\n if (result.status !== \"completed\") throw new PipelineExecutionError(result);\n // SAFETY: a completed run always carries its result value, as in Pipeline.runOrThrow.\n return result.value as Result;\n },\n get conversation() {\n return committed;\n },\n clear() {\n committed = null;\n generation++;\n },\n });\n}\n"]}
@@ -2,6 +2,7 @@ import type { PipelineStepContext, StandardSchemaV1 } from "../core/pipeline-typ
2
2
  import type { AgentEnvironment, AgentEnvironmentProvider } from "./environment.js";
3
3
  import type { AgentDurability, AgentExecutionIdentity } from "./checkpoint-types.js";
4
4
  import type { DefaultAgentTools } from "./default-tools.js";
5
+ import type { CodemodeExecutor } from "./codemode-executor.js";
5
6
  export type Awaitable<T> = T | Promise<T>;
6
7
  export type Input<S extends StandardSchemaV1> = NonNullable<S["~standard"]["types"]>["input"];
7
8
  export type Output<S extends StandardSchemaV1> = NonNullable<S["~standard"]["types"]>["output"];
@@ -18,7 +19,9 @@ export interface AgentTool<Arguments, Result> {
18
19
  };
19
20
  }
20
21
  export type Tools = Readonly<Record<string, AgentTool<unknown, unknown>>>;
21
- type RegisteredTools<Custom extends Tools> = Omit<DefaultAgentTools, keyof Custom> & Custom;
22
+ /** A standard workspace tool an agent's setup may select. */
23
+ export type DefaultAgentToolName = keyof DefaultAgentTools;
24
+ type RegisteredTools<Custom extends Tools, Defaults extends DefaultAgentToolName> = Omit<Pick<DefaultAgentTools, Defaults>, keyof Custom> & Custom;
22
25
  type ToolCall<Registry extends Tools> = {
23
26
  [Name in keyof Registry & string]: {
24
27
  readonly id: string;
@@ -26,8 +29,31 @@ type ToolCall<Registry extends Tools> = {
26
29
  readonly input: Registry[Name][typeof capabilityTypes]["input"];
27
30
  };
28
31
  }[keyof Registry & string];
29
- /** One built-in or custom call with raw model arguments; custom names replace defaults. */
30
- export type AgentCall<Registry extends Tools = {}> = ToolCall<RegisteredTools<Registry>>;
32
+ /** A code-mode script's JSON return value and bounded console lines. */
33
+ export interface CodemodeResult {
34
+ readonly result: unknown;
35
+ readonly logs: readonly string[];
36
+ readonly logsTruncated: boolean;
37
+ }
38
+ /** Code-mode settings; the executor defaults to a Node worker thread. */
39
+ export interface CodemodeOptions {
40
+ /** Where scripts run, such as `createWorkerLoaderCodemodeExecutor` on Cloudflare. */
41
+ readonly executor?: CodemodeExecutor;
42
+ }
43
+ /** `true` or options enable code mode; `false` or omission advertises the registry. */
44
+ export type CodemodeSetting = boolean | CodemodeOptions;
45
+ type CodemodeEnabled<Setting extends CodemodeSetting> = Setting extends false ? false : true;
46
+ /** The only capability a code-mode agent advertises; its scripts reach the registry. */
47
+ type CodemodeTools = {
48
+ readonly codemode: AgentTool<{
49
+ readonly code: string;
50
+ }, CodemodeResult>;
51
+ };
52
+ /**
53
+ * One selected default or custom call with raw model arguments; custom names replace
54
+ * defaults. With code mode, the only callable tool is `codemode`.
55
+ */
56
+ export type AgentCall<Registry extends Tools = {}, Codemode extends boolean = false, Defaults extends DefaultAgentToolName = DefaultAgentToolName> = Codemode extends true ? ToolCall<CodemodeTools> : ToolCall<RegisteredTools<Registry, Defaults>>;
31
57
  type ToolOutcome<Registry extends Tools> = {
32
58
  [Name in keyof Registry & string]: {
33
59
  readonly id: string;
@@ -43,12 +69,15 @@ type ToolOutcome<Registry extends Tools> = {
43
69
  };
44
70
  });
45
71
  }[keyof Registry & string];
46
- /** Input-order result or deliberately recoverable handler failure, including default tools. */
47
- export type AgentOutcome<Registry extends Tools = {}> = ToolOutcome<RegisteredTools<Registry>>;
72
+ /** Input-order result or deliberately recoverable handler failure, including selected defaults. */
73
+ export type AgentOutcome<Registry extends Tools = {}, Codemode extends boolean = false, Defaults extends DefaultAgentToolName = DefaultAgentToolName> = Codemode extends true ? ToolOutcome<CodemodeTools> : ToolOutcome<RegisteredTools<Registry, Defaults>>;
48
74
  /** A nonempty batch of independent calls, or the raw input to the final-result schema. */
49
- export type AgentDecision<Registry extends Tools, Result> = {
75
+ export type AgentDecision<Registry extends Tools, Result, Codemode extends boolean = false, Defaults extends DefaultAgentToolName = DefaultAgentToolName> = {
50
76
  readonly kind: "continue";
51
- readonly calls: readonly [AgentCall<Registry>, ...AgentCall<Registry>[]];
77
+ readonly calls: readonly [
78
+ AgentCall<Registry, Codemode, Defaults>,
79
+ ...AgentCall<Registry, Codemode, Defaults>[]
80
+ ];
52
81
  readonly result?: never;
53
82
  } | {
54
83
  readonly kind: "finish";
@@ -86,7 +115,7 @@ export interface AgentDecisionContext<Options extends object> extends PipelineSt
86
115
  }[];
87
116
  readonly resultJsonSchema: Readonly<Record<string, unknown>>;
88
117
  }
89
- export interface AgentDefinition<Id extends string, Options extends StandardSchemaV1<object, object>, Result extends StandardSchemaV1, State, Registry extends Tools> {
118
+ export interface AgentDefinition<Id extends string, Options extends StandardSchemaV1<object, object>, Result extends StandardSchemaV1, State, Registry extends Tools, Codemode extends CodemodeSetting = false, Defaults extends DefaultAgentToolName = DefaultAgentToolName> {
90
119
  readonly id: Id;
91
120
  readonly name?: string;
92
121
  readonly description?: string;
@@ -95,8 +124,19 @@ export interface AgentDefinition<Id extends string, Options extends StandardSche
95
124
  readonly inputSchema: Options;
96
125
  readonly resultSchema: Result;
97
126
  readonly resultJsonSchema?: Readonly<Record<string, unknown>>;
98
- /** Extend the standard tools; a custom tool with the same name replaces that default. */
127
+ /** Extend the selected standard tools; a custom tool with the same name replaces that default. */
99
128
  readonly tools?: Registry;
129
+ /**
130
+ * Standard workspace tools this agent may use. Defaults to all of read, write, edit, bash,
131
+ * list and search; `[]` grants none, so only custom tools remain.
132
+ */
133
+ readonly defaultTools?: readonly Defaults[];
134
+ /**
135
+ * Advertise one `codemode` tool instead of the registry. Its JavaScript scripts call every
136
+ * registered tool; decisions and outcomes then name only `codemode`. Pass `{ executor }` to
137
+ * run scripts somewhere other than a Node worker thread. Defaults to false.
138
+ */
139
+ readonly codemode?: Codemode;
100
140
  readonly limits?: AgentLimits;
101
141
  /** Workspace capabilities; descendants inherit them unless explicitly replaced. */
102
142
  readonly environment?: AgentEnvironmentProvider;
@@ -104,7 +144,7 @@ export interface AgentDefinition<Id extends string, Options extends StandardSche
104
144
  readonly durability?: AgentDurability<Output<Options>>;
105
145
  initialState(options: Output<Options>): State;
106
146
  decide(state: AgentState<NoInfer<State>>, context: AgentDecisionContext<Output<Options>>): Awaitable<unknown>;
107
- reduce?(state: AgentState<NoInfer<State>>, outcomes: readonly AgentOutcome<Registry>[]): NoInfer<State>;
147
+ reduce?(state: AgentState<NoInfer<State>>, outcomes: readonly AgentOutcome<Registry, CodemodeEnabled<Codemode>, Defaults>[]): NoInfer<State>;
108
148
  dryRun?(state: AgentState<NoInfer<State>>, context: AgentDecisionContext<Output<Options>>): Awaitable<unknown>;
109
149
  }
110
150
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"agent-types.js","sourceRoot":"","sources":["../../src/agent/agent-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { PipelineStepContext, StandardSchemaV1 } from \"../core/pipeline-types.js\";\nimport type { AgentEnvironment, AgentEnvironmentProvider } from \"./environment.js\";\nimport type { AgentDurability, AgentExecutionIdentity } from \"./checkpoint-types.js\";\nimport type { DefaultAgentTools } from \"./default-tools.js\";\n\nexport type Awaitable<T> = T | Promise<T>;\nexport type Input<S extends StandardSchemaV1> = NonNullable<S[\"~standard\"][\"types\"]>[\"input\"];\nexport type Output<S extends StandardSchemaV1> = NonNullable<S[\"~standard\"][\"types\"]>[\"output\"];\n/** Deeply read-only view of the owned plain-data state supplied to agent callbacks. */\nexport type AgentState<T> = { readonly [K in keyof T]: AgentState<T[K]> };\ndeclare const capabilityTypes: unique symbol;\n\n/** Opaque capability created by defineTool or pipelineTool; model decisions contain data only. */\nexport interface AgentTool<Arguments, Result> {\n readonly [capabilityTypes]: { readonly input: Arguments; readonly output: Result };\n}\n\nexport type Tools = Readonly<Record<string, AgentTool<unknown, unknown>>>;\ntype RegisteredTools<Custom extends Tools> = Omit<DefaultAgentTools, keyof Custom> & Custom;\n\ntype ToolCall<Registry extends Tools> = {\n [Name in keyof Registry & string]: {\n readonly id: string;\n readonly tool: Name;\n readonly input: Registry[Name][typeof capabilityTypes][\"input\"];\n };\n}[keyof Registry & string];\n\n/** One built-in or custom call with raw model arguments; custom names replace defaults. */\nexport type AgentCall<Registry extends Tools = {}> = ToolCall<RegisteredTools<Registry>>;\n\ntype ToolOutcome<Registry extends Tools> = {\n [Name in keyof Registry & string]: {\n readonly id: string;\n readonly tool: Name;\n } & (\n | {\n readonly ok: true;\n readonly value: Registry[Name][typeof capabilityTypes][\"output\"];\n }\n | { readonly ok: false; readonly error: { readonly code: string; readonly message: string } }\n );\n}[keyof Registry & string];\n\n/** Input-order result or deliberately recoverable handler failure, including default tools. */\nexport type AgentOutcome<Registry extends Tools = {}> = ToolOutcome<RegisteredTools<Registry>>;\n\n/** A nonempty batch of independent calls, or the raw input to the final-result schema. */\nexport type AgentDecision<Registry extends Tools, Result> =\n | {\n readonly kind: \"continue\";\n readonly calls: readonly [AgentCall<Registry>, ...AgentCall<Registry>[]];\n readonly result?: never;\n }\n | { readonly kind: \"finish\"; readonly result: Result; readonly calls?: never };\n\n/** Finite limits for this agent and its descendants; child limits may only tighten them. */\nexport interface AgentLimits {\n /** Decision callbacks, including finish. Defaults to 20. */\n readonly maxTurns?: number;\n /** Admitted subtree calls, including calls stopped before dispatch. Defaults to 100. */\n readonly maxCalls?: number;\n /** Subtree decision callback admissions. Defaults to 100; provider retries are application-owned. */\n readonly maxDecisions?: number;\n /** Pipeline-tool delegation edges below this agent. Defaults to 4; zero allows leaf tools only. */\n readonly maxDepth?: number;\n /** Active decision callbacks and leaf handlers across the subtree. Defaults to 1. */\n readonly maxConcurrency?: number;\n}\n\n/** Step services and the workspace capability available to a registered tool. */\nexport interface AgentToolContext extends PipelineStepContext<{}> {\n readonly environment: AgentEnvironment;\n readonly execution?: AgentExecutionIdentity;\n}\n\n/** Model-facing descriptors and ordinary step services, without executable tools. */\nexport interface AgentDecisionContext<Options extends object> extends PipelineStepContext<Options> {\n readonly environment: AgentEnvironment;\n readonly execution?: AgentExecutionIdentity;\n readonly turn: number;\n readonly stateVersion: number;\n readonly capabilities: readonly {\n readonly name: string;\n readonly description: string;\n readonly inputJsonSchema: Readonly<Record<string, unknown>>;\n }[];\n readonly resultJsonSchema: Readonly<Record<string, unknown>>;\n}\n\nexport interface AgentDefinition<\n Id extends string,\n Options extends StandardSchemaV1<object, object>,\n Result extends StandardSchemaV1,\n State,\n Registry extends Tools,\n> {\n readonly id: Id;\n readonly name?: string;\n readonly description?: string;\n /** Semantic revision; required when this agent uses or inherits durable recovery. */\n readonly implementationVersion?: string;\n readonly inputSchema: Options;\n readonly resultSchema: Result;\n readonly resultJsonSchema?: Readonly<Record<string, unknown>>;\n /** Extend the standard tools; a custom tool with the same name replaces that default. */\n readonly tools?: Registry;\n readonly limits?: AgentLimits;\n /** Workspace capabilities; descendants inherit them unless explicitly replaced. */\n readonly environment?: AgentEnvironmentProvider;\n /** Acknowledged recovery checkpoints; requires an explicit implementationVersion. */\n readonly durability?: AgentDurability<Output<Options>>;\n initialState(options: Output<Options>): State;\n decide(\n state: AgentState<NoInfer<State>>,\n context: AgentDecisionContext<Output<Options>>\n ): Awaitable<unknown>;\n reduce?(\n state: AgentState<NoInfer<State>>,\n outcomes: readonly AgentOutcome<Registry>[]\n ): NoInfer<State>;\n dryRun?(\n state: AgentState<NoInfer<State>>,\n context: AgentDecisionContext<Output<Options>>\n ): Awaitable<unknown>;\n}\n"]}
1
+ {"version":3,"file":"agent-types.js","sourceRoot":"","sources":["../../src/agent/agent-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { PipelineStepContext, StandardSchemaV1 } from \"../core/pipeline-types.js\";\nimport type { AgentEnvironment, AgentEnvironmentProvider } from \"./environment.js\";\nimport type { AgentDurability, AgentExecutionIdentity } from \"./checkpoint-types.js\";\nimport type { DefaultAgentTools } from \"./default-tools.js\";\nimport type { CodemodeExecutor } from \"./codemode-executor.js\";\n\nexport type Awaitable<T> = T | Promise<T>;\nexport type Input<S extends StandardSchemaV1> = NonNullable<S[\"~standard\"][\"types\"]>[\"input\"];\nexport type Output<S extends StandardSchemaV1> = NonNullable<S[\"~standard\"][\"types\"]>[\"output\"];\n/** Deeply read-only view of the owned plain-data state supplied to agent callbacks. */\nexport type AgentState<T> = { readonly [K in keyof T]: AgentState<T[K]> };\ndeclare const capabilityTypes: unique symbol;\n\n/** Opaque capability created by defineTool or pipelineTool; model decisions contain data only. */\nexport interface AgentTool<Arguments, Result> {\n readonly [capabilityTypes]: { readonly input: Arguments; readonly output: Result };\n}\n\nexport type Tools = Readonly<Record<string, AgentTool<unknown, unknown>>>;\n/** A standard workspace tool an agent's setup may select. */\nexport type DefaultAgentToolName = keyof DefaultAgentTools;\ntype RegisteredTools<Custom extends Tools, Defaults extends DefaultAgentToolName> = Omit<\n Pick<DefaultAgentTools, Defaults>,\n keyof Custom\n> &\n Custom;\n\ntype ToolCall<Registry extends Tools> = {\n [Name in keyof Registry & string]: {\n readonly id: string;\n readonly tool: Name;\n readonly input: Registry[Name][typeof capabilityTypes][\"input\"];\n };\n}[keyof Registry & string];\n\n/** A code-mode script's JSON return value and bounded console lines. */\nexport interface CodemodeResult {\n readonly result: unknown;\n readonly logs: readonly string[];\n readonly logsTruncated: boolean;\n}\n\n/** Code-mode settings; the executor defaults to a Node worker thread. */\nexport interface CodemodeOptions {\n /** Where scripts run, such as `createWorkerLoaderCodemodeExecutor` on Cloudflare. */\n readonly executor?: CodemodeExecutor;\n}\n\n/** `true` or options enable code mode; `false` or omission advertises the registry. */\nexport type CodemodeSetting = boolean | CodemodeOptions;\ntype CodemodeEnabled<Setting extends CodemodeSetting> = Setting extends false ? false : true;\n\n/** The only capability a code-mode agent advertises; its scripts reach the registry. */\ntype CodemodeTools = {\n readonly codemode: AgentTool<{ readonly code: string }, CodemodeResult>;\n};\n\n/**\n * One selected default or custom call with raw model arguments; custom names replace\n * defaults. With code mode, the only callable tool is `codemode`.\n */\nexport type AgentCall<\n Registry extends Tools = {},\n Codemode extends boolean = false,\n Defaults extends DefaultAgentToolName = DefaultAgentToolName,\n> = Codemode extends true ? ToolCall<CodemodeTools> : ToolCall<RegisteredTools<Registry, Defaults>>;\n\ntype ToolOutcome<Registry extends Tools> = {\n [Name in keyof Registry & string]: {\n readonly id: string;\n readonly tool: Name;\n } & (\n | {\n readonly ok: true;\n readonly value: Registry[Name][typeof capabilityTypes][\"output\"];\n }\n | { readonly ok: false; readonly error: { readonly code: string; readonly message: string } }\n );\n}[keyof Registry & string];\n\n/** Input-order result or deliberately recoverable handler failure, including selected defaults. */\nexport type AgentOutcome<\n Registry extends Tools = {},\n Codemode extends boolean = false,\n Defaults extends DefaultAgentToolName = DefaultAgentToolName,\n> = Codemode extends true\n ? ToolOutcome<CodemodeTools>\n : ToolOutcome<RegisteredTools<Registry, Defaults>>;\n\n/** A nonempty batch of independent calls, or the raw input to the final-result schema. */\nexport type AgentDecision<\n Registry extends Tools,\n Result,\n Codemode extends boolean = false,\n Defaults extends DefaultAgentToolName = DefaultAgentToolName,\n> =\n | {\n readonly kind: \"continue\";\n readonly calls: readonly [\n AgentCall<Registry, Codemode, Defaults>,\n ...AgentCall<Registry, Codemode, Defaults>[],\n ];\n readonly result?: never;\n }\n | { readonly kind: \"finish\"; readonly result: Result; readonly calls?: never };\n\n/** Finite limits for this agent and its descendants; child limits may only tighten them. */\nexport interface AgentLimits {\n /** Decision callbacks, including finish. Defaults to 20. */\n readonly maxTurns?: number;\n /** Admitted subtree calls, including calls stopped before dispatch. Defaults to 100. */\n readonly maxCalls?: number;\n /** Subtree decision callback admissions. Defaults to 100; provider retries are application-owned. */\n readonly maxDecisions?: number;\n /** Pipeline-tool delegation edges below this agent. Defaults to 4; zero allows leaf tools only. */\n readonly maxDepth?: number;\n /** Active decision callbacks and leaf handlers across the subtree. Defaults to 1. */\n readonly maxConcurrency?: number;\n}\n\n/** Step services and the workspace capability available to a registered tool. */\nexport interface AgentToolContext extends PipelineStepContext<{}> {\n readonly environment: AgentEnvironment;\n readonly execution?: AgentExecutionIdentity;\n}\n\n/** Model-facing descriptors and ordinary step services, without executable tools. */\nexport interface AgentDecisionContext<Options extends object> extends PipelineStepContext<Options> {\n readonly environment: AgentEnvironment;\n readonly execution?: AgentExecutionIdentity;\n readonly turn: number;\n readonly stateVersion: number;\n readonly capabilities: readonly {\n readonly name: string;\n readonly description: string;\n readonly inputJsonSchema: Readonly<Record<string, unknown>>;\n }[];\n readonly resultJsonSchema: Readonly<Record<string, unknown>>;\n}\n\nexport interface AgentDefinition<\n Id extends string,\n Options extends StandardSchemaV1<object, object>,\n Result extends StandardSchemaV1,\n State,\n Registry extends Tools,\n Codemode extends CodemodeSetting = false,\n Defaults extends DefaultAgentToolName = DefaultAgentToolName,\n> {\n readonly id: Id;\n readonly name?: string;\n readonly description?: string;\n /** Semantic revision; required when this agent uses or inherits durable recovery. */\n readonly implementationVersion?: string;\n readonly inputSchema: Options;\n readonly resultSchema: Result;\n readonly resultJsonSchema?: Readonly<Record<string, unknown>>;\n /** Extend the selected standard tools; a custom tool with the same name replaces that default. */\n readonly tools?: Registry;\n /**\n * Standard workspace tools this agent may use. Defaults to all of read, write, edit, bash,\n * list and search; `[]` grants none, so only custom tools remain.\n */\n readonly defaultTools?: readonly Defaults[];\n /**\n * Advertise one `codemode` tool instead of the registry. Its JavaScript scripts call every\n * registered tool; decisions and outcomes then name only `codemode`. Pass `{ executor }` to\n * run scripts somewhere other than a Node worker thread. Defaults to false.\n */\n readonly codemode?: Codemode;\n readonly limits?: AgentLimits;\n /** Workspace capabilities; descendants inherit them unless explicitly replaced. */\n readonly environment?: AgentEnvironmentProvider;\n /** Acknowledged recovery checkpoints; requires an explicit implementationVersion. */\n readonly durability?: AgentDurability<Output<Options>>;\n initialState(options: Output<Options>): State;\n decide(\n state: AgentState<NoInfer<State>>,\n context: AgentDecisionContext<Output<Options>>\n ): Awaitable<unknown>;\n reduce?(\n state: AgentState<NoInfer<State>>,\n outcomes: readonly AgentOutcome<Registry, CodemodeEnabled<Codemode>, Defaults>[]\n ): NoInfer<State>;\n dryRun?(\n state: AgentState<NoInfer<State>>,\n context: AgentDecisionContext<Output<Options>>\n ): Awaitable<unknown>;\n}\n"]}
@@ -1,17 +1,19 @@
1
1
  import type { StandardSchemaV1 } from "../core/pipeline-types.js";
2
- import type { AgentDefinition, Tools } from "./agent-types.js";
2
+ import type { AgentDefinition, CodemodeSetting, DefaultAgentToolName, Tools } from "./agent-types.js";
3
3
  export { pipelineTool } from "./pipeline-tool.js";
4
4
  export { defineTool, ToolError } from "./tools.js";
5
5
  export type { DefaultAgentTools } from "./default-tools.js";
6
- export type { AgentCall, AgentDecision, AgentDecisionContext, AgentLimits, AgentOutcome, AgentState, AgentTool, AgentToolContext, } from "./agent-types.js";
6
+ export type { AgentCall, AgentDecision, AgentDecisionContext, AgentLimits, AgentOutcome, AgentState, AgentTool, AgentToolContext, CodemodeOptions, CodemodeResult, CodemodeSetting, DefaultAgentToolName, } from "./agent-types.js";
7
+ export type { CodemodeExecution, CodemodeExecutionResult, CodemodeExecutor, CodemodeReply, } from "./codemode-executor.js";
7
8
  export type { AgentEnvironment, AgentEnvironmentContext, AgentEnvironmentProvider, AgentProjectInstruction, } from "./environment.js";
8
9
  export { createMemoryAgentCheckpointStore } from "./memory-checkpoint-store.js";
9
10
  export { plainAgentCheckpointCodec } from "./checkpoint-codec.js";
10
11
  export type { AgentCheckpointLease, AgentCheckpointStore, AgentCheckpointCodec, AgentDurability, AgentExecutionIdentity, } from "./checkpoint-types.js";
11
- export { defineModelAgent } from "./model-agent.js";
12
- export type { AgentModel, AgentModelRequest, AgentModelResponse } from "./model-types.js";
12
+ export { defineAgent } from "./model-agent.js";
13
+ export { createAgentSession, type AgentSession } from "./agent-session.js";
14
+ export type { AgentModel, AgentModelDescriptors, AgentModelRequest, AgentModelResponse, } from "./model-types.js";
13
15
  /** Build a bounded in-process agent as an ordinary pipeline with one target, agent. */
14
- export declare function defineAgent<const Id extends string, const Options extends StandardSchemaV1<object, object>, const Result extends StandardSchemaV1, State, const Registry extends Tools = {}>(definition: AgentDefinition<Id, Options, Result, State, Registry>): import("../core/pipeline-types.js").Pipeline<import("./agent-types.js").Input<Options>, import("./agent-types.js").Output<Result>, "agent", "agent", Id> & {
16
+ export declare function defineAgentLoop<const Id extends string, const Options extends StandardSchemaV1<object, object>, const Result extends StandardSchemaV1, State, const Registry extends Tools = {}, const Codemode extends CodemodeSetting = false, const Defaults extends DefaultAgentToolName = DefaultAgentToolName>(definition: AgentDefinition<Id, Options, Result, State, Registry, Codemode, Defaults>): import("../core/pipeline-types.js").Pipeline<import("./agent-types.js").Input<Options>, import("./agent-types.js").Output<Result>, "agent", "agent", Id> & {
15
17
  readonly optionsSchema: Options;
16
18
  readonly definition: import("../core/pipeline-types.js").PipelineDefinitionSnapshot;
17
19
  };
@@ -4,9 +4,10 @@ export { pipelineTool } from "./pipeline-tool.js";
4
4
  export { defineTool, ToolError } from "./tools.js";
5
5
  export { createMemoryAgentCheckpointStore } from "./memory-checkpoint-store.js";
6
6
  export { plainAgentCheckpointCodec } from "./checkpoint-codec.js";
7
- export { defineModelAgent } from "./model-agent.js";
7
+ export { defineAgent } from "./model-agent.js";
8
+ export { createAgentSession } from "./agent-session.js";
8
9
  /** Build a bounded in-process agent as an ordinary pipeline with one target, agent. */
9
- export function defineAgent(definition) {
10
+ export function defineAgentLoop(definition) {
10
11
  const { decide, dryRun } = definition;
11
12
  if (typeof decide !== "function" || (dryRun !== undefined && typeof dryRun !== "function"))
12
13
  throw agentError("TUBELESS_AGENT_INVALID_DEFINITION", "Agent requires callable decide/dryRun callbacks");
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAoBnD,OAAO,EAAE,gCAAgC,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AASlE,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,uFAAuF;AACvF,MAAM,UAAU,WAAW,CAMzB,UAAiE;IACjE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC;IACtC,IAAI,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,MAAM,KAAK,UAAU,CAAC;QACxF,MAAM,UAAU,CACd,mCAAmC,EACnC,iDAAiD,CAClD,CAAC;IACJ,OAAO,YAAY,CAAuC;QACxD,GAAG,UAAU;QACb,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC;QACrF,MAAM,EACJ,MAAM,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;KAC5F,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { StandardSchemaV1 } from \"../core/pipeline-types.js\";\nimport type { AgentDefinition, Tools } from \"./agent-types.js\";\nimport { agentError } from \"./agent-state.js\";\nimport { compileAgent } from \"./compile-agent.js\";\n\nexport { pipelineTool } from \"./pipeline-tool.js\";\nexport { defineTool, ToolError } from \"./tools.js\";\nexport type { DefaultAgentTools } from \"./default-tools.js\";\nexport type {\n AgentCall,\n AgentDecision,\n AgentDecisionContext,\n AgentLimits,\n AgentOutcome,\n AgentState,\n AgentTool,\n AgentToolContext,\n} from \"./agent-types.js\";\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentContext,\n AgentEnvironmentProvider,\n AgentProjectInstruction,\n} from \"./environment.js\";\n\nexport { createMemoryAgentCheckpointStore } from \"./memory-checkpoint-store.js\";\nexport { plainAgentCheckpointCodec } from \"./checkpoint-codec.js\";\nexport type {\n AgentCheckpointLease,\n AgentCheckpointStore,\n AgentCheckpointCodec,\n AgentDurability,\n AgentExecutionIdentity,\n} from \"./checkpoint-types.js\";\n\nexport { defineModelAgent } from \"./model-agent.js\";\nexport type { AgentModel, AgentModelRequest, AgentModelResponse } from \"./model-types.js\";\n\n/** Build a bounded in-process agent as an ordinary pipeline with one target, agent. */\nexport function defineAgent<\n const Id extends string,\n const Options extends StandardSchemaV1<object, object>,\n const Result extends StandardSchemaV1,\n State,\n const Registry extends Tools = {},\n>(definition: AgentDefinition<Id, Options, Result, State, Registry>) {\n const { decide, dryRun } = definition;\n if (typeof decide !== \"function\" || (dryRun !== undefined && typeof dryRun !== \"function\"))\n throw agentError(\n \"TUBELESS_AGENT_INVALID_DEFINITION\",\n \"Agent requires callable decide/dryRun callbacks\"\n );\n return compileAgent<Id, Options, Result, State, Registry>({\n ...definition,\n decide: async (state, context) => ({ decision: await decide(state, context), state }),\n dryRun:\n dryRun && (async (state, context) => ({ decision: await dryRun(state, context), state })),\n });\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AA8BnD,OAAO,EAAE,gCAAgC,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AASlE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAqB,MAAM,oBAAoB,CAAC;AAQ3E,uFAAuF;AACvF,MAAM,UAAU,eAAe,CAQ7B,UAAqF;IACrF,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC;IACtC,IAAI,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,MAAM,KAAK,UAAU,CAAC;QACxF,MAAM,UAAU,CACd,mCAAmC,EACnC,iDAAiD,CAClD,CAAC;IACJ,OAAO,YAAY,CAA2D;QAC5E,GAAG,UAAU;QACb,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC;QACrF,MAAM,EACJ,MAAM,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;KAC5F,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { StandardSchemaV1 } from \"../core/pipeline-types.js\";\nimport type {\n AgentDefinition,\n CodemodeSetting,\n DefaultAgentToolName,\n Tools,\n} from \"./agent-types.js\";\nimport { agentError } from \"./agent-state.js\";\nimport { compileAgent } from \"./compile-agent.js\";\n\nexport { pipelineTool } from \"./pipeline-tool.js\";\nexport { defineTool, ToolError } from \"./tools.js\";\nexport type { DefaultAgentTools } from \"./default-tools.js\";\nexport type {\n AgentCall,\n AgentDecision,\n AgentDecisionContext,\n AgentLimits,\n AgentOutcome,\n AgentState,\n AgentTool,\n AgentToolContext,\n CodemodeOptions,\n CodemodeResult,\n CodemodeSetting,\n DefaultAgentToolName,\n} from \"./agent-types.js\";\nexport type {\n CodemodeExecution,\n CodemodeExecutionResult,\n CodemodeExecutor,\n CodemodeReply,\n} from \"./codemode-executor.js\";\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentContext,\n AgentEnvironmentProvider,\n AgentProjectInstruction,\n} from \"./environment.js\";\n\nexport { createMemoryAgentCheckpointStore } from \"./memory-checkpoint-store.js\";\nexport { plainAgentCheckpointCodec } from \"./checkpoint-codec.js\";\nexport type {\n AgentCheckpointLease,\n AgentCheckpointStore,\n AgentCheckpointCodec,\n AgentDurability,\n AgentExecutionIdentity,\n} from \"./checkpoint-types.js\";\n\nexport { defineAgent } from \"./model-agent.js\";\nexport { createAgentSession, type AgentSession } from \"./agent-session.js\";\nexport type {\n AgentModel,\n AgentModelDescriptors,\n AgentModelRequest,\n AgentModelResponse,\n} from \"./model-types.js\";\n\n/** Build a bounded in-process agent as an ordinary pipeline with one target, agent. */\nexport function defineAgentLoop<\n const Id extends string,\n const Options extends StandardSchemaV1<object, object>,\n const Result extends StandardSchemaV1,\n State,\n const Registry extends Tools = {},\n const Codemode extends CodemodeSetting = false,\n const Defaults extends DefaultAgentToolName = DefaultAgentToolName,\n>(definition: AgentDefinition<Id, Options, Result, State, Registry, Codemode, Defaults>) {\n const { decide, dryRun } = definition;\n if (typeof decide !== \"function\" || (dryRun !== undefined && typeof dryRun !== \"function\"))\n throw agentError(\n \"TUBELESS_AGENT_INVALID_DEFINITION\",\n \"Agent requires callable decide/dryRun callbacks\"\n );\n return compileAgent<Id, Options, Result, State, Registry, Codemode, Defaults>({\n ...definition,\n decide: async (state, context) => ({ decision: await decide(state, context), state }),\n dryRun:\n dryRun && (async (state, context) => ({ decision: await dryRun(state, context), state })),\n });\n}\n"]}
@@ -32,17 +32,14 @@ export function anthropicModel(options = {}) {
32
32
  throw new Error("Invalid Anthropic model configuration");
33
33
  if (baseUrl !== undefined)
34
34
  providerBaseUrl("Anthropic", baseUrl);
35
- return async (request, context) => {
35
+ const decide = async (request, context) => {
36
36
  const selectedModel = (model ?? process.env.ANTHROPIC_MODEL)?.trim() || "claude-opus-5-5";
37
37
  const timeout = AbortSignal.timeout(timeoutMs);
38
38
  const signal = context.signal ? AbortSignal.any([context.signal, timeout]) : timeout;
39
39
  const base = providerBaseUrl("Anthropic", baseUrl ?? (process.env.ANTHROPIC_BASE_URL?.trim() || DEFAULT_BASE_URL));
40
40
  throwIfAborted(signal, "Anthropic decision");
41
41
  // Validate descriptors before either compaction or a decision can perform I/O.
42
- const tools = [
43
- ...context.capabilities.map((tool) => anthropicTool(tool.name, tool.description, "input", tool.inputJsonSchema, strict)),
44
- anthropicTool("_finish", "Finish with the final answer.", "result", context.resultJsonSchema, strict),
45
- ];
42
+ const tools = anthropicTools(context, strict);
46
43
  if (request.conversation !== null &&
47
44
  (!Array.isArray(request.conversation) || !request.conversation.every(record)))
48
45
  throw new Error("Invalid Anthropic conversation state");
@@ -155,6 +152,20 @@ export function anthropicModel(options = {}) {
155
152
  messages = [...messages, { role: "user", content: TOOL_RULE }];
156
153
  }
157
154
  };
155
+ return Object.assign(decide, {
156
+ checkDescriptors: (descriptors) => void anthropicTools(descriptors, strict),
157
+ });
158
+ }
159
+ // Strict mode accepts at most this many strict tools per request, including _finish.
160
+ const MAX_STRICT_TOOLS = 20;
161
+ /** Messages API tools for these descriptors, plus the adapter-only `_finish` tool. */
162
+ function anthropicTools({ capabilities, resultJsonSchema }, strict) {
163
+ if (strict && capabilities.length + 1 > MAX_STRICT_TOOLS)
164
+ throw new Error(`Anthropic strict mode allows at most ${MAX_STRICT_TOOLS} tools per request, including _finish; this agent has ${capabilities.length + 1}. Set strict: false, or advertise fewer tools with defaultTools, allowlists or codemode`);
165
+ return [
166
+ ...capabilities.map((tool) => anthropicTool(tool.name, tool.description, "input", tool.inputJsonSchema, strict)),
167
+ anthropicTool("_finish", "Finish with the final answer.", "result", resultJsonSchema, strict),
168
+ ];
158
169
  }
159
170
  /** Pair each pending `_finish` call with a tool_result so the next user prompt is valid. */
160
171
  function closeFinishedTools(messages) {
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/agent/anthropic.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAsCvD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AACrD,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC1D,MAAM,SAAS,GACb,6GAA6G,CAAC;AAChH,MAAM,oBAAoB,GACxB,sOAAsO,CAAC;AACzO,+DAA+D;AAC/D,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC,sGAAsG;AACtG,MAAM,UAAU,cAAc,CAAC,OAAO,GAA0B,EAAE;IAChE,MAAM,EACJ,KAAK,EACL,MAAM,EACN,SAAS,EACT,OAAO,EACP,eAAe,GAAG,IAAI,EACtB,SAAS,GAAG,MAAM,EAClB,MAAM,GAAG,IAAI,EACb,aAAa,GAAG,IAAI,EACpB,iBAAiB,GAAG,MAAM,EAC1B,SAAS,GAAG,OAAO,GACpB,GAAG,OAAO,CAAC;IACZ,IACE,CAAC,iBAAiB,KAAK,IAAI;QACzB,CAAC,CAAC,MA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I,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE,IAAI,EAAE,CAAC;IAC9D,IAAI,GAAG;QAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC;IACrC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,IAAI,EAAE,CAAC;IACvD,IAAI,KAAK;QAAE,OAAO,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE,CAAC;IACvD,MAAM,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;AACpG,CAAC","sourcesContent":["import type { AgentModel } from \"./model-types.js\";\nimport {\n anthropicDecision,\n anthropicMessage,\n anthropicTool,\n carriesCompaction,\n COMPACTION_BETA,\n} from \"./anthropic-protocol.js\";\nimport { MAX_REQUEST_BYTES, providerBaseUrl, providerRequest } from \"./provider-http.js\";\nimport { record } from \"./provider-schema.js\";\nimport { boundedToolOutputs } from \"./provider-tool-outputs.js\";\nimport { throwIfAborted } from \"../utilities/abort.js\";\n\n/** Messages API transport settings; credentials are resolved only when a decision executes. */\nexport interface AnthropicModelOptions {\n /** Defaults to ANTHROPIC_MODEL or claude-opus-5-5. Must support tool use. */\n readonly model?: string;\n /**\n * Sent as x-api-key. Without an explicit apiKey or authToken, ANTHROPIC_API_KEY is\n * used at execution time, then ANTHROPIC_AUTH_TOKEN.\n */\n readonly apiKey?: string;\n /** Sent as Authorization: Bearer, for compatible servers and gateways that expect it. */\n readonly authToken?: string;\n /**\n * API root without the version path. Defaults to ANTHROPIC_BASE_URL or\n * https://api.anthropic.com; set it for any server that implements the Messages API.\n */\n readonly baseUrl?: string;\n /** Sent as output_config.effort. Omitted by default; null also omits it. */\n readonly reasoningEffort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | null;\n /** Output cap for each request, including thinking; defaults to 32000 tokens. */\n readonly maxTokens?: number;\n /**\n * Send tools with strict: true (default). Unsupported constraints move into descriptions;\n * the harness still validates every argument. Disable for servers without strict tool use.\n */\n readonly strict?: boolean;\n /** Send top-level cache_control (default). Disable for servers that reject it. */\n readonly promptCaching?: boolean;\n /**\n * Compact above this history size (default 65536 bytes), or when the complete decision\n * exceeds the request limit. null never requests on-demand compaction.\n */\n readonly compactAfterBytes?: number | null;\n /** Combined deadline for compaction and decision requests; defaults to 600000 ms. */\n readonly timeoutMs?: number;\n}\n\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\nconst EFFORTS = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\nconst TOOL_RULE =\n \"Respond only by calling tools. Call _finish alone with the final answer. Never mix _finish with tool calls.\";\nconst SUMMARY_INSTRUCTIONS =\n \"Summarize this agent conversation so the agent can continue the task. Preserve the task, decisions, file paths, commands run, verified results, failures, and remaining work. Do not call tools; respond with the summary text only.\";\n// `{\"role\":\"user\",\"content\":[]}` plus a separator, rounded up.\nconst RESULT_MESSAGE_BYTES = 64;\n\n/** Create a dependency-free Anthropic Messages model with native history and on-demand compaction. */\nexport function anthropicModel(options: AnthropicModelOptions = {}): AgentModel {\n const {\n model,\n apiKey,\n authToken,\n baseUrl,\n reasoningEffort = null,\n maxTokens = 32_000,\n strict = true,\n promptCaching = true,\n compactAfterBytes = 65_536,\n timeoutMs = 600_000,\n } = options;\n if (\n (compactAfterBytes !== null &&\n (!Number.isSafeInteger(compactAfterBytes) ||\n compactAfterBytes < 1 ||\n compactAfterBytes >= MAX_REQUEST_BYTES)) ||\n !Number.isSafeInteger(maxTokens) ||\n maxTokens < 1 ||\n !Number.isSafeInteger(timeoutMs) ||\n timeoutMs < 1 ||\n timeoutMs > 2_147_483_647 ||\n typeof strict !== \"boolean\" ||\n typeof promptCaching !== \"boolean\" ||\n (apiKey !== undefined && authToken !== undefined) ||\n (authToken !== undefined && (typeof authToken !== \"string\" || !authToken.trim())) ||\n (model !== undefined && (typeof model !== \"string\" || !model.trim())) ||\n (apiKey !== undefined && (typeof apiKey !== \"string\" || !apiKey.trim())) ||\n (baseUrl !== undefined && typeof baseUrl !== \"string\") ||\n (reasoningEffort !== null && !EFFORTS.includes(reasoningEffort))\n )\n throw new Error(\"Invalid Anthropic model configuration\");\n if (baseUrl !== undefined) providerBaseUrl(\"Anthropic\", baseUrl);\n return async (request, context) => {\n const selectedModel = (model ?? process.env.ANTHROPIC_MODEL)?.trim() || \"claude-opus-5-5\";\n const timeout = AbortSignal.timeout(timeoutMs);\n const signal = context.signal ? AbortSignal.any([context.signal, timeout]) : timeout;\n const base = providerBaseUrl(\n \"Anthropic\",\n baseUrl ?? (process.env.ANTHROPIC_BASE_URL?.trim() || DEFAULT_BASE_URL)\n );\n throwIfAborted(signal, \"Anthropic decision\");\n // Validate descriptors before either compaction or a decision can perform I/O.\n const tools = [\n ...context.capabilities.map((tool) =>\n anthropicTool(tool.name, tool.description, \"input\", tool.inputJsonSchema, strict)\n ),\n anthropicTool(\n \"_finish\",\n \"Finish with the final answer.\",\n \"result\",\n context.resultJsonSchema,\n strict\n ),\n ];\n if (\n request.conversation !== null &&\n (!Array.isArray(request.conversation) || !request.conversation.every(record))\n )\n throw new Error(\"Invalid Anthropic conversation state\");\n // A restored session starts a new prompt with no tool outcomes. Close _finish\n // before appending that prompt; the Messages API rejects a second user message.\n const newPrompt = context.turn === 1 && request.outcomes.length === 0;\n let messages: unknown[] =\n request.conversation === null\n ? []\n : newPrompt\n ? closeFinishedTools(request.conversation)\n : [...request.conversation];\n const withPrompt = (history: readonly unknown[]) =>\n newPrompt ? appendUserText(history, request.task) : [...history];\n const send = (endpointLabel: string, payload: { messages: unknown[] }, beta: boolean) =>\n providerRequest(\n \"Anthropic\",\n endpointLabel,\n `${base}/v1/messages`,\n {\n ...credentials(apiKey, authToken),\n \"anthropic-version\": \"2023-06-01\",\n ...(beta || carriesCompaction(payload.messages)\n ? { \"anthropic-beta\": COMPACTION_BETA }\n : {}),\n },\n payload,\n signal\n );\n const system = `${request.instructions}\\n\\n${TOOL_RULE}`;\n // Summaries read the same system prompt and tools as the conversation.\n const compactRequest = {\n model: selectedModel,\n max_tokens: maxTokens,\n system,\n tools,\n compaction: { type: \"summarize\", instructions: SUMMARY_INSTRUCTIONS },\n messages,\n };\n const decisionRequest = {\n model: selectedModel,\n max_tokens: maxTokens,\n ...(reasoningEffort === null ? {} : { output_config: { effort: reasoningEffort } }),\n ...(promptCaching ? { cache_control: { type: \"ephemeral\" } } : {}),\n system,\n tools,\n // Current models reject forced tool choice; the system rule and retry below steer instead.\n tool_choice: { type: \"auto\" },\n messages,\n };\n const results = (availableBytes: number) =>\n request.outcomes.length === 0\n ? []\n : [\n {\n role: \"user\",\n content: boundedToolOutputs(\n \"Anthropic\",\n request.outcomes,\n availableBytes - RESULT_MESSAGE_BYTES,\n (outcome, output) => ({\n type: \"tool_result\",\n tool_use_id: outcome.id,\n content: output,\n ...(outcome.ok ? {} : { is_error: true }),\n })\n ),\n },\n ];\n const history = [...messages, ...results(MAX_REQUEST_BYTES)];\n const completed = withPrompt(history);\n const shouldCompact =\n compactAfterBytes !== null &&\n (request.outcomes.length > 0 || (newPrompt && request.conversation !== null)) &&\n (Buffer.byteLength(JSON.stringify(completed)) > compactAfterBytes ||\n Buffer.byteLength(JSON.stringify({ ...decisionRequest, messages: completed })) >\n MAX_REQUEST_BYTES);\n // Compaction covers completed history only. The new prompt stays verbatim.\n const nextRequest = shouldCompact ? compactRequest : decisionRequest;\n const payload = shouldCompact ? history : completed;\n const fits =\n Buffer.byteLength(JSON.stringify({ ...nextRequest, messages: payload })) <= MAX_REQUEST_BYTES;\n messages = fits\n ? payload\n : [\n ...messages,\n ...results(MAX_REQUEST_BYTES - Buffer.byteLength(JSON.stringify(nextRequest))),\n ];\n if (shouldCompact) {\n const summary = anthropicMessage(\n await send(\"compaction\", { ...compactRequest, messages }, true)\n );\n const [block] = summary.content;\n if (\n summary.stopReason === \"compaction\" &&\n summary.content.length === 1 &&\n block?.type === \"compaction\" &&\n typeof block.content === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n // The returned assistant message replaces every message it covered, unchanged.\n // The summarized history ended with tool results, so a user turn must follow it.\n messages = [\n { role: \"assistant\", content: [block] },\n { role: \"user\", content: \"Continue the task from this summary.\" },\n ];\n context.log.log(\"Compacted agent conversation\");\n } else {\n context.log.log(`Anthropic compaction returned no summary (${summary.stopReason})`);\n }\n }\n if (newPrompt && (shouldCompact || !fits)) messages = withPrompt(messages);\n for (let attempt = 0; ; attempt++) {\n const response = anthropicMessage(\n await send(\"messages\", { ...decisionRequest, messages }, false)\n );\n if (response.stopReason === \"max_tokens\")\n throw new Error(\"Anthropic response reached max_tokens; raise maxTokens\");\n if (response.stopReason === \"refusal\") throw new Error(\"Anthropic refused the request\");\n if (response.stopReason !== \"tool_use\" && response.stopReason !== \"end_turn\")\n throw new Error(`Anthropic stopped unexpectedly (${response.stopReason})`);\n if (response.content.length === 0) throw new Error(\"Anthropic returned empty content\");\n // Keep every block, including thinking and signatures, exactly as returned.\n messages = [...messages, { role: \"assistant\", content: response.content }];\n const decision = anthropicDecision(response.content);\n if (decision) return { decision, conversation: messages };\n if (attempt > 0) throw new Error(\"Anthropic returned no tool calls\");\n messages = [...messages, { role: \"user\", content: TOOL_RULE }];\n }\n };\n}\n\n/** Pair each pending `_finish` call with a tool_result so the next user prompt is valid. */\nfunction closeFinishedTools(messages: readonly unknown[]): unknown[] {\n const last = messages.at(-1);\n if (!record(last) || last.role !== \"assistant\" || !Array.isArray(last.content))\n return [...messages];\n const uses = last.content.filter((block) => record(block) && block.type === \"tool_use\");\n if (uses.length === 0) return [...messages];\n if (uses.some((block) => block.name !== \"_finish\"))\n throw new Error(\"Anthropic conversation has unfinished tool calls\");\n return [\n ...messages,\n {\n role: \"user\",\n content: uses.map((block) => ({\n type: \"tool_result\",\n tool_use_id: block.id,\n content: JSON.stringify(\n record(block.input) && Object.hasOwn(block.input, \"result\")\n ? block.input.result\n : block.input\n ),\n })),\n },\n ];\n}\n\n/** Add a user prompt, extending a trailing user message so roles keep alternating. */\nfunction appendUserText(messages: readonly unknown[], text: string): unknown[] {\n const last = messages.at(-1);\n if (record(last) && last.role === \"user\") {\n const content = Array.isArray(last.content)\n ? [...last.content, { type: \"text\", text }]\n : [\n { type: \"text\", text: last.content },\n { type: \"text\", text },\n ];\n return [...messages.slice(0, -1), { role: \"user\", content }];\n }\n return [...messages, { role: \"user\", content: text }];\n}\n\nfunction credentials(\n apiKey: string | undefined,\n authToken: string | undefined\n): Record<string, string> {\n if (authToken !== undefined) return { Authorization: `Bearer ${authToken.trim()}` };\n const key = (apiKey ?? process.env.ANTHROPIC_API_KEY)?.trim();\n if (key) return { \"x-api-key\": key };\n const token = process.env.ANTHROPIC_AUTH_TOKEN?.trim();\n if (token) return { Authorization: `Bearer ${token}` };\n throw new Error(\"ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is required for live model execution\");\n}\n"]}
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/agent/anthropic.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAsCvD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AACrD,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC1D,MAAM,SAAS,GACb,6GAA6G,CAAC;AAChH,MAAM,oBAAoB,GACxB,sOAAsO,CAAC;AACzO,+DAA+D;AAC/D,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC,sGAAsG;AACtG,MAAM,UAAU,cAAc,CA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model-types.js\";\nimport {\n anthropicDecision,\n anthropicMessage,\n anthropicTool,\n carriesCompaction,\n COMPACTION_BETA,\n} from \"./anthropic-protocol.js\";\nimport { MAX_REQUEST_BYTES, providerBaseUrl, providerRequest } from \"./provider-http.js\";\nimport { record } from \"./provider-schema.js\";\nimport { boundedToolOutputs } from \"./provider-tool-outputs.js\";\nimport { throwIfAborted } from \"../utilities/abort.js\";\n\n/** Messages API transport settings; credentials are resolved only when a decision executes. */\nexport interface AnthropicModelOptions {\n /** Defaults to ANTHROPIC_MODEL or claude-opus-5-5. Must support tool use. */\n readonly model?: string;\n /**\n * Sent as x-api-key. Without an explicit apiKey or authToken, ANTHROPIC_API_KEY is\n * used at execution time, then ANTHROPIC_AUTH_TOKEN.\n */\n readonly apiKey?: string;\n /** Sent as Authorization: Bearer, for compatible servers and gateways that expect it. */\n readonly authToken?: string;\n /**\n * API root without the version path. Defaults to ANTHROPIC_BASE_URL or\n * https://api.anthropic.com; set it for any server that implements the Messages API.\n */\n readonly baseUrl?: string;\n /** Sent as output_config.effort. Omitted by default; null also omits it. */\n readonly reasoningEffort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | null;\n /** Output cap for each request, including thinking; defaults to 32000 tokens. */\n readonly maxTokens?: number;\n /**\n * Send tools with strict: true (default). Unsupported constraints move into descriptions;\n * the harness still validates every argument. Disable for servers without strict tool use.\n */\n readonly strict?: boolean;\n /** Send top-level cache_control (default). Disable for servers that reject it. */\n readonly promptCaching?: boolean;\n /**\n * Compact above this history size (default 65536 bytes), or when the complete decision\n * exceeds the request limit. null never requests on-demand compaction.\n */\n readonly compactAfterBytes?: number | null;\n /** Combined deadline for compaction and decision requests; defaults to 600000 ms. */\n readonly timeoutMs?: number;\n}\n\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\nconst EFFORTS = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\nconst TOOL_RULE =\n \"Respond only by calling tools. Call _finish alone with the final answer. Never mix _finish with tool calls.\";\nconst SUMMARY_INSTRUCTIONS =\n \"Summarize this agent conversation so the agent can continue the task. Preserve the task, decisions, file paths, commands run, verified results, failures, and remaining work. Do not call tools; respond with the summary text only.\";\n// `{\"role\":\"user\",\"content\":[]}` plus a separator, rounded up.\nconst RESULT_MESSAGE_BYTES = 64;\n\n/** Create a dependency-free Anthropic Messages model with native history and on-demand compaction. */\nexport function anthropicModel(options: AnthropicModelOptions = {}): AgentModel {\n const {\n model,\n apiKey,\n authToken,\n baseUrl,\n reasoningEffort = null,\n maxTokens = 32_000,\n strict = true,\n promptCaching = true,\n compactAfterBytes = 65_536,\n timeoutMs = 600_000,\n } = options;\n if (\n (compactAfterBytes !== null &&\n (!Number.isSafeInteger(compactAfterBytes) ||\n compactAfterBytes < 1 ||\n compactAfterBytes >= MAX_REQUEST_BYTES)) ||\n !Number.isSafeInteger(maxTokens) ||\n maxTokens < 1 ||\n !Number.isSafeInteger(timeoutMs) ||\n timeoutMs < 1 ||\n timeoutMs > 2_147_483_647 ||\n typeof strict !== \"boolean\" ||\n typeof promptCaching !== \"boolean\" ||\n (apiKey !== undefined && authToken !== undefined) ||\n (authToken !== undefined && (typeof authToken !== \"string\" || !authToken.trim())) ||\n (model !== undefined && (typeof model !== \"string\" || !model.trim())) ||\n (apiKey !== undefined && (typeof apiKey !== \"string\" || !apiKey.trim())) ||\n (baseUrl !== undefined && typeof baseUrl !== \"string\") ||\n (reasoningEffort !== null && !EFFORTS.includes(reasoningEffort))\n )\n throw new Error(\"Invalid Anthropic model configuration\");\n if (baseUrl !== undefined) providerBaseUrl(\"Anthropic\", baseUrl);\n const decide: AgentModel = async (request, context) => {\n const selectedModel = (model ?? process.env.ANTHROPIC_MODEL)?.trim() || \"claude-opus-5-5\";\n const timeout = AbortSignal.timeout(timeoutMs);\n const signal = context.signal ? AbortSignal.any([context.signal, timeout]) : timeout;\n const base = providerBaseUrl(\n \"Anthropic\",\n baseUrl ?? (process.env.ANTHROPIC_BASE_URL?.trim() || DEFAULT_BASE_URL)\n );\n throwIfAborted(signal, \"Anthropic decision\");\n // Validate descriptors before either compaction or a decision can perform I/O.\n const tools = anthropicTools(context, strict);\n if (\n request.conversation !== null &&\n (!Array.isArray(request.conversation) || !request.conversation.every(record))\n )\n throw new Error(\"Invalid Anthropic conversation state\");\n // A restored session starts a new prompt with no tool outcomes. Close _finish\n // before appending that prompt; the Messages API rejects a second user message.\n const newPrompt = context.turn === 1 && request.outcomes.length === 0;\n let messages: unknown[] =\n request.conversation === null\n ? []\n : newPrompt\n ? closeFinishedTools(request.conversation)\n : [...request.conversation];\n const withPrompt = (history: readonly unknown[]) =>\n newPrompt ? appendUserText(history, request.task) : [...history];\n const send = (endpointLabel: string, payload: { messages: unknown[] }, beta: boolean) =>\n providerRequest(\n \"Anthropic\",\n endpointLabel,\n `${base}/v1/messages`,\n {\n ...credentials(apiKey, authToken),\n \"anthropic-version\": \"2023-06-01\",\n ...(beta || carriesCompaction(payload.messages)\n ? { \"anthropic-beta\": COMPACTION_BETA }\n : {}),\n },\n payload,\n signal\n );\n const system = `${request.instructions}\\n\\n${TOOL_RULE}`;\n // Summaries read the same system prompt and tools as the conversation.\n const compactRequest = {\n model: selectedModel,\n max_tokens: maxTokens,\n system,\n tools,\n compaction: { type: \"summarize\", instructions: SUMMARY_INSTRUCTIONS },\n messages,\n };\n const decisionRequest = {\n model: selectedModel,\n max_tokens: maxTokens,\n ...(reasoningEffort === null ? {} : { output_config: { effort: reasoningEffort } }),\n ...(promptCaching ? { cache_control: { type: \"ephemeral\" } } : {}),\n system,\n tools,\n // Current models reject forced tool choice; the system rule and retry below steer instead.\n tool_choice: { type: \"auto\" },\n messages,\n };\n const results = (availableBytes: number) =>\n request.outcomes.length === 0\n ? []\n : [\n {\n role: \"user\",\n content: boundedToolOutputs(\n \"Anthropic\",\n request.outcomes,\n availableBytes - RESULT_MESSAGE_BYTES,\n (outcome, output) => ({\n type: \"tool_result\",\n tool_use_id: outcome.id,\n content: output,\n ...(outcome.ok ? {} : { is_error: true }),\n })\n ),\n },\n ];\n const history = [...messages, ...results(MAX_REQUEST_BYTES)];\n const completed = withPrompt(history);\n const shouldCompact =\n compactAfterBytes !== null &&\n (request.outcomes.length > 0 || (newPrompt && request.conversation !== null)) &&\n (Buffer.byteLength(JSON.stringify(completed)) > compactAfterBytes ||\n Buffer.byteLength(JSON.stringify({ ...decisionRequest, messages: completed })) >\n MAX_REQUEST_BYTES);\n // Compaction covers completed history only. The new prompt stays verbatim.\n const nextRequest = shouldCompact ? compactRequest : decisionRequest;\n const payload = shouldCompact ? history : completed;\n const fits =\n Buffer.byteLength(JSON.stringify({ ...nextRequest, messages: payload })) <= MAX_REQUEST_BYTES;\n messages = fits\n ? payload\n : [\n ...messages,\n ...results(MAX_REQUEST_BYTES - Buffer.byteLength(JSON.stringify(nextRequest))),\n ];\n if (shouldCompact) {\n const summary = anthropicMessage(\n await send(\"compaction\", { ...compactRequest, messages }, true)\n );\n const [block] = summary.content;\n if (\n summary.stopReason === \"compaction\" &&\n summary.content.length === 1 &&\n block?.type === \"compaction\" &&\n typeof block.content === \"string\" &&\n typeof block.signature === \"string\"\n ) {\n // The returned assistant message replaces every message it covered, unchanged.\n // The summarized history ended with tool results, so a user turn must follow it.\n messages = [\n { role: \"assistant\", content: [block] },\n { role: \"user\", content: \"Continue the task from this summary.\" },\n ];\n context.log.log(\"Compacted agent conversation\");\n } else {\n context.log.log(`Anthropic compaction returned no summary (${summary.stopReason})`);\n }\n }\n if (newPrompt && (shouldCompact || !fits)) messages = withPrompt(messages);\n for (let attempt = 0; ; attempt++) {\n const response = anthropicMessage(\n await send(\"messages\", { ...decisionRequest, messages }, false)\n );\n if (response.stopReason === \"max_tokens\")\n throw new Error(\"Anthropic response reached max_tokens; raise maxTokens\");\n if (response.stopReason === \"refusal\") throw new Error(\"Anthropic refused the request\");\n if (response.stopReason !== \"tool_use\" && response.stopReason !== \"end_turn\")\n throw new Error(`Anthropic stopped unexpectedly (${response.stopReason})`);\n if (response.content.length === 0) throw new Error(\"Anthropic returned empty content\");\n // Keep every block, including thinking and signatures, exactly as returned.\n messages = [...messages, { role: \"assistant\", content: response.content }];\n const decision = anthropicDecision(response.content);\n if (decision) return { decision, conversation: messages };\n if (attempt > 0) throw new Error(\"Anthropic returned no tool calls\");\n messages = [...messages, { role: \"user\", content: TOOL_RULE }];\n }\n };\n return Object.assign(decide, {\n checkDescriptors: (descriptors: AgentModelDescriptors) =>\n void anthropicTools(descriptors, strict),\n });\n}\n\n// Strict mode accepts at most this many strict tools per request, including _finish.\nconst MAX_STRICT_TOOLS = 20;\n\n/** Messages API tools for these descriptors, plus the adapter-only `_finish` tool. */\nfunction anthropicTools(\n { capabilities, resultJsonSchema }: AgentModelDescriptors,\n strict: boolean\n) {\n if (strict && capabilities.length + 1 > MAX_STRICT_TOOLS)\n throw new Error(\n `Anthropic strict mode allows at most ${MAX_STRICT_TOOLS} tools per request, including _finish; this agent has ${capabilities.length + 1}. Set strict: false, or advertise fewer tools with defaultTools, allowlists or codemode`\n );\n return [\n ...capabilities.map((tool) =>\n anthropicTool(tool.name, tool.description, \"input\", tool.inputJsonSchema, strict)\n ),\n anthropicTool(\"_finish\", \"Finish with the final answer.\", \"result\", resultJsonSchema, strict),\n ];\n}\n\n/** Pair each pending `_finish` call with a tool_result so the next user prompt is valid. */\nfunction closeFinishedTools(messages: readonly unknown[]): unknown[] {\n const last = messages.at(-1);\n if (!record(last) || last.role !== \"assistant\" || !Array.isArray(last.content))\n return [...messages];\n const uses = last.content.filter((block) => record(block) && block.type === \"tool_use\");\n if (uses.length === 0) return [...messages];\n if (uses.some((block) => block.name !== \"_finish\"))\n throw new Error(\"Anthropic conversation has unfinished tool calls\");\n return [\n ...messages,\n {\n role: \"user\",\n content: uses.map((block) => ({\n type: \"tool_result\",\n tool_use_id: block.id,\n content: JSON.stringify(\n record(block.input) && Object.hasOwn(block.input, \"result\")\n ? block.input.result\n : block.input\n ),\n })),\n },\n ];\n}\n\n/** Add a user prompt, extending a trailing user message so roles keep alternating. */\nfunction appendUserText(messages: readonly unknown[], text: string): unknown[] {\n const last = messages.at(-1);\n if (record(last) && last.role === \"user\") {\n const content = Array.isArray(last.content)\n ? [...last.content, { type: \"text\", text }]\n : [\n { type: \"text\", text: last.content },\n { type: \"text\", text },\n ];\n return [...messages.slice(0, -1), { role: \"user\", content }];\n }\n return [...messages, { role: \"user\", content: text }];\n}\n\nfunction credentials(\n apiKey: string | undefined,\n authToken: string | undefined\n): Record<string, string> {\n if (authToken !== undefined) return { Authorization: `Bearer ${authToken.trim()}` };\n const key = (apiKey ?? process.env.ANTHROPIC_API_KEY)?.trim();\n if (key) return { \"x-api-key\": key };\n const token = process.env.ANTHROPIC_AUTH_TOKEN?.trim();\n if (token) return { Authorization: `Bearer ${token}` };\n throw new Error(\"ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is required for live model execution\");\n}\n"]}
@@ -59,6 +59,9 @@ export type SavedAgent = AgentSnapshot & ({
59
59
  } | {
60
60
  phase: "completed";
61
61
  result: unknown;
62
+ completedState?: {
63
+ state: unknown;
64
+ };
62
65
  decision?: never;
63
66
  failure?: never;
64
67
  } | {
@@ -62,6 +62,10 @@ function checkAgent(agent) {
62
62
  throw new Error("Invalid saved agent execution");
63
63
  if (agent.phase === "completed" && !Object.hasOwn(agent, "result"))
64
64
  throw new Error("Missing saved agent result");
65
+ if (agent.phase === "completed" &&
66
+ agent.completedState !== undefined &&
67
+ (!record(agent.completedState) || !Object.hasOwn(agent.completedState, "state")))
68
+ throw new Error("Invalid saved completed state");
65
69
  if (agent.phase === "failed" && !failure(agent.failure))
66
70
  throw new Error("Invalid saved agent failure");
67
71
  if (agent.phase === "calls") {
@@ -1 +1 @@
1
- {"version":3,"file":"checkpoint-format.js","sourceRoot":"","sources":["../../src/agent/checkpoint-format.ts"],"names":[],"mappings":"AAuDA,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,CACL,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QAC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AC","sourcesContent":["import type { AgentLimits, AgentOutcome, Tools } from \"./agent-types.js\";\n\nexport interface StoredBudget {\n depth: number;\n limits: Required<AgentLimits>;\n maxCalls: number;\n maxDecisions: number;\n}\nexport type CallOutcome = AgentOutcome<Tools>;\nexport type SavedCall = {\n id: string;\n tool: string;\n replay: \"safe\" | \"unsafe\";\n} & (\n | { kind: \"handler\"; input: unknown; validatedOptions?: never }\n | { kind: \"pipeline\"; input: object; validatedOptions: object }\n) &\n (\n | { status: \"pending\" | \"running\"; outcome?: never }\n | { status: \"completed\"; outcome: CallOutcome }\n );\nexport interface SavedDecision {\n state: unknown;\n calls: SavedCall[];\n admitted: boolean;\n}\ninterface AgentSnapshot {\n metadata: {\n definition: string;\n implementationVersion?: string;\n options: object;\n environment: string;\n cwd: string;\n cache: \"use\" | \"recompute\" | \"bypass\";\n };\n execution: { state: unknown; turn: number; stateVersion: number; calls: number };\n}\nexport type SavedAgent = AgentSnapshot &\n (\n | { phase: \"decide\"; decision?: never; result?: never; failure?: never }\n | { phase: \"calls\"; decision: SavedDecision; result?: never; failure?: never }\n | { phase: \"completed\"; result: unknown; decision?: never; failure?: never }\n | {\n phase: \"failed\";\n failure: { code: string; message: string };\n decision?: never;\n result?: never;\n }\n );\nexport interface Checkpoint {\n version: 1;\n agents: Record<string, SavedAgent>;\n budgets: Record<string, StoredBudget>;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n );\n}\nfunction natural(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction options(value: unknown): value is object {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction failure(value: unknown): boolean {\n return record(value) && typeof value.code === \"string\" && typeof value.message === \"string\";\n}\n\nfunction checkCall(call: unknown, admitted: boolean, ids: Set<string>): void {\n if (\n !record(call) ||\n typeof call.id !== \"string\" ||\n !call.id.trim() ||\n call.id.length > 256 ||\n ids.has(call.id) ||\n typeof call.tool !== \"string\" ||\n !/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(call.tool) ||\n ![\"handler\", \"pipeline\"].includes(String(call.kind)) ||\n ![\"safe\", \"unsafe\"].includes(String(call.replay)) ||\n ![\"pending\", \"running\", \"completed\"].includes(String(call.status)) ||\n !Object.hasOwn(call, \"input\")\n )\n throw new Error(\"Invalid saved call\");\n ids.add(call.id);\n if (call.kind === \"pipeline\" && (!options(call.input) || !options(call.validatedOptions)))\n throw new Error(\"Invalid saved pipeline options\");\n if (!admitted && call.status !== \"pending\") throw new Error(\"Unadmitted call has started\");\n if (call.status === \"completed\") {\n const outcome = call.outcome;\n if (\n !record(outcome) ||\n outcome.id !== call.id ||\n outcome.tool !== call.tool ||\n typeof outcome.ok !== \"boolean\" ||\n (outcome.ok ? !Object.hasOwn(outcome, \"value\") : !failure(outcome.error))\n )\n throw new Error(\"Invalid saved call outcome\");\n }\n}\n\nfunction checkAgent(agent: unknown): void {\n if (!record(agent) || !record(agent.metadata) || !record(agent.execution))\n throw new Error(\"Invalid saved agent\");\n const { metadata, execution } = agent;\n if (\n typeof metadata.definition !== \"string\" ||\n typeof metadata.environment !== \"string\" ||\n typeof metadata.cwd !== \"string\" ||\n !options(metadata.options) ||\n (metadata.implementationVersion !== undefined &&\n typeof metadata.implementationVersion !== \"string\") ||\n ![\"use\", \"recompute\", \"bypass\"].includes(String(metadata.cache))\n )\n throw new Error(\"Invalid saved agent metadata\");\n if (\n !Object.hasOwn(execution, \"state\") ||\n !natural(execution.turn) ||\n execution.turn < 1 ||\n !natural(execution.stateVersion) ||\n !natural(execution.calls) ||\n ![\"decide\", \"calls\", \"completed\", \"failed\"].includes(String(agent.phase))\n )\n throw new Error(\"Invalid saved agent execution\");\n if (agent.phase === \"completed\" && !Object.hasOwn(agent, \"result\"))\n throw new Error(\"Missing saved agent result\");\n if (agent.phase === \"failed\" && !failure(agent.failure))\n throw new Error(\"Invalid saved agent failure\");\n if (agent.phase === \"calls\") {\n const decision = agent.decision;\n if (\n !record(decision) ||\n !Object.hasOwn(decision, \"state\") ||\n !Array.isArray(decision.calls) ||\n decision.calls.length === 0 ||\n typeof decision.admitted !== \"boolean\"\n )\n throw new Error(\"Invalid saved call batch\");\n const ids = new Set<string>();\n for (const call of decision.calls) checkCall(call, decision.admitted, ids);\n }\n}\n\nfunction checkBudget(budget: unknown): void {\n if (\n !record(budget) ||\n !natural(budget.depth) ||\n !natural(budget.maxCalls) ||\n !natural(budget.maxDecisions) ||\n !record(budget.limits)\n )\n throw new Error(\"Invalid saved agent budget\");\n for (const name of [\n \"maxTurns\",\n \"maxCalls\",\n \"maxDecisions\",\n \"maxDepth\",\n \"maxConcurrency\",\n ] as const) {\n const bound = budget.limits[name];\n if (!natural(bound) || (![\"maxCalls\", \"maxDepth\"].includes(name) && bound === 0))\n throw new Error(\"Invalid saved agent limits\");\n }\n if (\n budget.maxCalls > Number(budget.limits.maxCalls) ||\n budget.maxDecisions > Number(budget.limits.maxDecisions)\n )\n throw new Error(\"Saved agent budget exceeds its limits\");\n}\n\n/** Validate receipts and counters before treating decoded storage as prepared work. */\nexport function checkedCheckpoint(value: unknown): Checkpoint {\n if (!record(value) || value.version !== 1 || !record(value.agents) || !record(value.budgets))\n throw new Error(\"Invalid agent checkpoint envelope\");\n for (const [key, agent] of Object.entries(value.agents)) {\n checkAgent(agent);\n if (!Object.hasOwn(value.budgets, key)) throw new Error(\"Missing saved agent budget\");\n }\n for (const budget of Object.values(value.budgets)) checkBudget(budget);\n // SAFETY: metadata, execution counters, call receipts and budget contracts were checked above.\n return value as unknown as Checkpoint;\n}\n"]}
1
+ {"version":3,"file":"checkpoint-format.js","sourceRoot":"","sources":["../../src/agent/checkpoint-format.ts"],"names":[],"mappings":"AA6DA,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,CACL,KAAK,KAAK,IAAI;QACd,OAAO,KAAK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CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC;QAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACvE,+FAA+F;IAC/F,OAAO,KAA8B,CAAC;AACxC,CAAC","sourcesContent":["import type { AgentLimits, AgentOutcome, Tools } from \"./agent-types.js\";\n\nexport interface StoredBudget {\n depth: number;\n limits: Required<AgentLimits>;\n maxCalls: number;\n maxDecisions: number;\n}\nexport type CallOutcome = AgentOutcome<Tools>;\nexport type SavedCall = {\n id: string;\n tool: string;\n replay: \"safe\" | \"unsafe\";\n} & (\n | { kind: \"handler\"; input: unknown; validatedOptions?: never }\n | { kind: \"pipeline\"; input: object; validatedOptions: object }\n) &\n (\n | { status: \"pending\" | \"running\"; outcome?: never }\n | { status: \"completed\"; outcome: CallOutcome }\n );\nexport interface SavedDecision {\n state: unknown;\n calls: SavedCall[];\n admitted: boolean;\n}\ninterface AgentSnapshot {\n metadata: {\n definition: string;\n implementationVersion?: string;\n options: object;\n environment: string;\n cwd: string;\n cache: \"use\" | \"recompute\" | \"bypass\";\n };\n execution: { state: unknown; turn: number; stateVersion: number; calls: number };\n}\nexport type SavedAgent = AgentSnapshot &\n (\n | { phase: \"decide\"; decision?: never; result?: never; failure?: never }\n | { phase: \"calls\"; decision: SavedDecision; result?: never; failure?: never }\n | {\n phase: \"completed\";\n result: unknown;\n completedState?: { state: unknown };\n decision?: never;\n failure?: never;\n }\n | {\n phase: \"failed\";\n failure: { code: string; message: string };\n decision?: never;\n result?: never;\n }\n );\nexport interface Checkpoint {\n version: 1;\n agents: Record<string, SavedAgent>;\n budgets: Record<string, StoredBudget>;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n );\n}\nfunction natural(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction options(value: unknown): value is object {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction failure(value: unknown): boolean {\n return record(value) && typeof value.code === \"string\" && typeof value.message === \"string\";\n}\n\nfunction checkCall(call: unknown, admitted: boolean, ids: Set<string>): void {\n if (\n !record(call) ||\n typeof call.id !== \"string\" ||\n !call.id.trim() ||\n call.id.length > 256 ||\n ids.has(call.id) ||\n typeof call.tool !== \"string\" ||\n !/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(call.tool) ||\n ![\"handler\", \"pipeline\"].includes(String(call.kind)) ||\n ![\"safe\", \"unsafe\"].includes(String(call.replay)) ||\n ![\"pending\", \"running\", \"completed\"].includes(String(call.status)) ||\n !Object.hasOwn(call, \"input\")\n )\n throw new Error(\"Invalid saved call\");\n ids.add(call.id);\n if (call.kind === \"pipeline\" && (!options(call.input) || !options(call.validatedOptions)))\n throw new Error(\"Invalid saved pipeline options\");\n if (!admitted && call.status !== \"pending\") throw new Error(\"Unadmitted call has started\");\n if (call.status === \"completed\") {\n const outcome = call.outcome;\n if (\n !record(outcome) ||\n outcome.id !== call.id ||\n outcome.tool !== call.tool ||\n typeof outcome.ok !== \"boolean\" ||\n (outcome.ok ? !Object.hasOwn(outcome, \"value\") : !failure(outcome.error))\n )\n throw new Error(\"Invalid saved call outcome\");\n }\n}\n\nfunction checkAgent(agent: unknown): void {\n if (!record(agent) || !record(agent.metadata) || !record(agent.execution))\n throw new Error(\"Invalid saved agent\");\n const { metadata, execution } = agent;\n if (\n typeof metadata.definition !== \"string\" ||\n typeof metadata.environment !== \"string\" ||\n typeof metadata.cwd !== \"string\" ||\n !options(metadata.options) ||\n (metadata.implementationVersion !== undefined &&\n typeof metadata.implementationVersion !== \"string\") ||\n ![\"use\", \"recompute\", \"bypass\"].includes(String(metadata.cache))\n )\n throw new Error(\"Invalid saved agent metadata\");\n if (\n !Object.hasOwn(execution, \"state\") ||\n !natural(execution.turn) ||\n execution.turn < 1 ||\n !natural(execution.stateVersion) ||\n !natural(execution.calls) ||\n ![\"decide\", \"calls\", \"completed\", \"failed\"].includes(String(agent.phase))\n )\n throw new Error(\"Invalid saved agent execution\");\n if (agent.phase === \"completed\" && !Object.hasOwn(agent, \"result\"))\n throw new Error(\"Missing saved agent result\");\n if (\n agent.phase === \"completed\" &&\n agent.completedState !== undefined &&\n (!record(agent.completedState) || !Object.hasOwn(agent.completedState, \"state\"))\n )\n throw new Error(\"Invalid saved completed state\");\n if (agent.phase === \"failed\" && !failure(agent.failure))\n throw new Error(\"Invalid saved agent failure\");\n if (agent.phase === \"calls\") {\n const decision = agent.decision;\n if (\n !record(decision) ||\n !Object.hasOwn(decision, \"state\") ||\n !Array.isArray(decision.calls) ||\n decision.calls.length === 0 ||\n typeof decision.admitted !== \"boolean\"\n )\n throw new Error(\"Invalid saved call batch\");\n const ids = new Set<string>();\n for (const call of decision.calls) checkCall(call, decision.admitted, ids);\n }\n}\n\nfunction checkBudget(budget: unknown): void {\n if (\n !record(budget) ||\n !natural(budget.depth) ||\n !natural(budget.maxCalls) ||\n !natural(budget.maxDecisions) ||\n !record(budget.limits)\n )\n throw new Error(\"Invalid saved agent budget\");\n for (const name of [\n \"maxTurns\",\n \"maxCalls\",\n \"maxDecisions\",\n \"maxDepth\",\n \"maxConcurrency\",\n ] as const) {\n const bound = budget.limits[name];\n if (!natural(bound) || (![\"maxCalls\", \"maxDepth\"].includes(name) && bound === 0))\n throw new Error(\"Invalid saved agent limits\");\n }\n if (\n budget.maxCalls > Number(budget.limits.maxCalls) ||\n budget.maxDecisions > Number(budget.limits.maxDecisions)\n )\n throw new Error(\"Saved agent budget exceeds its limits\");\n}\n\n/** Validate receipts and counters before treating decoded storage as prepared work. */\nexport function checkedCheckpoint(value: unknown): Checkpoint {\n if (!record(value) || value.version !== 1 || !record(value.agents) || !record(value.budgets))\n throw new Error(\"Invalid agent checkpoint envelope\");\n for (const [key, agent] of Object.entries(value.agents)) {\n checkAgent(agent);\n if (!Object.hasOwn(value.budgets, key)) throw new Error(\"Missing saved agent budget\");\n }\n for (const budget of Object.values(value.budgets)) checkBudget(budget);\n // SAFETY: metadata, execution counters, call receipts and budget contracts were checked above.\n return value as unknown as Checkpoint;\n}\n"]}
@@ -31,7 +31,9 @@ export declare class AgentCheckpointSession {
31
31
  completeCall(key: string, id: string, outcome: CallOutcome): Promise<void>;
32
32
  private changeCall;
33
33
  advance(key: string, execution: SavedAgent["execution"]): Promise<void>;
34
- finish(key: string, result: unknown): Promise<void>;
34
+ finish(key: string, result: unknown, completedState: {
35
+ state: unknown;
36
+ }): Promise<void>;
35
37
  fail(key: string, error: unknown, signal?: AbortSignal): Promise<void>;
36
38
  private update;
37
39
  close(): Promise<void>;
@@ -164,7 +164,7 @@ export class AgentCheckpointSession {
164
164
  checkpoint.agents[key] = { metadata: saved.metadata, execution, phase: "decide" };
165
165
  });
166
166
  }
167
- finish(key, result) {
167
+ finish(key, result, completedState) {
168
168
  return this.update((checkpoint) => {
169
169
  const saved = checkpoint.agents[key];
170
170
  if (!saved || saved.phase !== "decide")
@@ -174,6 +174,7 @@ export class AgentCheckpointSession {
174
174
  execution: saved.execution,
175
175
  phase: "completed",
176
176
  result,
177
+ completedState,
177
178
  };
178
179
  });
179
180
  }