@alvin0/ai-agent-sdk-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (623) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -0
  3. package/dist/agent/accounting/common.js +2 -0
  4. package/dist/agent/accounting/common.js.map +1 -0
  5. package/dist/agent/accounting/config.js +2 -0
  6. package/dist/agent/accounting/config.js.map +1 -0
  7. package/dist/agent/accounting/contracts.d.ts +36 -0
  8. package/dist/agent/accounting/contracts.d.ts.map +1 -0
  9. package/dist/agent/accounting/delivery/accounting-data.js +2 -0
  10. package/dist/agent/accounting/delivery/accounting-data.js.map +1 -0
  11. package/dist/agent/accounting/delivery/config.js +2 -0
  12. package/dist/agent/accounting/delivery/config.js.map +1 -0
  13. package/dist/agent/accounting/delivery/data.js +2 -0
  14. package/dist/agent/accounting/delivery/data.js.map +1 -0
  15. package/dist/agent/accounting/delivery/support-errors.js +2 -0
  16. package/dist/agent/accounting/delivery/support-errors.js.map +1 -0
  17. package/dist/agent/accounting/delivery/terminal.js +2 -0
  18. package/dist/agent/accounting/delivery/terminal.js.map +1 -0
  19. package/dist/agent/accounting/delivery-types.d.ts +43 -0
  20. package/dist/agent/accounting/delivery-types.d.ts.map +1 -0
  21. package/dist/agent/accounting/error.d.ts +18 -0
  22. package/dist/agent/accounting/error.d.ts.map +1 -0
  23. package/dist/agent/accounting/error.js +2 -0
  24. package/dist/agent/accounting/error.js.map +1 -0
  25. package/dist/agent/accounting/estimate.js +2 -0
  26. package/dist/agent/accounting/estimate.js.map +1 -0
  27. package/dist/agent/accounting/event-buffer.js +2 -0
  28. package/dist/agent/accounting/event-buffer.js.map +1 -0
  29. package/dist/agent/accounting/ledger.js +2 -0
  30. package/dist/agent/accounting/ledger.js.map +1 -0
  31. package/dist/agent/accounting/report.d.ts +70 -0
  32. package/dist/agent/accounting/report.d.ts.map +1 -0
  33. package/dist/agent/accounting/usage.d.ts +13 -0
  34. package/dist/agent/accounting/usage.d.ts.map +1 -0
  35. package/dist/agent/accounting/usage.js +2 -0
  36. package/dist/agent/accounting/usage.js.map +1 -0
  37. package/dist/agent/context/section.d.ts +15 -0
  38. package/dist/agent/context/section.d.ts.map +1 -0
  39. package/dist/agent/context/section.js +2 -0
  40. package/dist/agent/context/section.js.map +1 -0
  41. package/dist/agent/context/types.d.ts +98 -0
  42. package/dist/agent/context/types.d.ts.map +1 -0
  43. package/dist/agent/define/definition.d.ts +110 -0
  44. package/dist/agent/define/definition.d.ts.map +1 -0
  45. package/dist/agent/define/definition.js +2 -0
  46. package/dist/agent/define/definition.js.map +1 -0
  47. package/dist/agent/define/instructions.js +2 -0
  48. package/dist/agent/define/instructions.js.map +1 -0
  49. package/dist/agent/define/output-format.js +2 -0
  50. package/dist/agent/define/output-format.js.map +1 -0
  51. package/dist/agent/define/session/accounting.js +2 -0
  52. package/dist/agent/define/session/accounting.js.map +1 -0
  53. package/dist/agent/define/session/common.js +2 -0
  54. package/dist/agent/define/session/common.js.map +1 -0
  55. package/dist/agent/define/session/config.js +2 -0
  56. package/dist/agent/define/session/config.js.map +1 -0
  57. package/dist/agent/define/session/model-config.js +2 -0
  58. package/dist/agent/define/session/model-config.js.map +1 -0
  59. package/dist/agent/define/session/observer.js +2 -0
  60. package/dist/agent/define/session/observer.js.map +1 -0
  61. package/dist/agent/define/session/run-seal.js +2 -0
  62. package/dist/agent/define/session/run-seal.js.map +1 -0
  63. package/dist/agent/define/session/runtime-binding.js +2 -0
  64. package/dist/agent/define/session/runtime-binding.js.map +1 -0
  65. package/dist/agent/define/session/runtime-compaction.js +2 -0
  66. package/dist/agent/define/session/runtime-compaction.js.map +1 -0
  67. package/dist/agent/define/session/runtime-memory.js +2 -0
  68. package/dist/agent/define/session/runtime-memory.js.map +1 -0
  69. package/dist/agent/define/session/skills.js +2 -0
  70. package/dist/agent/define/session/skills.js.map +1 -0
  71. package/dist/agent/define/session/trace-accounting.js +2 -0
  72. package/dist/agent/define/session/trace-accounting.js.map +1 -0
  73. package/dist/agent/define/session/types.d.ts +217 -0
  74. package/dist/agent/define/session/types.d.ts.map +1 -0
  75. package/dist/agent/define/session/validation.js +2 -0
  76. package/dist/agent/define/session/validation.js.map +1 -0
  77. package/dist/agent/define/session.d.ts +77 -0
  78. package/dist/agent/define/session.d.ts.map +1 -0
  79. package/dist/agent/define/session.js +2 -0
  80. package/dist/agent/define/session.js.map +1 -0
  81. package/dist/agent/history/config.js +2 -0
  82. package/dist/agent/history/config.js.map +1 -0
  83. package/dist/agent/history/history.d.ts +33 -0
  84. package/dist/agent/history/history.d.ts.map +1 -0
  85. package/dist/agent/history/history.js +2 -0
  86. package/dist/agent/history/history.js.map +1 -0
  87. package/dist/agent/history/normalize.d.ts +7 -0
  88. package/dist/agent/history/normalize.d.ts.map +1 -0
  89. package/dist/agent/history/normalize.js +2 -0
  90. package/dist/agent/history/normalize.js.map +1 -0
  91. package/dist/agent/history/project.d.ts +14 -0
  92. package/dist/agent/history/project.d.ts.map +1 -0
  93. package/dist/agent/history/project.js +2 -0
  94. package/dist/agent/history/project.js.map +1 -0
  95. package/dist/agent/history/types.d.ts +85 -0
  96. package/dist/agent/history/types.d.ts.map +1 -0
  97. package/dist/agent/history/validation.js +2 -0
  98. package/dist/agent/history/validation.js.map +1 -0
  99. package/dist/agent/loop/events.d.ts +213 -0
  100. package/dist/agent/loop/events.d.ts.map +1 -0
  101. package/dist/agent/loop/queue.js +2 -0
  102. package/dist/agent/loop/queue.js.map +1 -0
  103. package/dist/agent/loop/run-turn.d.ts +8 -0
  104. package/dist/agent/loop/run-turn.d.ts.map +1 -0
  105. package/dist/agent/loop/run-turn.js +2 -0
  106. package/dist/agent/loop/run-turn.js.map +1 -0
  107. package/dist/agent/loop/schedule.d.ts +62 -0
  108. package/dist/agent/loop/schedule.d.ts.map +1 -0
  109. package/dist/agent/loop/schedule.js +3 -0
  110. package/dist/agent/loop/schedule.js.map +1 -0
  111. package/dist/agent/loop/turn/cancellation.js +2 -0
  112. package/dist/agent/loop/turn/cancellation.js.map +1 -0
  113. package/dist/agent/loop/turn/common.js +2 -0
  114. package/dist/agent/loop/turn/common.js.map +1 -0
  115. package/dist/agent/loop/turn/config.js +2 -0
  116. package/dist/agent/loop/turn/config.js.map +1 -0
  117. package/dist/agent/loop/turn/content.js +4 -0
  118. package/dist/agent/loop/turn/content.js.map +1 -0
  119. package/dist/agent/loop/turn/hooks.js +2 -0
  120. package/dist/agent/loop/turn/hooks.js.map +1 -0
  121. package/dist/agent/loop/turn/model-round.js +2 -0
  122. package/dist/agent/loop/turn/model-round.js.map +1 -0
  123. package/dist/agent/loop/turn/repetition.js +2 -0
  124. package/dist/agent/loop/turn/repetition.js.map +1 -0
  125. package/dist/agent/loop/turn/types.d.ts +82 -0
  126. package/dist/agent/loop/turn/types.d.ts.map +1 -0
  127. package/dist/agent/loop/turn/usage-stop.js +2 -0
  128. package/dist/agent/loop/turn/usage-stop.js.map +1 -0
  129. package/dist/agent/loop/turn/validation.js +2 -0
  130. package/dist/agent/loop/turn/validation.js.map +1 -0
  131. package/dist/agent/loop/types.d.ts +82 -0
  132. package/dist/agent/loop/types.d.ts.map +1 -0
  133. package/dist/agent/memory/accounting-binding.js +2 -0
  134. package/dist/agent/memory/accounting-binding.js.map +1 -0
  135. package/dist/agent/memory/compaction-config.d.ts +63 -0
  136. package/dist/agent/memory/compaction-config.d.ts.map +1 -0
  137. package/dist/agent/memory/compaction-config.js +2 -0
  138. package/dist/agent/memory/compaction-config.js.map +1 -0
  139. package/dist/agent/memory/compaction.d.ts +62 -0
  140. package/dist/agent/memory/compaction.d.ts.map +1 -0
  141. package/dist/agent/memory/compaction.js +6 -0
  142. package/dist/agent/memory/compaction.js.map +1 -0
  143. package/dist/agent/memory/memory.d.ts +61 -0
  144. package/dist/agent/memory/memory.d.ts.map +1 -0
  145. package/dist/agent/memory/memory.js +5 -0
  146. package/dist/agent/memory/memory.js.map +1 -0
  147. package/dist/agent/memory/persistence-types.d.ts +44 -0
  148. package/dist/agent/memory/persistence-types.d.ts.map +1 -0
  149. package/dist/agent/memory/surface-compaction.d.ts +6 -0
  150. package/dist/agent/memory/surface-compaction.d.ts.map +1 -0
  151. package/dist/agent/memory/surface-compaction.js +4 -0
  152. package/dist/agent/memory/surface-compaction.js.map +1 -0
  153. package/dist/agent/memory/token-estimator.d.ts +12 -0
  154. package/dist/agent/memory/token-estimator.d.ts.map +1 -0
  155. package/dist/agent/memory/token-estimator.js +2 -0
  156. package/dist/agent/memory/token-estimator.js.map +1 -0
  157. package/dist/agent/mode/run-agent.d.ts +79 -0
  158. package/dist/agent/mode/run-agent.d.ts.map +1 -0
  159. package/dist/agent/mode/run-agent.js +4 -0
  160. package/dist/agent/mode/run-agent.js.map +1 -0
  161. package/dist/agent/mode/user-input.d.ts +61 -0
  162. package/dist/agent/mode/user-input.d.ts.map +1 -0
  163. package/dist/agent/mode/user-input.js +2 -0
  164. package/dist/agent/mode/user-input.js.map +1 -0
  165. package/dist/agent/skill/catalog.d.ts +53 -0
  166. package/dist/agent/skill/catalog.d.ts.map +1 -0
  167. package/dist/agent/skill/catalog.js +2 -0
  168. package/dist/agent/skill/catalog.js.map +1 -0
  169. package/dist/agent/skill/definition.d.ts +106 -0
  170. package/dist/agent/skill/definition.d.ts.map +1 -0
  171. package/dist/agent/skill/definition.js +2 -0
  172. package/dist/agent/skill/definition.js.map +1 -0
  173. package/dist/agent/skill/provider/config.d.ts +11 -0
  174. package/dist/agent/skill/provider/config.d.ts.map +1 -0
  175. package/dist/agent/skill/provider/config.js +2 -0
  176. package/dist/agent/skill/provider/config.js.map +1 -0
  177. package/dist/agent/skill/provider/context.js +2 -0
  178. package/dist/agent/skill/provider/context.js.map +1 -0
  179. package/dist/agent/skill/provider/definition.d.ts +6 -0
  180. package/dist/agent/skill/provider/definition.d.ts.map +1 -0
  181. package/dist/agent/skill/provider/definition.js +2 -0
  182. package/dist/agent/skill/provider/definition.js.map +1 -0
  183. package/dist/agent/skill/provider/snapshot.js +2 -0
  184. package/dist/agent/skill/provider/snapshot.js.map +1 -0
  185. package/dist/agent/skill/provider/types.d.ts +49 -0
  186. package/dist/agent/skill/provider/types.d.ts.map +1 -0
  187. package/dist/agent/skill/tools.d.ts +45 -0
  188. package/dist/agent/skill/tools.d.ts.map +1 -0
  189. package/dist/agent/skill/tools.js +14 -0
  190. package/dist/agent/skill/tools.js.map +1 -0
  191. package/dist/agent/team/common.d.ts +26 -0
  192. package/dist/agent/team/common.d.ts.map +1 -0
  193. package/dist/agent/team/common.js +2 -0
  194. package/dist/agent/team/common.js.map +1 -0
  195. package/dist/agent/team/composed.d.ts +45 -0
  196. package/dist/agent/team/composed.d.ts.map +1 -0
  197. package/dist/agent/team/composed.js +2 -0
  198. package/dist/agent/team/composed.js.map +1 -0
  199. package/dist/agent/team/contracts.d.ts +54 -0
  200. package/dist/agent/team/contracts.d.ts.map +1 -0
  201. package/dist/agent/team/managed.d.ts +527 -0
  202. package/dist/agent/team/managed.d.ts.map +1 -0
  203. package/dist/agent/team/managed.js +4 -0
  204. package/dist/agent/team/managed.js.map +1 -0
  205. package/dist/agent/team/team.d.ts +142 -0
  206. package/dist/agent/team/team.d.ts.map +1 -0
  207. package/dist/agent/team/team.js +2 -0
  208. package/dist/agent/team/team.js.map +1 -0
  209. package/dist/agent/team/types.d.ts +170 -0
  210. package/dist/agent/team/types.d.ts.map +1 -0
  211. package/dist/agent/tool/approval.d.ts +106 -0
  212. package/dist/agent/tool/approval.d.ts.map +1 -0
  213. package/dist/agent/tool/approval.js +2 -0
  214. package/dist/agent/tool/approval.js.map +1 -0
  215. package/dist/agent/tool/capture.js +2 -0
  216. package/dist/agent/tool/capture.js.map +1 -0
  217. package/dist/agent/tool/config.js +2 -0
  218. package/dist/agent/tool/config.js.map +1 -0
  219. package/dist/agent/tool/definition.d.ts +227 -0
  220. package/dist/agent/tool/definition.d.ts.map +1 -0
  221. package/dist/agent/tool/definition.js +2 -0
  222. package/dist/agent/tool/definition.js.map +1 -0
  223. package/dist/agent/tool/errors.d.ts +82 -0
  224. package/dist/agent/tool/errors.d.ts.map +1 -0
  225. package/dist/agent/tool/errors.js +2 -0
  226. package/dist/agent/tool/errors.js.map +1 -0
  227. package/dist/agent/tool/execution.d.ts +60 -0
  228. package/dist/agent/tool/execution.d.ts.map +1 -0
  229. package/dist/agent/tool/execution.js +2 -0
  230. package/dist/agent/tool/execution.js.map +1 -0
  231. package/dist/agent/tool/output-budget.d.ts +159 -0
  232. package/dist/agent/tool/output-budget.d.ts.map +1 -0
  233. package/dist/agent/tool/output-budget.js +3 -0
  234. package/dist/agent/tool/output-budget.js.map +1 -0
  235. package/dist/agent/tool/pipeline.d.ts +98 -0
  236. package/dist/agent/tool/pipeline.d.ts.map +1 -0
  237. package/dist/agent/tool/pipeline.js +4 -0
  238. package/dist/agent/tool/pipeline.js.map +1 -0
  239. package/dist/agent/tool/registry.d.ts +70 -0
  240. package/dist/agent/tool/registry.d.ts.map +1 -0
  241. package/dist/agent/tool/registry.js +2 -0
  242. package/dist/agent/tool/registry.js.map +1 -0
  243. package/dist/agent/tool/schema.d.ts +12 -0
  244. package/dist/agent/tool/schema.d.ts.map +1 -0
  245. package/dist/agent/tool/schema.js +2 -0
  246. package/dist/agent/tool/schema.js.map +1 -0
  247. package/dist/agent/tool/source-types.d.ts +25 -0
  248. package/dist/agent/tool/source-types.d.ts.map +1 -0
  249. package/dist/agent/trace/trace.d.ts +63 -0
  250. package/dist/agent/trace/trace.d.ts.map +1 -0
  251. package/dist/agent/trace/trace.js +2 -0
  252. package/dist/agent/trace/trace.js.map +1 -0
  253. package/dist/agent.d.ts +52 -0
  254. package/dist/agent.js +1 -0
  255. package/dist/async/settlement.d.ts +6 -0
  256. package/dist/async/settlement.d.ts.map +1 -0
  257. package/dist/async/settlement.js +2 -0
  258. package/dist/async/settlement.js.map +1 -0
  259. package/dist/capability/common/config.js +2 -0
  260. package/dist/capability/common/config.js.map +1 -0
  261. package/dist/capability/common/data.js +2 -0
  262. package/dist/capability/common/data.js.map +1 -0
  263. package/dist/composition/agent/author.d.ts +12 -0
  264. package/dist/composition/agent/author.d.ts.map +1 -0
  265. package/dist/composition/agent/author.js +2 -0
  266. package/dist/composition/agent/author.js.map +1 -0
  267. package/dist/composition/agent/definition.js +2 -0
  268. package/dist/composition/agent/definition.js.map +1 -0
  269. package/dist/composition/agent/native-event.js +2 -0
  270. package/dist/composition/agent/native-event.js.map +1 -0
  271. package/dist/composition/agent/native-tools.js +2 -0
  272. package/dist/composition/agent/native-tools.js.map +1 -0
  273. package/dist/composition/agent/options.js +2 -0
  274. package/dist/composition/agent/options.js.map +1 -0
  275. package/dist/composition/agent/policy.js +2 -0
  276. package/dist/composition/agent/policy.js.map +1 -0
  277. package/dist/composition/agent/public-message.js +2 -0
  278. package/dist/composition/agent/public-message.js.map +1 -0
  279. package/dist/composition/agent/session.js +2 -0
  280. package/dist/composition/agent/session.js.map +1 -0
  281. package/dist/composition/agent/types.d.ts +218 -0
  282. package/dist/composition/agent/types.d.ts.map +1 -0
  283. package/dist/composition/common/counter.js +2 -0
  284. package/dist/composition/common/counter.js.map +1 -0
  285. package/dist/composition/common/errors.d.ts +15 -0
  286. package/dist/composition/common/errors.d.ts.map +1 -0
  287. package/dist/composition/common/errors.js +2 -0
  288. package/dist/composition/common/errors.js.map +1 -0
  289. package/dist/composition/common/json-data.js +2 -0
  290. package/dist/composition/common/json-data.js.map +1 -0
  291. package/dist/composition/credential/config.d.ts +5 -0
  292. package/dist/composition/credential/config.d.ts.map +1 -0
  293. package/dist/composition/credential/config.js +2 -0
  294. package/dist/composition/credential/config.js.map +1 -0
  295. package/dist/composition/credential/definition.d.ts +9 -0
  296. package/dist/composition/credential/definition.d.ts.map +1 -0
  297. package/dist/composition/credential/definition.js +2 -0
  298. package/dist/composition/credential/definition.js.map +1 -0
  299. package/dist/composition/credential/types.d.ts +38 -0
  300. package/dist/composition/credential/types.d.ts.map +1 -0
  301. package/dist/composition/delivery/ack.js +2 -0
  302. package/dist/composition/delivery/ack.js.map +1 -0
  303. package/dist/composition/delivery/attempt.js +2 -0
  304. package/dist/composition/delivery/attempt.js.map +1 -0
  305. package/dist/composition/delivery/batch.js +2 -0
  306. package/dist/composition/delivery/batch.js.map +1 -0
  307. package/dist/composition/delivery/checkpoint.js +2 -0
  308. package/dist/composition/delivery/checkpoint.js.map +1 -0
  309. package/dist/composition/delivery/event.js +2 -0
  310. package/dist/composition/delivery/event.js.map +1 -0
  311. package/dist/composition/delivery/resource.d.ts +11 -0
  312. package/dist/composition/delivery/resource.d.ts.map +1 -0
  313. package/dist/composition/delivery/resource.js +2 -0
  314. package/dist/composition/delivery/resource.js.map +1 -0
  315. package/dist/composition/delivery/staging.js +2 -0
  316. package/dist/composition/delivery/staging.js.map +1 -0
  317. package/dist/composition/diagnostics/config.js +2 -0
  318. package/dist/composition/diagnostics/config.js.map +1 -0
  319. package/dist/composition/diagnostics/ring.d.ts +12 -0
  320. package/dist/composition/diagnostics/ring.d.ts.map +1 -0
  321. package/dist/composition/diagnostics/ring.js +2 -0
  322. package/dist/composition/diagnostics/ring.js.map +1 -0
  323. package/dist/composition/exporter/definition.d.ts +7 -0
  324. package/dist/composition/exporter/definition.d.ts.map +1 -0
  325. package/dist/composition/exporter/definition.js +2 -0
  326. package/dist/composition/exporter/definition.js.map +1 -0
  327. package/dist/composition/exporter/lifecycle.js +2 -0
  328. package/dist/composition/exporter/lifecycle.js.map +1 -0
  329. package/dist/composition/exporter/preflight.js +2 -0
  330. package/dist/composition/exporter/preflight.js.map +1 -0
  331. package/dist/composition/exporter/types.d.ts +25 -0
  332. package/dist/composition/exporter/types.d.ts.map +1 -0
  333. package/dist/composition/exporter/types.js +2 -0
  334. package/dist/composition/exporter/types.js.map +1 -0
  335. package/dist/composition/identity/agent.js +2 -0
  336. package/dist/composition/identity/agent.js.map +1 -0
  337. package/dist/composition/lifecycle/bounded.js +2 -0
  338. package/dist/composition/lifecycle/bounded.js.map +1 -0
  339. package/dist/composition/lifecycle/operations.js +2 -0
  340. package/dist/composition/lifecycle/operations.js.map +1 -0
  341. package/dist/composition/lifecycle/types.d.ts +13 -0
  342. package/dist/composition/lifecycle/types.d.ts.map +1 -0
  343. package/dist/composition/lifecycle/types.js +2 -0
  344. package/dist/composition/lifecycle/types.js.map +1 -0
  345. package/dist/composition/logging/config.js +2 -0
  346. package/dist/composition/logging/config.js.map +1 -0
  347. package/dist/composition/logging/integration.js +2 -0
  348. package/dist/composition/logging/integration.js.map +1 -0
  349. package/dist/composition/logging/logger.d.ts +9 -0
  350. package/dist/composition/logging/logger.d.ts.map +1 -0
  351. package/dist/composition/logging/logger.js +2 -0
  352. package/dist/composition/logging/logger.js.map +1 -0
  353. package/dist/composition/memory/config.d.ts +10 -0
  354. package/dist/composition/memory/config.d.ts.map +1 -0
  355. package/dist/composition/memory/config.js +2 -0
  356. package/dist/composition/memory/config.js.map +1 -0
  357. package/dist/composition/memory/definition.d.ts +7 -0
  358. package/dist/composition/memory/definition.d.ts.map +1 -0
  359. package/dist/composition/memory/definition.js +2 -0
  360. package/dist/composition/memory/definition.js.map +1 -0
  361. package/dist/composition/memory/key.js +2 -0
  362. package/dist/composition/memory/key.js.map +1 -0
  363. package/dist/composition/memory/resume.js +2 -0
  364. package/dist/composition/memory/resume.js.map +1 -0
  365. package/dist/composition/memory/run.js +2 -0
  366. package/dist/composition/memory/run.js.map +1 -0
  367. package/dist/composition/model-catalog/config.js +2 -0
  368. package/dist/composition/model-catalog/config.js.map +1 -0
  369. package/dist/composition/model-catalog/manager.js +2 -0
  370. package/dist/composition/model-catalog/manager.js.map +1 -0
  371. package/dist/composition/model-catalog/options.js +2 -0
  372. package/dist/composition/model-catalog/options.js.map +1 -0
  373. package/dist/composition/model-catalog/types.d.ts +9 -0
  374. package/dist/composition/model-catalog/types.d.ts.map +1 -0
  375. package/dist/composition/observation/config.js +2 -0
  376. package/dist/composition/observation/config.js.map +1 -0
  377. package/dist/composition/observation/extensions.js +2 -0
  378. package/dist/composition/observation/extensions.js.map +1 -0
  379. package/dist/composition/observation/final-report.d.ts +6 -0
  380. package/dist/composition/observation/final-report.d.ts.map +1 -0
  381. package/dist/composition/observation/final-report.js +2 -0
  382. package/dist/composition/observation/final-report.js.map +1 -0
  383. package/dist/composition/observation/health.d.ts +13 -0
  384. package/dist/composition/observation/health.d.ts.map +1 -0
  385. package/dist/composition/observation/port.d.ts +11 -0
  386. package/dist/composition/observation/port.d.ts.map +1 -0
  387. package/dist/composition/observation/port.js +2 -0
  388. package/dist/composition/observation/port.js.map +1 -0
  389. package/dist/composition/preflight.js +2 -0
  390. package/dist/composition/preflight.js.map +1 -0
  391. package/dist/composition/provider/activation.js +2 -0
  392. package/dist/composition/provider/activation.js.map +1 -0
  393. package/dist/composition/provider/definition.d.ts +7 -0
  394. package/dist/composition/provider/definition.d.ts.map +1 -0
  395. package/dist/composition/provider/definition.js +2 -0
  396. package/dist/composition/provider/definition.js.map +1 -0
  397. package/dist/composition/provider/model-selection.js +2 -0
  398. package/dist/composition/provider/model-selection.js.map +1 -0
  399. package/dist/composition/provider/preflight.js +2 -0
  400. package/dist/composition/provider/preflight.js.map +1 -0
  401. package/dist/composition/provider/types.d.ts +38 -0
  402. package/dist/composition/provider/types.d.ts.map +1 -0
  403. package/dist/composition/provider/types.js +2 -0
  404. package/dist/composition/provider/types.js.map +1 -0
  405. package/dist/composition/queue/config.js +2 -0
  406. package/dist/composition/queue/config.js.map +1 -0
  407. package/dist/composition/queue/scheduler.js +2 -0
  408. package/dist/composition/queue/scheduler.js.map +1 -0
  409. package/dist/composition/queue/store.js +2 -0
  410. package/dist/composition/queue/store.js.map +1 -0
  411. package/dist/composition/runtime/config.js +2 -0
  412. package/dist/composition/runtime/config.js.map +1 -0
  413. package/dist/composition/runtime/owner.js +2 -0
  414. package/dist/composition/runtime/owner.js.map +1 -0
  415. package/dist/composition/runtime/public.d.ts +7 -0
  416. package/dist/composition/runtime/public.d.ts.map +1 -0
  417. package/dist/composition/runtime/public.js +2 -0
  418. package/dist/composition/runtime/public.js.map +1 -0
  419. package/dist/composition/runtime/types.d.ts +76 -0
  420. package/dist/composition/runtime/types.d.ts.map +1 -0
  421. package/dist/composition/startup.js +2 -0
  422. package/dist/composition/startup.js.map +1 -0
  423. package/dist/composition/team/config.js +2 -0
  424. package/dist/composition/team/config.js.map +1 -0
  425. package/dist/composition/team/options.js +2 -0
  426. package/dist/composition/team/options.js.map +1 -0
  427. package/dist/composition/team/runtime.js +2 -0
  428. package/dist/composition/team/runtime.js.map +1 -0
  429. package/dist/composition/team/types.d.ts +63 -0
  430. package/dist/composition/team/types.d.ts.map +1 -0
  431. package/dist/composition/tool-source/config.d.ts +5 -0
  432. package/dist/composition/tool-source/config.d.ts.map +1 -0
  433. package/dist/composition/tool-source/config.js +2 -0
  434. package/dist/composition/tool-source/config.js.map +1 -0
  435. package/dist/composition/tool-source/definition.d.ts +7 -0
  436. package/dist/composition/tool-source/definition.d.ts.map +1 -0
  437. package/dist/composition/tool-source/definition.js +2 -0
  438. package/dist/composition/tool-source/definition.js.map +1 -0
  439. package/dist/composition/tool-source/snapshot.js +2 -0
  440. package/dist/composition/tool-source/snapshot.js.map +1 -0
  441. package/dist/contract/adapter.d.ts +91 -0
  442. package/dist/contract/adapter.d.ts.map +1 -0
  443. package/dist/contract/adapter.js +2 -0
  444. package/dist/contract/adapter.js.map +1 -0
  445. package/dist/contract/call-config.d.ts +36 -0
  446. package/dist/contract/call-config.d.ts.map +1 -0
  447. package/dist/contract/call-config.js +2 -0
  448. package/dist/contract/call-config.js.map +1 -0
  449. package/dist/contract/generate-options.d.ts +41 -0
  450. package/dist/contract/generate-options.d.ts.map +1 -0
  451. package/dist/contract/model-info.d.ts +99 -0
  452. package/dist/contract/model-info.d.ts.map +1 -0
  453. package/dist/contract/output-format.d.ts +18 -0
  454. package/dist/contract/output-format.d.ts.map +1 -0
  455. package/dist/contract/retry-policy.d.ts +104 -0
  456. package/dist/contract/retry-policy.d.ts.map +1 -0
  457. package/dist/contract/retry-policy.js +2 -0
  458. package/dist/contract/retry-policy.js.map +1 -0
  459. package/dist/contract/tool.d.ts +65 -0
  460. package/dist/contract/tool.d.ts.map +1 -0
  461. package/dist/contract/tool.js +2 -0
  462. package/dist/contract/tool.js.map +1 -0
  463. package/dist/errors/agent-sdk-error.d.ts +88 -0
  464. package/dist/errors/agent-sdk-error.d.ts.map +1 -0
  465. package/dist/errors/agent-sdk-error.js +2 -0
  466. package/dist/errors/agent-sdk-error.js.map +1 -0
  467. package/dist/errors/capability-identity.d.ts +10 -0
  468. package/dist/errors/capability-identity.d.ts.map +1 -0
  469. package/dist/errors/capability-identity.js +2 -0
  470. package/dist/errors/capability-identity.js.map +1 -0
  471. package/dist/errors/failure.d.ts +33 -0
  472. package/dist/errors/failure.d.ts.map +1 -0
  473. package/dist/errors/failure.js +2 -0
  474. package/dist/errors/failure.js.map +1 -0
  475. package/dist/errors/model-error.d.ts +83 -0
  476. package/dist/errors/model-error.d.ts.map +1 -0
  477. package/dist/errors/model-error.js +2 -0
  478. package/dist/errors/model-error.js.map +1 -0
  479. package/dist/http/api-key.d.ts +47 -0
  480. package/dist/http/api-key.d.ts.map +1 -0
  481. package/dist/http/api-key.js +2 -0
  482. package/dist/http/api-key.js.map +1 -0
  483. package/dist/http/attribution.d.ts +51 -0
  484. package/dist/http/attribution.d.ts.map +1 -0
  485. package/dist/http/attribution.js +2 -0
  486. package/dist/http/attribution.js.map +1 -0
  487. package/dist/index.d.ts +70 -0
  488. package/dist/index.js +1 -0
  489. package/dist/logging/types.d.ts +53 -0
  490. package/dist/logging/types.d.ts.map +1 -0
  491. package/dist/logging/types.js +2 -0
  492. package/dist/logging/types.js.map +1 -0
  493. package/dist/memory.d.ts +10 -0
  494. package/dist/memory.js +1 -0
  495. package/dist/message/content.d.ts +125 -0
  496. package/dist/message/content.d.ts.map +1 -0
  497. package/dist/message/message.d.ts +154 -0
  498. package/dist/message/message.d.ts.map +1 -0
  499. package/dist/message/message.js +2 -0
  500. package/dist/message/message.js.map +1 -0
  501. package/dist/message/projection.d.ts +34 -0
  502. package/dist/message/projection.d.ts.map +1 -0
  503. package/dist/message/projection.js +2 -0
  504. package/dist/message/projection.js.map +1 -0
  505. package/dist/observability/bus.d.ts +7 -0
  506. package/dist/observability/bus.d.ts.map +1 -0
  507. package/dist/observability/bus.js +2 -0
  508. package/dist/observability/bus.js.map +1 -0
  509. package/dist/observability/exporters.d.ts +39 -0
  510. package/dist/observability/exporters.d.ts.map +1 -0
  511. package/dist/observability/exporters.js +2 -0
  512. package/dist/observability/exporters.js.map +1 -0
  513. package/dist/observability/logger.js +2 -0
  514. package/dist/observability/logger.js.map +1 -0
  515. package/dist/observability/projections.d.ts +12 -0
  516. package/dist/observability/projections.d.ts.map +1 -0
  517. package/dist/observability/projections.js +2 -0
  518. package/dist/observability/projections.js.map +1 -0
  519. package/dist/observability/types.d.ts +103 -0
  520. package/dist/observability/types.d.ts.map +1 -0
  521. package/dist/observability.d.ts +20 -0
  522. package/dist/observability.js +1 -0
  523. package/dist/observation/boundaries.js +2 -0
  524. package/dist/observation/boundaries.js.map +1 -0
  525. package/dist/observation/context.d.ts +39 -0
  526. package/dist/observation/context.d.ts.map +1 -0
  527. package/dist/observation/context.js +2 -0
  528. package/dist/observation/context.js.map +1 -0
  529. package/dist/observation/event.d.ts +50 -0
  530. package/dist/observation/event.d.ts.map +1 -0
  531. package/dist/observation/event.js +2 -0
  532. package/dist/observation/event.js.map +1 -0
  533. package/dist/observation/port.d.ts +56 -0
  534. package/dist/observation/port.d.ts.map +1 -0
  535. package/dist/observation/port.js +2 -0
  536. package/dist/observation/port.js.map +1 -0
  537. package/dist/observation/privacy.js +2 -0
  538. package/dist/observation/privacy.js.map +1 -0
  539. package/dist/observation/report.d.ts +117 -0
  540. package/dist/observation/report.d.ts.map +1 -0
  541. package/dist/observation/report.js +2 -0
  542. package/dist/observation/report.js.map +1 -0
  543. package/dist/observation/telemetry-types.d.ts +29 -0
  544. package/dist/observation/telemetry-types.d.ts.map +1 -0
  545. package/dist/observation/usage.d.ts +52 -0
  546. package/dist/observation/usage.d.ts.map +1 -0
  547. package/dist/observation/usage.js +2 -0
  548. package/dist/observation/usage.js.map +1 -0
  549. package/dist/platform/adapter.js +2 -0
  550. package/dist/platform/adapter.js.map +1 -0
  551. package/dist/platform/capability-operation.js +2 -0
  552. package/dist/platform/capability-operation.js.map +1 -0
  553. package/dist/platform/config.js +2 -0
  554. package/dist/platform/config.js.map +1 -0
  555. package/dist/platform/logger-platform.js +2 -0
  556. package/dist/platform/logger-platform.js.map +1 -0
  557. package/dist/platform/resources.js +2 -0
  558. package/dist/platform/resources.js.map +1 -0
  559. package/dist/plugin/provider-plugin.d.ts +37 -0
  560. package/dist/plugin/provider-plugin.d.ts.map +1 -0
  561. package/dist/plugin/provider-plugin.js +2 -0
  562. package/dist/plugin/provider-plugin.js.map +1 -0
  563. package/dist/primitives/brand.d.ts +61 -0
  564. package/dist/primitives/brand.d.ts.map +1 -0
  565. package/dist/primitives/brand.js +2 -0
  566. package/dist/primitives/brand.js.map +1 -0
  567. package/dist/primitives/freeze.d.ts +20 -0
  568. package/dist/primitives/freeze.d.ts.map +1 -0
  569. package/dist/primitives/freeze.js +2 -0
  570. package/dist/primitives/freeze.js.map +1 -0
  571. package/dist/primitives/json-snapshot.js +2 -0
  572. package/dist/primitives/json-snapshot.js.map +1 -0
  573. package/dist/primitives/json.d.ts +32 -0
  574. package/dist/primitives/json.d.ts.map +1 -0
  575. package/dist/primitives/json.js +2 -0
  576. package/dist/primitives/json.js.map +1 -0
  577. package/dist/primitives/never.d.ts +22 -0
  578. package/dist/primitives/never.d.ts.map +1 -0
  579. package/dist/primitives/never.js +2 -0
  580. package/dist/primitives/never.js.map +1 -0
  581. package/dist/primitives/snapshot.d.ts +10 -0
  582. package/dist/primitives/snapshot.d.ts.map +1 -0
  583. package/dist/primitives/snapshot.js +2 -0
  584. package/dist/primitives/snapshot.js.map +1 -0
  585. package/dist/primitives/version.d.ts +6 -0
  586. package/dist/primitives/version.d.ts.map +1 -0
  587. package/dist/primitives/version.js +2 -0
  588. package/dist/primitives/version.js.map +1 -0
  589. package/dist/provider.d.ts +19 -0
  590. package/dist/provider.js +1 -0
  591. package/dist/runtime/model-call-handle.js +2 -0
  592. package/dist/runtime/model-call-handle.js.map +1 -0
  593. package/dist/runtime/model-metadata.js +2 -0
  594. package/dist/runtime/model-metadata.js.map +1 -0
  595. package/dist/runtime/model-stream.js +2 -0
  596. package/dist/runtime/model-stream.js.map +1 -0
  597. package/dist/runtime/registry.d.ts +171 -0
  598. package/dist/runtime/registry.d.ts.map +1 -0
  599. package/dist/runtime/registry.js +2 -0
  600. package/dist/runtime/registry.js.map +1 -0
  601. package/dist/runtime/with-retry.d.ts +45 -0
  602. package/dist/runtime/with-retry.d.ts.map +1 -0
  603. package/dist/runtime/with-retry.js +2 -0
  604. package/dist/runtime/with-retry.js.map +1 -0
  605. package/dist/skills.d.ts +8 -0
  606. package/dist/skills.js +1 -0
  607. package/dist/stream/assembler.d.ts +86 -0
  608. package/dist/stream/assembler.d.ts.map +1 -0
  609. package/dist/stream/assembler.js +2 -0
  610. package/dist/stream/assembler.js.map +1 -0
  611. package/dist/stream/chunk.d.ts +135 -0
  612. package/dist/stream/chunk.d.ts.map +1 -0
  613. package/dist/stream/idle-timeout.d.ts +30 -0
  614. package/dist/stream/idle-timeout.d.ts.map +1 -0
  615. package/dist/stream/idle-timeout.js +2 -0
  616. package/dist/stream/idle-timeout.js.map +1 -0
  617. package/dist/support-safe/error.d.ts +29 -0
  618. package/dist/support-safe/error.d.ts.map +1 -0
  619. package/dist/support-safe/error.js +2 -0
  620. package/dist/support-safe/error.js.map +1 -0
  621. package/dist/tools.d.ts +15 -0
  622. package/dist/tools.js +1 -0
  623. package/package.json +96 -0
@@ -0,0 +1,82 @@
1
+ import { AgentSdkError } from "../../errors/agent-sdk-error.js";
2
+ //#region src/agent/tool/errors.d.ts
3
+ /** What the loop should do with a tool failure. */
4
+ type ToolErrorDisposition =
5
+ /** Feed the message back as the tool's result and let the model try again. */
6
+ 'respond-to-model' |
7
+ /** End the turn. A contract violation the model cannot recover from. */
8
+ 'fatal';
9
+ /** Codes the tool layer itself produces. */
10
+ declare const TOOL_ERROR_CODES: Readonly<{
11
+ /** The model named a tool that is not registered or not visible to it. */
12
+ readonly UNKNOWN_TOOL: 'UNKNOWN_TOOL';
13
+ /** Arguments failed the tool's own validation. */
14
+ readonly INVALID_ARGUMENTS: 'INVALID_ARGUMENTS';
15
+ /** The model emitted arguments that are not valid JSON. */
16
+ readonly MALFORMED_ARGUMENTS: 'MALFORMED_ARGUMENTS';
17
+ /** The tool exceeded its declared `timeoutMs`. */
18
+ readonly TIMEOUT: 'TOOL_TIMEOUT';
19
+ /** Cancelled after the tool body started. */
20
+ readonly ABORTED: 'TOOL_ABORTED';
21
+ /** Cancelled before the tool body was entered. */
22
+ readonly ABORTED_BEFORE_DISPATCH: 'TOOL_ABORTED_BEFORE_DISPATCH';
23
+ /** An interceptor refused the call. */
24
+ readonly DENIED: 'TOOL_DENIED';
25
+ /** The tool returned a value that is not losslessly JSON. */
26
+ readonly INVALID_RESULT: 'INVALID_TOOL_RESULT';
27
+ /** The tool threw something that carried no useful classification. */
28
+ readonly FAILED: 'TOOL_FAILED';
29
+ /** The turn had no remaining tool-call allowance. */
30
+ readonly BUDGET_EXHAUSTED: 'TOOL_BUDGET_EXHAUSTED';
31
+ /** Caller-owned durability failed before the tool side effect. */
32
+ readonly CHECKPOINT_FAILED: 'CHECKPOINT_FAILED';
33
+ /** In-process tool/interceptor ignored cancellation beyond the teardown budget. */
34
+ readonly TEARDOWN_TIMEOUT: 'TOOL_TEARDOWN_TIMEOUT';
35
+ }>;
36
+ /**
37
+ * A tool failure, carrying its disposition.
38
+ *
39
+ * Construct through {@link ToolError.respondToModel} or {@link ToolError.fatal}
40
+ * rather than the constructor, so the disposition is always a deliberate choice
41
+ * at the throw site instead of a default nobody looked at.
42
+ */
43
+ declare class ToolError extends AgentSdkError {
44
+ /** Whether this ends the turn or becomes the tool's result. */
45
+ readonly disposition: ToolErrorDisposition;
46
+ constructor(message: string, disposition: ToolErrorDisposition, code?: string, options?: ErrorOptions);
47
+ /**
48
+ * The normal case: report the failure to the model and continue the turn.
49
+ *
50
+ * Write the message FOR THE MODEL. It is the only thing the model will see, so
51
+ * "file not found: /tmp/x.txt" is useful and "ENOENT" is not.
52
+ * @param message - model-facing explanation of what went wrong.
53
+ * @param code - stable code for routing and metrics.
54
+ * @param options - optional cause.
55
+ */
56
+ static respondToModel(message: string, code?: string, options?: ErrorOptions): ToolError;
57
+ /**
58
+ * The rare case: end the turn.
59
+ *
60
+ * Reserve this for a broken contract — a tool registered with the wrong shape,
61
+ * a host invariant violated — where letting the model retry would just produce
62
+ * the same failure with more tokens spent.
63
+ * @param message - operator-facing explanation.
64
+ * @param code - stable code for routing.
65
+ * @param options - optional cause.
66
+ */
67
+ static fatal(message: string, code?: string, options?: ErrorOptions): ToolError;
68
+ }
69
+ /**
70
+ * Read the disposition of an arbitrary thrown value.
71
+ *
72
+ * Anything that is not an explicitly fatal {@link ToolError} is treated as
73
+ * `respond-to-model`. That default is the point: an ordinary `TypeError` from
74
+ * inside a tool body should reach the model as a failed tool result, not kill the
75
+ * user's turn.
76
+ * @param value - the caught value.
77
+ * @returns the disposition to apply.
78
+ */
79
+ declare function toolErrorDisposition(value: unknown): ToolErrorDisposition;
80
+ //#endregion
81
+ export { TOOL_ERROR_CODES, ToolError, ToolErrorDisposition, toolErrorDisposition };
82
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../../../src/agent/tool/errors.ts"],"mappings":";;;KAuBY;;;;;;cAOC,kBAAgB;;WAEb;;WAEK;;WAEE;;WAEZ;;WAEA;;WAEgB;;WAEjB;;WAEQ;;WAER;;WAEU;;WAEC;;WAED;;;;;;;;;cAUP,kBAAkB;;WAEpB,aAAa;EAEtB,YACE,iBACA,aAAa,sBACb,eACA,UAAU;;;;;;;;;;SAgBL,eACL,iBACA,eACA,UAAU,eACT;;;;;;;;;;;SAcI,MACL,iBACA,eACA,UAAU,eACT;;;;;;;;;;;;iBAeW,qBAAqB,iBAAiB"}
@@ -0,0 +1,2 @@
1
+ import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";const t=Object.freeze({UNKNOWN_TOOL:`UNKNOWN_TOOL`,INVALID_ARGUMENTS:`INVALID_ARGUMENTS`,MALFORMED_ARGUMENTS:`MALFORMED_ARGUMENTS`,TIMEOUT:`TOOL_TIMEOUT`,ABORTED:`TOOL_ABORTED`,ABORTED_BEFORE_DISPATCH:`TOOL_ABORTED_BEFORE_DISPATCH`,DENIED:`TOOL_DENIED`,INVALID_RESULT:`INVALID_TOOL_RESULT`,FAILED:`TOOL_FAILED`,BUDGET_EXHAUSTED:`TOOL_BUDGET_EXHAUSTED`,CHECKPOINT_FAILED:`CHECKPOINT_FAILED`,TEARDOWN_TIMEOUT:`TOOL_TEARDOWN_TIMEOUT`});var n=class n extends e{disposition;constructor(e,n,r=t.FAILED,i){super(e,r,i),this.name=`ToolError`,this.disposition=n}static respondToModel(e,r=t.FAILED,i){return new n(e,`respond-to-model`,r,i)}static fatal(e,r=t.FAILED,i){return new n(e,`fatal`,r,i)}};function r(e){return e instanceof n&&e.disposition===`fatal`?`fatal`:`respond-to-model`}export{t as TOOL_ERROR_CODES,n as ToolError,r as toolErrorDisposition};
2
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../../src/agent/tool/errors.ts"],"sourcesContent":["/**\n * The tool error taxonomy, and the single most important decision in the whole\n * tool layer: **a tool failure is normally INPUT FOR THE MODEL, not an exception\n * that ends the turn.**\n *\n * Both reference implementations converged on this independently. Codex spells it\n * as a two-variant enum (`FunctionCallError::{RespondToModel, Fatal}`) and\n * deepseek-harness spells it as a registry that normalizes any throw into an\n * `isError: true` result. The reasoning is the same: a model that asked for a\n * file that does not exist, or passed a malformed argument, has made a mistake it\n * can recover from — if it is told. Aborting the turn throws away everything the\n * model has already accomplished and gives the user nothing.\n *\n * So a thrown tool error becomes a tool result by default. `fatal` is the narrow\n * exception, reserved for a violated contract that the model cannot fix by trying\n * something else.\n *\n * @module ai-agent-sdk/agent/tool/errors\n */\n\nimport { AgentSdkError } from '../../errors/index.ts'\n\n/** What the loop should do with a tool failure. */\nexport type ToolErrorDisposition =\n /** Feed the message back as the tool's result and let the model try again. */\n | 'respond-to-model'\n /** End the turn. A contract violation the model cannot recover from. */\n | 'fatal'\n\n/** Codes the tool layer itself produces. */\nexport const TOOL_ERROR_CODES = Object.freeze({\n /** The model named a tool that is not registered or not visible to it. */\n UNKNOWN_TOOL: 'UNKNOWN_TOOL',\n /** Arguments failed the tool's own validation. */\n INVALID_ARGUMENTS: 'INVALID_ARGUMENTS',\n /** The model emitted arguments that are not valid JSON. */\n MALFORMED_ARGUMENTS: 'MALFORMED_ARGUMENTS',\n /** The tool exceeded its declared `timeoutMs`. */\n TIMEOUT: 'TOOL_TIMEOUT',\n /** Cancelled after the tool body started. */\n ABORTED: 'TOOL_ABORTED',\n /** Cancelled before the tool body was entered. */\n ABORTED_BEFORE_DISPATCH: 'TOOL_ABORTED_BEFORE_DISPATCH',\n /** An interceptor refused the call. */\n DENIED: 'TOOL_DENIED',\n /** The tool returned a value that is not losslessly JSON. */\n INVALID_RESULT: 'INVALID_TOOL_RESULT',\n /** The tool threw something that carried no useful classification. */\n FAILED: 'TOOL_FAILED',\n /** The turn had no remaining tool-call allowance. */\n BUDGET_EXHAUSTED: 'TOOL_BUDGET_EXHAUSTED',\n /** Caller-owned durability failed before the tool side effect. */\n CHECKPOINT_FAILED: 'CHECKPOINT_FAILED',\n /** In-process tool/interceptor ignored cancellation beyond the teardown budget. */\n TEARDOWN_TIMEOUT: 'TOOL_TEARDOWN_TIMEOUT',\n} as const)\n\n/**\n * A tool failure, carrying its disposition.\n *\n * Construct through {@link ToolError.respondToModel} or {@link ToolError.fatal}\n * rather than the constructor, so the disposition is always a deliberate choice\n * at the throw site instead of a default nobody looked at.\n */\nexport class ToolError extends AgentSdkError {\n /** Whether this ends the turn or becomes the tool's result. */\n readonly disposition: ToolErrorDisposition\n\n constructor(\n message: string,\n disposition: ToolErrorDisposition,\n code: string = TOOL_ERROR_CODES.FAILED,\n options?: ErrorOptions,\n ) {\n super(message, code, options)\n this.name = 'ToolError'\n this.disposition = disposition\n }\n\n /**\n * The normal case: report the failure to the model and continue the turn.\n *\n * Write the message FOR THE MODEL. It is the only thing the model will see, so\n * \"file not found: /tmp/x.txt\" is useful and \"ENOENT\" is not.\n * @param message - model-facing explanation of what went wrong.\n * @param code - stable code for routing and metrics.\n * @param options - optional cause.\n */\n static respondToModel(\n message: string,\n code: string = TOOL_ERROR_CODES.FAILED,\n options?: ErrorOptions,\n ): ToolError {\n return new ToolError(message, 'respond-to-model', code, options)\n }\n\n /**\n * The rare case: end the turn.\n *\n * Reserve this for a broken contract — a tool registered with the wrong shape,\n * a host invariant violated — where letting the model retry would just produce\n * the same failure with more tokens spent.\n * @param message - operator-facing explanation.\n * @param code - stable code for routing.\n * @param options - optional cause.\n */\n static fatal(\n message: string,\n code: string = TOOL_ERROR_CODES.FAILED,\n options?: ErrorOptions,\n ): ToolError {\n return new ToolError(message, 'fatal', code, options)\n }\n}\n\n/**\n * Read the disposition of an arbitrary thrown value.\n *\n * Anything that is not an explicitly fatal {@link ToolError} is treated as\n * `respond-to-model`. That default is the point: an ordinary `TypeError` from\n * inside a tool body should reach the model as a failed tool result, not kill the\n * user's turn.\n * @param value - the caught value.\n * @returns the disposition to apply.\n */\nexport function toolErrorDisposition(value: unknown): ToolErrorDisposition {\n return value instanceof ToolError && value.disposition === 'fatal'\n ? 'fatal'\n : 'respond-to-model'\n}\n"],"mappings":"gEA8BA,MAAa,EAAmB,OAAO,OAAO,CAE5C,aAAc,eAEd,kBAAmB,oBAEnB,oBAAqB,sBAErB,QAAS,eAET,QAAS,eAET,wBAAyB,+BAEzB,OAAQ,cAER,eAAgB,sBAEhB,OAAQ,cAER,iBAAkB,wBAElB,kBAAmB,oBAEnB,iBAAkB,uBACpB,CAAU,EASV,IAAa,EAAb,MAAa,UAAkB,CAAc,CAE3C,YAEA,YACE,EACA,EACA,EAAe,EAAiB,OAChC,EACA,CACA,MAAM,EAAS,EAAM,CAAO,EAC5B,KAAK,KAAO,YACZ,KAAK,YAAc,CACrB,CAWA,OAAO,eACL,EACA,EAAe,EAAiB,OAChC,EACW,CACX,OAAO,IAAI,EAAU,EAAS,mBAAoB,EAAM,CAAO,CACjE,CAYA,OAAO,MACL,EACA,EAAe,EAAiB,OAChC,EACW,CACX,OAAO,IAAI,EAAU,EAAS,QAAS,EAAM,CAAO,CACtD,CACF,EAYA,SAAgB,EAAqB,EAAsC,CACzE,OAAO,aAAiB,GAAa,EAAM,cAAgB,QACvD,QACA,kBACN"}
@@ -0,0 +1,60 @@
1
+ import { JsonObject } from "../../primitives/json.js";
2
+ import { ToolExecutionResult } from "./definition.js";
3
+ import { ToolCallContext, ToolInterceptor } from "./pipeline.js";
4
+ //#region src/agent/tool/execution.d.ts
5
+ /** Claims describe what a backend actually enforces, not permissions granted by policy. */
6
+ interface ToolExecutionCapabilities {
7
+ readonly cancellation: 'cooperative' | 'forced';
8
+ readonly filesystem: 'host' | 'restricted' | 'none';
9
+ readonly network: 'host' | 'restricted' | 'none';
10
+ readonly cleanup: 'best-effort' | 'guaranteed';
11
+ }
12
+ interface ToolExecutionRequest {
13
+ readonly operationId: string;
14
+ readonly toolName: string;
15
+ readonly args: unknown;
16
+ /** Trusted host identity; never sourced from model arguments. */
17
+ readonly identity: JsonObject;
18
+ readonly signal: AbortSignal;
19
+ }
20
+ interface ToolExecutionBackend {
21
+ readonly id: string;
22
+ readonly capabilities: ToolExecutionCapabilities;
23
+ execute(request: ToolExecutionRequest, local: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult>;
24
+ }
25
+ declare const localToolExecutionBackend: ToolExecutionBackend;
26
+ interface ToolOperation {
27
+ readonly operationId: string;
28
+ readonly toolName: string;
29
+ readonly args: unknown;
30
+ readonly identity: JsonObject;
31
+ }
32
+ type ToolOperationClaim = {
33
+ readonly status: 'claimed';
34
+ } | {
35
+ readonly status: 'completed';
36
+ readonly operation: ToolOperation;
37
+ readonly result: ToolExecutionResult;
38
+ } | {
39
+ readonly status: 'unknown';
40
+ readonly operation: ToolOperation;
41
+ };
42
+ /** Separate from conversation memory. The host adapter must durably and atomically claim an ID.
43
+ * An existing in-progress claim is unknown after restart, never implicitly retryable.
44
+ * complete must persist before resolving. Reconciliation is host-owned. */
45
+ interface ToolExecutionStore {
46
+ claim(operation: ToolOperation, signal: AbortSignal): Promise<ToolOperationClaim>;
47
+ complete(operation: ToolOperation, result: ToolExecutionResult, signal: AbortSignal): Promise<void>;
48
+ }
49
+ /** Attach via session.interceptors. Policy and approval still run before this adapter,
50
+ * and post-policy still sanitizes both fresh and recovered results. No automatic retry. */
51
+ declare function createToolExecutionInterceptor(options: {
52
+ readonly backend?: ToolExecutionBackend;
53
+ readonly identity: JsonObject;
54
+ /** Stable across recovery, scoped to tenant/session by the authenticated host. */
55
+ readonly operationId: (call: ToolCallContext) => string;
56
+ readonly store?: ToolExecutionStore;
57
+ }): ToolInterceptor;
58
+ //#endregion
59
+ export { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend };
60
+ //# sourceMappingURL=execution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.d.ts","names":[],"sources":["../../../src/agent/tool/execution.ts"],"mappings":";;;;;UAMiB;WACN;WACA;WACA;WACA;;UAEM;WACN;WACA;WACA;;WAEA,UAAU;WACV,QAAQ;;UAEF;WACN;WACA,cAAc;EACvB,QAAQ,SAAS,sBAAsB,aAAa,QAAQ,uBAAuB,QAAQ;;cAEhF,2BAA2B;UAMvB;WACN;WACA;WACA;WACA,UAAU;;KAET;WACG;;WACA;WAA8B,WAAW;WAAwB,QAAQ;;WACzE;WAA4B,WAAW;;;;;UAKrC;EACf,MAAM,WAAW,eAAe,QAAQ,cAAc,QAAQ;EAC9D,SAAS,WAAW,eAAe,QAAQ,qBAAqB,QAAQ,cAAc;;;;iBAKxE,+BAA+B;WACpC,UAAU;WACV,UAAU;;WAEV,cAAc,MAAM;WACpB,QAAQ;IACf"}
@@ -0,0 +1,2 @@
1
+ import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{ToolError as n}from"./errors.js";const r=Object.freeze({id:`local`,capabilities:Object.freeze({cancellation:`cooperative`,filesystem:`host`,network:`host`,cleanup:`best-effort`}),execute:(e,t)=>t()});function i(i){let o=i.backend??r,s=o.execute.bind(o),c=t(i.identity),l=i.operationId,u=i.store,d=u?.claim.bind(u),f=u?.complete.bind(u);return Object.freeze({name:`execution:${o.id}`,around:async(r,i)=>{let o=l(r);if(typeof o!=`string`||o.length===0||o.length>512)throw n.fatal(`invalid operation identity`,`INVALID_OPERATION_ID`);let u=t({operationId:o,toolName:r.toolName,args:r.args,identity:c});if(r.signal.aborted)throw n.fatal(`execution cancelled`,`TOOL_ABORTED`);if(d!==void 0){if(!e(u.args)||!e(u.identity))throw n.fatal(`durable operation input must be lossless JSON`,`INVALID_OPERATION_INPUT`);let i=await d(u,r.signal);if(i.status!==`claimed`){if(a(i.operation)!==a(u))throw n.fatal(`operation identity conflicts with saved input`,`OPERATION_ID_CONFLICT`);if(i.status===`unknown`)throw n.fatal(`operation outcome is unknown; reconcile before retrying`,`OPERATION_OUTCOME_UNKNOWN`);return t(i.result)}}if(r.signal.aborted)throw n.fatal(`execution cancelled after claim; reconcile operation`,`OPERATION_OUTCOME_UNKNOWN`);let p=await s({...u,signal:r.signal},i);return await f?.(u,p,r.signal),p}})}function a(e){return e===void 0?`undefined`:typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[${e.map(a).join(`,`)}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${a(e[t])}`).join(`,`)}}`}export{i as createToolExecutionInterceptor,r as localToolExecutionBackend};
2
+ //# sourceMappingURL=execution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.js","names":[],"sources":["../../../src/agent/tool/execution.ts"],"sourcesContent":["import { isJsonValue, detachedFrozen, type JsonObject } from '../../primitives/index.ts'\nimport type { ToolExecutionResult } from './definition.ts'\nimport { ToolError } from './errors.ts'\nimport type { ToolCallContext, ToolInterceptor } from './pipeline.ts'\n\n/** Claims describe what a backend actually enforces, not permissions granted by policy. */\nexport interface ToolExecutionCapabilities {\n readonly cancellation: 'cooperative' | 'forced'\n readonly filesystem: 'host' | 'restricted' | 'none'\n readonly network: 'host' | 'restricted' | 'none'\n readonly cleanup: 'best-effort' | 'guaranteed'\n}\nexport interface ToolExecutionRequest {\n readonly operationId: string\n readonly toolName: string\n readonly args: unknown\n /** Trusted host identity; never sourced from model arguments. */\n readonly identity: JsonObject\n readonly signal: AbortSignal\n}\nexport interface ToolExecutionBackend {\n readonly id: string\n readonly capabilities: ToolExecutionCapabilities\n execute(request: ToolExecutionRequest, local: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult>\n}\nexport const localToolExecutionBackend: ToolExecutionBackend = Object.freeze({\n id: 'local',\n capabilities: Object.freeze({ cancellation: 'cooperative', filesystem: 'host', network: 'host', cleanup: 'best-effort' }),\n execute: (_request: ToolExecutionRequest, local: () => Promise<ToolExecutionResult>) => local(),\n})\n\nexport interface ToolOperation {\n readonly operationId: string\n readonly toolName: string\n readonly args: unknown\n readonly identity: JsonObject\n}\nexport type ToolOperationClaim =\n | { readonly status: 'claimed' }\n | { readonly status: 'completed'; readonly operation: ToolOperation; readonly result: ToolExecutionResult }\n | { readonly status: 'unknown'; readonly operation: ToolOperation }\n\n/** Separate from conversation memory. The host adapter must durably and atomically claim an ID.\n * An existing in-progress claim is unknown after restart, never implicitly retryable.\n * complete must persist before resolving. Reconciliation is host-owned. */\nexport interface ToolExecutionStore {\n claim(operation: ToolOperation, signal: AbortSignal): Promise<ToolOperationClaim>\n complete(operation: ToolOperation, result: ToolExecutionResult, signal: AbortSignal): Promise<void>\n}\n\n/** Attach via session.interceptors. Policy and approval still run before this adapter,\n * and post-policy still sanitizes both fresh and recovered results. No automatic retry. */\nexport function createToolExecutionInterceptor(options: {\n readonly backend?: ToolExecutionBackend\n readonly identity: JsonObject\n /** Stable across recovery, scoped to tenant/session by the authenticated host. */\n readonly operationId: (call: ToolCallContext) => string\n readonly store?: ToolExecutionStore\n}): ToolInterceptor {\n const backend = options.backend ?? localToolExecutionBackend\n const execute = backend.execute.bind(backend)\n const identity = detachedFrozen(options.identity)\n const operationId = options.operationId\n const store = options.store\n const claim = store?.claim.bind(store), complete = store?.complete.bind(store)\n return Object.freeze({\n name: `execution:${backend.id}`,\n around: async (call: ToolCallContext, local: () => Promise<ToolExecutionResult>) => {\n const id = operationId(call)\n if (typeof id !== 'string' || id.length === 0 || id.length > 512) throw ToolError.fatal('invalid operation identity', 'INVALID_OPERATION_ID')\n const operation = detachedFrozen({ operationId: id, toolName: call.toolName, args: call.args, identity })\n if (call.signal.aborted) throw ToolError.fatal('execution cancelled', 'TOOL_ABORTED')\n if (claim !== undefined) {\n if (!isJsonValue(operation.args) || !isJsonValue(operation.identity)) throw ToolError.fatal('durable operation input must be lossless JSON', 'INVALID_OPERATION_INPUT')\n const previous = await claim(operation, call.signal)\n if (previous.status !== 'claimed') {\n if (canonical(previous.operation) !== canonical(operation)) throw ToolError.fatal('operation identity conflicts with saved input', 'OPERATION_ID_CONFLICT')\n if (previous.status === 'unknown') throw ToolError.fatal('operation outcome is unknown; reconcile before retrying', 'OPERATION_OUTCOME_UNKNOWN')\n return detachedFrozen(previous.result)\n }\n }\n if (call.signal.aborted) throw ToolError.fatal('execution cancelled after claim; reconcile operation', 'OPERATION_OUTCOME_UNKNOWN')\n // A throw, cancellation, or failed completion write leaves the durable claim\n // unresolved. A subsequent attempt must reconcile; it cannot execute again.\n const result = await execute({ ...operation, signal: call.signal }, local)\n await complete?.(operation, result, call.signal)\n return result\n },\n })\n}\n\nfunction canonical(value: unknown): string {\n if (value === undefined) return 'undefined'\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`\n return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`).join(',')}}`\n}\n"],"mappings":"6JAyBA,MAAa,EAAkD,OAAO,OAAO,CAC3E,GAAI,QACJ,aAAc,OAAO,OAAO,CAAE,aAAc,cAAe,WAAY,OAAQ,QAAS,OAAQ,QAAS,aAAc,CAAC,EACxH,SAAU,EAAgC,IAA8C,EAAM,CAChG,CAAC,EAuBD,SAAgB,EAA+B,EAM3B,CAClB,IAAM,EAAU,EAAQ,SAAW,EAC7B,EAAU,EAAQ,QAAQ,KAAK,CAAO,EACtC,EAAW,EAAe,EAAQ,QAAQ,EAC1C,EAAc,EAAQ,YACtB,EAAQ,EAAQ,MAChB,EAAQ,GAAO,MAAM,KAAK,CAAK,EAAG,EAAW,GAAO,SAAS,KAAK,CAAK,EAC7E,OAAO,OAAO,OAAO,CACnB,KAAM,aAAa,EAAQ,KAC3B,OAAQ,MAAO,EAAuB,IAA8C,CAClF,IAAM,EAAK,EAAY,CAAI,EAC3B,GAAI,OAAO,GAAO,UAAY,EAAG,SAAW,GAAK,EAAG,OAAS,IAAK,MAAM,EAAU,MAAM,6BAA8B,sBAAsB,EAC5I,IAAM,EAAY,EAAe,CAAE,YAAa,EAAI,SAAU,EAAK,SAAU,KAAM,EAAK,KAAM,UAAS,CAAC,EACxG,GAAI,EAAK,OAAO,QAAS,MAAM,EAAU,MAAM,sBAAuB,cAAc,EACpF,GAAI,IAAU,IAAA,GAAW,CACvB,GAAI,CAAC,EAAY,EAAU,IAAI,GAAK,CAAC,EAAY,EAAU,QAAQ,EAAG,MAAM,EAAU,MAAM,gDAAiD,yBAAyB,EACtK,IAAM,EAAW,MAAM,EAAM,EAAW,EAAK,MAAM,EACnD,GAAI,EAAS,SAAW,UAAW,CACjC,GAAI,EAAU,EAAS,SAAS,IAAM,EAAU,CAAS,EAAG,MAAM,EAAU,MAAM,gDAAiD,uBAAuB,EAC1J,GAAI,EAAS,SAAW,UAAW,MAAM,EAAU,MAAM,0DAA2D,2BAA2B,EAC/I,OAAO,EAAe,EAAS,MAAM,CACvC,CACF,CACA,GAAI,EAAK,OAAO,QAAS,MAAM,EAAU,MAAM,uDAAwD,2BAA2B,EAGlI,IAAM,EAAS,MAAM,EAAQ,CAAE,GAAG,EAAW,OAAQ,EAAK,MAAO,EAAG,CAAK,EAEzE,OADA,MAAM,IAAW,EAAW,EAAQ,EAAK,MAAM,EACxC,CACT,CACF,CAAC,CACH,CAEA,SAAS,EAAU,EAAwB,CAIzC,OAHI,IAAU,IAAA,GAAkB,YACV,OAAO,GAAU,WAAnC,EAAoD,KAAK,UAAU,CAAK,EACxE,MAAM,QAAQ,CAAK,EAAU,IAAI,EAAM,IAAI,CAAS,CAAC,CAAC,KAAK,GAAG,EAAE,GAC7D,IAAI,OAAO,KAAK,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAO,GAAG,KAAK,UAAU,CAAG,EAAE,GAAG,EAAW,EAAkC,EAAI,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE,EAC5I"}
@@ -0,0 +1,159 @@
1
+ import { ContentBlock } from "../../message/content.js";
2
+ import { ToolDefinition } from "./definition.js";
3
+ //#region src/agent/tool/output-budget.d.ts
4
+ /**
5
+ * What happens to output that exceeds its budget.
6
+ *
7
+ * - `auto` — spill when a store is mounted, otherwise truncate.
8
+ * - `truncate` — always cut the middle; never needs a store.
9
+ * - `spill` — save the full text and show a preview; falls back to truncating
10
+ * when no store is mounted or the store fails, because losing the result
11
+ * entirely is worse than shortening it.
12
+ */
13
+ type ToolOutputOverflowPolicy = 'auto' | 'truncate' | 'spill';
14
+ /** A saved copy of one oversized tool result. */
15
+ interface SpillRecord {
16
+ /** Opaque handle the retrieval tool resolves; also shown to the model. */
17
+ readonly locator: string;
18
+ /** Exact size of the saved text. */
19
+ readonly bytes: number;
20
+ /**
21
+ * One sentence telling the model how to get the rest.
22
+ *
23
+ * Written by the backend, because only it knows what the locator IS — a file
24
+ * a shell can grep, or a handle only the built-in retrieval tool resolves.
25
+ */
26
+ readonly retrieval: string;
27
+ }
28
+ /** A slice of a saved tool result. */
29
+ interface SpillSlice {
30
+ readonly text: string;
31
+ /** Total code points in the saved text, so a reader can page through it. */
32
+ readonly totalChars: number;
33
+ /** Where this slice starts. */
34
+ readonly offset: number;
35
+ }
36
+ /**
37
+ * Where oversized tool output goes when the policy spills it.
38
+ *
39
+ * The port is deliberately tiny: core is a universal package and cannot open a
40
+ * file, so a host that wants durable spill implements this over its own
41
+ * storage. {@link createMemorySpillStore} covers the common case.
42
+ */
43
+ interface SpillStore {
44
+ /**
45
+ * Save one oversized result.
46
+ * @param text - The complete model-facing text.
47
+ * @param context - What produced it, for naming and diagnostics.
48
+ * @returns The locator the model can retrieve it by.
49
+ */
50
+ save(text: string, context: {
51
+ readonly toolName: string;
52
+ readonly callId: string;
53
+ }): Promise<SpillRecord> | SpillRecord;
54
+ /**
55
+ * Read part of a saved result.
56
+ * @param locator - A locator returned by {@link SpillStore.save}.
57
+ * @param range - Where to start and how much to read, in code points.
58
+ * @returns The slice, or undefined when the locator is unknown or expired.
59
+ */
60
+ read(locator: string, range: {
61
+ readonly offset: number;
62
+ readonly limit: number;
63
+ }): Promise<SpillSlice | undefined> | SpillSlice | undefined;
64
+ /**
65
+ * Find matching lines in a saved result.
66
+ * @param locator - A locator returned by {@link SpillStore.save}.
67
+ * @param pattern - A regular expression source, matched per line.
68
+ * @param limit - Maximum lines returned.
69
+ * @returns Matching `line-number: text` entries, or undefined when unknown.
70
+ */
71
+ search(locator: string, pattern: string, limit: number): Promise<readonly string[] | undefined> | readonly string[] | undefined;
72
+ }
73
+ /** Bounds for the built-in in-process store. */
74
+ interface MemorySpillStoreLimits {
75
+ /** Saved results kept before the oldest is evicted. Defaults to 64. */
76
+ readonly maxEntries?: number;
77
+ /** Total characters kept across all entries. Defaults to 32,000,000. */
78
+ readonly maxChars?: number;
79
+ }
80
+ /**
81
+ * A spill store that keeps text in this process.
82
+ *
83
+ * Universal, so it works in a browser and in a worker as well as on a server,
84
+ * and enough for the case the policy exists for: the text leaves the model's
85
+ * context immediately and is read back through the retrieval tool. It is not
86
+ * durable — a restart loses it, and the locators in an old transcript stop
87
+ * resolving. A host that needs durability implements {@link SpillStore} over
88
+ * its own filesystem or object storage.
89
+ * @param limits - Retention bounds.
90
+ * @returns The store.
91
+ */
92
+ declare function createMemorySpillStore(limits?: MemorySpillStoreLimits): SpillStore;
93
+ /**
94
+ * Deterministic token estimate for text.
95
+ *
96
+ * Four characters per token, the same heuristic compaction uses, and the same
97
+ * order of magnitude as Codex's `approx_token_count`. It is an estimate: a real
98
+ * tokenizer differs, and dense scripts differ more. It is used to decide when
99
+ * to shorten output, never to bill anything.
100
+ * @param text - The text to measure.
101
+ * @returns The estimated token count.
102
+ */
103
+ declare function estimateTextTokens(text: string): number;
104
+ /**
105
+ * Estimated tokens for the text a tool result puts in front of the model.
106
+ *
107
+ * Only text is counted. An image block is left alone — shortening it produces a
108
+ * corrupt image rather than a smaller one.
109
+ * @param content - The result's content blocks.
110
+ * @returns The estimated token count of the text blocks.
111
+ */
112
+ declare function estimateTextBlockTokens(content: readonly ContentBlock[]): number;
113
+ /** The result of shortening one oversized text. */
114
+ interface TruncatedText {
115
+ readonly text: string;
116
+ /** Estimated tokens the original held. */
117
+ readonly originalTokens: number;
118
+ }
119
+ /**
120
+ * Cut the middle out of a text to fit a token budget.
121
+ *
122
+ * The middle goes because the two ends carry the most: a command's invocation
123
+ * and its verdict, a file's header and its tail. Codex splits its budget the
124
+ * same way. The marker states how much left, so the model can see that it is
125
+ * reading a fragment rather than a short result.
126
+ * @param text - The full text.
127
+ * @param maxTokens - Estimated tokens the model may read.
128
+ * @returns The shortened text and what the original held.
129
+ */
130
+ declare function truncateMiddleToTokens(text: string, maxTokens: number): TruncatedText;
131
+ /**
132
+ * The head/tail preview shown in place of a spilled result.
133
+ * @param text - The full text.
134
+ * @param maxTokens - Estimated tokens the preview may hold.
135
+ * @returns The preview.
136
+ */
137
+ declare function previewForSpill(text: string, maxTokens: number): string;
138
+ /** The name the retrieval tool is registered under. */
139
+ declare const SPILL_TOOL_NAME = "read_tool_output";
140
+ interface ReadSpillArgs {
141
+ readonly locator: string;
142
+ readonly offset?: number;
143
+ readonly limit?: number;
144
+ readonly pattern?: string;
145
+ }
146
+ /**
147
+ * The tool that reads back what a spill took out of the context.
148
+ *
149
+ * Spilling without this would be worse than truncating: the model would be
150
+ * told its output exists somewhere and given no way to reach it. Registered
151
+ * automatically wherever a store is mounted.
152
+ * @param store - The mounted store.
153
+ * @param defaultLimit - Characters one read returns when none is asked for.
154
+ * @returns The tool definition.
155
+ */
156
+ declare function readSpillTool(store: SpillStore, defaultLimit?: number): ToolDefinition<ReadSpillArgs>;
157
+ //#endregion
158
+ export { MemorySpillStoreLimits, SPILL_TOOL_NAME, SpillRecord, SpillSlice, SpillStore, ToolOutputOverflowPolicy, TruncatedText, createMemorySpillStore, estimateTextBlockTokens, estimateTextTokens, previewForSpill, readSpillTool, truncateMiddleToTokens };
159
+ //# sourceMappingURL=output-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-budget.d.ts","names":[],"sources":["../../../src/agent/tool/output-budget.ts"],"mappings":";;;;;;;;;;;;KAqCY;;UAGK;;WAEN;;WAEA;;;;;;;WAOA;;;UAIM;WACN;;WAEA;;WAEA;;;;;;;;;UAUM;;;;;;;EAOf,KAAK,cAAc;aAAoB;aAA2B;MAClE,QAAQ,eAAe;;;;;;;EAOvB,KAAK,iBAAiB;aAAkB;aAAyB;MACjE,QAAQ,0BAA0B;;;;;;;;EAQlC,OAAO,iBAAiB,iBAAiB,gBACzC;;;UAIe;;WAEN;;WAEA;;;;;;;;;;;;;;iBAeK,uBAAuB,SAAQ,yBAA8B;;;;;;;;;;;iBAiF7D,mBAAmB;;;;;;;;;iBAYnB,wBAAwB,kBAAkB;;UAQzC;WACN;;WAEA;;;;;;;;;;;;;iBAcK,uBAAuB,cAAc,oBAAoB;;;;;;;iBAyBzD,gBAAgB,cAAc;;cAKjC;UAEH;WACC;WACA;WACA;WACA;;;;;;;;;;;;iBAaK,cAAc,OAAO,YAAY,wBAAuB,eAAe"}
@@ -0,0 +1,3 @@
1
+ import{defineTool as e}from"./definition.js";function t(e={}){let t=n(e.maxEntries??64,`maxEntries`),r=n(e.maxChars??32e6,`maxChars`),i=new Map,a=0,o=0,s=e=>{for(;(i.size>=t||a+e>r)&&i.size>0;){let e=i.keys().next().value;if(e===void 0)break;a-=[...i.get(e)??``].length,i.delete(e)}};return{save(e,t){let n=[...e].length;s(n),o+=1;let r=`spill:${t.toolName}:${String(o)}`;return i.set(r,e),a+=n,{locator:r,bytes:new TextEncoder().encode(e).byteLength,retrieval:`Call read_tool_output with locator "${r}" to read the rest, or with a pattern to search it.`}},read(e,t){let n=i.get(e);if(n===void 0)return;let r=[...n],a=Math.min(Math.max(0,t.offset),r.length);return{text:r.slice(a,a+Math.max(1,t.limit)).join(``),totalChars:r.length,offset:a}},search(e,t,n){let r=i.get(e);if(r===void 0)return;let a=new RegExp(t),o=[],s=r.split(`
2
+ `);for(let e=0;e<s.length&&o.length<n;e++){let t=s[e]??``;a.test(t)&&o.push(`${String(e+1)}: ${t}`)}return Object.freeze(o)}}}function n(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`spill store ${t} must be a positive safe integer`);return e}function r(e){return Math.ceil(e.length/4)}function i(e){return e.reduce((e,t)=>t.type===`text`?e+r(t.text):e,0)}function a(e,t){let n=r(e);if(n<=t)return{text:e,originalTokens:n};let i=Math.max(1,t*4),a=Math.max(1,Math.floor(i*.66)),o=Math.max(0,i-a),s=[...e],c=n-t,l=`\n\n[... ${String(c)} estimated tokens omitted from the middle ...]\n\n`;return{text:s.slice(0,a).join(``)+l+(o===0?``:s.slice(s.length-o).join(``)),originalTokens:n}}function o(e,t){return a(e,t).text}const s=`read_tool_output`;function c(t,n=8e3){return e({name:s,description:`Read or search the full output of an earlier tool call that was too large to show in full. Pass the locator from that result. Use pattern to find matching lines, or offset/limit to page through it.`,parameters:{type:`object`,properties:{locator:{type:`string`,description:`The locator printed with the shortened result.`},offset:{type:`number`,description:`Character offset to start reading from.`},limit:{type:`number`,description:`Characters to read; defaults to ${String(n)}.`},pattern:{type:`string`,description:`Regular expression matched per line; returns matching lines with numbers.`}},required:[`locator`],additionalProperties:!1},budgetExempt:!0,parse:u,isConcurrencySafe:()=>!0,execute:async e=>{if(e.pattern!==void 0){let n=await t.search(e.locator,e.pattern,200);return n===void 0?l(e.locator):{locator:e.locator,matches:[...n]}}let r=await t.read(e.locator,{offset:e.offset??0,limit:e.limit??n});if(r===void 0)return l(e.locator);let i=r.offset+[...r.text].length;return{locator:e.locator,offset:r.offset,nextOffset:i<r.totalChars?i:null,totalChars:r.totalChars,text:r.text}}})}function l(e){return{locator:e,error:`no saved output for this locator; it may have expired. Re-run the original call more narrowly if you still need it.`}}function u(e){if(typeof e!=`object`||!e)throw TypeError(`arguments must be an object`);let t=e,n=t.locator;if(typeof n!=`string`||n.length===0)throw TypeError(`locator must be a non-empty string`);let r=d(t.offset,`offset`),i=d(t.limit,`limit`),a=t.pattern;if(a!==void 0&&typeof a!=`string`)throw TypeError(`pattern must be a string`);return{locator:n,...r===void 0?{}:{offset:r},...i===void 0?{}:{limit:i},...a===void 0||a===``?{}:{pattern:a}}}function d(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw TypeError(`${t} must be a non-negative number`);return Math.floor(e)}}export{s as SPILL_TOOL_NAME,t as createMemorySpillStore,i as estimateTextBlockTokens,r as estimateTextTokens,o as previewForSpill,c as readSpillTool,a as truncateMiddleToTokens};
3
+ //# sourceMappingURL=output-budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-budget.js","names":[],"sources":["../../../src/agent/tool/output-budget.ts"],"sourcesContent":["/**\n * How much of a tool's output the model is allowed to read.\n *\n * A tool result enters the model's context unchanged, so one `cat` of a\n * generated bundle can spend a context window that the turn then has no way to\n * recover — the provider rejects the next request, and everything already paid\n * for is lost. Both reference harnesses stop this at the RESULT boundary rather\n * than waiting for the request to be assembled, and they differ only in where\n * the removed text goes:\n *\n * - **Codex** truncates the middle to a token budget and tells the model how\n * much was dropped (`truncate_middle_with_token_budget`). Cheap and needs no\n * storage; the model recovers by re-running a narrower command.\n * - **The DeepSeek harness** spills the full text to a store, and hands the\n * model a bounded preview plus a locator to read or search (`dsh-spill`).\n * Nothing is lost, but it needs somewhere to put the text.\n *\n * Both are offered here. `auto` — the default — takes the second when a store\n * is mounted and the first when none is, so the cheap path works everywhere and\n * the lossless one turns itself on the moment it can.\n *\n * @module ai-agent-sdk/agent/tool/output-budget\n */\n\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { JsonObject } from '../../primitives/index.ts'\nimport { defineTool, type ToolDefinition } from './definition.ts'\n\n/**\n * What happens to output that exceeds its budget.\n *\n * - `auto` — spill when a store is mounted, otherwise truncate.\n * - `truncate` — always cut the middle; never needs a store.\n * - `spill` — save the full text and show a preview; falls back to truncating\n * when no store is mounted or the store fails, because losing the result\n * entirely is worse than shortening it.\n */\nexport type ToolOutputOverflowPolicy = 'auto' | 'truncate' | 'spill'\n\n/** A saved copy of one oversized tool result. */\nexport interface SpillRecord {\n /** Opaque handle the retrieval tool resolves; also shown to the model. */\n readonly locator: string\n /** Exact size of the saved text. */\n readonly bytes: number\n /**\n * One sentence telling the model how to get the rest.\n *\n * Written by the backend, because only it knows what the locator IS — a file\n * a shell can grep, or a handle only the built-in retrieval tool resolves.\n */\n readonly retrieval: string\n}\n\n/** A slice of a saved tool result. */\nexport interface SpillSlice {\n readonly text: string\n /** Total code points in the saved text, so a reader can page through it. */\n readonly totalChars: number\n /** Where this slice starts. */\n readonly offset: number\n}\n\n/**\n * Where oversized tool output goes when the policy spills it.\n *\n * The port is deliberately tiny: core is a universal package and cannot open a\n * file, so a host that wants durable spill implements this over its own\n * storage. {@link createMemorySpillStore} covers the common case.\n */\nexport interface SpillStore {\n /**\n * Save one oversized result.\n * @param text - The complete model-facing text.\n * @param context - What produced it, for naming and diagnostics.\n * @returns The locator the model can retrieve it by.\n */\n save(text: string, context: { readonly toolName: string; readonly callId: string }):\n Promise<SpillRecord> | SpillRecord\n /**\n * Read part of a saved result.\n * @param locator - A locator returned by {@link SpillStore.save}.\n * @param range - Where to start and how much to read, in code points.\n * @returns The slice, or undefined when the locator is unknown or expired.\n */\n read(locator: string, range: { readonly offset: number; readonly limit: number }):\n Promise<SpillSlice | undefined> | SpillSlice | undefined\n /**\n * Find matching lines in a saved result.\n * @param locator - A locator returned by {@link SpillStore.save}.\n * @param pattern - A regular expression source, matched per line.\n * @param limit - Maximum lines returned.\n * @returns Matching `line-number: text` entries, or undefined when unknown.\n */\n search(locator: string, pattern: string, limit: number):\n Promise<readonly string[] | undefined> | readonly string[] | undefined\n}\n\n/** Bounds for the built-in in-process store. */\nexport interface MemorySpillStoreLimits {\n /** Saved results kept before the oldest is evicted. Defaults to 64. */\n readonly maxEntries?: number\n /** Total characters kept across all entries. Defaults to 32,000,000. */\n readonly maxChars?: number\n}\n\n/**\n * A spill store that keeps text in this process.\n *\n * Universal, so it works in a browser and in a worker as well as on a server,\n * and enough for the case the policy exists for: the text leaves the model's\n * context immediately and is read back through the retrieval tool. It is not\n * durable — a restart loses it, and the locators in an old transcript stop\n * resolving. A host that needs durability implements {@link SpillStore} over\n * its own filesystem or object storage.\n * @param limits - Retention bounds.\n * @returns The store.\n */\nexport function createMemorySpillStore(limits: MemorySpillStoreLimits = {}): SpillStore {\n const maxEntries = positive(limits.maxEntries ?? 64, 'maxEntries')\n const maxChars = positive(limits.maxChars ?? 32_000_000, 'maxChars')\n // Insertion-ordered, which makes the oldest entry the first key.\n const entries = new Map<string, string>()\n let held = 0\n let counter = 0\n\n // One text larger than the whole allowance evicts everything and is still\n // kept: dropping the save would leave the model a locator that resolves to\n // nothing, which is worse than briefly exceeding a soft retention bound. The\n // next save evicts it.\n const evictUntil = (room: number): void => {\n while ((entries.size >= maxEntries || held + room > maxChars) && entries.size > 0) {\n const oldest = entries.keys().next().value\n if (oldest === undefined) break\n held -= [...entries.get(oldest) ?? ''].length\n entries.delete(oldest)\n }\n }\n\n return {\n save(text, context) {\n const chars = [...text].length\n evictUntil(chars)\n counter += 1\n const locator = `spill:${context.toolName}:${String(counter)}`\n entries.set(locator, text)\n held += chars\n return {\n locator,\n bytes: new TextEncoder().encode(text).byteLength,\n retrieval: `Call read_tool_output with locator \"${locator}\" to read the rest,`\n + ' or with a pattern to search it.',\n }\n },\n read(locator, range) {\n const text = entries.get(locator)\n if (text === undefined) return undefined\n const points = [...text]\n const offset = Math.min(Math.max(0, range.offset), points.length)\n return {\n text: points.slice(offset, offset + Math.max(1, range.limit)).join(''),\n totalChars: points.length,\n offset,\n }\n },\n search(locator, pattern, limit) {\n const text = entries.get(locator)\n if (text === undefined) return undefined\n // An invalid pattern is the model's mistake to correct, so it surfaces as\n // a thrown tool error rather than as silently zero matches.\n const expression = new RegExp(pattern)\n const found: string[] = []\n const lines = text.split('\\n')\n for (let index = 0; index < lines.length && found.length < limit; index++) {\n const line = lines[index] ?? ''\n if (expression.test(line)) found.push(`${String(index + 1)}: ${line}`)\n }\n return Object.freeze(found)\n },\n }\n}\n\nfunction positive(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`spill store ${name} must be a positive safe integer`)\n }\n return value\n}\n\n/**\n * Deterministic token estimate for text.\n *\n * Four characters per token, the same heuristic compaction uses, and the same\n * order of magnitude as Codex's `approx_token_count`. It is an estimate: a real\n * tokenizer differs, and dense scripts differ more. It is used to decide when\n * to shorten output, never to bill anything.\n * @param text - The text to measure.\n * @returns The estimated token count.\n */\nexport function estimateTextTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/**\n * Estimated tokens for the text a tool result puts in front of the model.\n *\n * Only text is counted. An image block is left alone — shortening it produces a\n * corrupt image rather than a smaller one.\n * @param content - The result's content blocks.\n * @returns The estimated token count of the text blocks.\n */\nexport function estimateTextBlockTokens(content: readonly ContentBlock[]): number {\n return content.reduce(\n (total, block) => block.type === 'text' ? total + estimateTextTokens(block.text) : total,\n 0,\n )\n}\n\n/** The result of shortening one oversized text. */\nexport interface TruncatedText {\n readonly text: string\n /** Estimated tokens the original held. */\n readonly originalTokens: number\n}\n\n/**\n * Cut the middle out of a text to fit a token budget.\n *\n * The middle goes because the two ends carry the most: a command's invocation\n * and its verdict, a file's header and its tail. Codex splits its budget the\n * same way. The marker states how much left, so the model can see that it is\n * reading a fragment rather than a short result.\n * @param text - The full text.\n * @param maxTokens - Estimated tokens the model may read.\n * @returns The shortened text and what the original held.\n */\nexport function truncateMiddleToTokens(text: string, maxTokens: number): TruncatedText {\n const originalTokens = estimateTextTokens(text)\n if (originalTokens <= maxTokens) return { text, originalTokens }\n const budget = Math.max(1, maxTokens * 4)\n // Two thirds to the head: a command's own output usually leads with what it\n // did, and the tail is mostly the verdict.\n const head = Math.max(1, Math.floor(budget * 0.66))\n const tail = Math.max(0, budget - head)\n const points = [...text]\n const removed = originalTokens - maxTokens\n const marker = `\\n\\n[... ${String(removed)} estimated tokens omitted from the middle ...]\\n\\n`\n return {\n text: points.slice(0, head).join('')\n + marker\n + (tail === 0 ? '' : points.slice(points.length - tail).join('')),\n originalTokens,\n }\n}\n\n/**\n * The head/tail preview shown in place of a spilled result.\n * @param text - The full text.\n * @param maxTokens - Estimated tokens the preview may hold.\n * @returns The preview.\n */\nexport function previewForSpill(text: string, maxTokens: number): string {\n return truncateMiddleToTokens(text, maxTokens).text\n}\n\n/** The name the retrieval tool is registered under. */\nexport const SPILL_TOOL_NAME = 'read_tool_output'\n\ninterface ReadSpillArgs {\n readonly locator: string\n readonly offset?: number\n readonly limit?: number\n readonly pattern?: string\n}\n\n/**\n * The tool that reads back what a spill took out of the context.\n *\n * Spilling without this would be worse than truncating: the model would be\n * told its output exists somewhere and given no way to reach it. Registered\n * automatically wherever a store is mounted.\n * @param store - The mounted store.\n * @param defaultLimit - Characters one read returns when none is asked for.\n * @returns The tool definition.\n */\nexport function readSpillTool(store: SpillStore, defaultLimit = 8_000): ToolDefinition<ReadSpillArgs> {\n return defineTool({\n name: SPILL_TOOL_NAME,\n description: 'Read or search the full output of an earlier tool call that was too large to'\n + ' show in full. Pass the locator from that result. Use pattern to find matching lines,'\n + ' or offset/limit to page through it.',\n parameters: {\n type: 'object',\n properties: {\n locator: { type: 'string', description: 'The locator printed with the shortened result.' },\n offset: { type: 'number', description: 'Character offset to start reading from.' },\n limit: { type: 'number', description: `Characters to read; defaults to ${String(defaultLimit)}.` },\n pattern: {\n type: 'string',\n description: 'Regular expression matched per line; returns matching lines with numbers.',\n },\n },\n required: ['locator'],\n additionalProperties: false,\n },\n // Reading back is not exploration, and a model that cannot reach its own\n // spilled output is worse off than one whose output was simply cut.\n budgetExempt: true,\n parse: parseReadSpill,\n isConcurrencySafe: () => true,\n execute: async (args) => {\n if (args.pattern !== undefined) {\n const matches = await store.search(args.locator, args.pattern, 200)\n if (matches === undefined) return unknownLocator(args.locator)\n return { locator: args.locator, matches: [...matches] }\n }\n const slice = await store.read(args.locator, {\n offset: args.offset ?? 0,\n limit: args.limit ?? defaultLimit,\n })\n if (slice === undefined) return unknownLocator(args.locator)\n const end = slice.offset + [...slice.text].length\n return {\n locator: args.locator,\n offset: slice.offset,\n nextOffset: end < slice.totalChars ? end : null,\n totalChars: slice.totalChars,\n text: slice.text,\n }\n },\n })\n}\n\nfunction unknownLocator(locator: string): JsonObject {\n // A store that has evicted or lost the entry is a normal outcome, not a\n // crash: the model needs to know to re-run the original call instead.\n return {\n locator,\n error: 'no saved output for this locator; it may have expired. Re-run the original call'\n + ' more narrowly if you still need it.',\n }\n}\n\nfunction parseReadSpill(raw: unknown): ReadSpillArgs {\n if (typeof raw !== 'object' || raw === null) throw new TypeError('arguments must be an object')\n const value = raw as Record<string, unknown>\n const locator = value['locator']\n if (typeof locator !== 'string' || locator.length === 0) {\n throw new TypeError('locator must be a non-empty string')\n }\n const offset = optionalCount(value['offset'], 'offset')\n const limit = optionalCount(value['limit'], 'limit')\n const pattern = value['pattern']\n if (pattern !== undefined && typeof pattern !== 'string') {\n throw new TypeError('pattern must be a string')\n }\n return {\n locator,\n ...offset === undefined ? {} : { offset },\n ...limit === undefined ? {} : { limit },\n ...pattern === undefined || pattern === '' ? {} : { pattern },\n }\n}\n\nfunction optionalCount(value: unknown, name: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new TypeError(`${name} must be a non-negative number`)\n }\n return Math.floor(value)\n}\n"],"mappings":"6CAsHA,SAAgB,EAAuB,EAAiC,CAAC,EAAe,CACtF,IAAM,EAAa,EAAS,EAAO,YAAc,GAAI,YAAY,EAC3D,EAAW,EAAS,EAAO,UAAY,KAAY,UAAU,EAE7D,EAAU,IAAI,IAChB,EAAO,EACP,EAAU,EAMR,EAAc,GAAuB,CACzC,MAAQ,EAAQ,MAAQ,GAAc,EAAO,EAAO,IAAa,EAAQ,KAAO,GAAG,CACjF,IAAM,EAAS,EAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MACrC,GAAI,IAAW,IAAA,GAAW,MAC1B,GAAQ,CAAC,GAAG,EAAQ,IAAI,CAAM,GAAK,EAAE,CAAC,CAAC,OACvC,EAAQ,OAAO,CAAM,CACvB,CACF,EAEA,MAAO,CACL,KAAK,EAAM,EAAS,CAClB,IAAM,EAAQ,CAAC,GAAG,CAAI,CAAC,CAAC,OACxB,EAAW,CAAK,EAChB,GAAW,EACX,IAAM,EAAU,SAAS,EAAQ,SAAS,GAAG,OAAO,CAAO,IAG3D,OAFA,EAAQ,IAAI,EAAS,CAAI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AK,MAAM,CAAK,CAFsC,CAG/D"}
@@ -0,0 +1,98 @@
1
+ import { ToolCallId } from "../../primitives/brand.js";
2
+ import { JsonObject } from "../../primitives/json.js";
3
+ import { ContentBlock } from "../../message/content.js";
4
+ import { SdkLogger } from "../../logging/types.js";
5
+ import { ToolCallPosition, ToolDefinition, ToolExecutionMode, ToolExecutionResult, ToolFailure } from "./definition.js";
6
+ import { ApprovalBroker, ApprovalRequest } from "./approval.js";
7
+ import { ToolCatalog } from "./registry.js";
8
+ //#region src/agent/tool/pipeline.d.ts
9
+ interface ToolCallRequest {
10
+ readonly callId: ToolCallId;
11
+ readonly toolName: string;
12
+ readonly rawArguments: string;
13
+ }
14
+ interface ToolCallContext extends ToolCallPosition {
15
+ readonly callId: ToolCallId;
16
+ readonly toolName: string;
17
+ readonly tool: ToolDefinition | undefined;
18
+ readonly rawArguments: string;
19
+ readonly args: unknown;
20
+ readonly signal: AbortSignal;
21
+ readonly logger?: SdkLogger;
22
+ }
23
+ type PreToolDecision = {
24
+ kind: 'allow';
25
+ } | {
26
+ kind: 'deny';
27
+ reason: string;
28
+ } | {
29
+ kind: 'ask';
30
+ reason?: string;
31
+ };
32
+ type PostToolDecision = {
33
+ kind: 'accept';
34
+ } | {
35
+ kind: 'replace';
36
+ content: readonly ContentBlock[];
37
+ meta?: JsonObject;
38
+ } | {
39
+ kind: 'block';
40
+ feedback: readonly ContentBlock[];
41
+ code?: string;
42
+ };
43
+ interface ToolInterceptor {
44
+ readonly name: string;
45
+ readonly before?: (call: ToolCallContext, next: () => Promise<PreToolDecision>) => Promise<PreToolDecision>;
46
+ readonly around?: (call: ToolCallContext, next: () => Promise<ToolExecutionResult>) => Promise<ToolExecutionResult>;
47
+ readonly after?: (call: ToolCallContext, result: ToolExecutionResult, next: () => Promise<PostToolDecision>) => Promise<PostToolDecision>;
48
+ }
49
+ interface DispatchToolCallOptions {
50
+ readonly catalog: ToolCatalog;
51
+ readonly call: ToolCallRequest;
52
+ readonly position: ToolCallPosition;
53
+ readonly signal: AbortSignal;
54
+ readonly logger?: SdkLogger;
55
+ readonly interceptors?: readonly ToolInterceptor[];
56
+ readonly approvals?: ApprovalBroker;
57
+ /** Maximum wait after a timed-out in-process tool ignores cancellation. */
58
+ readonly teardownTimeoutMs?: number;
59
+ /** Timeout used when the tool definition does not declare one. */
60
+ readonly defaultTimeoutMs?: number;
61
+ /** Called immediately before an approval broker is awaited. */
62
+ readonly onApprovalRequest?: (request: ApprovalRequest) => Promise<void> | void;
63
+ /** Called exactly once after an approval wait settles or fails. */
64
+ readonly onApprovalSettled?: (status: 'success' | 'error' | 'aborted', error?: unknown) => void;
65
+ }
66
+ interface PreparedToolCall {
67
+ readonly options: DispatchToolCallOptions;
68
+ readonly context: ToolCallContext;
69
+ readonly argumentFailure?: ToolFailure;
70
+ readonly mode: ToolExecutionMode;
71
+ }
72
+ interface AuthorizedToolCall extends PreparedToolCall {
73
+ readonly tool: ToolDefinition;
74
+ }
75
+ type AuthorizationOutcome = {
76
+ readonly kind: 'authorized';
77
+ readonly call: AuthorizedToolCall;
78
+ } | {
79
+ readonly kind: 'final';
80
+ readonly result: ToolExecutionResult;
81
+ };
82
+ declare function toolFailure(message: string, code: string, extra?: {
83
+ meta?: JsonObject;
84
+ additionalContext?: readonly ContentBlock[];
85
+ }): ToolFailure;
86
+ /** Resolve, parse exactly once, validate and classify one call. */
87
+ declare function prepareToolCall(options: DispatchToolCallOptions): PreparedToolCall;
88
+ /** Ordered pre-policy and approval stage. */
89
+ declare function authorizeToolCall(prepared: PreparedToolCall): Promise<AuthorizationOutcome>;
90
+ /** Body/around stage; this is the only stage the scheduler overlaps. */
91
+ declare function dispatchAuthorizedToolCall(call: AuthorizedToolCall): Promise<ToolExecutionResult>;
92
+ /** Ordered post-policy stage. */
93
+ declare function finalizeToolCall(call: AuthorizedToolCall, executed: ToolExecutionResult): Promise<ToolExecutionResult>;
94
+ /** Compatibility facade for callers that do not need scheduling. */
95
+ declare function dispatchToolCall(options: DispatchToolCallOptions): Promise<ToolExecutionResult>;
96
+ //#endregion
97
+ export { AuthorizationOutcome, AuthorizedToolCall, DispatchToolCallOptions, PostToolDecision, PreToolDecision, PreparedToolCall, ToolCallContext, ToolCallRequest, ToolInterceptor, authorizeToolCall, dispatchAuthorizedToolCall, dispatchToolCall, finalizeToolCall, prepareToolCall, toolFailure };
98
+ //# sourceMappingURL=pipeline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipeline.d.ts","names":[],"sources":["../../../src/agent/tool/pipeline.ts"],"mappings":";;;;;;;;UAeiB;WACN,QAAQ;WACR;WACA;;UAEM,wBAAwB;WAC9B,QAAQ;WACR;WACA,MAAM;WACN;WACA;WACA,QAAQ;WACR,SAAS;;KAER;EACN;;EACA;EAAc;;EACd;EAAa;;KACP;EACN;;EACA;EAAiB,kBAAkB;EAAgB,OAAO;;EAC1D;EAAe,mBAAmB;EAAgB;;UACvC;WACN;WACA,UAAU,MAAM,iBAAiB,YAAY,QAAQ,qBAAqB,QAAQ;WAClF,UAAU,MAAM,iBAAiB,YAAY,QAAQ,yBAAyB,QAAQ;WACtF,SACP,MAAM,iBACN,QAAQ,qBACR,YAAY,QAAQ,sBACjB,QAAQ;;UAEE;WACN,SAAS;WACT,MAAM;WACN,UAAU;WACV,QAAQ;WACR,SAAS;WACT,wBAAwB;WACxB,YAAY;;WAEZ;;WAEA;;WAEA,qBAAqB,SAAS,oBAAoB;;WAElD,qBAAqB,yCAAyC;;UAExD;WACN,SAAS;WACT,SAAS;WACT,kBAAkB;WAClB,MAAM;;UAEA,2BAA2B;WAA4B,MAAM;;KAClE;WACG;WAA6B,MAAM;;WACnC;WAAwB,QAAQ;;iBAE/B,YACd,iBACA,cACA;EAAS,OAAO;EAAY,6BAA6B;IACxD;;iBAWa,gBAAgB,SAAS,0BAA0B;;iBA+B7C,kBAAkB,UAAU,mBAAmB,QAAQ;;iBA8DvD,2BAA2B,MAAM,qBAAqB,QAAQ;;iBA8E9D,iBAAiB,MAAM,oBAAoB,UAAU,sBAAsB,QAAQ;;iBAqCnF,iBAAiB,SAAS,0BAA0B,QAAQ"}
@@ -0,0 +1,4 @@
1
+ import{isJsonValue as e}from"../../primitives/json.js";import{waitForSettlement as t}from"../../async/settlement.js";import{executionModeOf as n,renderJsonValue as r}from"./definition.js";import{TOOL_ERROR_CODES as i,ToolError as a,toolErrorDisposition as o}from"./errors.js";import{createApprovalRequest as s}from"./approval.js";function c(e,t,n={}){return{isError:!0,error:{message:e,code:t},content:[{type:`text`,text:`Error: ${e}`}],...n.meta===void 0?{}:{meta:n.meta},...n.additionalContext===void 0?{}:{additionalContext:n.additionalContext}}}function l(e){let{catalog:t,call:r,position:a,signal:o}=e,s=t.get(r.toolName),l,u;if(s===void 0)u=c(`no tool named "${r.toolName}" is available`,i.UNKNOWN_TOOL);else{let e=h(r.rawArguments);if(!e.ok)u=c(e.message,i.MALFORMED_ARGUMENTS);else if(s.parse===void 0)l=e.value;else try{l=s.parse(e.value)}catch(e){u=c(`invalid arguments: ${g(e)}`,i.INVALID_ARGUMENTS)}}return{options:e,context:{...a,callId:r.callId,toolName:r.toolName,tool:s,rawArguments:r.rawArguments,args:l,signal:o,...e.logger===void 0?{}:{logger:e.logger}},...u===void 0?{}:{argumentFailure:u},mode:u===void 0?n(s,l):`exclusive`}}async function u(e){if(e.argumentFailure!==void 0)return{kind:`final`,result:e.argumentFailure};let t=await v(e.options.interceptors??[],t=>t.before?.bind(t,e.context),()=>Promise.resolve({kind:`allow`}))();if(t.kind===`deny`)return{kind:`final`,result:c(t.reason,i.DENIED)};if(t.kind===`ask`){let n=e.options.approvals;if(n===void 0)return{kind:`final`,result:c(t.reason??`this tool requires approval, and no approver is configured`,i.DENIED)};let r=s({...e.options.position,callId:e.context.callId,toolName:e.context.toolName,args:e.context.args,turn:e.context.turn,step:e.context.step,...t.reason===void 0?{}:{reason:t.reason}}),o=new AbortController,l=AbortSignal.any([e.context.signal,o.signal]),u=n.request(r,l);try{await e.options.onApprovalRequest?.(r)}catch(t){throw o.abort(t),await u.catch(()=>void 0),e.options.onApprovalSettled?.(`error`,t),t}let d;try{d=await u,e.options.onApprovalSettled?.(d===`abort`||e.context.signal.aborted?`aborted`:`success`)}catch(t){throw e.options.onApprovalSettled?.(e.context.signal.aborted?`aborted`:`error`,t),t}if(d!==`allow`&&d!==`deny`&&d!==`abort`)throw a.fatal(`invalid approval decision`,`INVALID_APPROVAL_DECISION`);if(d===`abort`)throw a.fatal(`the turn was withdrawn while awaiting approval`,i.ABORTED);if(d===`deny`)return{kind:`final`,result:c(t.reason??`the call to "${e.context.toolName}" was not approved`,i.DENIED)}}let n=e.context.tool;return n===void 0?{kind:`final`,result:c(`no tool named "${e.context.toolName}" is available`,i.UNKNOWN_TOOL)}:{kind:`authorized`,call:{...e,tool:n}}}async function d(t){let{context:n,tool:s}=t;if(n.signal.aborted)return c(`the call was cancelled before it started`,i.ABORTED_BEFORE_DISPATCH);let l=async l=>{let u=[],d=!1,f={...t.options.position,turn:n.turn,step:n.step,callId:n.callId,toolName:n.toolName,signal:l,...n.logger===void 0?{}:{logger:n.logger},concludeTurn:()=>{d=!0},addContext:e=>{typeof e==`string`?u.push({type:`text`,text:e}):u.push(...e)}},p;try{let e=await s.execute(n.args,f);p=e===void 0?void 0:e}catch(e){if(o(e)===`fatal`)throw e;return l.aborted&&!(e instanceof a)?c(`the call was cancelled`,i.ABORTED):c(g(e),e instanceof a?e.code:i.FAILED,{additionalContext:u})}if(p!==void 0&&!e(p))return c(`tool "${s.name}" returned a value that is not lossless JSON; return plain objects, arrays, strings, finite numbers, booleans, or null`,i.INVALID_RESULT);let m,h;try{m=s.render===void 0?r(p):s.render(p,n.args),h=s.meta?.(p,n.args)}catch(e){return{isError:!1,value:p,content:r(p),...u.length===0?{}:{additionalContext:u},...d?{concludesTurn:!0}:{},meta:{renderError:g(e)}}}return{isError:!1,value:p,content:m,...h===void 0?{}:{meta:h},...u.length===0?{}:{additionalContext:u},...d?{concludesTurn:!0}:{}}},u=await v(t.options.interceptors??[],e=>e.around?.bind(e,n),()=>y(s.timeoutMs??t.options.defaultTimeoutMs,n.signal,l,t.options.teardownTimeoutMs??3e4))();if(!u.isError||u.meta!==void 0||s.meta===void 0)return u;try{let e=s.meta(void 0,n.args);return e===void 0?u:{...u,meta:e}}catch{return u}}async function f(e,t){let n=await v(e.options.interceptors??[],n=>n.after?.bind(n,e.context,t),()=>Promise.resolve({kind:`accept`}))();return n.kind===`accept`?t:n.kind===`replace`?t.isError?{isError:!0,error:{message:n.content.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
2
+ `)||`the tool result was replaced by policy`,code:i.DENIED},content:n.content,...n.meta===void 0?{}:{meta:n.meta}}:{isError:!1,value:void 0,content:n.content,...n.meta===void 0?{}:{meta:n.meta},...t.concludesTurn===!0?{concludesTurn:!0}:{}}:{isError:!0,error:{message:n.feedback.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
3
+ `)||`the result was blocked by policy`,code:n.code??i.DENIED},content:n.feedback}}async function p(e){if(e.signal.aborted)return c(`the call was cancelled before it started`,i.ABORTED_BEFORE_DISPATCH);let n=_(e.defaultTimeoutMs??6e5,`defaultTimeoutMs`),r=_(e.teardownTimeoutMs??3e4,`teardownTimeoutMs`),o=AbortSignal.timeout(n),s=AbortSignal.any([e.signal,o]),l=m({...e,signal:s,defaultTimeoutMs:n,teardownTimeoutMs:r});try{return await b(l,s)}catch(u){if(!s.aborted)throw u;if(!await t(l,r))throw a.fatal(`tool pipeline ignored cancellation for more than ${r}ms; the in-process operation may still be running`,i.TEARDOWN_TIMEOUT,{cause:u});return o.aborted&&!e.signal.aborted?c(`the tool pipeline exceeded its ${n}ms time limit`,i.TIMEOUT):await l}}async function m(e){let t=await u(l(e));return t.kind===`final`?t.result:await f(t.call,await d(t.call))}function h(e){let t=e.trim();if(t.length===0)return{ok:!0,value:{}};try{return{ok:!0,value:JSON.parse(t)}}catch(e){return{ok:!1,message:`arguments were not valid JSON: ${g(e)}`}}}function g(e){if(e instanceof Error&&e.message.length>0)return e.message;let t=String(e);return t.length>0?t:`the tool failed without a message`}function _(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function v(e,t,n){let r=n;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i===void 0)continue;let a=t(i);if(a===void 0)continue;let o=r;r=()=>a(o)}return r}async function y(e,n,r,o){if(e===void 0)return await r(n);let s=new AbortController,l=!1,u=setTimeout(()=>{l=!0,s.abort(Error(`tool timed out after ${e}ms`))},e),d=r(AbortSignal.any([n,s.signal]));try{let t=await b(d,s.signal);return l?c(`the tool exceeded its ${e}ms time limit`,i.TIMEOUT):t}catch(n){if(!l)throw n;if(!await t(d,o))throw a.fatal(`tool ignored timeout cancellation for more than ${o}ms; the in-process operation may still be running`,i.TEARDOWN_TIMEOUT,{cause:n});return c(`the tool exceeded its ${e}ms time limit`,i.TIMEOUT)}finally{clearTimeout(u)}}async function b(e,t){if(t.aborted)throw t.reason??Error(`tool timed out`);return await new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason??Error(`tool timed out`))};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})})}export{u as authorizeToolCall,d as dispatchAuthorizedToolCall,p as dispatchToolCall,f as finalizeToolCall,l as prepareToolCall,c as toolFailure};
4
+ //# sourceMappingURL=pipeline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipeline.js","names":[],"sources":["../../../src/agent/tool/pipeline.ts"],"sourcesContent":["/** Staged tool dispatch: prepare/authorize/dispatch/finalize. */\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { ToolCallId } from '../../primitives/index.ts'\nimport { isJsonValue, type JsonObject, type JsonValue } from '../../primitives/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { createApprovalRequest, type ApprovalBroker, type ApprovalRequest } from './approval.ts'\nimport {\n executionModeOf, renderJsonValue, type ToolCallPosition, type ToolDefinition,\n type ToolExecutionMode, type ToolExecutionResult, type ToolFailure, type ToolRunContext,\n type ToolSuccess,\n} from './definition.ts'\nimport { TOOL_ERROR_CODES, ToolError, toolErrorDisposition } from './errors.ts'\nimport type { ToolCatalog } from './registry.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\n\nexport interface ToolCallRequest {\n readonly callId: ToolCallId\n readonly toolName: string\n readonly rawArguments: string\n}\nexport interface ToolCallContext extends ToolCallPosition {\n readonly callId: ToolCallId\n readonly toolName: string\n readonly tool: ToolDefinition | undefined\n readonly rawArguments: string\n readonly args: unknown\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n}\nexport type PreToolDecision =\n | { kind: 'allow' }\n | { kind: 'deny'; reason: string }\n | { kind: 'ask'; reason?: string }\nexport type PostToolDecision =\n | { kind: 'accept' }\n | { kind: 'replace'; content: readonly ContentBlock[]; meta?: JsonObject }\n | { kind: 'block'; feedback: readonly ContentBlock[]; code?: string }\nexport interface ToolInterceptor {\n readonly name: string\n readonly before?: (call: ToolCallContext, next: () => Promise<PreToolDecision>) => Promise<PreToolDecision>\n readonly around?: (call: ToolCallContext, next: () => Promise<ToolExecutionResult>) => Promise<ToolExecutionResult>\n readonly after?: (\n call: ToolCallContext,\n result: ToolExecutionResult,\n next: () => Promise<PostToolDecision>,\n ) => Promise<PostToolDecision>\n}\nexport interface DispatchToolCallOptions {\n readonly catalog: ToolCatalog\n readonly call: ToolCallRequest\n readonly position: ToolCallPosition\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n /** Maximum wait after a timed-out in-process tool ignores cancellation. */\n readonly teardownTimeoutMs?: number\n /** Timeout used when the tool definition does not declare one. */\n readonly defaultTimeoutMs?: number\n /** Called immediately before an approval broker is awaited. */\n readonly onApprovalRequest?: (request: ApprovalRequest) => Promise<void> | void\n /** Called exactly once after an approval wait settles or fails. */\n readonly onApprovalSettled?: (status: 'success' | 'error' | 'aborted', error?: unknown) => void\n}\nexport interface PreparedToolCall {\n readonly options: DispatchToolCallOptions\n readonly context: ToolCallContext\n readonly argumentFailure?: ToolFailure\n readonly mode: ToolExecutionMode\n}\nexport interface AuthorizedToolCall extends PreparedToolCall { readonly tool: ToolDefinition }\nexport type AuthorizationOutcome =\n | { readonly kind: 'authorized'; readonly call: AuthorizedToolCall }\n | { readonly kind: 'final'; readonly result: ToolExecutionResult }\n\nexport function toolFailure(\n message: string,\n code: string,\n extra: { meta?: JsonObject; additionalContext?: readonly ContentBlock[] } = {},\n): ToolFailure {\n return {\n isError: true,\n error: { message, code },\n content: [{ type: 'text', text: `Error: ${message}` }],\n ...extra.meta === undefined ? {} : { meta: extra.meta },\n ...extra.additionalContext === undefined ? {} : { additionalContext: extra.additionalContext },\n }\n}\n\n/** Resolve, parse exactly once, validate and classify one call. */\nexport function prepareToolCall(options: DispatchToolCallOptions): PreparedToolCall {\n const { catalog, call, position, signal } = options\n const tool = catalog.get(call.toolName)\n let args: unknown\n let argumentFailure: ToolFailure | undefined\n if (tool === undefined) {\n argumentFailure = toolFailure(`no tool named \"${call.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL)\n } else {\n const parsed = parseRawArguments(call.rawArguments)\n if (!parsed.ok) argumentFailure = toolFailure(parsed.message, TOOL_ERROR_CODES.MALFORMED_ARGUMENTS)\n else if (tool.parse === undefined) args = parsed.value\n else {\n try { args = tool.parse(parsed.value) }\n catch (error: unknown) {\n argumentFailure = toolFailure(`invalid arguments: ${messageOf(error)}`, TOOL_ERROR_CODES.INVALID_ARGUMENTS)\n }\n }\n }\n const context: ToolCallContext = {\n ...position, callId: call.callId, toolName: call.toolName, tool,\n rawArguments: call.rawArguments, args, signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n }\n return {\n options, context,\n ...argumentFailure === undefined ? {} : { argumentFailure },\n mode: argumentFailure === undefined ? executionModeOf(tool, args) : 'exclusive',\n }\n}\n\n/** Ordered pre-policy and approval stage. */\nexport async function authorizeToolCall(prepared: PreparedToolCall): Promise<AuthorizationOutcome> {\n if (prepared.argumentFailure !== undefined) return { kind: 'final', result: prepared.argumentFailure }\n const interceptors = prepared.options.interceptors ?? []\n const decision = await chain<PreToolDecision>(\n interceptors,\n interceptor => interceptor.before?.bind(interceptor, prepared.context),\n () => Promise.resolve({ kind: 'allow' } as const),\n )()\n if (decision.kind === 'deny') return { kind: 'final', result: toolFailure(decision.reason, TOOL_ERROR_CODES.DENIED) }\n if (decision.kind === 'ask') {\n const broker = prepared.options.approvals\n if (broker === undefined) {\n return { kind: 'final', result: toolFailure(\n decision.reason ?? 'this tool requires approval, and no approver is configured',\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const request = createApprovalRequest({\n ...prepared.options.position,\n callId: prepared.context.callId, toolName: prepared.context.toolName,\n args: prepared.context.args, turn: prepared.context.turn, step: prepared.context.step,\n ...decision.reason === undefined ? {} : { reason: decision.reason },\n })\n // Start the broker first. The streamed approval event is backpressured, and\n // a UI is allowed to answer synchronously while handling it. Publishing\n // before request() installs its waiter loses that answer and parks forever.\n const publication = new AbortController()\n const signal = AbortSignal.any([prepared.context.signal, publication.signal])\n const pending = broker.request(request, signal)\n try {\n await prepared.options.onApprovalRequest?.(request)\n } catch (error: unknown) {\n publication.abort(error)\n await pending.catch(() => undefined)\n prepared.options.onApprovalSettled?.('error', error)\n throw error\n }\n let answer: Awaited<typeof pending>\n try {\n answer = await pending\n prepared.options.onApprovalSettled?.(\n answer === 'abort' || prepared.context.signal.aborted ? 'aborted' : 'success',\n )\n } catch (error) {\n prepared.options.onApprovalSettled?.(prepared.context.signal.aborted ? 'aborted' : 'error', error)\n throw error\n }\n if (answer !== 'allow' && answer !== 'deny' && answer !== 'abort') throw ToolError.fatal('invalid approval decision', 'INVALID_APPROVAL_DECISION')\n if (answer === 'abort') throw ToolError.fatal('the turn was withdrawn while awaiting approval', TOOL_ERROR_CODES.ABORTED)\n if (answer === 'deny') return { kind: 'final', result: toolFailure(\n decision.reason ?? `the call to \"${prepared.context.toolName}\" was not approved`,\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const tool = prepared.context.tool\n if (tool === undefined) return { kind: 'final', result: toolFailure(\n `no tool named \"${prepared.context.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL,\n ) }\n return { kind: 'authorized', call: { ...prepared, tool } }\n}\n\n/** Body/around stage; this is the only stage the scheduler overlaps. */\nexport async function dispatchAuthorizedToolCall(call: AuthorizedToolCall): Promise<ToolExecutionResult> {\n const { context, tool } = call\n if (context.signal.aborted) return toolFailure(\n 'the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH,\n )\n const body = async (signal: AbortSignal): Promise<ToolExecutionResult> => {\n const extraContext: ContentBlock[] = []\n let concludes = false\n const runContext: ToolRunContext = {\n ...call.options.position,\n turn: context.turn, step: context.step, callId: context.callId,\n toolName: context.toolName, signal,\n ...(context.logger === undefined ? {} : { logger: context.logger }),\n concludeTurn: () => { concludes = true },\n addContext: content => {\n if (typeof content === 'string') extraContext.push({ type: 'text', text: content })\n else extraContext.push(...content)\n },\n }\n let value: JsonValue | undefined\n try {\n const returned = await tool.execute(context.args as never, runContext)\n value = returned === undefined ? undefined : returned\n } catch (error: unknown) {\n if (toolErrorDisposition(error) === 'fatal') throw error\n if (signal.aborted && !(error instanceof ToolError)) return toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n return toolFailure(messageOf(error), error instanceof ToolError ? error.code : TOOL_ERROR_CODES.FAILED, {\n additionalContext: extraContext,\n })\n }\n if (value !== undefined && !isJsonValue(value)) return toolFailure(\n `tool \"${tool.name}\" returned a value that is not lossless JSON; return plain objects, arrays, strings, finite numbers, booleans, or null`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n )\n let content: readonly ContentBlock[]\n let meta: JsonObject | undefined\n try {\n content = tool.render === undefined ? renderJsonValue(value) : tool.render(value, context.args as never)\n meta = tool.meta?.(value, context.args as never)\n } catch (error: unknown) {\n return {\n isError: false, value, content: renderJsonValue(value),\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n meta: { renderError: messageOf(error) },\n } satisfies ToolSuccess\n }\n return {\n isError: false, value, content,\n ...meta === undefined ? {} : { meta },\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n } satisfies ToolSuccess\n }\n const executed = await chain<ToolExecutionResult>(\n call.options.interceptors ?? [],\n interceptor => interceptor.around?.bind(interceptor, context),\n () => withTimeout(\n tool.timeoutMs ?? call.options.defaultTimeoutMs,\n context.signal,\n body,\n call.options.teardownTimeoutMs ?? 30_000,\n ),\n )()\n if (!executed.isError || executed.meta !== undefined || tool.meta === undefined) return executed\n // Provenance and UI metadata are just as important for a failed call as for a\n // successful one. In particular, remote bridges use this to identify which\n // integration produced the error. Metadata is a side channel, so a buggy\n // metadata callback must never replace the original tool failure.\n try {\n const meta = tool.meta(undefined, context.args as never)\n return meta === undefined ? executed : { ...executed, meta }\n } catch {\n return executed\n }\n}\n\n/** Ordered post-policy stage. */\nexport async function finalizeToolCall(call: AuthorizedToolCall, executed: ToolExecutionResult): Promise<ToolExecutionResult> {\n const verdict = await chain<PostToolDecision>(\n call.options.interceptors ?? [],\n interceptor => interceptor.after?.bind(interceptor, call.context, executed),\n () => Promise.resolve({ kind: 'accept' } as const),\n )()\n if (verdict.kind === 'accept') return executed\n if (verdict.kind === 'replace') {\n // Replacement is a sanitization boundary, not a model-content-only edit.\n // Rebuild the envelope so raw value, metadata, errors, and additional\n // context cannot escape through public events, history, or telemetry.\n if (executed.isError) {\n const text = verdict.content.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the tool result was replaced by policy', code: TOOL_ERROR_CODES.DENIED },\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n }\n }\n return {\n isError: false,\n value: undefined,\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n ...executed.concludesTurn === true ? { concludesTurn: true as const } : {},\n }\n }\n const text = verdict.feedback.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the result was blocked by policy', code: verdict.code ?? TOOL_ERROR_CODES.DENIED },\n content: verdict.feedback,\n }\n}\n\n/** Compatibility facade for callers that do not need scheduling. */\nexport async function dispatchToolCall(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n if (options.signal.aborted) {\n return toolFailure('the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH)\n }\n const timeoutMs = positiveSafeInteger(options.defaultTimeoutMs ?? 10 * 60_000, 'defaultTimeoutMs')\n const teardownTimeoutMs = positiveSafeInteger(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const deadline = AbortSignal.timeout(timeoutMs)\n const signal = AbortSignal.any([options.signal, deadline])\n const pending = dispatchToolCallInternal({\n ...options, signal, defaultTimeoutMs: timeoutMs, teardownTimeoutMs,\n })\n try {\n return await raceWithSignal(pending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool pipeline ignored cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n if (deadline.aborted && !options.signal.aborted) {\n return toolFailure(`the tool pipeline exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n }\n return await pending\n }\n}\n\nasync function dispatchToolCallInternal(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n const authorization = await authorizeToolCall(prepareToolCall(options))\n if (authorization.kind === 'final') return authorization.result\n return await finalizeToolCall(authorization.call, await dispatchAuthorizedToolCall(authorization.call))\n}\n\nfunction parseRawArguments(raw: string): { ok: true; value: unknown } | { ok: false; message: string } {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return { ok: true, value: {} }\n try { return { ok: true, value: JSON.parse(trimmed) as unknown } }\n catch (error: unknown) { return { ok: false, message: `arguments were not valid JSON: ${messageOf(error)}` } }\n}\nfunction messageOf(value: unknown): string {\n if (value instanceof Error && value.message.length > 0) return value.message\n const rendered = String(value)\n return rendered.length > 0 ? rendered : 'the tool failed without a message'\n}\nfunction positiveSafeInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`)\n return value\n}\nfunction chain<T>(\n interceptors: readonly ToolInterceptor[],\n pick: (interceptor: ToolInterceptor) => ((next: () => Promise<T>) => Promise<T>) | undefined,\n terminal: () => Promise<T>,\n): () => Promise<T> {\n let next = terminal\n for (let index = interceptors.length - 1; index >= 0; index--) {\n const interceptor = interceptors[index]\n if (interceptor === undefined) continue\n const hook = pick(interceptor)\n if (hook === undefined) continue\n const inner = next\n next = () => hook(inner)\n }\n return next\n}\nasync function withTimeout(\n timeoutMs: number | undefined,\n outer: AbortSignal,\n run: (signal: AbortSignal) => Promise<ToolExecutionResult>,\n teardownTimeoutMs: number,\n): Promise<ToolExecutionResult> {\n if (timeoutMs === undefined) return await run(outer)\n const expiry = new AbortController()\n let expired = false\n const timer = setTimeout(() => {\n expired = true\n expiry.abort(new Error(`tool timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n const pending = run(AbortSignal.any([outer, expiry.signal]))\n try {\n const result = await raceWithSignal(pending, expiry.signal)\n return expired\n ? toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n : result\n } catch (error: unknown) {\n if (!expired) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool ignored timeout cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n return toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n } finally { clearTimeout(timer) }\n}\n\nasync function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw signal.reason ?? new Error('tool timed out')\n return await new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener('abort', abort)\n reject(signal.reason ?? new Error('tool timed out'))\n }\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { signal.removeEventListener('abort', abort); resolve(value) },\n error => { signal.removeEventListener('abort', abort); reject(error) },\n )\n })\n}\n"],"mappings":"0UA2EA,SAAgB,EACd,EACA,EACA,EAA4E,CAAC,EAChE,CACb,MAAO,CACL,QAAS,GACT,MAAO,CAAE,UAAS,MAAK,EACvB,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,UAAU,GAAU,CAAC,EACrD,GAAG,EAAM,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAM,EAAM,IAAK,EACtD,GAAG,EAAM,oBAAsB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAmB,EAAM,iBAAkB,CAC/F,CACF,CAGA,SAAgB,EAAgB,EAAoD,CAClF,GAAM,CAAE,UAAS,OAAM,WAAU,UAAW,EACtC,EAAO,EAAQ,IAAI,EAAK,QAAQ,EAClC,EACA,EACJ,GAAI,IAAS,IAAA,GACX,EAAkB,EAAY,kBAAkB,EAAK,SAAS,gBAAiB,EAAiB,YAAY,MACvG,CACL,IAAM,EAAS,EAAkB,EAAK,YAAY,EAClD,GAAI,CAAC,EAAO,GAAI,EAAkB,EAAY,EAAO,QAAS,EAAiB,mBAAmB,OAC7F,GAAI,EAAK,QAAU,IAAA,GAAW,EAAO,EAAO,WAE/C,GAAI,CAAE,EAAO,EAAK,MAAM,EAAO,KAAK,CAAE,OAC/B,EAAgB,CACrB,EAAkB,EAAY,sBAAsB,EAAU,CAAK,IAAK,EAAiB,i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