@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 @@
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../src/runtime/registry.ts"],"sourcesContent":["/**\n * The adapter registry and the streaming call API.\n *\n * This is the deepseek-harness `LlmRuntime` with its dependency-injection\n * framework removed: a plain `Map` for routes, an ordered array for the\n * interception point that was a cordis waterfall, and a listener set for the\n * topology event. What is kept is everything that made it trustworthy  E * all-or-nothing validating registration, an atomic route swap, prepare/dispatch\n * generation binding, and a single failure funnel at the adapter boundary.\n *\n * @module ai-agent-sdk/core/runtime/registry\n */\n\nimport type { ModelAdapter } from '../contract/adapter.ts'\nimport {\n callConfigEquals,\n type CallConfig,\n type CallConfigAdapterDefaults,\n} from '../contract/call-config.ts'\nimport type { GenerateOptions } from '../contract/generate-options.ts'\nimport type {\n ModelContext,\n ModelCatalogOptions,\n ModelCatalogSnapshot,\n ModelInfo,\n ModelModality,\n ProviderInfo,\n ResolvedModelInfo,\n} from '../contract/model-info.ts'\nimport { resolveRetryPolicy, type ResolvedRetryPolicy } from '../contract/retry-policy.ts'\nimport { ModelError, REGISTRY_ERROR_CODES } from '../errors/model-error.ts'\nimport { deepFreeze } from '../primitives/freeze.ts'\nimport { SDK_VERSION } from '../primitives/version.ts'\nimport type { ObservationResource } from '../observation/event.ts'\nimport type { ObservationPort } from '../observation/port.ts'\nimport type { ModelCallHandle, ModelInvocationContext } from '../observation/report.ts'\nimport type { StreamChunk } from '../stream/chunk.ts'\nimport { createModelCallHandle } from './model-call-handle.ts'\nimport { normalizeResolvedModelInfo, resolveCallWithModelInfo,\n validateCatalogModels, validateModelCatalogSnapshot } from './model-metadata.ts'\nimport { streamAdapter, type PreparedDispatch,\n type RuntimeAdapterRegistration } from './model-stream.ts'\nimport {\n PLUGIN_ERROR_CODES,\n PluginError,\n type AdapterRegistrationHandle,\n type ModelProviderPlugin,\n type ModelProviderRegistrar,\n type PluginRegistrationHandle,\n type StreamMiddleware,\n} from '../plugin/provider-plugin.ts'\n\nexport type { AdapterRegistrationHandle, StreamMiddleware } from '../plugin/provider-plugin.ts'\n\n/**\n * Wraps every streaming model call. Call `next()` to reach the adapter, or yield\n * your own chunks to short-circuit it entirely.\n *\n * This is the extension point for retry, caching, request logging, replay, and\n * test doubles. Middleware registered EARLIER sits further out.\n */\n/** One call whose configuration and adapter registration were resolved together. */\nexport interface PreparedCall {\n /** Detached, deep-frozen config with any adapter-owned default materialized. */\n readonly config: CallConfig\n /** Immutable retry policy captured with the adapter registration. */\n readonly retryPolicy: ResolvedRetryPolicy\n /** Context capacity resolved with the registration-bound call. */\n readonly context?: ModelContext\n /** Exact model modalities captured with the dispatch generation. */\n readonly inputModalities?: readonly ModelModality[]\n /** Complete validated capability snapshot bound to this adapter generation. */\n readonly model: ResolvedModelInfo\n /** Which config fields the adapter supplied rather than the caller. */\n readonly adapterDefaults: CallConfigAdapterDefaults\n /**\n * Dispatch this call ONCE, through the registration captured at preparation.\n * @param options - the assembled request, carrying the prepared config.\n * @returns the chunk stream, including middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle\n}\n\nexport interface ModelRegistryOptions {\n /** Maximum model rows accepted from one adapter catalog. Defaults to 2,048. */\n readonly maxCatalogModels?: number\n /** Maximum serialized bytes accepted from a catalog or model-info record. Defaults to 4 MiB. */\n readonly maxCatalogBytes?: number\n /** Default observation port; a per-call invocation context may override it. */\n readonly observation?: ObservationPort\n /** Safe SDK/service/runtime identity copied onto observation events. */\n readonly observationResource?: ObservationResource\n}\n\ntype AdapterRegistration = RuntimeAdapterRegistration\n\ninterface InstalledPlugin {\n readonly routes: ReadonlySet<string>\n readonly registrations: readonly AdapterRegistration[]\n readonly middleware: readonly StreamMiddleware[]\n readonly cleanup?: () => void\n}\n\n\nfunction containThenable(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false\n let then: unknown\n try {\n then = Reflect.get(value, 'then')\n } catch {\n return true\n }\n if (typeof then !== 'function') return false\n try { void Promise.resolve(value).catch(() => {}) } catch { /* hostile thenable contained */ }\n return true\n}\n\nfunction synchronousCleanupFailure(cleanup: () => void): unknown | undefined {\n try {\n const result: unknown = cleanup()\n return containThenable(result) ? new TypeError('plugin cleanup must be synchronous') : undefined\n } catch (error) {\n return error\n }\n}\n\n\n/**\n * Routes model calls to registered adapters.\n *\n * Construct one per application or isolated runtime scope, register the adapters\n * you use, then call {@link stream} or {@link prepareCall}.\n */\nexport class ModelRegistry {\n private adapters = new Map<string, AdapterRegistration>()\n private middleware: StreamMiddleware[] = []\n private listeners = new Set<() => void>()\n private plugins = new Map<string, InstalledPlugin>()\n private readonly maxCatalogModels: number\n private readonly maxCatalogBytes: number\n private readonly observation: ObservationPort | undefined\n private readonly observationResource: ObservationResource\n\n constructor(options: ModelRegistryOptions = {}) {\n this.maxCatalogModels = positiveSafeInteger(options.maxCatalogModels ?? 2_048, 'maxCatalogModels')\n this.maxCatalogBytes = positiveSafeInteger(options.maxCatalogBytes ?? 4 * 1024 * 1024, 'maxCatalogBytes')\n this.observation = options.observation\n this.observationResource = deepFreeze(options.observationResource ?? {\n sdkName: 'ai-agent-sdk',\n sdkVersion: SDK_VERSION,\n runtime: 'unknown',\n })\n }\n\n /** Install one provider plugin as a single synchronous topology transaction. */\n install(plugin: ModelProviderPlugin): PluginRegistrationHandle {\n const pluginId = typeof plugin?.id === 'string' ? plugin.id : ''\n const fail = (message: string, cause?: unknown, cleanupFailures: readonly unknown[] = []): never => {\n const causes = [...cause === undefined ? [] : [cause], ...cleanupFailures]\n const wrappedCause = causes.length <= 1 ? causes[0] : new AggregateError(causes, `plugin ${pluginId} install cleanup failed`)\n throw new PluginError(message, PLUGIN_ERROR_CODES.INSTALL_FAILED, pluginId, wrappedCause === undefined ? undefined : { cause: wrappedCause })\n }\n if (pluginId.trim().length === 0 || pluginId !== pluginId.trim()) fail('plugin id must be a non-empty trimmed string')\n if (this.plugins.has(pluginId)) fail(`plugin \"${pluginId}\" is already installed`)\n if (typeof plugin.displayName !== 'string' || plugin.displayName.trim().length === 0) fail(`plugin \"${pluginId}\" displayName must be non-empty`)\n if (typeof plugin.setup !== 'function') fail(`plugin \"${pluginId}\" setup must be a function`)\n const family = plugin.family ?? pluginId\n if (typeof family !== 'string' || family.trim().length === 0 || family !== family.trim()) {\n fail(`plugin \"${pluginId}\" family must be a non-empty trimmed string`)\n }\n const owner = Object.freeze({ pluginId, family })\n\n interface StagedAdapter {\n active: boolean\n routes: string[]\n readonly adapter: ModelAdapter\n }\n interface StagedMiddleware { active: boolean; readonly middleware: StreamMiddleware }\n const stagedAdapters: StagedAdapter[] = []\n const stagedMiddleware: StagedMiddleware[] = []\n let staging = true\n\n const registrar: ModelProviderRegistrar = {\n registerAdapter: (routes, adapter) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (routes.length === 0) throw new ModelError('an adapter must register at least one provider route', REGISTRY_ERROR_CODES.INVALID_ADAPTER)\n const item: StagedAdapter = { active: true, routes: [...routes], adapter }\n // Validate metadata and conflicts without mutating live routes.\n const occupied = new Set(stagedAdapters.filter(value => value.active).flatMap(value => value.routes))\n for (const route of routes) if (occupied.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(routes, adapter, new Set(), owner)\n stagedAdapters.push(item)\n const handle = (() => {\n if (staging) item.active = false\n }) as AdapterRegistrationHandle\n handle.replace = (next) => {\n if (!staging || !item.active) throw new ModelError('a disposed staged registration cannot replace routes', REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED)\n const occupiedByOthers = new Set(stagedAdapters.filter(value => value.active && value !== item).flatMap(value => value.routes))\n for (const route of next) if (occupiedByOthers.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(next, adapter, new Set(), owner)\n item.routes = [...next]\n }\n return handle\n },\n use: (middleware) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (typeof middleware !== 'function') throw new TypeError('plugin middleware must be a function')\n const item: StagedMiddleware = { active: true, middleware }\n stagedMiddleware.push(item)\n return () => { if (staging) item.active = false }\n },\n }\n\n let cleanup: (() => void) | undefined\n try {\n const result = plugin.setup(registrar)\n if (containThenable(result)) fail(`plugin \"${pluginId}\" setup must be synchronous`)\n if (result !== undefined && typeof result !== 'function') fail(`plugin \"${pluginId}\" setup must be synchronous and return void or cleanup`)\n cleanup = typeof result === 'function' ? result : undefined\n } catch (error) {\n if (error instanceof PluginError && error.code === PLUGIN_ERROR_CODES.INSTALL_FAILED) throw error\n fail(`plugin \"${pluginId}\" setup failed`, error)\n } finally {\n staging = false\n }\n\n const registrations: AdapterRegistration[] = []\n const routeNames = new Set<string>()\n try {\n for (const item of stagedAdapters) {\n if (!item.active) continue\n for (const route of item.routes) {\n if (routeNames.has(route)) throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n routeNames.add(route)\n }\n registrations.push(...this.prepareRoutes(item.routes, item.adapter, new Set(), owner))\n }\n } catch (error) {\n const cleanupFailures: unknown[] = []\n if (cleanup) {\n const cleanupFailure = synchronousCleanupFailure(cleanup)\n if (cleanupFailure !== undefined) cleanupFailures.push(cleanupFailure)\n }\n fail(`plugin \"${pluginId}\" commit validation failed`, error, cleanupFailures)\n }\n\n const committedMiddleware = stagedMiddleware.filter(item => item.active).map(item => item.middleware)\n for (const registration of registrations) this.adapters.set(registration.provider.id, registration)\n this.middleware.push(...committedMiddleware)\n const installed: InstalledPlugin = {\n routes: routeNames,\n registrations,\n middleware: committedMiddleware,\n ...(cleanup === undefined ? {} : { cleanup }),\n }\n this.plugins.set(pluginId, installed)\n this.emitAdaptersUpdated()\n\n let disposed = false\n const dispose = (() => {\n if (disposed) return\n disposed = true\n this.plugins.delete(pluginId)\n for (const registration of installed.registrations) {\n if (this.adapters.get(registration.provider.id) === registration) this.adapters.delete(registration.provider.id)\n }\n for (let index = installed.middleware.length - 1; index >= 0; index--) {\n const middleware = installed.middleware[index]\n const liveIndex = middleware === undefined ? -1 : this.middleware.lastIndexOf(middleware)\n if (liveIndex >= 0) this.middleware.splice(liveIndex, 1)\n }\n this.emitAdaptersUpdated()\n const failures: unknown[] = []\n if (installed.cleanup) {\n const cleanupFailure = synchronousCleanupFailure(installed.cleanup)\n if (cleanupFailure !== undefined) failures.push(cleanupFailure)\n }\n if (failures.length > 0) {\n throw new PluginError(\n `plugin \"${pluginId}\" cleanup failed`,\n PLUGIN_ERROR_CODES.CLEANUP_FAILED,\n pluginId,\n { cause: new AggregateError(failures, `plugin \"${pluginId}\" cleanup failed`) },\n )\n }\n }) as PluginRegistrationHandle\n Object.defineProperty(dispose, 'pluginId', { value: pluginId, enumerable: true })\n return dispose\n }\n\n /**\n * Register an adapter for the given routes.\n *\n * All-or-nothing: if ANY route conflicts, nothing is registered. A partial\n * registration would leave the caller believing a route exists when it does not.\n * @param providers - every route this adapter should serve; must be non-empty.\n * @param adapter - the adapter that streams calls for those routes.\n * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.\n */\n registerAdapter(\n providers: readonly string[],\n adapter: ModelAdapter,\n ): AdapterRegistrationHandle {\n if (providers.length === 0) {\n throw new ModelError(\n 'an adapter must register at least one provider route',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n /** Routes this registration currently holds; `replace` rewrites it. */\n const owned = new Set<string>()\n // `owned` being empty cannot signal disposal on its own, because\n // `replace([])` legally leaves a live registration holding no routes.\n let released = false\n\n this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned))\n\n const handle = (() => {\n if (released) return\n released = true\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n this.emitAdaptersUpdated()\n }) as AdapterRegistrationHandle\n\n handle.replace = (next: readonly string[]): void => {\n // Registering after disposal would leak: nothing remains to release what\n // this call would put back into the map.\n if (released) {\n throw new ModelError(\n 'a disposed adapter registration cannot replace its routes',\n REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED,\n )\n }\n this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned))\n }\n return handle\n }\n\n /**\n * Validate one candidate route set, treating routes this registration already\n * holds as available. Mutates nothing  Ea rejected candidate leaves the registry\n * exactly as it was.\n */\n private prepareRoutes(\n providers: readonly string[],\n adapter: ModelAdapter,\n owned: ReadonlySet<string>,\n owner?: Readonly<{ pluginId: string; family: string }>,\n ): AdapterRegistration[] {\n const unique = new Set<string>()\n const registrations: AdapterRegistration[] = []\n for (const provider of providers) {\n if (typeof provider !== 'string' || provider.length === 0) {\n throw new ModelError(\n 'adapter provider route names must be non-empty strings',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n if (unique.has(provider) || (this.adapters.has(provider) && !owned.has(provider))) {\n throw new ModelError(\n `an adapter for provider route \"${provider}\" is already registered`,\n REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER,\n )\n }\n const info = adapter.providerInfo(provider)\n if (typeof info.id !== 'string' || info.id !== provider\n || typeof info.name !== 'string' || info.name.length === 0) {\n throw new ModelError(\n `adapter metadata for route \"${provider}\" must preserve its id and carry a non-empty name`,\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n unique.add(provider)\n registrations.push({\n adapter,\n provider: { id: info.id, name: info.name },\n ...(owner === undefined ? {} : owner),\n // Captured at REGISTRATION time, not per call. An adapter whose policy\n // follows mutable configuration re-registers via `handle.replace`.\n retryPolicy: adapter.providerRetryPolicy(provider)\n ?? resolveRetryPolicy(undefined, `provider \"${provider}\" retryPolicy`),\n })\n }\n return registrations\n }\n\n /**\n * Swap this registration's routes in ONE synchronous section, so no caller can\n * observe the registry between the release and the re-registration.\n */\n private commitRoutes(\n owned: Set<string>,\n registrations: readonly AdapterRegistration[],\n ): void {\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n for (const registration of registrations) {\n this.adapters.set(registration.provider.id, registration)\n owned.add(registration.provider.id)\n }\n this.emitAdaptersUpdated()\n }\n\n /**\n * Install streaming middleware.\n * @param middleware - wrapper invoked around every call; earlier registrations sit further out.\n * @returns a disposer that removes exactly this middleware.\n */\n use(middleware: StreamMiddleware): () => void {\n this.middleware.push(middleware)\n return () => {\n const index = this.middleware.indexOf(middleware)\n if (index >= 0) this.middleware.splice(index, 1)\n }\n }\n\n /**\n * Observe route-topology changes (registration, replacement, disposal).\n * @param listener - payload-free notification; re-read `listProviders()` for new state.\n * @returns a disposer that removes the listener.\n */\n onAdaptersUpdated(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => void this.listeners.delete(listener)\n }\n\n /**\n * Notify topology observers.\n *\n * Each listener is contained independently: a topology notification is not a\n * veto, so one broken observer must not starve the others or roll back a\n * registration that already happened.\n */\n private emitAdaptersUpdated(): void {\n for (const listener of [...this.listeners]) {\n try {\n listener()\n } catch {\n // Contained deliberately; see above.\n }\n }\n }\n\n /**\n * Describe every route with a registered adapter.\n * @returns detached provider metadata, in registration order.\n */\n listProviders(): ProviderInfo[] {\n return [...this.adapters.values()].map(({ provider }) => ({ ...provider }))\n }\n\n /**\n * List the models one route advertises.\n *\n * Re-validated here rather than trusted, because a malformed catalog entry\n * surfaces in a caller's model picker where its origin is far from obvious.\n * @param provider - a registered route.\n * @returns detached, validated model metadata.\n */\n async listModels(provider: string, signal?: AbortSignal): Promise<ModelInfo[]> {\n const registration = this.registration(provider)\n const models = await registration.adapter.listModels(provider, signal)\n return validateCatalogModels(provider, models, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /** Resolve and validate one uncached adapter-level catalog generation. */\n async modelCatalog(provider: string, options: ModelCatalogOptions = {}): Promise<ModelCatalogSnapshot> {\n const registration = this.registration(provider)\n const snapshot = await registration.adapter.modelCatalog(provider, options)\n return validateModelCatalogSnapshot(provider, snapshot, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /**\n * Resolve metadata for one exact model.\n * @param provider - a registered route.\n * @param model - exact model id.\n * @param signal - cancellation for adapter-side resolution.\n * @returns validated, detached metadata.\n */\n async resolveModelInfo(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n const registration = this.registration(provider)\n const resolved = await registration.adapter.resolveModel(provider, model, signal)\n return normalizeResolvedModelInfo(registration.provider.id, model, resolved, this.maxCatalogBytes)\n }\n\n /** The retry policy captured for one route. */\n retryPolicy(provider: string): ResolvedRetryPolicy {\n return this.registration(provider).retryPolicy\n }\n\n /**\n * Resolve one call under its CURRENT adapter registration, returning a one-shot\n * handle that keeps that registration through to dispatch.\n * @param config - route, model, and optional request controls.\n * @param signal - cancellation for adapter-side capability lookup.\n * @returns the prepared config and its registration-bound stream entry point.\n */\n async prepareCall(\n config: CallConfig,\n signal?: AbortSignal,\n invocationContext?: ModelInvocationContext,\n ): Promise<PreparedCall> {\n const registration = this.registration(config.provider)\n const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal, invocationContext)\n const modelInfo = normalizeResolvedModelInfo(\n registration.provider.id, config.model, adapterCall.model, this.maxCatalogBytes,\n )\n const resolved = resolveCallWithModelInfo(config, modelInfo)\n const resolvedConfig = deepFreeze(structuredClone(resolved.config))\n const context = resolved.context === undefined\n ? undefined\n : deepFreeze(structuredClone(resolved.context))\n const adapterDefaults = deepFreeze<CallConfigAdapterDefaults>({\n ...config.reasoningEffort === undefined && resolvedConfig.reasoningEffort !== undefined\n ? { reasoningEffort: true as const }\n : {},\n ...config.maxTokens === undefined && resolvedConfig.maxTokens !== undefined\n ? { maxTokens: true as const }\n : {},\n })\n\n let dispatched = false\n const model = deepFreeze(structuredClone(modelInfo))\n return Object.freeze({\n config: resolvedConfig,\n model,\n retryPolicy: registration.retryPolicy,\n adapterDefaults,\n ...context === undefined ? {} : { context },\n ...modelInfo.inputModalities === undefined\n ? {}\n : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },\n stream: (options: GenerateOptions, context = invocationContext): ModelCallHandle => {\n // Both guards below exist so a stale handle fails loudly instead of\n // quietly dispatching against a configuration nobody vetted.\n if (dispatched) {\n throw new ModelError(\n 'a prepared call can only be dispatched once',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n if (!callConfigEquals(options, resolvedConfig)) {\n throw new ModelError(\n 'prepared call config changed before adapter dispatch',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n dispatched = true\n return this.dispatch(options, context, {\n registration,\n config: resolvedConfig,\n modelInfo,\n dispatch: (request, activeContext) => adapterCall.stream(request, activeContext),\n })\n },\n })\n }\n\n /**\n * Stream one model call as raw chunks.\n *\n * Adapter selection, dispatch, and iteration failures become terminal `error` or\n * `aborted` finish chunks. Middleware and consumer failures stay THROWN  Ethose\n * are bugs in code the caller controls, and converting them to a finish reason\n * would hide them.\n * @param options - the full request; `options.provider` selects the adapter.\n * @returns the chunk stream, wrapped by any installed middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle {\n return this.dispatch(options, context)\n }\n\n private dispatch(\n options: GenerateOptions,\n context?: ModelInvocationContext,\n prepared?: PreparedDispatch,\n ): ModelCallHandle {\n let dispatchState: 'not-sent' | 'unknown' = 'not-sent'\n const registration = prepared?.registration ?? this.adapters.get(options.provider)\n return createModelCallHandle({\n options,\n ...(registration?.family === undefined ? {} : { providerFamily: registration.family }),\n ...(registration?.pluginId === undefined ? {} : { providerPluginId: registration.pluginId }),\n ...(registration === undefined ? {} : { isRetryable: (code: string) => (\n registration.retryPolicy.mode === 'always'\n || registration.retryPolicy.retryableCodes.includes(code)\n ) }),\n ...(context === undefined ? {} : { context }),\n ...(this.observation === undefined ? {} : { defaultObservation: this.observation }),\n resource: this.observationResource,\n routePresent: prepared !== undefined || this.adapters.has(options.provider),\n dispatchState: () => dispatchState,\n stream: activeContext => this.dispatchRaw(\n options,\n activeContext,\n () => { dispatchState = 'unknown' },\n prepared,\n ),\n })\n }\n\n /**\n * Compose installed middleware around the adapter boundary.\n *\n * Composition is deferred to the first iteration rather than done eagerly, so\n * that `stream()` ALWAYS returns an iterable and every failure — including a\n * middleware that throws synchronously — surfaces on the same path. Composing\n * eagerly would give callers two different error channels for the same class of\n * fault, and they would inevitably handle only one.\n *\n * The middleware list is snapshotted here so that installing or removing\n * middleware mid-stream cannot change the chain of a call already in flight.\n */\n private dispatchRaw(\n options: GenerateOptions,\n context: ModelInvocationContext,\n onDispatch: () => void,\n prepared?: PreparedDispatch,\n ): AsyncIterable<StreamChunk> {\n const chain = [...this.middleware]\n const run = (): AsyncIterable<StreamChunk> => {\n let next = (): AsyncIterable<StreamChunk> => streamAdapter({\n options, context, onDispatch, maxCatalogBytes: this.maxCatalogBytes,\n registration: provider => this.registration(provider),\n registeredAdapter: provider => this.adapters.get(provider)?.adapter,\n ...(prepared === undefined ? {} : { prepared }),\n })\n for (let index = chain.length - 1; index >= 0; index--) {\n const middleware = chain[index]\n if (middleware === undefined) continue\n const inner = next\n next = () => middleware(options, inner, context)\n }\n return next()\n }\n return {\n async * [Symbol.asyncIterator]() {\n yield* run()\n },\n }\n }\n\n private registration(provider: string): AdapterRegistration {\n const registration = this.adapters.get(provider)\n if (registration === undefined) {\n throw new ModelError(\n `no adapter registered for provider route \"${provider}\"`,\n REGISTRY_ERROR_CODES.NO_ADAPTER,\n )\n }\n return registration\n }\n\n}\n\nfunction positiveSafeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`ModelRegistry ${label} must be a positive safe integer`)\n }\n return value\n}\n"],"mappings":"qoBAuGA,SAAS,EAAgB,EAAyB,CAChD,IAAK,OAAO,GAAU,WAAY,IAAmB,OAAO,GAAU,WAAY,MAAO,GACzF,IAAI,EACJ,GAAI,CACF,EAAO,QAAQ,IAAI,EAAO,MAAM,CAClC,MAAQ,CACN,MAAO,EACT,CACA,GAAI,OAAO,GAAS,WAAY,MAAO,GACvC,GAAI,CAAE,QAAa,QAAQ,CAAK,CAAC,CAAC,UAAY,CAAC,CAAC,CAAE,MAAQ,CAAmC,CAC7F,MAAO,EACT,CAEA,SAAS,EAA0B,EAA0C,CAC3E,GAAI,CAEF,OAAO,EADiB,EACI,CAAC,EAAQ,UAAU,oCAAoC,EAAI,IAAA,EACzF,OAAS,EAAO,CACd,OAAO,CACT,CACF,CASA,IAA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,CACL,OAAS,OAAO,gBAAiB,CAC/B,MAAO,EAAI,CACb,CACF,CACF,CAEA,aAAqB,EAAuC,CAC1D,IAAM,EAAe,KAAK,SAAS,IAAI,CAAQ,EAC/C,GAAI,IAAiB,IAAA,GACnB,MAAM,IAAI,EACR,6CAA6C,EAAS,GACtD,EAAqB,UACvB,EAEF,OAAO,CACT,CAEF,EAEA,SAAS,EAAoB,EAAe,EAAuB,CACjE,GAAI,CAAC,OAAO,cAAc,CAAK,GAAK,EAAQ,EAC1C,MAAU,WAAW,iBAAiB,EAAM,iCAAiC,EAE/E,OAAO,CACT"}
@@ -0,0 +1,45 @@
1
+ import { ModelFailure } from "../errors/failure.js";
2
+ import { RetryPolicyConfig } from "../contract/retry-policy.js";
3
+ import { ModelAdapter } from "../contract/adapter.js";
4
+ //#region src/runtime/with-retry.d.ts
5
+ /** One retry that is about to be waited out. */
6
+ interface RetryAttempt {
7
+ /** The route whose call failed. */
8
+ readonly provider: string;
9
+ /** 1-based retry number. */
10
+ readonly attempt: number;
11
+ /** Retry ceiling, or `undefined` under an `always` policy. */
12
+ readonly maxRetries: number | undefined;
13
+ /** The failure being recovered from. */
14
+ readonly failure: ModelFailure;
15
+ /** How long the decorator will wait before re-dispatching. */
16
+ readonly delayMs: number;
17
+ }
18
+ /** Options for {@link withRetry}. */
19
+ interface WithRetryOptions {
20
+ /**
21
+ * Policy to apply. Omission uses the wrapped adapter's own per-route policy,
22
+ * falling back to the shared defaults.
23
+ */
24
+ policy?: RetryPolicyConfig;
25
+ /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */
26
+ random?: () => number;
27
+ /** Observe each scheduled retry  Ethe hook for logging and metrics. */
28
+ onRetry?: (attempt: RetryAttempt) => void;
29
+ /** Maximum wait while closing an unsuccessful attempt. Defaults to 30s. */
30
+ teardownTimeoutMs?: number;
31
+ }
32
+ /**
33
+ * Wrap an adapter so eligible transient failures are retried with bounded
34
+ * exponential backoff and jitter.
35
+ *
36
+ * Only failures that occur BEFORE the first chunk reaches the consumer are
37
+ * retried; see the module note for why.
38
+ * @param adapter - the adapter to wrap; its metadata methods are delegated unchanged.
39
+ * @param options - policy, jitter source, and retry observer.
40
+ * @returns a new adapter with retry behaviour; the original is unmodified.
41
+ */
42
+ declare function withRetry(adapter: ModelAdapter, options?: WithRetryOptions): ModelAdapter;
43
+ //#endregion
44
+ export { RetryAttempt, WithRetryOptions, withRetry };
45
+ //# sourceMappingURL=with-retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"with-retry.d.ts","names":[],"sources":["../../src/runtime/with-retry.ts"],"mappings":";;;;;UAkCiB;;WAEN;;WAEA;;WAEA;;WAEA,SAAS;;WAET;;;UAIM;;;;;EAKf,SAAS;;EAET;;EAEA,WAAW,SAAS;;EAEpB;;;;;;;;;;;;iBAySc,UAAU,SAAS,cAAc,UAAS,mBAAwB"}
@@ -0,0 +1,2 @@
1
+ import{waitForSettlement as e}from"../async/settlement.js";import{MODEL_ERROR_CODES as t,ModelError as n}from"../errors/model-error.js";import{normalizeModelFailure as r}from"../errors/failure.js";import{ModelAdapter as i}from"../contract/adapter.js";import{backoffDelayMs as a,resolveRetryPolicy as o}from"../contract/retry-policy.js";function s(e,t,n,r){let i=t.providerRetryAfterMs;return i!==void 0&&Number.isFinite(i)&&i>0?i<=e.maxDelayMs?i:e.mode===`always`?a(e,n,r):`give-up`:a(e,n,r)}function c(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}var l=class extends i{inner;options;constructor(e,t){super(),this.inner=e,this.options=t}providerInfo(e){return this.inner.providerInfo(e)}providerRetryPolicy(e){return this.inner.providerRetryPolicy(e)}listModels(e){return this.inner.listModels(e)}resolveModel(e,t,n){return this.inner.resolveModel(e,t,n)}async prepareCall(e,t,n,r){let i=await this.inner.prepareCall(e,t,n,r),a=this.policyFor(e);return{model:i.model,stream:(e,t=r)=>this.retryStream(e,e=>i.stream(e,t),a,t)}}stream(e,t){return this.retryStream(e,e=>this.inner.stream(e,t),this.policyFor(e.provider),t)}policyFor(e){return this.options.policy===void 0?this.inner.providerRetryPolicy(e)??o(void 0,`withRetry("${e}").policy`):o(this.options.policy,`withRetry("${e}").policy`)}async*retryStream(e,n,r,i){if(r.mode===`always`&&e.signal===void 0){yield{type:`finish`,reason:{kind:`error`,failure:{message:`an always retry policy requires an AbortSignal or deadline`,code:t.INVALID_REQUEST}}};return}let a=this.options.random??Math.random,o=0;for(;;){let l=await this.runAttempt(e,n);if(l.kind===`forward`){yield*l.chunks;return}let u=l.failure;if(e.signal?.aborted===!0||u.code===t.ABORTED){yield{type:`finish`,reason:{kind:`aborted`,failure:u}};return}if(!(r.mode===`always`||r.retryableCodes.includes(u.code)&&o<r.maxRetries)){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}let d=s(r,u,o+1,a);if(d===`give-up`){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}o+=1,i?.recordProviderRetry?.({nextAttemptNumber:o+1,delayMs:d,failureCode:u.code});try{this.options.onRetry?.({provider:e.provider,attempt:o,maxRetries:r.mode===`normal`?r.maxRetries:void 0,failure:u,delayMs:d})}catch{}if(!await c(d,e.signal)){yield{type:`finish`,reason:{kind:`aborted`,failure:{message:`model call aborted while waiting to retry`,code:t.ABORTED}}};return}}}async runAttempt(e,n){let i;try{i=n(e)[Symbol.asyncIterator]()}catch(e){return{kind:`retryable`,failure:r(e)}}let a;try{a=await i.next()}catch(e){return await f(i,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:r(e)}}if(a.done===!0)return{kind:`retryable`,failure:{message:`the adapter produced no chunks`,code:t.UNKNOWN}};let o=a.value;return o.type===`finish`&&o.reason.kind===`error`?(await f(i,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:o.reason.failure}):{kind:`forward`,chunks:d(o,i,this.options.teardownTimeoutMs??3e4)}}};function u(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be a positive finite number`);return e}async function*d(e,t,n){let r=!1;try{for(yield e;;){let e=await t.next();if(e.done===!0){r=!0;return}yield e.value}}finally{r||await f(t,n)}}async function f(r,i){let a=r.return?.();if(a!==void 0&&!await e(Promise.resolve(a),u(i,`withRetry teardownTimeoutMs`)))throw new n(`retry attempt teardown exceeded ${i}ms`,t.TEARDOWN_TIMEOUT)}function p(e,t={}){return new l(e,t)}export{p as withRetry};
2
+ //# sourceMappingURL=with-retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"with-retry.js","names":[],"sources":["../../src/runtime/with-retry.ts"],"sourcesContent":["/**\n * Retry as an adapter DECORATOR.\n *\n * In deepseek-harness this was a plugin on the agent loop's failed-step hook,\n * which let it restart a whole step and recover its attempt count from a durable\n * session log. A standalone SDK has neither, so retry moves down to the adapter\n * and holds its attempt count in the call's own closure.\n *\n * That relocation brings one hard constraint, and it is the thing to understand\n * about this module: a retry may only happen while NOTHING has been yielded\n * downstream yet. Once a text delta has reached the consumer, re-running the\n * request would replay those tokens and the consumer would render them twice.\n * So a failure that arrives mid-stream is forwarded, not retried  Erecovering\n * from it requires re-running the whole turn, which only the caller can decide.\n *\n * @module ai-agent-sdk/core/runtime/with-retry\n */\n\nimport { ModelAdapter, type PreparedAdapterCall } from '../contract/adapter.ts'\nimport type { GenerateOptions } from '../contract/generate-options.ts'\nimport type { ModelInfo, ResolvedModelInfo } from '../contract/model-info.ts'\nimport {\n backoffDelayMs,\n resolveRetryPolicy,\n type ResolvedRetryPolicy,\n type RetryPolicyConfig,\n} from '../contract/retry-policy.ts'\nimport { normalizeModelFailure, type ModelFailure } from '../errors/failure.ts'\nimport { MODEL_ERROR_CODES, ModelError } from '../errors/model-error.ts'\nimport type { StreamChunk } from '../stream/chunk.ts'\nimport type { ModelInvocationContext } from '../observation/report.ts'\nimport { waitForSettlement } from '../async/settlement.ts'\n\n/** One retry that is about to be waited out. */\nexport interface RetryAttempt {\n /** The route whose call failed. */\n readonly provider: string\n /** 1-based retry number. */\n readonly attempt: number\n /** Retry ceiling, or `undefined` under an `always` policy. */\n readonly maxRetries: number | undefined\n /** The failure being recovered from. */\n readonly failure: ModelFailure\n /** How long the decorator will wait before re-dispatching. */\n readonly delayMs: number\n}\n\n/** Options for {@link withRetry}. */\nexport interface WithRetryOptions {\n /**\n * Policy to apply. Omission uses the wrapped adapter's own per-route policy,\n * falling back to the shared defaults.\n */\n policy?: RetryPolicyConfig\n /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */\n random?: () => number\n /** Observe each scheduled retry  Ethe hook for logging and metrics. */\n onRetry?: (attempt: RetryAttempt) => void\n /** Maximum wait while closing an unsuccessful attempt. Defaults to 30s. */\n teardownTimeoutMs?: number\n}\n\n/** Resolve a delay that honours a provider-requested `retry-after` when sane. */\nfunction delayFor(\n policy: ResolvedRetryPolicy,\n failure: ModelFailure,\n attempt: number,\n random: () => number,\n): number | 'give-up' {\n const requested = failure.providerRetryAfterMs\n if (requested !== undefined && Number.isFinite(requested) && requested > 0) {\n if (requested <= policy.maxDelayMs) return requested\n // The provider asked for longer than this policy is willing to wait. Under a\n // bounded policy that is a refusal: sleeping less than asked would just earn\n // another rate-limit response. An `always` policy has nowhere to give up to,\n // so it falls back to local backoff and keeps trying.\n return policy.mode === 'always' ? backoffDelayMs(policy, attempt, random) : 'give-up'\n }\n return backoffDelayMs(policy, attempt, random)\n}\n\n/** Sleep, resolving early and reporting false if the signal aborts first. */\nfunction cancellableDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted === true) return Promise.resolve(false)\n return new Promise((resolve) => {\n const onAbort = (): void => {\n clearTimeout(timer)\n resolve(false)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve(true)\n }, delayMs)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nclass RetryingAdapter extends ModelAdapter {\n private readonly inner: ModelAdapter\n private readonly options: WithRetryOptions\n\n // Explicit fields rather than constructor parameter properties: Node's\n // strip-only TypeScript mode rejects those, and this package is meant to run\n // under `node file.ts` without a build step.\n constructor(inner: ModelAdapter, options: WithRetryOptions) {\n super()\n this.inner = inner\n this.options = options\n }\n\n override providerInfo(provider: string): ReturnType<ModelAdapter['providerInfo']> {\n return this.inner.providerInfo(provider)\n }\n\n override providerRetryPolicy(provider: string): ResolvedRetryPolicy | undefined {\n return this.inner.providerRetryPolicy(provider)\n }\n\n override listModels(provider: string): Promise<readonly ModelInfo[]> {\n return this.inner.listModels(provider)\n }\n\n override resolveModel(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n return this.inner.resolveModel(provider, model, signal)\n }\n\n override async prepareCall(\n provider: string,\n model: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<PreparedAdapterCall> {\n const prepared = await this.inner.prepareCall(provider, model, signal, context)\n const policy = this.policyFor(provider)\n return {\n model: prepared.model,\n // Retries reuse the SAME prepared generation. Re-preparing mid-retry could\n // pair a fresh endpoint with capabilities resolved against the old one,\n // which is exactly what the prepare/dispatch binding exists to prevent.\n stream: (options, invocation = context) => this.retryStream(options, request => prepared.stream(request, invocation), policy, invocation),\n }\n }\n\n stream(options: GenerateOptions, context?: ModelInvocationContext): AsyncIterable<StreamChunk> {\n return this.retryStream(\n options,\n request => this.inner.stream(request, context),\n this.policyFor(options.provider),\n context,\n )\n }\n\n private policyFor(provider: string): ResolvedRetryPolicy {\n if (this.options.policy !== undefined) {\n return resolveRetryPolicy(this.options.policy, `withRetry(\"${provider}\").policy`)\n }\n return this.inner.providerRetryPolicy(provider)\n ?? resolveRetryPolicy(undefined, `withRetry(\"${provider}\").policy`)\n }\n\n private async * retryStream(\n options: GenerateOptions,\n dispatch: (request: GenerateOptions) => AsyncIterable<StreamChunk>,\n policy: ResolvedRetryPolicy,\n context?: ModelInvocationContext,\n ): AsyncGenerator<StreamChunk> {\n if (policy.mode === 'always' && options.signal === undefined) {\n yield {\n type: 'finish',\n reason: {\n kind: 'error',\n failure: {\n message: 'an always retry policy requires an AbortSignal or deadline',\n code: MODEL_ERROR_CODES.INVALID_REQUEST,\n },\n },\n }\n return\n }\n const random = this.options.random ?? Math.random\n let retries = 0\n\n while (true) {\n const attempt = await this.runAttempt(options, dispatch)\n if (attempt.kind === 'forward') {\n yield* attempt.chunks\n return\n }\n\n const failure = attempt.failure\n // An abort is the caller's decision, never a transient fault.\n if (options.signal?.aborted === true || failure.code === MODEL_ERROR_CODES.ABORTED) {\n yield { type: 'finish', reason: { kind: 'aborted', failure } }\n return\n }\n\n const eligible = policy.mode === 'always'\n || (policy.retryableCodes.includes(failure.code) && retries < policy.maxRetries)\n if (!eligible) {\n yield { type: 'finish', reason: { kind: 'error', failure } }\n return\n }\n\n const delayMs = delayFor(policy, failure, retries + 1, random)\n if (delayMs === 'give-up') {\n yield { type: 'finish', reason: { kind: 'error', failure } }\n return\n }\n\n retries += 1\n context?.recordProviderRetry?.({\n nextAttemptNumber: retries + 1,\n delayMs,\n failureCode: failure.code,\n })\n try {\n this.options.onRetry?.({\n provider: options.provider,\n attempt: retries,\n maxRetries: policy.mode === 'normal' ? policy.maxRetries : undefined,\n failure,\n delayMs,\n })\n } catch {\n // Metrics/logging observers do not own request availability.\n }\n if (!await cancellableDelay(delayMs, options.signal)) {\n yield {\n type: 'finish',\n reason: {\n kind: 'aborted',\n failure: {\n message: 'model call aborted while waiting to retry',\n code: MODEL_ERROR_CODES.ABORTED,\n },\n },\n }\n return\n }\n }\n }\n\n /**\n * Run one attempt WITHOUT yielding anything downstream.\n *\n * Buffering is what makes retry safe: until the attempt either produces its\n * first chunk or fails, nothing has been committed to the consumer. Once a\n * chunk exists the attempt is no longer retryable, so it switches to\n * `forward` and streams the rest through untouched.\n */\n private async runAttempt(\n options: GenerateOptions,\n dispatch: (request: GenerateOptions) => AsyncIterable<StreamChunk>,\n ): Promise<\n | { kind: 'forward'; chunks: AsyncIterable<StreamChunk> }\n | { kind: 'retryable'; failure: ModelFailure }\n > {\n let iterator: AsyncIterator<StreamChunk>\n try {\n iterator = dispatch(options)[Symbol.asyncIterator]()\n } catch (error: unknown) {\n return { kind: 'retryable', failure: normalizeModelFailure(error) }\n }\n\n let first: IteratorResult<StreamChunk>\n try {\n first = await iterator.next()\n } catch (error: unknown) {\n await closeIterator(iterator, this.options.teardownTimeoutMs ?? 30_000)\n return { kind: 'retryable', failure: normalizeModelFailure(error) }\n }\n\n // A stream that ends with no chunks at all told us nothing; treat it as the\n // degenerate empty response rather than a silently successful turn.\n if (first.done === true) {\n return {\n kind: 'retryable',\n failure: {\n message: 'the adapter produced no chunks',\n code: MODEL_ERROR_CODES.UNKNOWN,\n },\n }\n }\n\n // An adapter behind the registry's funnel reports failure as a terminal\n // error finish rather than a throw. As the FIRST chunk, that is still a\n // clean nothing-emitted failure and remains retryable.\n const chunk = first.value\n if (chunk.type === 'finish' && chunk.reason.kind === 'error') {\n await closeIterator(iterator, this.options.teardownTimeoutMs ?? 30_000)\n return { kind: 'retryable', failure: chunk.reason.failure }\n }\n\n return {\n kind: 'forward',\n chunks: resume(chunk, iterator, this.options.teardownTimeoutMs ?? 30_000),\n }\n }\n}\n\nfunction positiveFinite(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be a positive finite number`)\n return value\n}\n\n/** Re-attach an already-read first chunk to the front of its iterator. */\nasync function* resume(\n first: StreamChunk,\n iterator: AsyncIterator<StreamChunk>,\n teardownTimeoutMs: number,\n): AsyncGenerator<StreamChunk> {\n let exhausted = false\n try {\n yield first\n while (true) {\n const next = await iterator.next()\n if (next.done === true) {\n exhausted = true\n return\n }\n yield next.value\n }\n } finally {\n if (!exhausted) await closeIterator(iterator, teardownTimeoutMs)\n }\n}\n\nasync function closeIterator(iterator: AsyncIterator<StreamChunk>, timeoutMs: number): Promise<void> {\n const closing = iterator.return?.()\n if (closing === undefined) return\n const settled = await waitForSettlement(\n Promise.resolve(closing),\n positiveFinite(timeoutMs, 'withRetry teardownTimeoutMs'),\n )\n if (!settled) {\n throw new ModelError(\n `retry attempt teardown exceeded ${timeoutMs}ms`,\n MODEL_ERROR_CODES.TEARDOWN_TIMEOUT,\n )\n }\n}\n\n/**\n * Wrap an adapter so eligible transient failures are retried with bounded\n * exponential backoff and jitter.\n *\n * Only failures that occur BEFORE the first chunk reaches the consumer are\n * retried; see the module note for why.\n * @param adapter - the adapter to wrap; its metadata methods are delegated unchanged.\n * @param options - policy, jitter source, and retry observer.\n * @returns a new adapter with retry behaviour; the original is unmodified.\n */\nexport function withRetry(adapter: ModelAdapter, options: WithRetryOptions = {}): ModelAdapter {\n return new RetryingAdapter(adapter, options)\n}\n"],"mappings":"gVA+DA,SAAS,EACP,EACA,EACA,EACA,EACoB,CACpB,IAAM,EAAY,EAAQ,qBAS1B,OARI,IAAc,IAAA,IAAa,OAAO,SAAS,CAAS,GAAK,EAAY,EACnE,GAAa,EAAO,WAAmB,EAKpC,EAAO,OAAS,SAAW,EAAe,EAAQ,EAAS,CAAM,EAAI,UAEvE,EAAe,EAAQ,EAAS,CAAM,CAC/C,CAGA,SAAS,EAAiB,EAAiB,EAAwC,CAEjF,OADI,GAAQ,UAAY,GAAa,QAAQ,QAAQ,EAAK,EACnD,IAAI,QAAS,GAAY,CAC9B,IAAM,MAAsB,CAC1B,aAAa,CAAK,EAClB,EAAQ,EAAK,CACf,EACM,EAAQ,eAAiB,CAC7B,GAAQ,oBAAoB,QAAS,CAAO,EAC5C,EAAQ,EAAI,CACd,EAAG,CAAO,EACV,GAAQ,iBAAiB,QAAS,EAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH,CAEA,IAAM,EAAN,cAA8B,CAAa,CACzC,MACA,QAKA,YAAY,EAAqB,EAA2B,CAC1D,MAAM,EACN,KAAK,MAAQ,EACb,KAAK,QAAU,CACjB,CAEA,aAAsB,EAA4D,CAChF,OAAO,KAAK,MAAM,aAAa,CAAQ,CACzC,CA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ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, SKILL_ID_PATTERN, SkillCandidate, SkillDefinition, SkillDefinitionInput, SkillInvocationPolicy, SkillLookupOptions, SkillProvider, SkillProviderListOptions, SkillResourceBase, SkillResourceSummary, SkillSource, SkillSummary, defineSkill, defineSkillProvider, validateCandidate, validateSkillId, validateSkillResourcePath, validateSkillSource } from "./agent/skill/definition.js";
3
+ import { SKILL_ERROR_CODES, SKILL_PROVIDER_API_VERSION } from "./agent/skill/provider/config.js";
4
+ import { ActivatedSkillSnapshot, RuntimeSkillCandidate, RuntimeSkillLookupOptions, RuntimeSkillSource, SkillCatalogSnapshot, SkillProviderDefinition, SkillProviderPlugin, SkillProviderPluginDefinition, SkillReference } from "./agent/skill/provider/types.js";
5
+ import { SkillCatalog, SkillCatalogOptions } from "./agent/skill/catalog.js";
6
+ import { AgentSkillOptions, ResolvedAgentSkillOptions, SKILL_TOOL_NAMES, createSkillTools, renderSkillCatalog, resolveSkillOptions } from "./agent/skill/tools.js";
7
+ import { defineSkillProviderPlugin } from "./agent/skill/provider/definition.js";
8
+ export { type ActivatedSkillSnapshot, type AgentSkillOptions, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, type ResolvedAgentSkillOptions, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, createSkillTools, defineSkill, defineSkillProvider, defineSkillProviderPlugin, renderSkillCatalog, resolveSkillOptions, validateCandidate, validateSkillId, validateSkillResourcePath, validateSkillSource };
package/dist/skills.js ADDED
@@ -0,0 +1 @@
1
+ import{MAX_SKILL_DESCRIPTION_CHARS as e,MAX_SKILL_ID_CHARS as t,MAX_SKILL_INSTRUCTIONS_CHARS as n,MAX_SKILL_NAME_CHARS as r,MAX_SKILL_RESOURCE_CHARS as i,MAX_SKILL_RESOURCE_PATH_CHARS as a,SKILL_ID_PATTERN as o,defineSkill as s,defineSkillProvider as c,validateCandidate as l,validateSkillId as u,validateSkillResourcePath as d,validateSkillSource as f}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as p,SKILL_PROVIDER_API_VERSION as m}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as h}from"./agent/skill/provider/definition.js";import{SkillCatalog as g}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as _,createSkillTools as v,renderSkillCatalog as y,resolveSkillOptions as b}from"./agent/skill/tools.js";export{e as MAX_SKILL_DESCRIPTION_CHARS,t as MAX_SKILL_ID_CHARS,n as MAX_SKILL_INSTRUCTIONS_CHARS,r as MAX_SKILL_NAME_CHARS,i as MAX_SKILL_RESOURCE_CHARS,a as MAX_SKILL_RESOURCE_PATH_CHARS,p as SKILL_ERROR_CODES,o as SKILL_ID_PATTERN,m as SKILL_PROVIDER_API_VERSION,_ as SKILL_TOOL_NAMES,g as SkillCatalog,v as createSkillTools,s as defineSkill,c as defineSkillProvider,h as defineSkillProviderPlugin,y as renderSkillCatalog,b as resolveSkillOptions,l as validateCandidate,u as validateSkillId,d as validateSkillResourcePath,f as validateSkillSource};
@@ -0,0 +1,86 @@
1
+ import { ContentBlock } from "../message/content.js";
2
+ import { FinishReason, ReplayEnvelope, StreamChunk, TokenUsage } from "./chunk.js";
3
+ import { Message, MessageSource } from "../message/message.js";
4
+ //#region src/stream/assembler.d.ts
5
+ /**
6
+ * Incrementally assembles {@link StreamChunk}s into {@link ContentBlock}s and a
7
+ * final assistant {@link Message}.
8
+ *
9
+ * Tolerant by design: it accepts delta-only protocols that never send
10
+ * `block-start`, and it IGNORES deltas that arrive for an index already closed by
11
+ * `block-end`. That last rule is a containment boundary  Ea misbehaving adapter
12
+ * cannot grow memory without bound or corrupt a block a consumer has already
13
+ * been told is final.
14
+ */
15
+ declare class BlockAssembler {
16
+ private partials;
17
+ /** Block indexes in FIRST-SEEN order; the stream's own ordering, not sorted. */
18
+ private order;
19
+ private _usage;
20
+ private _finish;
21
+ private _replayState;
22
+ /**
23
+ * Feed one chunk into the assembly state.
24
+ * @param chunk - the next chunk, in stream order.
25
+ */
26
+ push(chunk: StreamChunk): void;
27
+ private ensure;
28
+ private assemble;
29
+ /** Invariant accessor: every index in `order` has a partial. */
30
+ private mustGet;
31
+ /**
32
+ * The ONE keep/drop decision over all seen blocks, so emitted blocks and
33
+ * replay metadata cannot disagree about what survived.
34
+ *
35
+ * Max-token truncation drops tool calls: a call cut off mid-arguments has
36
+ * incomplete JSON, and executing it would act on arguments the model never
37
+ * finished choosing.
38
+ */
39
+ private assembled;
40
+ /**
41
+ * Assemble every block seen so far, in stream order.
42
+ * @returns one block per seen index, minus tool calls dropped by max-token
43
+ * truncation. An open block assembles from its accumulated deltas.
44
+ */
45
+ blocks(): ContentBlock[];
46
+ /** Whether the canonical stream contains host tool calls, including calls
47
+ * dropped from blocks() on truncation. No incomplete arguments are parsed. */
48
+ get hasToolCalls(): boolean;
49
+ /** Canonical text blocks with their original stream indexes, in first-seen
50
+ * order. Shares first-close-wins semantics with blocks(), including ignored
51
+ * straggler deltas and authoritative block-end replacements. */
52
+ textBlocks(): {
53
+ index: number;
54
+ block: Extract<ContentBlock, {
55
+ type: 'text';
56
+ }>;
57
+ beforeNativeCall: boolean;
58
+ }[];
59
+ /**
60
+ * Assemble the prefix an INTERRUPTED stream can safely finalize: closed and
61
+ * open text/reasoning blocks carrying non-whitespace content.
62
+ *
63
+ * Tool calls are omitted because interruption precedes dispatch, so keeping one
64
+ * would oblige the caller to fabricate a result for a call that never ran.
65
+ * @returns the kept blocks; empty when nothing usable streamed first.
66
+ */
67
+ interruptedBlocks(): ContentBlock[];
68
+ /** Usage from the `usage` chunk; undefined until one arrives. */
69
+ get usage(): TokenUsage | undefined;
70
+ /** Finish reason; `{ kind: 'stop' }` when the stream ended without one. */
71
+ get finish(): FinishReason;
72
+ /**
73
+ * Replay metadata, with per-block entries pruned in step with {@link blocks}.
74
+ * Undefined when the envelope did not align with the emitted blocks.
75
+ */
76
+ get replayState(): ReplayEnvelope | undefined;
77
+ /**
78
+ * The assembled assistant message.
79
+ * @param source - producer attribution for the message.
80
+ * @returns a frozen assistant-role message over {@link blocks}.
81
+ */
82
+ message(source: MessageSource): Message;
83
+ }
84
+ //#endregion
85
+ export { BlockAssembler };
86
+ //# sourceMappingURL=assembler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembler.d.ts","names":[],"sources":["../../src/stream/assembler.ts"],"mappings":";;;;;;;;;;;;;;cAuCa;UACH;;UAEA;UACA;UACA;UACA;;;;;EAMR,KAAK,OAAO;UAuDJ;UAUA;;UAyBA;;;;;;;;;UAgBA;;;;;;EA2BR,UAAU;;;MAMN;;;;EAUJ;IAAgB;IAAe,OAAO,QAAQ;MAAgB;;IAAiB;;;;;;;;;;EAqB/E,qBAAqB;;MAajB,SAAS;;MAKT,UAAU;;;;;MAQV,eAAe;;;;;;EASnB,QAAQ,QAAQ,gBAAgB"}
@@ -0,0 +1,2 @@
1
+ import{ToolCallId as e}from"../primitives/brand.js";import{assertNever as t}from"../primitives/never.js";import{createMessage as n}from"../message/message.js";var r=class{partials=new Map;order=[];_usage;_finish;_replayState;push(e){switch(e.type){case`block-start`:this.partials.has(e.index)||(this.order.push(e.index),this.partials.set(e.index,{blockType:e.blockType,text:``,toolCallArguments:``}));return;case`text-delta`:case`reasoning-delta`:{let t=this.ensure(e.index,e.type===`text-delta`?`text`:`reasoning`);if(t.block!==void 0)return;t.text+=e.text,e.type===`text-delta`&&e.phase!==void 0&&(t.textPhase=e.phase);return}case`tool-call-delta`:{let t=this.ensure(e.index,`tool-call`);if(t.block!==void 0)return;t.toolCallId=e.id,e.name!==void 0&&e.name.length>0&&(t.toolCallName=e.name),t.toolCallArguments+=e.argumentsDelta;return}case`image-delta`:return;case`block-end`:{let t=this.ensure(e.index,e.block.type);if(t.block!==void 0)return;t.block=e.block;return}case`usage`:this._usage=e.usage;return;case`finish`:this._finish=e.reason,this._replayState=e.replayState;return;default:return t(e,`BlockAssembler.push`)}}ensure(e,t){let n=this.partials.get(e);return n===void 0&&(n={blockType:t,text:``,toolCallArguments:``},this.partials.set(e,n),this.order.push(e)),n}assemble(t,n){if(t.block!==void 0)return t.block;switch(t.blockType){case`text`:return{type:`text`,text:t.text,...t.textPhase===void 0?{}:{phase:t.textPhase}};case`reasoning`:return{type:`reasoning`,text:t.text};case`tool-call`:return{type:`tool-call`,id:t.toolCallId??e(`call-${n}`),name:t.toolCallName??``,arguments:t.toolCallArguments};default:throw Error(`cannot assemble incomplete block of type "${t.blockType}"`)}}mustGet(e){let t=this.partials.get(e);if(t===void 0)throw Error(`BlockAssembler invariant violated: no partial for index ${e}`);return t}assembled(){let e=this.order.map(e=>this.assemble(this.mustGet(e),e)),t=this.finish.kind===`max-tokens`?e.map(e=>e.type!==`tool-call`):void 0,n=t===void 0?e:e.filter((e,n)=>t[n]===!0),r=this._replayState;return r?.blocks===void 0?{blocks:n,replay:r}:r.blocks.length===e.length?{blocks:n,replay:t===void 0||n.length===e.length?r:{response:r.response,blocks:r.blocks.filter((e,n)=>t[n]===!0)}}:{blocks:n,replay:void 0}}blocks(){return this.assembled().blocks}get hasToolCalls(){return this.order.some(e=>{let t=this.mustGet(e);return(t.block?.type??t.blockType)===`tool-call`})}textBlocks(){let e=this.order.findLastIndex(e=>{let t=this.mustGet(e);return(t.block?.type??t.blockType)===`native-tool-call`});return this.order.flatMap((t,n)=>{let r=this.mustGet(t);if((r.block?.type??r.blockType)!==`text`)return[];let i=this.assemble(r,t);return i.type===`text`?[{index:t,block:i,beforeNativeCall:n<e}]:[]})}interruptedBlocks(){return this.order.map(e=>{let t=this.mustGet(e),n=t.block?.type??t.blockType;if(n===`text`||n===`reasoning`)return this.assemble(t,e)}).filter(e=>(e?.type===`text`||e?.type===`reasoning`)&&e.text.trim()!==``)}get usage(){return this._usage}get finish(){return this._finish??{kind:`stop`}}get replayState(){return this.assembled().replay}message(e){return n({role:`assistant`,content:this.blocks(),source:e})}};export{r as BlockAssembler};
2
+ //# sourceMappingURL=assembler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembler.js","names":[],"sources":["../../src/stream/assembler.ts"],"sourcesContent":["/**\n * The single canonical chunk-to-message assembly algorithm.\n *\n * Every consumer that needs a finished message from a stream uses this, so that\n * \"what the user saw streaming\" and \"what got stored in history\" cannot drift\n * apart. Feed it every chunk, then read {@link BlockAssembler.blocks},\n * {@link BlockAssembler.message}, `usage`, and `finish` once the stream ends  Eor\n * {@link BlockAssembler.interruptedBlocks} when cancellation cut it short.\n *\n * @module ai-agent-sdk/core/stream/assembler\n */\n\nimport type { AssistantTextPhase, ContentBlock } from '../message/content.ts'\nimport { createMessage, type Message, type MessageSource } from '../message/message.ts'\nimport { ToolCallId } from '../primitives/brand.ts'\nimport { assertNever } from '../primitives/never.ts'\nimport type { FinishReason, ReplayEnvelope, StreamChunk, TokenUsage } from './chunk.ts'\n\ninterface PartialBlock {\n blockType: string\n text: string\n textPhase?: AssistantTextPhase\n toolCallId?: ToolCallId\n toolCallName?: string\n toolCallArguments: string\n /** Set by `block-end`  Eauthoritative, and freezes this partial against further deltas. */\n block?: ContentBlock\n}\n\n/**\n * Incrementally assembles {@link StreamChunk}s into {@link ContentBlock}s and a\n * final assistant {@link Message}.\n *\n * Tolerant by design: it accepts delta-only protocols that never send\n * `block-start`, and it IGNORES deltas that arrive for an index already closed by\n * `block-end`. That last rule is a containment boundary  Ea misbehaving adapter\n * cannot grow memory without bound or corrupt a block a consumer has already\n * been told is final.\n */\nexport class BlockAssembler {\n private partials = new Map<number, PartialBlock>()\n /** Block indexes in FIRST-SEEN order; the stream's own ordering, not sorted. */\n private order: number[] = []\n private _usage: TokenUsage | undefined\n private _finish: FinishReason | undefined\n private _replayState: ReplayEnvelope | undefined\n\n /**\n * Feed one chunk into the assembly state.\n * @param chunk - the next chunk, in stream order.\n */\n push(chunk: StreamChunk): void {\n switch (chunk.type) {\n case 'block-start': {\n if (!this.partials.has(chunk.index)) {\n this.order.push(chunk.index)\n this.partials.set(chunk.index, {\n blockType: chunk.blockType,\n text: '',\n toolCallArguments: '',\n })\n }\n return\n }\n case 'text-delta':\n case 'reasoning-delta': {\n const partial = this.ensure(chunk.index, chunk.type === 'text-delta' ? 'text' : 'reasoning')\n if (partial.block !== undefined) return // closed by block-end; ignore stragglers\n partial.text += chunk.text\n if (chunk.type === 'text-delta' && chunk.phase !== undefined) partial.textPhase = chunk.phase\n return\n }\n case 'tool-call-delta': {\n const partial = this.ensure(chunk.index, 'tool-call')\n if (partial.block !== undefined) return // closed by block-end; ignore stragglers\n partial.toolCallId = chunk.id\n if (chunk.name !== undefined && chunk.name.length > 0) partial.toolCallName = chunk.name\n partial.toolCallArguments += chunk.argumentsDelta\n return\n }\n case 'image-delta':\n // Progressive images are presentation-only. The authoritative final\n // image arrives inside the native-tool-call `block-end`.\n return\n case 'block-end': {\n const partial = this.ensure(chunk.index, chunk.block.type)\n // First close wins. Ignoring re-close stragglers keeps the streamed\n // output and the final assembled block in agreement.\n if (partial.block !== undefined) return\n partial.block = chunk.block\n return\n }\n case 'usage': {\n this._usage = chunk.usage\n return\n }\n case 'finish': {\n this._finish = chunk.reason\n this._replayState = chunk.replayState\n return\n }\n default:\n return assertNever(chunk, 'BlockAssembler.push')\n }\n }\n\n private ensure(index: number, blockType: string): PartialBlock {\n let partial = this.partials.get(index)\n if (partial === undefined) {\n partial = { blockType, text: '', toolCallArguments: '' }\n this.partials.set(index, partial)\n this.order.push(index)\n }\n return partial\n }\n\n private assemble(partial: PartialBlock, index: number): ContentBlock {\n if (partial.block !== undefined) return partial.block\n switch (partial.blockType) {\n case 'text': return {\n type: 'text',\n text: partial.text,\n ...partial.textPhase === undefined ? {} : { phase: partial.textPhase },\n }\n case 'reasoning': return { type: 'reasoning', text: partial.text }\n case 'tool-call': return {\n type: 'tool-call',\n // A synthesized id keeps the result correlatable even from a provider\n // that only sent the id on a chunk we never received.\n id: partial.toolCallId ?? ToolCallId(`call-${index}`),\n name: partial.toolCallName ?? '',\n arguments: partial.toolCallArguments,\n }\n default:\n // An extension block type that never received its authoritative\n // `block-end`: only the adapter that invented it knows how to build one.\n throw new Error(`cannot assemble incomplete block of type \"${partial.blockType}\"`)\n }\n }\n\n /** Invariant accessor: every index in `order` has a partial. */\n private mustGet(index: number): PartialBlock {\n const partial = this.partials.get(index)\n if (partial === undefined) {\n throw new Error(`BlockAssembler invariant violated: no partial for index ${index}`)\n }\n return partial\n }\n\n /**\n * The ONE keep/drop decision over all seen blocks, so emitted blocks and\n * replay metadata cannot disagree about what survived.\n *\n * Max-token truncation drops tool calls: a call cut off mid-arguments has\n * incomplete JSON, and executing it would act on arguments the model never\n * finished choosing.\n */\n private assembled(): { blocks: ContentBlock[]; replay: ReplayEnvelope | undefined } {\n const all = this.order.map(index => this.assemble(this.mustGet(index), index))\n const kept = this.finish.kind === 'max-tokens'\n ? all.map(block => block.type !== 'tool-call')\n : undefined\n const blocks = kept === undefined ? all : all.filter((_, position) => kept[position] === true)\n const envelope = this._replayState\n if (envelope?.blocks === undefined) return { blocks, replay: envelope }\n // A per-block envelope that does not line up with the blocks it describes is\n // discarded whole: a misaligned mapping is worse than no mapping.\n if (envelope.blocks.length !== all.length) return { blocks, replay: undefined }\n return {\n blocks,\n replay: kept === undefined || blocks.length === all.length\n ? envelope\n : {\n response: envelope.response,\n blocks: envelope.blocks.filter((_, position) => kept[position] === true),\n },\n }\n }\n\n /**\n * Assemble every block seen so far, in stream order.\n * @returns one block per seen index, minus tool calls dropped by max-token\n * truncation. An open block assembles from its accumulated deltas.\n */\n blocks(): ContentBlock[] {\n return this.assembled().blocks\n }\n\n /** Whether the canonical stream contains host tool calls, including calls\n * dropped from blocks() on truncation. No incomplete arguments are parsed. */\n get hasToolCalls(): boolean {\n return this.order.some(index => {\n const partial = this.mustGet(index)\n return (partial.block?.type ?? partial.blockType) === 'tool-call'\n })\n }\n\n /** Canonical text blocks with their original stream indexes, in first-seen\n * order. Shares first-close-wins semantics with blocks(), including ignored\n * straggler deltas and authoritative block-end replacements. */\n textBlocks(): { index: number; block: Extract<ContentBlock, { type: 'text' }>; beforeNativeCall: boolean }[] {\n const lastNative = this.order.findLastIndex(index => {\n const partial = this.mustGet(index)\n return (partial.block?.type ?? partial.blockType) === 'native-tool-call'\n })\n return this.order.flatMap((index, position) => {\n const partial = this.mustGet(index)\n if ((partial.block?.type ?? partial.blockType) !== 'text') return []\n const block = this.assemble(partial, index)\n return block.type === 'text' ? [{ index, block, beforeNativeCall: position < lastNative }] : []\n })\n }\n\n /**\n * Assemble the prefix an INTERRUPTED stream can safely finalize: closed and\n * open text/reasoning blocks carrying non-whitespace content.\n *\n * Tool calls are omitted because interruption precedes dispatch, so keeping one\n * would oblige the caller to fabricate a result for a call that never ran.\n * @returns the kept blocks; empty when nothing usable streamed first.\n */\n interruptedBlocks(): ContentBlock[] {\n return this.order\n .map((index) => {\n const partial = this.mustGet(index)\n const type = partial.block?.type ?? partial.blockType\n if (type !== 'text' && type !== 'reasoning') return undefined\n return this.assemble(partial, index)\n })\n .filter((block): block is ContentBlock =>\n (block?.type === 'text' || block?.type === 'reasoning') && block.text.trim() !== '')\n }\n\n /** Usage from the `usage` chunk; undefined until one arrives. */\n get usage(): TokenUsage | undefined {\n return this._usage\n }\n\n /** Finish reason; `{ kind: 'stop' }` when the stream ended without one. */\n get finish(): FinishReason {\n return this._finish ?? { kind: 'stop' }\n }\n\n /**\n * Replay metadata, with per-block entries pruned in step with {@link blocks}.\n * Undefined when the envelope did not align with the emitted blocks.\n */\n get replayState(): ReplayEnvelope | undefined {\n return this.assembled().replay\n }\n\n /**\n * The assembled assistant message.\n * @param source - producer attribution for the message.\n * @returns a frozen assistant-role message over {@link blocks}.\n */\n message(source: MessageSource): Message {\n return createMessage({ role: 'assistant', content: this.blocks(), source })\n }\n}\n"],"mappings":"+JAuCA,IAAa,EAAb,KAA4B,CAC1B,SAAmB,IAAI,IAEvB,MAA0B,CAAC,EAC3B,OACA,QACA,aAMA,KAAK,EAA0B,CAC7B,OAAQ,EAAM,KAAd,CACE,IAAK,cACE,KAAK,SAAS,IAAI,EAAM,KAAK,IAChC,KAAK,MAAM,KAAK,EAAM,KAAK,EAC3B,KAAK,SAAS,IAAI,EAAM,MAAO,CAC7B,UAAW,EAAM,UACjB,KAAM,GACN,kBAAmB,EACrB,CAAC,GAEH,OAEF,IAAK,aACL,IAAK,kBAAmB,CACtB,IAAM,EAAU,KAAK,OAAO,EAAM,MAAO,EAAM,OAAS,aAAe,OAAS,WAAW,EAC3F,GAAI,EAAQ,QAAU,IAAA,GAAW,OACjC,EAAQ,MAAQ,EAAM,KAClB,EAAM,OAAS,cAAgB,EAAM,QAAU,IAAA,KAAW,EAAQ,UAAY,EAAM,OACxF,MACF,CACA,IAAK,kBAAmB,CACtB,IAAM,EAAU,KAAK,OAAO,EAAM,MAAO,WAAW,EACpD,GAAI,EAAQ,QAAU,IAAA,GAAW,OACjC,EAAQ,WAAa,EAAM,GACvB,EAAM,OAAS,IAAA,IAAa,EAAM,KAAK,OAAS,IAAG,EAAQ,aAAe,EAAM,MACpF,EAAQ,mBAAqB,EAAM,eACnC,MACF,CACA,IAAK,cAGH,OACF,IAAK,YAAa,CAChB,IAAM,EAAU,KAAK,OAAO,EAAM,MAAO,EAAM,MAAM,IAAI,EAGzD,G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C,OAAS,QAAU,IAAS,YAChC,OAAO,KAAK,SAAS,EAAS,CAAK,CACrC,CAAC,CAAC,CACD,OAAQ,IACN,GAAO,OAAS,QAAU,GAAO,OAAS,cAAgB,EAAM,KAAK,KAAK,IAAM,EAAE,CACzF,CAGA,IAAI,OAAgC,CAClC,OAAO,KAAK,MACd,CAGA,IAAI,QAAuB,CACzB,OAAO,KAAK,SAAW,CAAE,KAAM,MAAO,CACxC,CAMA,IAAI,aAA0C,CAC5C,OAAO,KAAK,UAAU,CAAC,CAAC,MAC1B,CAOA,QAAQ,EAAgC,CACtC,OAAO,EAAc,CAAE,KAAM,YAAa,QAAS,KAAK,OAAO,EAAG,QAAO,CAAC,CAC5E,CACF"}
@@ -0,0 +1,135 @@
1
+ import { ToolCallId } from "../primitives/brand.js";
2
+ import { ModelFailure } from "../errors/failure.js";
3
+ import { AssistantTextPhase, ContentBlock, ContentBlockType, ImageMediaType } from "../message/content.js";
4
+ //#region src/stream/chunk.d.ts
5
+ /**
6
+ * Why a model response stopped. Merge-extensible, so an adapter can surface a
7
+ * provider-specific reason without a core release.
8
+ *
9
+ * `aborted` and `error` carry their failure inline because a stream that fails
10
+ * still has to END — a thrown exception mid-iteration would strand whatever text
11
+ * had already been assembled.
12
+ */
13
+ interface FinishReasonMap {
14
+ 'stop': {
15
+ kind: 'stop';
16
+ };
17
+ 'tool-calls': {
18
+ kind: 'tool-calls';
19
+ };
20
+ 'max-tokens': {
21
+ kind: 'max-tokens';
22
+ };
23
+ 'aborted': {
24
+ kind: 'aborted';
25
+ failure: ModelFailure;
26
+ };
27
+ 'error': {
28
+ kind: 'error';
29
+ failure: ModelFailure;
30
+ };
31
+ }
32
+ /** Any known finish reason. Switch on `kind` and fall through unknowns. */
33
+ type FinishReason = FinishReasonMap[keyof FinishReasonMap];
34
+ /**
35
+ * Token accounting for one model call.
36
+ *
37
+ * Counts are DISJOINT, which is the one thing to get right here: `inputTokens` is
38
+ * UNCACHED input only, and cached input is reported separately, so billed input is
39
+ * the sum of the three. Providers disagree — some fold cache hits into a single
40
+ * prompt total — and the adapter subtracts them back out to honour this
41
+ * convention. Without it, every cost calculation double-counts cache hits.
42
+ */
43
+ interface TokenUsage {
44
+ /** Uncached input tokens. */
45
+ inputTokens: number;
46
+ outputTokens: number;
47
+ /**
48
+ * Exact full-call total.
49
+ *
50
+ * Set only when authoritative: preserved from a provider total, or derived from
51
+ * aggregate counters that agree. Omitted rather than guessed.
52
+ */
53
+ totalTokens?: number;
54
+ cacheReadTokens?: number;
55
+ cacheWriteTokens?: number;
56
+ reasoningTokens?: number;
57
+ }
58
+ /**
59
+ * Adapter-private lossless-JSON state for replaying a successful response.
60
+ *
61
+ * Carried by the terminal `finish` chunk and stored on the assembled message.
62
+ * Both halves stay opaque above the adapter; only the SPLIT is shared vocabulary,
63
+ * which is what lets assembly keep stored metadata aligned with stored content
64
+ * without understanding either half.
65
+ */
66
+ interface ReplayEnvelope {
67
+ /** Response-level adapter-private metadata (ids, native stop reason). */
68
+ response: unknown;
69
+ /**
70
+ * Per-block adapter-private metadata, one entry per emitted block in first-seen
71
+ * stream order.
72
+ *
73
+ * When assembly drops a block it drops the entry at the same position. An
74
+ * envelope whose length does not match the emitted block count is discarded
75
+ * whole, because a misaligned mapping is worse than none. An adapter whose
76
+ * metadata is independent of block structure omits this field.
77
+ */
78
+ blocks?: readonly unknown[];
79
+ }
80
+ /**
81
+ * The raw streaming protocol every adapter emits.
82
+ *
83
+ * Contract adapters must honour:
84
+ * - `index` correlates the deltas of interleaved blocks. It is adapter-assigned in
85
+ * first-seen order and need not match any provider's own numbering.
86
+ * - `block-end` carries the AUTHORITATIVE assembled block, so a consumer that
87
+ * trusts it never has to re-derive one from deltas.
88
+ * - `usage` precedes the terminal `finish`, and NOTHING follows `finish`.
89
+ * - tool arguments stay raw JSON strings.
90
+ *
91
+ * An adapter may throw, but the registry normalizes that into a terminal `error`
92
+ * or `aborted` finish before a consumer ever sees it.
93
+ */
94
+ type StreamChunk = {
95
+ type: 'block-start';
96
+ index: number;
97
+ blockType: ContentBlockType;
98
+ } | {
99
+ type: 'text-delta';
100
+ index: number;
101
+ text: string;
102
+ phase?: AssistantTextPhase;
103
+ } | {
104
+ type: 'reasoning-delta';
105
+ index: number;
106
+ text: string;
107
+ } | {
108
+ type: 'image-delta';
109
+ index: number;
110
+ itemId: string;
111
+ data: string;
112
+ mediaType: ImageMediaType;
113
+ partialIndex?: number;
114
+ } | {
115
+ type: 'tool-call-delta';
116
+ index: number;
117
+ id: ToolCallId;
118
+ name?: string;
119
+ argumentsDelta: string;
120
+ } | {
121
+ type: 'block-end';
122
+ index: number;
123
+ block: ContentBlock;
124
+ } | {
125
+ type: 'usage';
126
+ usage: TokenUsage;
127
+ } | {
128
+ type: 'finish';
129
+ reason: FinishReason;
130
+ /** Replay metadata for a successful response; see {@link ReplayEnvelope}. */
131
+ replayState?: ReplayEnvelope;
132
+ };
133
+ //#endregion
134
+ export { FinishReason, FinishReasonMap, ReplayEnvelope, StreamChunk, TokenUsage };
135
+ //# sourceMappingURL=chunk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunk.d.ts","names":[],"sources":["../../src/stream/chunk.ts"],"mappings":";;;;;;;;;;;;UAkBiB;EACf;IAAU;;EACV;IAAgB;;EAChB;IAAgB;;EAChB;IAAa;IAAiB,SAAS;;EACvC;IAAW;IAAe,SAAS;;;;KAIzB,eAAe,sBAAsB;;;;;;;;;;UAWhC;;EAEf;EACA;;;;;;;EAOA;EACA;EACA;EACA;;;;;;;;;;UAWe;;EAEf;;;;;;;;;;EAUA;;;;;;;;;;;;;;;;KAiBU;EACN;EAAqB;EAAe,WAAW;;EAC/C;EAAoB;EAAe;EAAc,QAAQ;;EACzD;EAAyB;EAAe;;EAE1C;EACA;EACA;EACA;EACA,WAAW;EACX;;EAEE;EAAyB;EAAe,IAAI;EAAY;EAAe;;EACvE;EAAmB;EAAe,OAAO;;EACzC;EAAe,OAAO;;EAExB;EACA,QAAQ;;EAER,cAAc"}
@@ -0,0 +1,30 @@
1
+ //#region src/stream/idle-timeout.d.ts
2
+ /**
3
+ * An idle watchdog for streaming responses.
4
+ *
5
+ * The failure this guards against is specific and nasty: a provider accepts the
6
+ * request, returns 200, sends some or none of the body, and then simply stops
7
+ * without closing the connection. No error is ever delivered, so a plain
8
+ * `for await` waits forever and the caller's request hangs with no diagnostic.
9
+ *
10
+ * The bound is on IDLE time between chunks, not on total duration, because a
11
+ * legitimately long generation can take minutes while never being idle.
12
+ *
13
+ * @module ai-agent-sdk/core/stream/idle-timeout
14
+ */
15
+ /**
16
+ * Wrap an async iterable so that any gap longer than `timeoutMs` between values
17
+ * fails instead of hanging.
18
+ *
19
+ * The timer is armed per pending read and cleared as soon as a value arrives, so
20
+ * a stream that keeps producing never accumulates timers. On expiry the source
21
+ * iterator is closed, which is what actually aborts the underlying request.
22
+ * @param iterable - the source stream.
23
+ * @param timeoutMs - maximum idle interval; non-finite or non-positive disables the watchdog.
24
+ * @param onTimeout - builds the error to throw, so callers keep their own taxonomy.
25
+ * @returns the same values, with an idle bound applied.
26
+ */
27
+ declare function withIdleTimeout<T>(iterable: AsyncIterable<T>, timeoutMs: number, onTimeout: () => Error, teardownTimeoutMs?: number): AsyncGenerator<T>;
28
+ //#endregion
29
+ export { withIdleTimeout };
30
+ //# sourceMappingURL=idle-timeout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idle-timeout.d.ts","names":[],"sources":["../../src/stream/idle-timeout.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BuB,gBAAgB,GACrC,UAAU,cAAc,IACxB,mBACA,iBAAiB,OACjB,6BACC,eAAe"}
@@ -0,0 +1,2 @@
1
+ import{waitForSettlement as e}from"../async/settlement.js";async function*t(t,n,r,i=3e4){if(!Number.isFinite(n)||n<=0){yield*t;return}let a=t[Symbol.asyncIterator](),o=!1;try{for(;;){let e,t=new Promise((t,i)=>{e=setTimeout(()=>i(r()),n)}),i;try{i=await Promise.race([a.next(),t])}finally{e!==void 0&&clearTimeout(e),t.catch(()=>{})}if(i.done===!0){o=!0;return}yield i.value}}finally{if(!o){if(!Number.isFinite(i)||i<=0)throw RangeError(`teardownTimeoutMs must be a positive finite number`);let t=a.return?.bind(a);if(t!==void 0){let n=Promise.resolve().then(async()=>{await t()});if(!await e(n,i))throw Error(`stream source ignored cancellation for more than ${i}ms`)}}}}export{t as withIdleTimeout};
2
+ //# sourceMappingURL=idle-timeout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idle-timeout.js","names":[],"sources":["../../src/stream/idle-timeout.ts"],"sourcesContent":["/**\n * An idle watchdog for streaming responses.\n *\n * The failure this guards against is specific and nasty: a provider accepts the\n * request, returns 200, sends some or none of the body, and then simply stops\n * without closing the connection. No error is ever delivered, so a plain\n * `for await` waits forever and the caller's request hangs with no diagnostic.\n *\n * The bound is on IDLE time between chunks, not on total duration, because a\n * legitimately long generation can take minutes while never being idle.\n *\n * @module ai-agent-sdk/core/stream/idle-timeout\n */\n\n/**\n * Wrap an async iterable so that any gap longer than `timeoutMs` between values\n * fails instead of hanging.\n *\n * The timer is armed per pending read and cleared as soon as a value arrives, so\n * a stream that keeps producing never accumulates timers. On expiry the source\n * iterator is closed, which is what actually aborts the underlying request.\n * @param iterable - the source stream.\n * @param timeoutMs - maximum idle interval; non-finite or non-positive disables the watchdog.\n * @param onTimeout - builds the error to throw, so callers keep their own taxonomy.\n * @returns the same values, with an idle bound applied.\n */\nexport async function* withIdleTimeout<T>(\n iterable: AsyncIterable<T>,\n timeoutMs: number,\n onTimeout: () => Error,\n teardownTimeoutMs = 30_000,\n): AsyncGenerator<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n yield* iterable\n return\n }\n const iterator = iterable[Symbol.asyncIterator]()\n let exhausted = false\n try {\n while (true) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const expiry = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(onTimeout()), timeoutMs)\n })\n let result: IteratorResult<T>\n try {\n // Both branches settle: `iterator.next()` on data or source failure, the\n // timer on silence. Whichever loses the race is discarded, and the timer\n // is always cleared so a resolved read cannot leave the process alive.\n result = await Promise.race([iterator.next(), expiry])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n // The losing `expiry` promise rejects later with nothing awaiting it.\n // Attach a no-op handler so that rejection is never \"unhandled\".\n void expiry.catch(() => {})\n }\n if (result.done === true) {\n exhausted = true\n return\n }\n yield result.value\n }\n } finally {\n if (!exhausted) {\n if (!Number.isFinite(teardownTimeoutMs) || teardownTimeoutMs <= 0) {\n throw new RangeError('teardownTimeoutMs must be a positive finite number')\n }\n const close = iterator.return?.bind(iterator)\n if (close !== undefined) {\n const closing = Promise.resolve().then(async () => { await close() })\n if (!await waitForSettlement(closing, teardownTimeoutMs)) {\n throw new Error(`stream source ignored cancellation for more than ${teardownTimeoutMs}ms`)\n }\n }\n }\n }\n}\nimport { waitForSettlement } from '../async/settlement.ts'\n"],"mappings":"2DA0BA,eAAuB,EACrB,EACA,EACA,EACA,EAAoB,IACD,CACnB,GAAI,CAAC,OAAO,SAAS,CAAS,GAAK,GAAa,EAAG,CACjD,MAAO,EACP,MACF,CACA,IAAM,EAAW,EAAS,OAAO,cAAc,CAAC,EAC5C,EAAY,GAChB,GAAI,CACF,OAAa,CACX,IAAI,EACE,EAAS,IAAI,SAAgB,EAAU,IAAW,CACtD,EAAQ,eAAiB,EAAO,EAAU,CAAC,EAAG,CAAS,CACzD,CAAC,EACG,EACJ,GAAI,CAIF,EAAS,MAAM,QAAQ,KAAK,CAAC,EAAS,KAAK,EAAG,CAAM,CAAC,CACvD,QAAU,CACJ,IAAU,IAAA,IAAW,aAAa,CAAK,EAG3C,EAAY,UAAY,CAAC,CAAC,CAC5B,CACA,GAAI,EAAO,OAAS,GAAM,CACxB,EAAY,GACZ,MACF,CACA,MAAM,EAAO,KACf,CACF,QAAU,CACR,GAAI,CAAC,EAAW,CACd,GAAI,CAAC,OAAO,SAAS,CAAiB,GAAK,GAAqB,EAC9D,MAAU,WAAW,oDAAoD,EAE3E,IAAM,EAAQ,EAAS,QAAQ,KAAK,CAAQ,EAC5C,GAAI,IAAU,IAAA,GAAW,CACvB,IAAM,EAAU,QAAQ,QAAQ,CAAC,CAAC,KAAK,SAAY,CAAE,MAAM,EAAM,CAAE,CAAC,EACpE,GAAI,CAAC,MAAM,EAAkB,EAAS,CAAiB,EACrD,MAAU,MAAM,oDAAoD,EAAkB,GAAG,CAE7F,CACF,CACF,CACF"}
@@ -0,0 +1,29 @@
1
+ //#region src/support-safe/error.d.ts
2
+ interface UsageCoverageSummary {
3
+ readonly logicalCalls: number;
4
+ readonly attempts: number;
5
+ readonly complete: number;
6
+ readonly partial: number;
7
+ readonly estimated: number;
8
+ readonly missing: number;
9
+ readonly notApplicable: number;
10
+ readonly possiblyBilledAttemptsWithoutUsage: number;
11
+ }
12
+ /** Metadata-only error shape safe for default diagnostics and public support artifacts. */
13
+ interface SupportSafeError {
14
+ readonly code: string;
15
+ readonly stage: string;
16
+ readonly message: string;
17
+ readonly provider?: string;
18
+ readonly route?: string;
19
+ readonly origin?: string;
20
+ readonly status?: number;
21
+ readonly requestId?: string;
22
+ readonly retryable?: boolean;
23
+ readonly dispatchState?: 'not-sent' | 'sent' | 'unknown';
24
+ readonly usageCoverage: UsageCoverageSummary;
25
+ readonly possiblyBilledAttemptsWithoutUsage: number;
26
+ }
27
+ //#endregion
28
+ export { SupportSafeError, UsageCoverageSummary };
29
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","names":[],"sources":["../../src/support-safe/error.ts"],"mappings":";UAAiB;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,eAAe;WACf"}
@@ -0,0 +1,2 @@
1
+ const e=Object.freeze({logicalCalls:0,attempts:0,complete:0,partial:0,estimated:0,missing:0,notApplicable:0,possiblyBilledAttemptsWithoutUsage:0});export{e as NOT_APPLICABLE_USAGE_COVERAGE};
2
+ //# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../src/support-safe/error.ts"],"sourcesContent":["export interface UsageCoverageSummary {\n readonly logicalCalls: number\n readonly attempts: number\n readonly complete: number\n readonly partial: number\n readonly estimated: number\n readonly missing: number\n readonly notApplicable: number\n readonly possiblyBilledAttemptsWithoutUsage: number\n}\n\n/** Metadata-only error shape safe for default diagnostics and public support artifacts. */\nexport interface SupportSafeError {\n readonly code: string\n readonly stage: string\n readonly message: string\n readonly provider?: string\n readonly route?: string\n readonly origin?: string\n readonly status?: number\n readonly requestId?: string\n readonly retryable?: boolean\n readonly dispatchState?: 'not-sent' | 'sent' | 'unknown'\n readonly usageCoverage: UsageCoverageSummary\n readonly possiblyBilledAttemptsWithoutUsage: number\n}\n\nexport const NOT_APPLICABLE_USAGE_COVERAGE: UsageCoverageSummary = Object.freeze({\n logicalCalls: 0, attempts: 0, complete: 0, partial: 0,\n estimated: 0, missing: 0, notApplicable: 0,\n possiblyBilledAttemptsWithoutUsage: 0,\n})\n"],"mappings":"AA2BA,MAAa,EAAsD,OAAO,OAAO,CAC/E,aAAc,EAAG,SAAU,EAAG,SAAU,EAAG,QAAS,EACpD,UAAW,EAAG,QAAS,EAAG,cAAe,EACzC,mCAAoC,CACtC,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { JsonObject, JsonValue } from "./primitives/json.js";
2
+ import { SdkLogger } from "./logging/types.js";
3
+ import { ToolSchema } from "./contract/tool.js";
4
+ import { ToolCallPosition, ToolDefinition, ToolExecutionMode, ToolExecutionResult, ToolFailure, ToolRunContext, ToolSuccess, defineTool, executionModeOf, renderJsonValue } from "./agent/tool/definition.js";
5
+ import { MemorySpillStoreLimits, SPILL_TOOL_NAME, SpillRecord, SpillSlice, SpillStore, ToolOutputOverflowPolicy, TruncatedText, createMemorySpillStore, estimateTextBlockTokens, estimateTextTokens, previewForSpill, readSpillTool, truncateMiddleToTokens } from "./agent/tool/output-budget.js";
6
+ import { ApprovalBroker, ApprovalDecision, ApprovalRequest, ApprovalStateStore, InteractiveApprovalBroker, InteractiveApprovalBrokerOptions, createApprovalBroker, createApprovalRequest, fixedApprovalBroker, withApprovalPersistence } from "./agent/tool/approval.js";
7
+ import { REGISTRY_ERROR_CODES, ToolCatalog, ToolFilter, ToolRegistry } from "./agent/tool/registry.js";
8
+ import { AuthorizationOutcome, AuthorizedToolCall, DispatchToolCallOptions, PostToolDecision, PreToolDecision, PreparedToolCall, ToolCallContext, ToolCallRequest, ToolInterceptor, authorizeToolCall, dispatchAuthorizedToolCall, dispatchToolCall, finalizeToolCall, prepareToolCall, toolFailure } from "./agent/tool/pipeline.js";
9
+ import { ToolCatalogSnapshot, ToolSource, ToolSourceDefinition, ToolSourceRunReference, ToolSourceSnapshotOptions } from "./agent/tool/source-types.js";
10
+ import { TOOL_ERROR_CODES, ToolError, ToolErrorDisposition, toolErrorDisposition } from "./agent/tool/errors.js";
11
+ import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
12
+ import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
13
+ import { TOOL_SOURCE_API_VERSION } from "./composition/tool-source/config.js";
14
+ import { defineToolSource } from "./composition/tool-source/definition.js";
15
+ export { type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AuthorizationOutcome, type AuthorizedToolCall, type DispatchToolCallOptions, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type JsonObject, type JsonValue, type MemorySpillStoreLimits, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RuntimeSchema, SPILL_TOOL_NAME, type SdkLogger, type SpillRecord, type SpillSlice, type SpillStore, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, TOOL_SOURCE_API_VERSION, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCatalog, type ToolCatalogSnapshot, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSchema, type ToolSource, type ToolSourceDefinition, type ToolSourceRunReference, type ToolSourceSnapshotOptions, type ToolSuccess, type TruncatedText, authorizeToolCall, createApprovalBroker, createApprovalRequest, createMemorySpillStore, createToolExecutionInterceptor, defineTool, defineToolFromSchema, defineToolSource, dispatchAuthorizedToolCall, dispatchToolCall, estimateTextBlockTokens, estimateTextTokens, executionModeOf, finalizeToolCall, fixedApprovalBroker, localToolExecutionBackend, prepareToolCall, previewForSpill, readSpillTool, renderJsonValue, toolErrorDisposition, toolFailure, truncateMiddleToTokens, withApprovalPersistence };
package/dist/tools.js ADDED
@@ -0,0 +1 @@
1
+ import{defineTool as e,executionModeOf as t,renderJsonValue as n}from"./agent/tool/definition.js";import{REGISTRY_ERROR_CODES as r,ToolRegistry as i}from"./agent/tool/registry.js";import{SPILL_TOOL_NAME as a,createMemorySpillStore as o,estimateTextBlockTokens as s,estimateTextTokens as c,previewForSpill as l,readSpillTool as u,truncateMiddleToTokens as d}from"./agent/tool/output-budget.js";import{TOOL_ERROR_CODES as f,ToolError as p,toolErrorDisposition as m}from"./agent/tool/errors.js";import{createApprovalBroker as h,createApprovalRequest as g,fixedApprovalBroker as _,withApprovalPersistence as v}from"./agent/tool/approval.js";import{authorizeToolCall as y,dispatchAuthorizedToolCall as b,dispatchToolCall as x,finalizeToolCall as S,prepareToolCall as C,toolFailure as w}from"./agent/tool/pipeline.js";import{TOOL_SOURCE_API_VERSION as T}from"./composition/tool-source/config.js";import{defineToolSource as E}from"./composition/tool-source/definition.js";import{defineToolFromSchema as D}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as O,localToolExecutionBackend as k}from"./agent/tool/execution.js";export{a as SPILL_TOOL_NAME,f as TOOL_ERROR_CODES,r as TOOL_REGISTRY_ERROR_CODES,T as TOOL_SOURCE_API_VERSION,p as ToolError,i as ToolRegistry,y as authorizeToolCall,h as createApprovalBroker,g as createApprovalRequest,o as createMemorySpillStore,O as createToolExecutionInterceptor,e as defineTool,D as defineToolFromSchema,E as defineToolSource,b as dispatchAuthorizedToolCall,x as dispatchToolCall,s as estimateTextBlockTokens,c as estimateTextTokens,t as executionModeOf,S as finalizeToolCall,_ as fixedApprovalBroker,k as localToolExecutionBackend,C as prepareToolCall,l as previewForSpill,u as readSpillTool,n as renderJsonValue,m as toolErrorDisposition,w as toolFailure,d as truncateMiddleToTokens,v as withApprovalPersistence};