@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,53 @@
1
+ import { JsonObject } from "../primitives/json.js";
2
+ //#region src/logging/types.d.ts
3
+ type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
4
+ /** Minimal structured logger contract shared without reversing observation ownership. */
5
+ interface SdkLogger {
6
+ child(fields: Readonly<JsonObject>): SdkLogger;
7
+ trace(message: string, fields?: Readonly<JsonObject>): void;
8
+ debug(message: string, fields?: Readonly<JsonObject>): void;
9
+ info(message: string, fields?: Readonly<JsonObject>): void;
10
+ warn(message: string, fields?: Readonly<JsonObject>): void;
11
+ error(message: string, fields?: Readonly<JsonObject>): void;
12
+ fatal(message: string, fields?: Readonly<JsonObject>): void;
13
+ }
14
+ type LoggedOperationStatus = 'success' | 'error' | 'aborted' | 'rejected' | 'unknown';
15
+ /** Metadata-only operation envelope shared by runtime-active integrations. */
16
+ type IntegrationOperationEvidenceFields = (JsonObject & {
17
+ readonly integrationSchemaVersion: 1;
18
+ readonly integrationFamily: string;
19
+ readonly integrationOperation: string;
20
+ readonly operationId: string;
21
+ readonly kind: 'logical-start';
22
+ }) | (JsonObject & {
23
+ readonly integrationSchemaVersion: 1;
24
+ readonly integrationFamily: string;
25
+ readonly integrationOperation: string;
26
+ readonly operationId: string;
27
+ readonly kind: 'attempt-start';
28
+ readonly attemptId: string;
29
+ readonly attemptNumber: number;
30
+ }) | (JsonObject & {
31
+ readonly integrationSchemaVersion: 1;
32
+ readonly integrationFamily: string;
33
+ readonly integrationOperation: string;
34
+ readonly operationId: string;
35
+ readonly kind: 'attempt-terminal';
36
+ readonly attemptId: string;
37
+ readonly attemptNumber: number;
38
+ readonly status: LoggedOperationStatus;
39
+ readonly durationMs: number;
40
+ readonly errorCode?: string;
41
+ }) | (JsonObject & {
42
+ readonly integrationSchemaVersion: 1;
43
+ readonly integrationFamily: string;
44
+ readonly integrationOperation: string;
45
+ readonly operationId: string;
46
+ readonly kind: 'logical-terminal';
47
+ readonly status: LoggedOperationStatus;
48
+ readonly durationMs: number;
49
+ readonly errorCode?: string;
50
+ });
51
+ //#endregion
52
+ export { IntegrationOperationEvidenceFields, LogLevel, SdkLogger };
53
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/logging/types.ts"],"mappings":";;KAEY;;UAGK;EACf,MAAM,QAAQ,SAAS,cAAc;EACrC,MAAM,iBAAiB,SAAS,SAAS;EACzC,MAAM,iBAAiB,SAAS,SAAS;EACzC,KAAK,iBAAiB,SAAS,SAAS;EACxC,KAAK,iBAAiB,SAAS,SAAS;EACxC,MAAM,iBAAiB,SAAS,SAAS;EACzC,MAAM,iBAAiB,SAAS,SAAS;;KAGtC;;KAGO,sCACP;WACU;WACA;WACA;WACA;WACA;MAEV;WACU;WACA;WACA;WACA;WACA;WACA;WACA;MAEV;WACU;WACA;WACA;WACA;WACA;WACA;WACA;WACA,QAAQ;WACR;WACA;MAEV;WACU;WACA;WACA;WACA;WACA;WACA,QAAQ;WACR;WACA"}
@@ -0,0 +1,2 @@
1
+ const e=Object.freeze({child:()=>e,trace:()=>void 0,debug:()=>void 0,info:()=>void 0,warn:()=>void 0,error:()=>void 0,fatal:()=>void 0});export{e as CLOSED_RUNTIME_LOGGER};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/logging/types.ts"],"sourcesContent":["import type { JsonObject } from '../primitives/json.ts'\n\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'\n\n/** Minimal structured logger contract shared without reversing observation ownership. */\nexport interface SdkLogger {\n child(fields: Readonly<JsonObject>): SdkLogger\n trace(message: string, fields?: Readonly<JsonObject>): void\n debug(message: string, fields?: Readonly<JsonObject>): void\n info(message: string, fields?: Readonly<JsonObject>): void\n warn(message: string, fields?: Readonly<JsonObject>): void\n error(message: string, fields?: Readonly<JsonObject>): void\n fatal(message: string, fields?: Readonly<JsonObject>): void\n}\n\ntype LoggedOperationStatus = 'success' | 'error' | 'aborted' | 'rejected' | 'unknown'\n\n/** Metadata-only operation envelope shared by runtime-active integrations. */\nexport type IntegrationOperationEvidenceFields =\n | (JsonObject & {\n readonly integrationSchemaVersion: 1\n readonly integrationFamily: string\n readonly integrationOperation: string\n readonly operationId: string\n readonly kind: 'logical-start'\n })\n | (JsonObject & {\n readonly integrationSchemaVersion: 1\n readonly integrationFamily: string\n readonly integrationOperation: string\n readonly operationId: string\n readonly kind: 'attempt-start'\n readonly attemptId: string\n readonly attemptNumber: number\n })\n | (JsonObject & {\n readonly integrationSchemaVersion: 1\n readonly integrationFamily: string\n readonly integrationOperation: string\n readonly operationId: string\n readonly kind: 'attempt-terminal'\n readonly attemptId: string\n readonly attemptNumber: number\n readonly status: LoggedOperationStatus\n readonly durationMs: number\n readonly errorCode?: string\n })\n | (JsonObject & {\n readonly integrationSchemaVersion: 1\n readonly integrationFamily: string\n readonly integrationOperation: string\n readonly operationId: string\n readonly kind: 'logical-terminal'\n readonly status: LoggedOperationStatus\n readonly durationMs: number\n readonly errorCode?: string\n })\n\nexport const CLOSED_RUNTIME_LOGGER: SdkLogger = Object.freeze({\n child: () => CLOSED_RUNTIME_LOGGER,\n trace: () => undefined, debug: () => undefined, info: () => undefined,\n warn: () => undefined, error: () => undefined, fatal: () => undefined,\n})\n"],"mappings":"AA0DA,MAAa,EAAmC,OAAO,OAAO,CAC5D,UAAa,EACb,UAAa,IAAA,GAAW,UAAa,IAAA,GAAW,SAAY,IAAA,GAC5D,SAAY,IAAA,GAAW,UAAa,IAAA,GAAW,UAAa,IAAA,EAC9D,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { SdkLogger } from "./logging/types.js";
2
+ import { AgentCompactionConfig, AgentCompactionOptions, resolveCompactionConfig } from "./agent/memory/compaction-config.js";
3
+ import { COMPACTION_INSTRUCTION, CompactionResult, ContextCompactor, ContextCompactorOptions } from "./agent/memory/compaction.js";
4
+ import { AgentMemory, AgentMemoryConfig, AgentMemoryConfigInput, AgentMemoryItem, AgentMemoryKind, AgentMemorySeed, AgentMemorySnapshot, resolveMemoryConfig } from "./agent/memory/memory.js";
5
+ import { MemoryBinding, MemoryCommitInput, MemoryCommitResult, MemoryLoadResult, MemoryScope, MemoryStore, MemoryStoreDefinition, MemoryStoreOptions } from "./agent/memory/persistence-types.js";
6
+ import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
7
+ import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
8
+ import { MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION } from "./composition/memory/config.js";
9
+ import { defineMemoryStore } from "./composition/memory/definition.js";
10
+ export { type AgentCompactionConfig, type AgentCompactionOptions, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, COMPACTION_INSTRUCTION, type CompactionResult, ContextCompactor, type ContextCompactorOptions, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type SdkLogger, defineMemoryStore, estimateContextTokens, estimateMessageTokens, resolveCompactionConfig, resolveMemoryConfig, selectCompactablePrefix };
package/dist/memory.js ADDED
@@ -0,0 +1 @@
1
+ import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{estimateContextTokens as n,estimateMessageTokens as r}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as i}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as a,ContextCompactor as o}from"./agent/memory/compaction.js";import{resolveCompactionConfig as s}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as c,MEMORY_STORE_API_VERSION as l}from"./composition/memory/config.js";import{defineMemoryStore as u}from"./composition/memory/definition.js";export{e as AgentMemory,a as COMPACTION_INSTRUCTION,o as ContextCompactor,c as MEMORY_ERROR_CODES,l as MEMORY_STORE_API_VERSION,u as defineMemoryStore,n as estimateContextTokens,r as estimateMessageTokens,s as resolveCompactionConfig,t as resolveMemoryConfig,i as selectCompactablePrefix};
@@ -0,0 +1,125 @@
1
+ import { ToolCallId } from "../primitives/brand.js";
2
+ import { JsonValue } from "../primitives/json.js";
3
+ //#region src/message/content.d.ts
4
+ /** Whether assistant text is interim narration or the terminal answer. */
5
+ type AssistantTextPhase = 'commentary' | 'final-answer';
6
+ /** Plain text visible to the end user. */
7
+ interface TextBlock {
8
+ type: 'text';
9
+ text: string;
10
+ /** Provider-supplied or loop-inferred phase for assistant text. */
11
+ phase?: AssistantTextPhase;
12
+ /** Provider-returned citations and other public annotations. */
13
+ annotations?: readonly TextAnnotation[];
14
+ }
15
+ interface UrlCitationAnnotation {
16
+ type: 'url-citation';
17
+ url: string;
18
+ title?: string;
19
+ startIndex?: number;
20
+ endIndex?: number;
21
+ /** Adapter-private citation payload needed for byte-faithful replay. */
22
+ providerState?: unknown;
23
+ }
24
+ interface TextAnnotationMap {
25
+ 'url-citation': UrlCitationAnnotation;
26
+ }
27
+ type TextAnnotation = TextAnnotationMap[keyof TextAnnotationMap];
28
+ /**
29
+ * Reasoning / thinking content, kept distinct from visible text.
30
+ *
31
+ * `providerState` exists for a concrete reason: Anthropic requires a response's
32
+ * thinking block to be echoed back byte-identically, with its signature, on the
33
+ * next request of a tool-use loop. Dropping it degrades quality and can be
34
+ * rejected outright, so the block carries whatever the adapter needs to
35
+ * reconstruct itself. The value is adapter-private and opaque above that layer.
36
+ */
37
+ interface ReasoningBlock {
38
+ type: 'reasoning';
39
+ text: string;
40
+ /** Adapter-private lossless state needed to replay this block on a later request. */
41
+ providerState?: unknown;
42
+ }
43
+ /** Raster image media types both supported providers accept. */
44
+ type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
45
+ /**
46
+ * Where an image's bytes come from.
47
+ *
48
+ * Inline rather than a handle into a durable attachment store, because an SDK
49
+ * cannot assume its host has one. A consumer that does have durable storage
50
+ * resolves its own reference into one of these before building the request.
51
+ */
52
+ type ImageSource = {
53
+ kind: 'base64';
54
+ mediaType: ImageMediaType;
55
+ data: string;
56
+ } | {
57
+ kind: 'url';
58
+ url: string;
59
+ } | {
60
+ kind: 'file';
61
+ fileId: string;
62
+ };
63
+ type ImageDetail = 'auto' | 'low' | 'high' | 'original';
64
+ /** An image, valid in user content and echoed in assistant content. */
65
+ interface ImageBlock {
66
+ type: 'image';
67
+ source: ImageSource;
68
+ detail?: ImageDetail;
69
+ }
70
+ /** A tool the provider ran internally, such as web search or image generation. */
71
+ interface NativeToolCallBlock {
72
+ type: 'native-tool-call';
73
+ /** Provider item id, used for replay and GUI correlation. */
74
+ id: string;
75
+ /** Neutral tool name (`web-search`, `image-generation`, or an extension). */
76
+ name: string;
77
+ status?: string;
78
+ arguments?: JsonValue;
79
+ /** Public result content, including generated images. */
80
+ content: ContentBlock[];
81
+ /** Adapter-private item needed for stateless replay. */
82
+ providerState?: unknown;
83
+ }
84
+ /** A tool invocation requested by the model. */
85
+ interface ToolCallBlock {
86
+ type: 'tool-call';
87
+ /** Provider-issued call id; correlates with the matching tool result. */
88
+ id: ToolCallId;
89
+ name: string;
90
+ /**
91
+ * Arguments as the RAW JSON string the model produced.
92
+ *
93
+ * Deliberately not parsed here. Models emit invalid JSON often enough that
94
+ * parsing at the transport boundary would turn a recoverable "tell the model it
95
+ * sent bad arguments" into an unrecoverable stream failure. The tool layer
96
+ * parses, and reports any error back into the conversation.
97
+ */
98
+ arguments: string;
99
+ }
100
+ /** The result of a tool invocation, sent back to the model. */
101
+ interface ToolResultBlock {
102
+ type: 'tool-result';
103
+ toolCallId: ToolCallId;
104
+ content: ContentBlock[];
105
+ isError?: boolean;
106
+ }
107
+ /**
108
+ * Merge-extensible content blocks keyed by `type`. Widen by declaration merging
109
+ * this interface; a new CORE block must land with support in every adapter.
110
+ */
111
+ interface ContentBlockMap {
112
+ 'text': TextBlock;
113
+ 'reasoning': ReasoningBlock;
114
+ 'image': ImageBlock;
115
+ 'native-tool-call': NativeToolCallBlock;
116
+ 'tool-call': ToolCallBlock;
117
+ 'tool-result': ToolResultBlock;
118
+ }
119
+ /** The block `type` tag vocabulary; widens with {@link ContentBlockMap}. */
120
+ type ContentBlockType = keyof ContentBlockMap;
121
+ /** Any known content block. Switch on `type` and fall through unknowns. */
122
+ type ContentBlock = ContentBlockMap[ContentBlockType];
123
+ //#endregion
124
+ export { AssistantTextPhase, ContentBlock, ContentBlockMap, ContentBlockType, ImageBlock, ImageDetail, ImageMediaType, ImageSource, NativeToolCallBlock, ReasoningBlock, TextAnnotation, TextAnnotationMap, TextBlock, ToolCallBlock, ToolResultBlock, UrlCitationAnnotation };
125
+ //# sourceMappingURL=content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.d.ts","names":[],"sources":["../../src/message/content.ts"],"mappings":";;;;KAgBY;;UAGK;EACf;EACA;;EAEA,QAAQ;;EAER,uBAAuB;;UAGR;EACf;EACA;EACA;EACA;EACA;;EAEA;;UAGe;EACf,gBAAgB;;KAGN,iBAAiB,wBAAwB;;;;;;;;;;UAWpC;EACf;EACA;;EAEA;;;KAIU;;;;;;;;KASA;EACN;EAAgB,WAAW;EAAgB;;EAC3C;EAAa;;EACb;EAAc;;KAER;;UAGK;EACf;EACA,QAAQ;EACR,SAAS;;;UAIM;EACf;;EAEA;;EAEA;EACA;EACA,YAAY;;EAEZ,SAAS;;EAET;;;UAIe;EACf;;EAEA,IAAI;EACJ;;;;;;;;;EASA;;;UAIe;EACf;EACA,YAAY;EACZ,SAAS;EACT;;;;;;UAOe;EACf,QAAQ;EACR,aAAa;EACb,SAAS;EACT,oBAAoB;EACpB,aAAa;EACb,eAAe;;;KAIL,yBAAyB;;KAGzB,eAAe,gBAAgB"}
@@ -0,0 +1,154 @@
1
+ import { MessageId, ToolCallId } from "../primitives/brand.js";
2
+ import { ContentBlock, ToolResultBlock } from "./content.js";
3
+ //#region src/message/message.d.ts
4
+ /** Provider/model identity and adapter-private replay data for an assistant message. */
5
+ interface AssistantProvenance {
6
+ /** Provider route that produced the message. */
7
+ provider: string;
8
+ /** Model id that produced the message. */
9
+ model: string;
10
+ /**
11
+ * Lossless-JSON adapter state needed to replay the provider response.
12
+ *
13
+ * Exposed to an adapter only when that same adapter instance owns both this
14
+ * historical route and the route being called, because one provider's opaque
15
+ * state is meaningless  Eand possibly rejected  Eat another's endpoint.
16
+ */
17
+ replayState?: unknown;
18
+ }
19
+ /** Source of an assistant message produced by a routed model. */
20
+ interface ModelMessageSource extends AssistantProvenance {
21
+ kind: 'model';
22
+ }
23
+ /** Source of a message carrying one tool result. */
24
+ interface ToolMessageSource {
25
+ kind: 'tool';
26
+ callId: ToolCallId;
27
+ }
28
+ /** Source of a user-role message sent by another long-lived agent session. */
29
+ interface AgentMessageSource {
30
+ readonly kind: 'agent-message';
31
+ readonly teamId: string;
32
+ readonly messageId: string;
33
+ readonly sender: string;
34
+ readonly senderAgentId: string;
35
+ }
36
+ /** Source of a message received from an interoperable A2A protocol peer. */
37
+ interface A2AMessageSource {
38
+ readonly kind: 'a2a-message';
39
+ readonly contextId: string;
40
+ readonly messageId: string;
41
+ readonly taskId?: string;
42
+ }
43
+ /**
44
+ * Merge-extensible record of where a message came from. Widen by declaration
45
+ * merging; switch on `kind` and fall through unknowns.
46
+ */
47
+ interface MessageSourceMap {
48
+ /** Typed or supplied by the end user. */
49
+ user: {
50
+ kind: 'user';
51
+ };
52
+ /** Injected by the application rather than the user (assembled context, notices). */
53
+ app: {
54
+ kind: 'app';
55
+ producer: string;
56
+ };
57
+ /** Produced by a model through a provider route. */
58
+ model: ModelMessageSource;
59
+ /** The result of one tool call. */
60
+ tool: ToolMessageSource;
61
+ /** Attributed context delivered through the in-process A2A control plane. */
62
+ 'agent-message': AgentMessageSource;
63
+ /** Input received through an A2A protocol server transport. */
64
+ 'a2a-message': A2AMessageSource;
65
+ }
66
+ /** Any known message source. */
67
+ type MessageSource = MessageSourceMap[keyof MessageSourceMap];
68
+ /** One immutable message, shared by history, requests, and consumers. */
69
+ interface Message {
70
+ /** Stable identity, preserved across every representation boundary. */
71
+ readonly id: MessageId;
72
+ /** Provider-neutral conversation role. */
73
+ readonly role: 'system' | 'user' | 'assistant';
74
+ /** The exact model-facing blocks. */
75
+ readonly content: readonly ContentBlock[];
76
+ /** Who produced this message. */
77
+ readonly source: MessageSource;
78
+ }
79
+ /** A user-role message. */
80
+ interface UserMessage extends Message {
81
+ readonly role: 'user';
82
+ }
83
+ /** A model-produced assistant message. */
84
+ interface AssistantMessage extends Message {
85
+ readonly role: 'assistant';
86
+ readonly source: ModelMessageSource;
87
+ }
88
+ /** A tool result, carried as a user-role message with a single tool-result block. */
89
+ interface ToolResultMessage extends Message {
90
+ readonly role: 'user';
91
+ readonly content: readonly [ToolResultBlock];
92
+ readonly source: ToolMessageSource;
93
+ }
94
+ type NewMessage = Omit<Message, 'id'>;
95
+ type NewUserMessage = Omit<UserMessage, 'id' | 'role'>;
96
+ type NewAssistantMessage = Omit<AssistantMessage, 'id' | 'role' | 'source'> & {
97
+ readonly source: Omit<ModelMessageSource, 'kind'> & {
98
+ readonly kind?: never;
99
+ };
100
+ };
101
+ /**
102
+ * Detach and deep-freeze a message whose identity already exists.
103
+ *
104
+ * Clones first, so freezing cannot reach back into a caller's live object graph.
105
+ * @param message - a complete message, including its identity.
106
+ * @returns an immutable snapshot preserving that identity.
107
+ */
108
+ declare function freezeMessage<T extends Message>(message: T): T;
109
+ /**
110
+ * Create one identified message and freeze it before publication.
111
+ *
112
+ * The `id?: never` phantom parameter is what stops a caller from supplying an
113
+ * identity: identity is minted here so it cannot be duplicated across messages.
114
+ * @param input - complete role, content, and source.
115
+ * @returns an immutable message with a fresh identity.
116
+ */
117
+ declare function createMessage<T extends NewMessage>(input: T & {
118
+ readonly id?: never;
119
+ }): T & Pick<Message, 'id'>;
120
+ /**
121
+ * Create one identified user-role message.
122
+ * @param input - complete content and source.
123
+ * @returns an immutable user message with a fresh identity.
124
+ */
125
+ declare function createUserMessage<T extends NewUserMessage>(input: T & {
126
+ readonly id?: never;
127
+ readonly role?: never;
128
+ }): T & Pick<UserMessage, 'id' | 'role'>;
129
+ /**
130
+ * Create one identified model-produced assistant message.
131
+ * @param input - content plus the provider, model, and optional replay state.
132
+ * @returns an immutable assistant message with fixed role/source tags.
133
+ */
134
+ declare function createAssistantMessage(input: NewAssistantMessage & {
135
+ readonly id?: never;
136
+ readonly role?: never;
137
+ }): AssistantMessage;
138
+ /** Convenience shape for the common "user typed some text" case. */
139
+ declare function createTextMessage(text: string): UserMessage;
140
+ /** Input whose acceptance creates one tool-result message. */
141
+ interface ToolResultMessageInput {
142
+ readonly callId: ToolCallId;
143
+ readonly content: readonly ContentBlock[];
144
+ readonly isError: boolean;
145
+ }
146
+ /**
147
+ * Create and freeze one identified tool-result message.
148
+ * @param input - call identity, result blocks, and outcome.
149
+ * @returns an immutable user-role tool-result message.
150
+ */
151
+ declare function createToolResultMessage(input: ToolResultMessageInput): ToolResultMessage;
152
+ //#endregion
153
+ export { A2AMessageSource, AgentMessageSource, AssistantMessage, AssistantProvenance, Message, MessageSource, MessageSourceMap, ModelMessageSource, ToolMessageSource, ToolResultMessage, ToolResultMessageInput, UserMessage, createAssistantMessage, createMessage, createTextMessage, createToolResultMessage, createUserMessage, freezeMessage };
154
+ //# sourceMappingURL=message.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message.d.ts","names":[],"sources":["../../src/message/message.ts"],"mappings":";;;;UAsBiB;;EAEf;;EAEA;;;;;;;;EAQA;;;UAIe,2BAA2B;EAC1C;;;UAIe;EACf;EACA,QAAQ;;;UAIO;WACN;WACA;WACA;WACA;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;UAOM;;EAEf;IAAQ;;;EAER;IAAO;IAAa;;;EAEpB,OAAO;;EAEP,MAAM;;EAEN,iBAAiB;;EAEjB,eAAe;;;KAIL,gBAAgB,uBAAuB;;UAGlC;;WAEN,IAAI;;WAEJ;;WAEA,kBAAkB;;WAElB,QAAQ;;;UAIF,oBAAoB;WAC1B;;;UAIM,yBAAyB;WAC/B;WACA,QAAQ;;;UAIF,0BAA0B;WAChC;WACA,mBAAmB;WACnB,QAAQ;;KAGd,aAAa,KAAK;KAClB,iBAAiB,KAAK;KACtB,sBAAsB,KAAK;WACrB,QAAQ,KAAK;aAAyC;;;;;;;;;;iBAejD,cAAc,UAAU,SAAS,SAAS,IAAI;;;;;;;;;iBAY9C,cAAc,UAAU,YACtC,OAAO;WAAe;IACrB,IAAI,KAAK;;;;;;iBASI,kBAAkB,UAAU,gBAC1C,OAAO;WAAe;WAAqB;IAC1C,IAAI,KAAK;;;;;;iBASI,uBACd,OAAO;WAAiC;WAAqB;IAC5D;;iBASa,kBAAkB,eAAe;;UAKhC;WACN,QAAQ;WACR,kBAAkB;WAClB;;;;;;;iBAQK,wBAAwB,OAAO,yBAAyB"}
@@ -0,0 +1,2 @@
1
+ import{MessageId as e}from"../primitives/brand.js";import{deepFreeze as t}from"../primitives/freeze.js";import{systemRandomId as n}from"../platform/adapter.js";function r(){return e(n())}function i(e){return t(structuredClone(e))}function a(e){return i({...e,id:r()})}function o(e){return a({...e,role:`user`})}function s(e){return a({role:`assistant`,content:e.content,source:{kind:`model`,...e.source}})}function c(e){return o({content:[{type:`text`,text:e}],source:{kind:`user`}})}function l(e){return o({source:{kind:`tool`,callId:e.callId},content:[{type:`tool-result`,toolCallId:e.callId,content:[...e.content],isError:e.isError}]})}export{s as createAssistantMessage,a as createMessage,c as createTextMessage,l as createToolResultMessage,o as createUserMessage,i as freezeMessage};
2
+ //# sourceMappingURL=message.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message.js","names":[],"sources":["../../src/message/message.ts"],"sourcesContent":["import { systemRandomId } from '../platform/adapter.ts'\n/**\n * The message value type, its identity, and immutable construction helpers.\n *\n * Two decisions carry most of the weight here:\n *\n * 1. `role` is a neutral three-value enum, and WHO produced a message lives in\n * `source` instead. Providers disagree about roles  Ea tool result is its own\n * role in one API and a user-role block in another  Eso provenance is kept on\n * a separate axis that no provider dictates.\n * 2. Messages are frozen before publication. History is shared by reference\n * across turns, retries, and (for the caller) any UI; a single in-place edit\n * would silently rewrite the past, and cache-prefix reuse with it.\n *\n * @module ai-agent-sdk/core/message/message\n */\n\nimport { deepFreeze } from '../primitives/freeze.ts'\nimport { MessageId, type ToolCallId } from '../primitives/brand.ts'\nimport type { ContentBlock, ToolResultBlock } from './content.ts'\n\n/** Provider/model identity and adapter-private replay data for an assistant message. */\nexport interface AssistantProvenance {\n /** Provider route that produced the message. */\n provider: string\n /** Model id that produced the message. */\n model: string\n /**\n * Lossless-JSON adapter state needed to replay the provider response.\n *\n * Exposed to an adapter only when that same adapter instance owns both this\n * historical route and the route being called, because one provider's opaque\n * state is meaningless  Eand possibly rejected  Eat another's endpoint.\n */\n replayState?: unknown\n}\n\n/** Source of an assistant message produced by a routed model. */\nexport interface ModelMessageSource extends AssistantProvenance {\n kind: 'model'\n}\n\n/** Source of a message carrying one tool result. */\nexport interface ToolMessageSource {\n kind: 'tool'\n callId: ToolCallId\n}\n\n/** Source of a user-role message sent by another long-lived agent session. */\nexport interface AgentMessageSource {\n readonly kind: 'agent-message'\n readonly teamId: string\n readonly messageId: string\n readonly sender: string\n readonly senderAgentId: string\n}\n\n/** Source of a message received from an interoperable A2A protocol peer. */\nexport interface A2AMessageSource {\n readonly kind: 'a2a-message'\n readonly contextId: string\n readonly messageId: string\n readonly taskId?: string\n}\n\n/**\n * Merge-extensible record of where a message came from. Widen by declaration\n * merging; switch on `kind` and fall through unknowns.\n */\nexport interface MessageSourceMap {\n /** Typed or supplied by the end user. */\n user: { kind: 'user' }\n /** Injected by the application rather than the user (assembled context, notices). */\n app: { kind: 'app'; producer: string }\n /** Produced by a model through a provider route. */\n model: ModelMessageSource\n /** The result of one tool call. */\n tool: ToolMessageSource\n /** Attributed context delivered through the in-process A2A control plane. */\n 'agent-message': AgentMessageSource\n /** Input received through an A2A protocol server transport. */\n 'a2a-message': A2AMessageSource\n}\n\n/** Any known message source. */\nexport type MessageSource = MessageSourceMap[keyof MessageSourceMap]\n\n/** One immutable message, shared by history, requests, and consumers. */\nexport interface Message {\n /** Stable identity, preserved across every representation boundary. */\n readonly id: MessageId\n /** Provider-neutral conversation role. */\n readonly role: 'system' | 'user' | 'assistant'\n /** The exact model-facing blocks. */\n readonly content: readonly ContentBlock[]\n /** Who produced this message. */\n readonly source: MessageSource\n}\n\n/** A user-role message. */\nexport interface UserMessage extends Message {\n readonly role: 'user'\n}\n\n/** A model-produced assistant message. */\nexport interface AssistantMessage extends Message {\n readonly role: 'assistant'\n readonly source: ModelMessageSource\n}\n\n/** A tool result, carried as a user-role message with a single tool-result block. */\nexport interface ToolResultMessage extends Message {\n readonly role: 'user'\n readonly content: readonly [ToolResultBlock]\n readonly source: ToolMessageSource\n}\n\ntype NewMessage = Omit<Message, 'id'>\ntype NewUserMessage = Omit<UserMessage, 'id' | 'role'>\ntype NewAssistantMessage = Omit<AssistantMessage, 'id' | 'role' | 'source'> & {\n readonly source: Omit<ModelMessageSource, 'kind'> & { readonly kind?: never }\n}\n\n/** Generate a UUID from the required Web Crypto source. */\nfunction newMessageId(): MessageId {\n return MessageId(systemRandomId())\n}\n\n/**\n * Detach and deep-freeze a message whose identity already exists.\n *\n * Clones first, so freezing cannot reach back into a caller's live object graph.\n * @param message - a complete message, including its identity.\n * @returns an immutable snapshot preserving that identity.\n */\nexport function freezeMessage<T extends Message>(message: T): T {\n return deepFreeze(structuredClone(message))\n}\n\n/**\n * Create one identified message and freeze it before publication.\n *\n * The `id?: never` phantom parameter is what stops a caller from supplying an\n * identity: identity is minted here so it cannot be duplicated across messages.\n * @param input - complete role, content, and source.\n * @returns an immutable message with a fresh identity.\n */\nexport function createMessage<T extends NewMessage>(\n input: T & { readonly id?: never },\n): T & Pick<Message, 'id'> {\n return freezeMessage({ ...input, id: newMessageId() })\n}\n\n/**\n * Create one identified user-role message.\n * @param input - complete content and source.\n * @returns an immutable user message with a fresh identity.\n */\nexport function createUserMessage<T extends NewUserMessage>(\n input: T & { readonly id?: never; readonly role?: never },\n): T & Pick<UserMessage, 'id' | 'role'> {\n return createMessage({ ...input, role: 'user' })\n}\n\n/**\n * Create one identified model-produced assistant message.\n * @param input - content plus the provider, model, and optional replay state.\n * @returns an immutable assistant message with fixed role/source tags.\n */\nexport function createAssistantMessage(\n input: NewAssistantMessage & { readonly id?: never; readonly role?: never },\n): AssistantMessage {\n return createMessage({\n role: 'assistant',\n content: input.content,\n source: { kind: 'model', ...input.source },\n })\n}\n\n/** Convenience shape for the common \"user typed some text\" case. */\nexport function createTextMessage(text: string): UserMessage {\n return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })\n}\n\n/** Input whose acceptance creates one tool-result message. */\nexport interface ToolResultMessageInput {\n readonly callId: ToolCallId\n readonly content: readonly ContentBlock[]\n readonly isError: boolean\n}\n\n/**\n * Create and freeze one identified tool-result message.\n * @param input - call identity, result blocks, and outcome.\n * @returns an immutable user-role tool-result message.\n */\nexport function createToolResultMessage(input: ToolResultMessageInput): ToolResultMessage {\n return createUserMessage({\n source: { kind: 'tool', callId: input.callId },\n content: [{\n type: 'tool-result',\n toolCallId: input.callId,\n content: [...input.content],\n isError: input.isError,\n }] as const,\n })\n}\n"],"mappings":"gKA4HA,SAAS,GAA0B,CACjC,OAAO,EAAU,EAAe,CAAC,CACnC,CASA,SAAgB,EAAiC,EAAe,CAC9D,OAAO,EAAW,gBAAgB,CAAO,CAAC,CAC5C,CAUA,SAAgB,EACd,EACyB,CACzB,OAAO,EAAc,CAAE,GAAG,EAAO,GAAI,EAAa,CAAE,CAAC,CACvD,CAOA,SAAgB,EACd,EACsC,CACtC,OAAO,EAAc,CAAE,GAAG,EAAO,KAAM,MAAO,CAAC,CACjD,CAOA,SAAgB,EACd,EACkB,CAClB,OAAO,EAAc,CACnB,KAAM,YACN,QAAS,EAAM,QACf,OAAQ,CAAE,KAAM,QAAS,GAAG,EAAM,MAAO,CAC3C,CAAC,CACH,CAGA,SAAgB,EAAkB,EAA2B,CAC3D,OAAO,EAAkB,CAAE,QAAS,CAAC,CAAE,KAAM,OAAQ,MAAK,CAAC,EAAG,OAAQ,CAAE,KAAM,MAAO,CAAE,CAAC,CAC1F,CAcA,SAAgB,EAAwB,EAAkD,CACxF,OAAO,EAAkB,CACvB,OAAQ,CAAE,KAAM,OAAQ,OAAQ,EAAM,MAAO,EAC7C,QAAS,CAAC,CACR,KAAM,cACN,WAAY,EAAM,OAClB,QAAS,CAAC,GAAG,EAAM,OAAO,EAC1B,QAAS,EAAM,OACjB,CAAC,CACH,CAAC,CACH"}
@@ -0,0 +1,34 @@
1
+ import { ContentBlock, ImageBlock } from "./content.js";
2
+ import { Message } from "./message.js";
3
+ //#region src/message/projection.d.ts
4
+ /**
5
+ * Whether any block in this content is (or contains) an image.
6
+ *
7
+ * Recurses into tool results, because a tool that returns a screenshot puts the
8
+ * image one level down where a shallow scan would miss it.
9
+ * @param content - the blocks to inspect.
10
+ * @returns true when at least one image block is present at any depth.
11
+ */
12
+ declare function contentHasImage(content: readonly ContentBlock[]): boolean;
13
+ /**
14
+ * The deterministic text that stands in for one omitted image.
15
+ *
16
+ * Deterministic on purpose: a stable string keeps the request prefix
17
+ * byte-identical across turns, which is what lets provider prompt caching keep
18
+ * working on the unchanged part of a long history.
19
+ * @param block - the image being replaced.
20
+ * @returns model-visible replacement text.
21
+ */
22
+ declare function textOnlyImageText(block: ImageBlock): string;
23
+ /**
24
+ * Project every image in a message list into text.
25
+ *
26
+ * Returns the SAME array identity when nothing changed, so callers can use a
27
+ * reference check to skip re-freezing and re-cloning an untouched history.
28
+ * @param messages - the conversation as assembled.
29
+ * @returns an equivalent list whose images have become text.
30
+ */
31
+ declare function projectImagesForTextModel(messages: readonly Message[]): readonly Message[];
32
+ //#endregion
33
+ export { contentHasImage, projectImagesForTextModel, textOnlyImageText };
34
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.d.ts","names":[],"sources":["../../src/message/projection.ts"],"mappings":";;;;;;;;;;;iBAyBgB,gBAAgB,kBAAkB;;;;;;;;;;iBAelC,kBAAkB,OAAO;;;;;;;;;iBA6BzB,0BACd,mBAAmB,qBACT"}
@@ -0,0 +1,2 @@
1
+ import{freezeMessage as e}from"./message.js";function t(e){return e.some(e=>e.type===`image`||(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content))}function n(e){return`[image omitted: the selected model does not accept image input (${e.source.kind===`url`?e.source.url:e.source.kind===`file`?e.source.fileId:e.source.mediaType})]`}function r(e){return e.map(e=>e.type===`image`?{type:`text`,text:n(e)}:(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content)?{...e,content:r(e.content)}:e)}function i(n){let i=!1,a=n.map(n=>t(n.content)?(i=!0,e({...n,content:r(n.content)})):n);return i?a:n}export{t as contentHasImage,i as projectImagesForTextModel,n as textOnlyImageText};
2
+ //# sourceMappingURL=projection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.js","names":[],"sources":["../../src/message/projection.ts"],"sourcesContent":["/**\n * Content inspection and the text-only-model projection.\n *\n * Why the projection exists: conversation history outlives any single model\n * choice. A user attaches an image, the conversation continues, and later the\n * caller switches to a cheaper text-only model  Eor a summarizer runs on the same\n * history. Sending the image would be rejected by the provider, and silently\n * deleting it would leave the model reading a conversation that references\n * something invisible. Replacing it with a deterministic textual stand-in keeps\n * the history coherent and the request valid.\n *\n * @module ai-agent-sdk/core/message/projection\n */\n\nimport type { ContentBlock, ImageBlock } from './content.ts'\nimport { freezeMessage, type Message } from './message.ts'\n\n/**\n * Whether any block in this content is (or contains) an image.\n *\n * Recurses into tool results, because a tool that returns a screenshot puts the\n * image one level down where a shallow scan would miss it.\n * @param content - the blocks to inspect.\n * @returns true when at least one image block is present at any depth.\n */\nexport function contentHasImage(content: readonly ContentBlock[]): boolean {\n return content.some(block => block.type === 'image'\n || ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasImage(block.content)))\n}\n\n/**\n * The deterministic text that stands in for one omitted image.\n *\n * Deterministic on purpose: a stable string keeps the request prefix\n * byte-identical across turns, which is what lets provider prompt caching keep\n * working on the unchanged part of a long history.\n * @param block - the image being replaced.\n * @returns model-visible replacement text.\n */\nexport function textOnlyImageText(block: ImageBlock): string {\n const detail = block.source.kind === 'url'\n ? block.source.url\n : block.source.kind === 'file' ? block.source.fileId : block.source.mediaType\n return `[image omitted: the selected model does not accept image input (${detail})]`\n}\n\n/** Replace image blocks with their textual stand-in, recursing into tool results. */\nfunction projectContent(content: readonly ContentBlock[]): ContentBlock[] {\n return content.map((block) => {\n if (block.type === 'image') {\n return { type: 'text', text: textOnlyImageText(block) } satisfies ContentBlock\n }\n if ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasImage(block.content)) {\n return { ...block, content: projectContent(block.content) } satisfies ContentBlock\n }\n return block\n })\n}\n\n/**\n * Project every image in a message list into text.\n *\n * Returns the SAME array identity when nothing changed, so callers can use a\n * reference check to skip re-freezing and re-cloning an untouched history.\n * @param messages - the conversation as assembled.\n * @returns an equivalent list whose images have become text.\n */\nexport function projectImagesForTextModel(\n messages: readonly Message[],\n): readonly Message[] {\n let changed = false\n const projected = messages.map((message) => {\n if (!contentHasImage(message.content)) return message\n changed = true\n return freezeMessage({ ...message, content: projectContent(message.content) })\n })\n return changed ? projected : messages\n}\n"],"mappings":"6CAyBA,SAAgB,EAAgB,EAA2C,CACzE,OAAO,EAAQ,KAAK,GAAS,EAAM,OAAS,UACrC,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAgB,EAAM,OAAO,CAAE,CACxC,CAWA,SAAgB,EAAkB,EAA2B,CAI3D,MAAO,mEAHQ,EAAM,OAAO,OAAS,MACjC,EAAM,OAAO,IACb,EAAM,OAAO,OAAS,OAAS,EAAM,OAAO,OAAS,EAAM,OAAO,UACW,GACnF,CAGA,SAAS,EAAe,EAAkD,CACxE,OAAO,EAAQ,IAAK,GACd,EAAM,OAAS,QACV,CAAE,KAAM,OAAQ,KAAM,EAAkB,CAAK,CAAE,GAEnD,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAgB,EAAM,OAAO,EACzB,CAAE,GAAG,EAAO,QAAS,EAAe,EAAM,OAAO,CAAE,EAErD,CACR,CACH,CAUA,SAAgB,EACd,EACoB,CACpB,IAAI,EAAU,GACR,EAAY,EAAS,IAAK,GACzB,EAAgB,EAAQ,OAAO,GACpC,EAAU,GACH,EAAc,CAAE,GAAG,EAAS,QAAS,EAAe,EAAQ,OAAO,CAAE,CAAC,GAF/B,CAG/C,EACD,OAAO,EAAU,EAAY,CAC/B"}
@@ -0,0 +1,7 @@
1
+ import { Observability, ObservabilityOptions } from "./types.js";
2
+ //#region src/observability/bus.d.ts
3
+ /** Create one Universal observation bus. Construction validates every durability claim. */
4
+ declare function createObservability(options?: ObservabilityOptions): Observability;
5
+ //#endregion
6
+ export { createObservability };
7
+ //# sourceMappingURL=bus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus.d.ts","names":[],"sources":["../../src/observability/bus.ts"],"mappings":";;;iBA8nBgB,oBAAoB,UAAS,uBAA4B"}
@@ -0,0 +1,2 @@
1
+ import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{createObservationRunScope as t,createOperationId as n}from"../observation/context.js";import{safeErrorRecord as r}from"../observation/event.js";import{createCoreSpan as i,snapshotObservationSpan as a}from"../observation/port.js";import{sanitizeObservationEvent as o,serializedEventBytes as s}from"../observation/privacy.js";import{createBusLogger as c}from"./logger.js";const l={none:0,"local-durable":1,"remote-acknowledged":2},u=new Set([`ABORT_ERR`,`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ETIMEDOUT`,`OBSERVABILITY_EXPORT_FAILED`,`OBSERVABILITY_FLUSH_TIMEOUT`,`OBSERVABILITY_PROCESSOR_FAILED`,`OTEL_PROVIDER_UNCONFIGURED`]),d=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/,f=new Set([`none`,`metadata`,`redacted`,`full`]),p=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function m(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function h(t,n){let i=r(t);return e({type:[`AbortError`,`Error`,`RangeError`,`TypeError`].includes(i.type)?i.type:`Error`,message:n,...i.code!==void 0&&u.has(i.code)?{code:i.code}:{},...i.retryable===void 0?{}:{retryable:i.retryable},...i.status===void 0?{}:{status:i.status}})}function g(e,t,n=`none`,r){return Object.freeze({eventId:e,status:t,durable:t===`accepted`&&n!==`none`,boundary:n,...r===void 0?{}:{reason:r}})}function _(e){try{let t=Reflect.get(e,`eventId`);return typeof t==`string`&&t.length>0?t:n()}catch{return n()}}function v(e){let t=`none`;for(let n of e)n.requirement===`required`&&l[n.boundary]>l[t]&&(t=n.boundary);return t}function y(e,t){let n=new Set;for(let r of t){let t=r.exporter?.id;if(typeof t!=`string`||!d.test(t))throw TypeError(`observation exporter id must be a safe 1-64 character identifier`);if(n.has(t))throw TypeError(`duplicate observation exporter id: ${t}`);if(n.add(t),r.requirement!==`required`&&r.requirement!==`best-effort`)throw TypeError(`observation exporter ${t} has an invalid requirement`);if(!(r.boundary in l))throw TypeError(`observation exporter ${t} has an invalid boundary`);let i=r.exporter.supportedBoundaries??[`none`];if(typeof r.exporter.export!=`function`)throw TypeError(`observation exporter ${t} has no export function`);if(!i.includes(r.boundary))throw TypeError(`observation exporter ${t} does not support ${r.boundary}`);if(e===`operational`&&r.requirement===`required`)throw TypeError(`operational observation exporters must be best-effort`)}if(e!==`operational`&&!t.some(e=>e.requirement===`required`&&e.boundary!==`none`))throw TypeError(`${e} observability requires a durable required exporter`);return Object.freeze(t.map(e=>Object.freeze({...e})))}function b(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(`observation deadline exceeded`,`TimeoutError`)),e),i=()=>n.abort(t?.reason??new DOMException(`observation aborted`,`AbortError`));return t?.aborted===!0?i():t?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,clear(){clearTimeout(r),t?.removeEventListener(`abort`,i)}}}function x(e,t){return t.aborted?Promise.reject(t.reason??Error(`observation aborted`)):new Promise((n,r)=>{let i=()=>{a(),r(t.reason??Error(`observation aborted`))},a=()=>t.removeEventListener(`abort`,i);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})})}function S(e){try{let t=e.reason;return typeof t==`object`&&!!t&&Reflect.get(t,`name`)===`TimeoutError`}catch{return!1}}function C(e){return Object.freeze({complete:e.complete,exportedEvents:e.exportedEvents,pendingEvents:e.pendingEvents,rejectedCritical:e.rejectedCritical,timedOut:e.timedOut})}function w(e,t){return e.eventId===t.eventId&&e.sequence===t.sequence&&e.name===t.name&&e.phase===t.phase&&e.occurredAt===t.occurredAt&&e.monotonicMs===t.monotonicMs&&e.priority===t.priority&&JSON.stringify(e.resource)===JSON.stringify(t.resource)&&JSON.stringify(e.correlation)===JSON.stringify(t.correlation)}var T=class{mode;resource;registrations;processors;options;queue=[];queueBytes=0;closing=!1;closed=!1;shutdownPromise;flushChain=Promise.resolve();protectedFailures=new Set;healthScope=t();healthRunId=n();healthCorrelation=i({name:`sdk.integration.request`,runId:this.healthRunId,startedAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs()}).correlation;counters={accepted:0,exported:0,droppedVerbose:0,droppedNormal:0,criticalRejected:0,processorFailures:0,exporterFailures:0,flushTimeouts:0,requiredFailure:!1};constructor(t){if(this.mode=t.mode??`operational`,![`operational`,`reliable`,`audit`].includes(this.mode))throw TypeError(`invalid observation mode`);this.resource=e({sdkName:`ai-agent-sdk`,sdkVersion:t.resource?.sdkVersion??`0.1.0`,...t.resource?.serviceName===void 0?{}:{serviceName:t.resource.serviceName},...t.resource?.serviceVersion===void 0?{}:{serviceVersion:t.resource.serviceVersion},runtime:t.resource?.runtime??`unknown`}),this.registrations=y(this.mode,t.exporters??[]);let n=new Set;for(let e of t.processors??[]){if(typeof e.id!=`string`||!d.test(e.id))throw TypeError(`processor id must be a safe 1-64 character identifier`);if(n.has(e.id))throw TypeError(`duplicate observation processor id: ${e.id}`);if(typeof e.transform!=`function`)throw TypeError(`observation processor ${e.id} is invalid`);n.add(e.id)}if(this.processors=Object.freeze([...t.processors??[]]),!f.has(t.content??`none`))throw TypeError(`invalid observation content policy`);if(!p.has(t.minimumLogLevel??`info`))throw TypeError(`invalid minimum log level`);let r=new Set;for(let e of t.redactors??[]){if(typeof e.id!=`string`||!d.test(e.id)||typeof e.redact!=`function`)throw TypeError(`invalid observation content redactor`);if(r.has(e.id))throw TypeError(`duplicate observation redactor id: ${e.id}`);r.add(e.id)}this.options={content:t.content??`none`,includeErrorStacks:t.includeErrorStacks??!1,minimumLogLevel:t.minimumLogLevel??`info`,maxQueueEvents:m(t.maxQueueEvents??1e4,`maxQueueEvents`),maxQueueBytes:m(t.maxQueueBytes??16777216,`maxQueueBytes`),maxBatchEvents:m(t.maxBatchEvents??256,`maxBatchEvents`),maxBatchBytes:m(t.maxBatchBytes??524288,`maxBatchBytes`),flushTimeoutMs:m(t.flushTimeoutMs??1e4,`flushTimeoutMs`),shutdownTimeoutMs:m(t.shutdownTimeoutMs??3e4,`shutdownTimeoutMs`),redactors:Object.freeze([...t.redactors??[]]),...t.onHealthChange===void 0?{}:{onHealthChange:t.onHealthChange},...t.openSpan===void 0?{}:{openSpan:t.openSpan}}}openSpan(e){let t=this.options.openSpan;if(t===void 0)return i(e);try{let n=a(t(e));if(n!==void 0)return n;this.counters.processorFailures++,this.recordFailure(`span:invalid`,TypeError(`invalid span`),`observation span backend returned an invalid span`,!1)}catch(e){this.counters.processorFailures++,this.recordFailure(`span:throw`,e,`observation span backend failed`,!1)}return i(e)}capture(e){let t=_(e);if(this.closing||this.closed)return g(t,`rejected`,`none`,`closed`);let n;try{n=this.prepareEvent(e,!1)}catch(e){return this.counters.processorFailures++,this.counters.lastFailure=h(e,`observation processor failed`),this.notifyHealth(),this.recordFailure(`processor:capture`,e,`observation processor failed`,!0),g(t,`rejected`,`none`,`processor-failed`)}let r=this.enqueue(n,!1);return r.status===`accepted`?this.stageExporters(n,r):r}async checkpoint(e,t){let n=this.capture(e);if(n.status!==`accepted`||this.mode===`operational`)return n;let r=this.queue.find(e=>e.event.eventId===n.eventId)?.event;if(r===void 0)return g(n.eventId,`rejected`,`none`,`exporter-unavailable`);let i=new Set(this.queue.filter(e=>e.event.priority===`critical`&&e.event.correlation.runId===r.correlation.runId&&e.event.sequence<=r.sequence).map(e=>e.event.eventId));return(await this.scheduleFlush(i,this.options.flushTimeoutMs,t)).requiredComplete?g(n.eventId,`accepted`,v(this.registrations)):g(n.eventId,`rejected`,`none`,`exporter-unavailable`)}logger(e){return c({minimumLevel:this.options.minimumLogLevel,resource:this.resource,emit:e=>{this.capture(e)}},e)}health(){let t=this.closed?`closed`:this.counters.requiredFailure||this.counters.criticalRejected>0||this.counters.flushTimeouts>0?`failed`:this.counters.processorFailures>0||this.counters.exporterFailures>0||this.counters.droppedVerbose>0||this.counters.droppedNormal>0?`degraded`:`healthy`;return e({state:t,queuedEvents:this.queue.length,queuedBytes:this.queueBytes,accepted:this.counters.accepted,exported:this.counters.exported,droppedVerbose:this.counters.droppedVerbose,droppedNormal:this.counters.droppedNormal,criticalRejected:this.counters.criticalRejected,processorFailures:this.counters.processorFailures,exporterFailures:this.counters.exporterFailures,flushTimeouts:this.counters.flushTimeouts,...this.counters.lastExportAt===void 0?{}:{lastExportAt:this.counters.lastExportAt},...this.counters.lastFailure===void 0?{}:{lastFailure:this.counters.lastFailure}})}flush(e){if(this.closed||this.closing)throw TypeError(`observability is closed`);return this.scheduleFlush(new Set(this.queue.map(e=>e.event.eventId)),this.options.flushTimeoutMs,e).then(C)}shutdown(e){if(this.shutdownPromise!==void 0)return this.shutdownPromise;this.closing=!0;let t=new Set(this.queue.map(e=>e.event.eventId));return this.shutdownPromise=(async()=>{let n=b(this.options.shutdownTimeoutMs,e),r;try{r=C(await this.scheduleFlush(t,this.options.shutdownTimeoutMs,n.signal));for(let e of[...this.registrations].reverse()){let t=e.exporter.shutdown;if(t!==void 0)try{await x(Promise.resolve(t.call(e.exporter,n.signal)),n.signal)}catch(t){this.recordExporterFailure(e,t,!1),r=Object.freeze({...r,complete:!1})}}}finally{n.clear(),this.closed=!0,this.notifyHealth()}return r})(),this.shutdownPromise}prepareEvent(e,t){let n={content:this.options.content,redactors:this.options.redactors??[],includeErrorStacks:this.options.includeErrorStacks},r=o(e,n);if(t)return r;for(let e of this.processors){let t=e.transform(r);if(t===void 0)throw TypeError(`observation processor ${e.id} returned undefined`);let i=o(t,n);if(!w(r,i))throw TypeError(`observation processor ${e.id} changed the immutable event envelope`);r=i}return r}enqueue(e,t){let n=s(e);return n>this.options.maxBatchBytes||n>this.options.maxQueueBytes||!this.makeCapacity(n,t)?(!t&&e.priority===`critical`&&this.counters.criticalRejected++,t||(this.counters.lastFailure=h(RangeError(`capacity`),`observation queue capacity exhausted`),this.notifyHealth()),g(e.eventId,`rejected`,`none`,`capacity`)):(this.queue.push({event:e,bytes:n,protected:t,pending:new Set(this.registrations.map(e=>e.exporter.id))}),this.queueBytes+=n,this.counters.accepted++,this.notifyHealth(),g(e.eventId,`accepted`))}stageExporters(e,t){let n=this.queue.find(t=>t.event.eventId===e.eventId);if(n===void 0)return g(e.eventId,`rejected`,`none`,`exporter-unavailable`);let r=!1;for(let t of this.registrations){let i=t.exporter.stage;if(i!==void 0)try{let n=i.call(t.exporter,e);n!==void 0&&Promise.resolve(n).catch(()=>void 0)}catch(i){if(this.recordExporterFailure(t,i,!1),n.pending.delete(t.exporter.id),r=!0,t.requirement===`required`)return this.removeEntry(n,!1),e.priority===`critical`&&this.counters.criticalRejected++,this.notifyHealth(),g(e.eventId,`rejected`,`none`,`exporter-unavailable`)}}return r&&n.pending.size===0&&this.removeEntry(n,!1),t}makeCapacity(e,t){for(;this.queue.length+1>this.options.maxQueueEvents||this.queueBytes+e>this.options.maxQueueBytes;){let e=this.queue.findIndex(e=>e.event.priority===`verbose`);if(e===-1&&(e=this.queue.findIndex(e=>e.event.priority===`normal`)),e===-1)return!1;let[n]=this.queue.splice(e,1);if(n===void 0)return!1;this.queueBytes-=n.bytes,t||(n.event.priority===`verbose`?this.counters.droppedVerbose++:this.counters.droppedNormal++)}return!0}scheduleFlush(e,t,n){let r,i,a=new Promise((e,t)=>{r=e,i=t}),o=async()=>{try{r(await this.flushInternal(e,t,n))}catch(e){i(e)}};return this.flushChain=this.flushChain.then(o,o),a}async flushInternal(t,r,i){let a=this.counters.exported,o=b(r,i),s=!1,c=!1;try{if(this.registrations.length===0)for(let e of[...this.queue])t.has(e.event.eventId)&&this.removeEntry(e,!1);for(let r of this.registrations)for(;;){let i=this.queue.filter(e=>t.has(e.event.eventId)&&e.pending.has(r.exporter.id));if(i.length===0)break;let a=[],l=0;for(let e of i){if(a.length>=this.options.maxBatchEvents||l+e.bytes>this.options.maxBatchBytes)break;a.push(e),l+=e.bytes}if(a.length===0)break;let u=e({schemaVersion:1,batchId:n(),createdAt:new Date().toISOString(),events:a.map(e=>e.event)}),d;try{if(d=await x(Promise.resolve(r.exporter.export(u,o.signal)),o.signal),d.batchId!==u.batchId||d.accepted!==!0)throw TypeError(`observation exporter ${r.exporter.id} returned an invalid acknowledgment`)}catch(e){if(s=!0,c||=S(o.signal),this.recordExporterFailure(r,e,!0),r.requirement===`best-effort`)for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!1);break}this.counters.lastExportAt=new Date().toISOString();for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!0);this.notifyHealth()}}finally{S(o.signal)&&(c=!0,this.counters.flushTimeouts++,this.counters.lastFailure=h(o.signal.reason,`observation flush timed out`),this.notifyHealth()),o.clear()}let l=this.queue.filter(e=>t.has(e.event.eventId)),u=this.registrations.filter(e=>e.requirement===`required`).map(e=>e.exporter.id),d=l.every(e=>u.every(t=>!e.pending.has(t)));return Object.freeze({complete:!s&&!c&&l.length===0,requiredComplete:d,exportedEvents:this.counters.exported-a,pendingEvents:l.length,rejectedCritical:this.counters.criticalRejected,timedOut:c})}removeEntry(e,t){let n=this.queue.indexOf(e);n!==-1&&(this.queue.splice(n,1),this.queueBytes-=e.bytes,t&&this.counters.exported++)}recordExporterFailure(e,t,n){this.counters.exporterFailures++,e.requirement===`required`&&(this.counters.requiredFailure=!0),this.counters.lastFailure=h(t,`observation exporter failed`),this.notifyHealth(),n&&this.recordFailure(`exporter:${e.exporter.id}`,t,`observation exporter failed`,!0)}recordFailure(e,t,r,i){if(this.counters.lastFailure=h(t,r),this.notifyHealth(),!(!i||this.protectedFailures.has(e)||this.closing||this.closed)){this.protectedFailures.add(e);try{let t=this.prepareEvent({schemaVersion:1,eventId:n(),sequence:this.healthScope.nextSequence(),name:`sdk.observer.failure`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs(),priority:`critical`,resource:this.resource,correlation:this.healthCorrelation,data:{observerId:e,failureKind:`contained`,count:1,error:{...this.counters.lastFailure}}},!0);this.enqueue(t,!0)}catch{}}}notifyHealth(){let e=this.options.onHealthChange;if(e!==void 0)try{e(this.health())}catch{}}};function E(e={}){return new T(e)}export{E as createObservability};
2
+ //# sourceMappingURL=bus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus.js","names":[],"sources":["../../src/observability/bus.ts"],"sourcesContent":["import {\n SDK_VERSION,\n deepFreeze,\n} from '../primitives/index.ts'\nimport {\n createCoreSpan,\n createObservationRunScope,\n createOperationId,\n safeErrorRecord,\n snapshotObservationSpan,\n type CaptureReceipt,\n type ObservationBoundary,\n type ObservationEvent,\n type ObservationResource,\n type ObservationSpan,\n type OpenObservationSpanInput,\n type SafeErrorRecord,\n} from '../observation/index.ts'\nimport { createBusLogger } from './logger.ts'\nimport { sanitizeObservationEvent, serializedEventBytes } from './privacy.ts'\nimport type {\n ExportAck,\n FlushResult,\n LoggerContext,\n LogLevel,\n ObservationBatch,\n ObservationExporterRegistration,\n ObservationHealthSnapshot,\n ObservationProcessor,\n Observability,\n ObservabilityOptions,\n SdkLogger,\n} from './types.ts'\n\nconst DEFAULT_MAX_QUEUE_EVENTS = 10_000\nconst DEFAULT_MAX_QUEUE_BYTES = 16 * 1024 * 1024\nconst DEFAULT_MAX_BATCH_EVENTS = 256\nconst DEFAULT_MAX_BATCH_BYTES = 512 * 1024\nconst DEFAULT_FLUSH_TIMEOUT_MS = 10_000\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000\n\ninterface QueueEntry {\n readonly event: ObservationEvent\n readonly bytes: number\n readonly pending: Set<string>\n readonly protected: boolean\n}\n\ninterface MutableHealth {\n accepted: number\n exported: number\n droppedVerbose: number\n droppedNormal: number\n criticalRejected: number\n processorFailures: number\n exporterFailures: number\n flushTimeouts: number\n lastExportAt?: string\n lastFailure?: SafeErrorRecord\n requiredFailure: boolean\n}\n\ninterface FlushOutcome extends FlushResult {\n readonly requiredComplete: boolean\n}\n\nconst BOUNDARY_RANK: Readonly<Record<ObservationBoundary, number>> = {\n none: 0, 'local-durable': 1, 'remote-acknowledged': 2,\n}\nconst SAFE_FAILURE_CODES = new Set([\n 'ABORT_ERR', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH',\n 'ETIMEDOUT', 'OBSERVABILITY_EXPORT_FAILED', 'OBSERVABILITY_FLUSH_TIMEOUT',\n 'OBSERVABILITY_PROCESSOR_FAILED', 'OTEL_PROVIDER_UNCONFIGURED',\n])\nconst COMPONENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/\nconst CONTENT_POLICIES = new Set(['none', 'metadata', 'redacted', 'full'])\nconst LOG_LEVELS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])\n\nfunction positiveSafeInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`)\n return value\n}\n\nfunction safeFailure(error: unknown, message: string): SafeErrorRecord {\n const source = safeErrorRecord(error)\n return deepFreeze({\n type: ['AbortError', 'Error', 'RangeError', 'TypeError'].includes(source.type) ? source.type : 'Error',\n message,\n ...source.code !== undefined && SAFE_FAILURE_CODES.has(source.code) ? { code: source.code } : {},\n ...source.retryable === undefined ? {} : { retryable: source.retryable },\n ...source.status === undefined ? {} : { status: source.status },\n })\n}\n\nfunction receipt(\n eventId: string,\n status: CaptureReceipt['status'],\n boundary: ObservationBoundary = 'none',\n reason?: CaptureReceipt['reason'],\n): CaptureReceipt {\n return Object.freeze({\n eventId, status, durable: status === 'accepted' && boundary !== 'none', boundary,\n ...reason === undefined ? {} : { reason },\n })\n}\n\nfunction eventIdOf(event: unknown): string {\n try {\n const value = Reflect.get(event as object, 'eventId')\n return typeof value === 'string' && value.length > 0 ? value : createOperationId()\n } catch { return createOperationId() }\n}\n\nfunction requiredBoundary(registrations: readonly ObservationExporterRegistration[]): ObservationBoundary {\n let result: ObservationBoundary = 'none'\n for (const registration of registrations) {\n if (registration.requirement === 'required'\n && BOUNDARY_RANK[registration.boundary] > BOUNDARY_RANK[result]) result = registration.boundary\n }\n return result\n}\n\nfunction validateRegistrations(\n mode: Observability['mode'],\n registrations: readonly ObservationExporterRegistration[],\n): readonly ObservationExporterRegistration[] {\n const ids = new Set<string>()\n for (const registration of registrations) {\n const id = registration.exporter?.id\n if (typeof id !== 'string' || !COMPONENT_ID_PATTERN.test(id)) {\n throw new TypeError('observation exporter id must be a safe 1-64 character identifier')\n }\n if (ids.has(id)) throw new TypeError(`duplicate observation exporter id: ${id}`)\n ids.add(id)\n if (registration.requirement !== 'required' && registration.requirement !== 'best-effort') {\n throw new TypeError(`observation exporter ${id} has an invalid requirement`)\n }\n if (!(registration.boundary in BOUNDARY_RANK)) throw new TypeError(`observation exporter ${id} has an invalid boundary`)\n const supported = registration.exporter.supportedBoundaries ?? ['none']\n if (typeof registration.exporter.export !== 'function') {\n throw new TypeError(`observation exporter ${id} has no export function`)\n }\n if (!supported.includes(registration.boundary)) {\n throw new TypeError(`observation exporter ${id} does not support ${registration.boundary}`)\n }\n if (mode === 'operational' && registration.requirement === 'required') {\n throw new TypeError('operational observation exporters must be best-effort')\n }\n }\n if (mode !== 'operational' && !registrations.some(registration => (\n registration.requirement === 'required' && registration.boundary !== 'none'\n ))) throw new TypeError(`${mode} observability requires a durable required exporter`)\n return Object.freeze(registrations.map(registration => Object.freeze({ ...registration })))\n}\n\nfunction deadlineSignal(timeoutMs: number, external?: AbortSignal): { signal: AbortSignal; clear(): void } {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(new DOMException('observation deadline exceeded', 'TimeoutError')), timeoutMs)\n const abort = () => controller.abort(external?.reason ?? new DOMException('observation aborted', 'AbortError'))\n if (external?.aborted === true) abort()\n else external?.addEventListener('abort', abort, { once: true })\n return {\n signal: controller.signal,\n clear() { clearTimeout(timeout); external?.removeEventListener('abort', abort) },\n }\n}\n\nfunction raceAbort<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason ?? new Error('observation aborted'))\n return new Promise<T>((resolve, reject) => {\n const abort = () => { cleanup(); reject(signal.reason ?? new Error('observation aborted')) }\n const cleanup = () => signal.removeEventListener('abort', abort)\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { cleanup(); resolve(value) },\n error => { cleanup(); reject(error) },\n )\n })\n}\n\nfunction isTimeoutAbort(signal: AbortSignal): boolean {\n try {\n const reason = signal.reason\n return typeof reason === 'object' && reason !== null\n && Reflect.get(reason, 'name') === 'TimeoutError'\n } catch { return false }\n}\n\nfunction publicFlushResult(outcome: FlushOutcome): FlushResult {\n return Object.freeze({\n complete: outcome.complete,\n exportedEvents: outcome.exportedEvents,\n pendingEvents: outcome.pendingEvents,\n rejectedCritical: outcome.rejectedCritical,\n timedOut: outcome.timedOut,\n })\n}\n\nfunction sameEnvelope(left: ObservationEvent, right: ObservationEvent): boolean {\n return left.eventId === right.eventId && left.sequence === right.sequence\n && left.name === right.name && left.phase === right.phase\n && left.occurredAt === right.occurredAt && left.monotonicMs === right.monotonicMs\n && left.priority === right.priority\n && JSON.stringify(left.resource) === JSON.stringify(right.resource)\n && JSON.stringify(left.correlation) === JSON.stringify(right.correlation)\n}\n\nclass ObservationBus implements Observability {\n readonly mode: Observability['mode']\n readonly resource: ObservationResource\n private readonly registrations: readonly ObservationExporterRegistration[]\n private readonly processors: readonly ObservationProcessor[]\n private readonly options: Required<Pick<ObservabilityOptions,\n 'content' | 'includeErrorStacks' | 'minimumLogLevel' | 'maxQueueEvents' | 'maxQueueBytes'\n | 'maxBatchEvents' | 'maxBatchBytes' | 'flushTimeoutMs' | 'shutdownTimeoutMs'>>\n & Pick<ObservabilityOptions, 'redactors' | 'onHealthChange' | 'openSpan'>\n private readonly queue: QueueEntry[] = []\n private queueBytes = 0\n private closing = false\n private closed = false\n private shutdownPromise: Promise<FlushResult> | undefined\n private flushChain: Promise<void> = Promise.resolve()\n private readonly protectedFailures = new Set<string>()\n private readonly healthScope = createObservationRunScope()\n private readonly healthRunId = createOperationId()\n private readonly healthCorrelation = createCoreSpan({\n name: 'sdk.integration.request', runId: this.healthRunId,\n startedAt: new Date().toISOString(), monotonicMs: this.healthScope.monotonicMs(),\n }).correlation\n private readonly counters: MutableHealth = {\n accepted: 0, exported: 0, droppedVerbose: 0, droppedNormal: 0,\n criticalRejected: 0, processorFailures: 0, exporterFailures: 0,\n flushTimeouts: 0, requiredFailure: false,\n }\n\n constructor(input: ObservabilityOptions) {\n this.mode = input.mode ?? 'operational'\n if (!['operational', 'reliable', 'audit'].includes(this.mode)) throw new TypeError('invalid observation mode')\n this.resource = deepFreeze({\n sdkName: 'ai-agent-sdk',\n sdkVersion: input.resource?.sdkVersion ?? SDK_VERSION,\n ...input.resource?.serviceName === undefined ? {} : { serviceName: input.resource.serviceName },\n ...input.resource?.serviceVersion === undefined ? {} : { serviceVersion: input.resource.serviceVersion },\n runtime: input.resource?.runtime ?? 'unknown',\n })\n this.registrations = validateRegistrations(this.mode, input.exporters ?? [])\n const processorIds = new Set<string>()\n for (const processor of input.processors ?? []) {\n if (typeof processor.id !== 'string' || !COMPONENT_ID_PATTERN.test(processor.id)) {\n throw new TypeError('processor id must be a safe 1-64 character identifier')\n }\n if (processorIds.has(processor.id)) throw new TypeError(`duplicate observation processor id: ${processor.id}`)\n if (typeof processor.transform !== 'function') throw new TypeError(`observation processor ${processor.id} is invalid`)\n processorIds.add(processor.id)\n }\n this.processors = Object.freeze([...(input.processors ?? [])])\n if (!CONTENT_POLICIES.has(input.content ?? 'none')) throw new TypeError('invalid observation content policy')\n if (!LOG_LEVELS.has(input.minimumLogLevel ?? 'info')) throw new TypeError('invalid minimum log level')\n const redactorIds = new Set<string>()\n for (const redactor of input.redactors ?? []) {\n if (typeof redactor.id !== 'string' || !COMPONENT_ID_PATTERN.test(redactor.id)\n || typeof redactor.redact !== 'function') throw new TypeError('invalid observation content redactor')\n if (redactorIds.has(redactor.id)) throw new TypeError(`duplicate observation redactor id: ${redactor.id}`)\n redactorIds.add(redactor.id)\n }\n this.options = {\n content: input.content ?? 'none',\n includeErrorStacks: input.includeErrorStacks ?? false,\n minimumLogLevel: input.minimumLogLevel ?? 'info',\n maxQueueEvents: positiveSafeInteger(input.maxQueueEvents ?? DEFAULT_MAX_QUEUE_EVENTS, 'maxQueueEvents'),\n maxQueueBytes: positiveSafeInteger(input.maxQueueBytes ?? DEFAULT_MAX_QUEUE_BYTES, 'maxQueueBytes'),\n maxBatchEvents: positiveSafeInteger(input.maxBatchEvents ?? DEFAULT_MAX_BATCH_EVENTS, 'maxBatchEvents'),\n maxBatchBytes: positiveSafeInteger(input.maxBatchBytes ?? DEFAULT_MAX_BATCH_BYTES, 'maxBatchBytes'),\n flushTimeoutMs: positiveSafeInteger(input.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS, 'flushTimeoutMs'),\n shutdownTimeoutMs: positiveSafeInteger(input.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS, 'shutdownTimeoutMs'),\n redactors: Object.freeze([...(input.redactors ?? [])]),\n ...input.onHealthChange === undefined ? {} : { onHealthChange: input.onHealthChange },\n ...input.openSpan === undefined ? {} : { openSpan: input.openSpan },\n }\n }\n\n openSpan(input: OpenObservationSpanInput): ObservationSpan {\n const backend = this.options.openSpan\n if (backend === undefined) return createCoreSpan(input)\n try {\n const span = snapshotObservationSpan(backend(input))\n if (span !== undefined) return span\n this.counters.processorFailures++\n this.recordFailure('span:invalid', new TypeError('invalid span'), 'observation span backend returned an invalid span', false)\n } catch (error) {\n this.counters.processorFailures++\n this.recordFailure('span:throw', error, 'observation span backend failed', false)\n }\n return createCoreSpan(input)\n }\n\n capture(event: ObservationEvent): CaptureReceipt {\n const eventId = eventIdOf(event)\n if (this.closing || this.closed) return receipt(eventId, 'rejected', 'none', 'closed')\n let processed: ObservationEvent\n try {\n processed = this.prepareEvent(event, false)\n } catch (error) {\n this.counters.processorFailures++\n this.counters.lastFailure = safeFailure(error, 'observation processor failed')\n this.notifyHealth()\n this.recordFailure('processor:capture', error, 'observation processor failed', true)\n return receipt(eventId, 'rejected', 'none', 'processor-failed')\n }\n const captured = this.enqueue(processed, false)\n if (captured.status !== 'accepted') return captured\n return this.stageExporters(processed, captured)\n }\n\n async checkpoint(event: ObservationEvent, signal?: AbortSignal): Promise<CaptureReceipt> {\n const captured = this.capture(event)\n if (captured.status !== 'accepted') return captured\n if (this.mode === 'operational') return captured\n const terminal = this.queue.find(entry => entry.event.eventId === captured.eventId)?.event\n if (terminal === undefined) return receipt(captured.eventId, 'rejected', 'none', 'exporter-unavailable')\n const targetIds = new Set(this.queue\n .filter(entry => entry.event.priority === 'critical'\n && entry.event.correlation.runId === terminal.correlation.runId\n && entry.event.sequence <= terminal.sequence)\n .map(entry => entry.event.eventId))\n const outcome = await this.scheduleFlush(targetIds, this.options.flushTimeoutMs, signal)\n if (!outcome.requiredComplete) return receipt(captured.eventId, 'rejected', 'none', 'exporter-unavailable')\n return receipt(captured.eventId, 'accepted', requiredBoundary(this.registrations))\n }\n\n logger(context?: LoggerContext): SdkLogger {\n return createBusLogger({\n minimumLevel: this.options.minimumLogLevel as LogLevel,\n resource: this.resource,\n emit: event => { this.capture(event) },\n }, context)\n }\n\n health(): ObservationHealthSnapshot {\n const state: ObservationHealthSnapshot['state'] = this.closed\n ? 'closed'\n : this.counters.requiredFailure || this.counters.criticalRejected > 0 || this.counters.flushTimeouts > 0\n ? 'failed'\n : this.counters.processorFailures > 0 || this.counters.exporterFailures > 0\n || this.counters.droppedVerbose > 0 || this.counters.droppedNormal > 0\n ? 'degraded'\n : 'healthy'\n return deepFreeze({\n state,\n queuedEvents: this.queue.length,\n queuedBytes: this.queueBytes,\n accepted: this.counters.accepted,\n exported: this.counters.exported,\n droppedVerbose: this.counters.droppedVerbose,\n droppedNormal: this.counters.droppedNormal,\n criticalRejected: this.counters.criticalRejected,\n processorFailures: this.counters.processorFailures,\n exporterFailures: this.counters.exporterFailures,\n flushTimeouts: this.counters.flushTimeouts,\n ...this.counters.lastExportAt === undefined ? {} : { lastExportAt: this.counters.lastExportAt },\n ...this.counters.lastFailure === undefined ? {} : { lastFailure: this.counters.lastFailure },\n })\n }\n\n flush(signal?: AbortSignal): Promise<FlushResult> {\n if (this.closed || this.closing) throw new TypeError('observability is closed')\n return this.scheduleFlush(\n new Set(this.queue.map(entry => entry.event.eventId)), this.options.flushTimeoutMs, signal,\n ).then(publicFlushResult)\n }\n\n shutdown(signal?: AbortSignal): Promise<FlushResult> {\n if (this.shutdownPromise !== undefined) return this.shutdownPromise\n this.closing = true\n const targetIds = new Set(this.queue.map(entry => entry.event.eventId))\n this.shutdownPromise = (async () => {\n const deadline = deadlineSignal(this.options.shutdownTimeoutMs, signal)\n let result: FlushResult\n try {\n result = publicFlushResult(await this.scheduleFlush(\n targetIds, this.options.shutdownTimeoutMs, deadline.signal,\n ))\n for (const registration of [...this.registrations].reverse()) {\n const shutdown = registration.exporter.shutdown\n if (shutdown === undefined) continue\n try { await raceAbort(Promise.resolve(shutdown.call(registration.exporter, deadline.signal)), deadline.signal) }\n catch (error) {\n this.recordExporterFailure(registration, error, false)\n result = Object.freeze({ ...result, complete: false })\n }\n }\n } finally {\n deadline.clear()\n this.closed = true\n this.notifyHealth()\n }\n return result\n })()\n return this.shutdownPromise\n }\n\n private prepareEvent(event: ObservationEvent, protectedPath: boolean): ObservationEvent {\n const privacy = {\n content: this.options.content,\n redactors: this.options.redactors ?? [],\n includeErrorStacks: this.options.includeErrorStacks,\n }\n let current = sanitizeObservationEvent(event, privacy)\n if (protectedPath) return current\n for (const processor of this.processors) {\n const next = processor.transform(current)\n if (next === undefined) throw new TypeError(`observation processor ${processor.id} returned undefined`)\n const sanitized = sanitizeObservationEvent(next, privacy)\n if (!sameEnvelope(current, sanitized)) {\n throw new TypeError(`observation processor ${processor.id} changed the immutable event envelope`)\n }\n current = sanitized\n }\n return current\n }\n\n private enqueue(event: ObservationEvent, protectedPath: boolean): CaptureReceipt {\n const bytes = serializedEventBytes(event)\n if (bytes > this.options.maxBatchBytes || bytes > this.options.maxQueueBytes\n || !this.makeCapacity(bytes, protectedPath)) {\n if (!protectedPath && event.priority === 'critical') this.counters.criticalRejected++\n if (!protectedPath) {\n this.counters.lastFailure = safeFailure(new RangeError('capacity'), 'observation queue capacity exhausted')\n this.notifyHealth()\n }\n return receipt(event.eventId, 'rejected', 'none', 'capacity')\n }\n this.queue.push({\n event, bytes, protected: protectedPath,\n pending: new Set(this.registrations.map(registration => registration.exporter.id)),\n })\n this.queueBytes += bytes\n this.counters.accepted++\n this.notifyHealth()\n return receipt(event.eventId, 'accepted')\n }\n\n private stageExporters(event: ObservationEvent, captured: CaptureReceipt): CaptureReceipt {\n const entry = this.queue.find(candidate => candidate.event.eventId === event.eventId)\n if (entry === undefined) return receipt(event.eventId, 'rejected', 'none', 'exporter-unavailable')\n let removedPending = false\n for (const registration of this.registrations) {\n const stage = registration.exporter.stage\n if (stage === undefined) continue\n try {\n const pending = stage.call(registration.exporter, event)\n if (pending !== undefined) void Promise.resolve(pending).catch(() => undefined)\n } catch (error) {\n this.recordExporterFailure(registration, error, false)\n entry.pending.delete(registration.exporter.id)\n removedPending = true\n if (registration.requirement === 'required') {\n this.removeEntry(entry, false)\n if (event.priority === 'critical') this.counters.criticalRejected++\n this.notifyHealth()\n return receipt(event.eventId, 'rejected', 'none', 'exporter-unavailable')\n }\n }\n }\n if (removedPending && entry.pending.size === 0) this.removeEntry(entry, false)\n return captured\n }\n\n private makeCapacity(incomingBytes: number, protectedPath: boolean): boolean {\n while (this.queue.length + 1 > this.options.maxQueueEvents\n || this.queueBytes + incomingBytes > this.options.maxQueueBytes) {\n let index = this.queue.findIndex(entry => entry.event.priority === 'verbose')\n if (index === -1) index = this.queue.findIndex(entry => entry.event.priority === 'normal')\n if (index === -1) return false\n const [removed] = this.queue.splice(index, 1)\n if (removed === undefined) return false\n this.queueBytes -= removed.bytes\n if (!protectedPath) {\n if (removed.event.priority === 'verbose') this.counters.droppedVerbose++\n else this.counters.droppedNormal++\n }\n }\n return true\n }\n\n private scheduleFlush(targetIds: ReadonlySet<string>, timeoutMs: number, signal?: AbortSignal): Promise<FlushOutcome> {\n let resolveResult!: (result: FlushOutcome) => void\n let rejectResult!: (error: unknown) => void\n const result = new Promise<FlushOutcome>((resolve, reject) => { resolveResult = resolve; rejectResult = reject })\n const task = async () => {\n try { resolveResult(await this.flushInternal(targetIds, timeoutMs, signal)) }\n catch (error) { rejectResult(error) }\n }\n this.flushChain = this.flushChain.then(task, task)\n return result\n }\n\n private async flushInternal(\n targetIds: ReadonlySet<string>,\n timeoutMs: number,\n external?: AbortSignal,\n ): Promise<FlushOutcome> {\n const beforeExported = this.counters.exported\n const deadline = deadlineSignal(timeoutMs, external)\n let failed = false\n let timedOut = false\n try {\n if (this.registrations.length === 0) {\n for (const entry of [...this.queue]) if (targetIds.has(entry.event.eventId)) this.removeEntry(entry, false)\n }\n for (const registration of this.registrations) {\n while (true) {\n const candidates = this.queue.filter(entry => (\n targetIds.has(entry.event.eventId) && entry.pending.has(registration.exporter.id)\n ))\n if (candidates.length === 0) break\n const entries: QueueEntry[] = []\n let bytes = 0\n for (const entry of candidates) {\n if (entries.length >= this.options.maxBatchEvents || bytes + entry.bytes > this.options.maxBatchBytes) break\n entries.push(entry)\n bytes += entry.bytes\n }\n if (entries.length === 0) break\n const batch: ObservationBatch = deepFreeze({\n schemaVersion: 1,\n batchId: createOperationId(),\n createdAt: new Date().toISOString(),\n events: entries.map(entry => entry.event),\n })\n let ack: ExportAck\n try {\n ack = await raceAbort(Promise.resolve(registration.exporter.export(batch, deadline.signal)), deadline.signal)\n if (ack.batchId !== batch.batchId || ack.accepted !== true) {\n throw new TypeError(`observation exporter ${registration.exporter.id} returned an invalid acknowledgment`)\n }\n } catch (error) {\n failed = true\n timedOut ||= isTimeoutAbort(deadline.signal)\n this.recordExporterFailure(registration, error, true)\n if (registration.requirement === 'best-effort') {\n for (const entry of entries) {\n entry.pending.delete(registration.exporter.id)\n if (entry.pending.size === 0) this.removeEntry(entry, false)\n }\n }\n break\n }\n this.counters.lastExportAt = new Date().toISOString()\n for (const entry of entries) {\n entry.pending.delete(registration.exporter.id)\n if (entry.pending.size === 0) this.removeEntry(entry, true)\n }\n this.notifyHealth()\n }\n }\n } finally {\n if (isTimeoutAbort(deadline.signal)) {\n timedOut = true\n this.counters.flushTimeouts++\n this.counters.lastFailure = safeFailure(deadline.signal.reason, 'observation flush timed out')\n this.notifyHealth()\n }\n deadline.clear()\n }\n const pendingEntries = this.queue.filter(entry => targetIds.has(entry.event.eventId))\n const requiredIds = this.registrations\n .filter(registration => registration.requirement === 'required')\n .map(registration => registration.exporter.id)\n const requiredComplete = pendingEntries.every(entry => requiredIds.every(id => !entry.pending.has(id)))\n return Object.freeze({\n complete: !failed && !timedOut && pendingEntries.length === 0,\n requiredComplete,\n exportedEvents: this.counters.exported - beforeExported,\n pendingEvents: pendingEntries.length,\n rejectedCritical: this.counters.criticalRejected,\n timedOut,\n })\n }\n\n private removeEntry(entry: QueueEntry, exported: boolean): void {\n const index = this.queue.indexOf(entry)\n if (index === -1) return\n this.queue.splice(index, 1)\n this.queueBytes -= entry.bytes\n if (exported) this.counters.exported++\n }\n\n private recordExporterFailure(\n registration: ObservationExporterRegistration,\n error: unknown,\n emitProtected: boolean,\n ): void {\n this.counters.exporterFailures++\n if (registration.requirement === 'required') this.counters.requiredFailure = true\n this.counters.lastFailure = safeFailure(error, 'observation exporter failed')\n this.notifyHealth()\n if (emitProtected) this.recordFailure(\n `exporter:${registration.exporter.id}`, error, 'observation exporter failed', true,\n )\n }\n\n private recordFailure(key: string, error: unknown, message: string, emit: boolean): void {\n this.counters.lastFailure = safeFailure(error, message)\n this.notifyHealth()\n if (!emit || this.protectedFailures.has(key) || this.closing || this.closed) return\n this.protectedFailures.add(key)\n try {\n const event = this.prepareEvent({\n schemaVersion: 1,\n eventId: createOperationId(),\n sequence: this.healthScope.nextSequence(),\n name: 'sdk.observer.failure',\n phase: 'point',\n occurredAt: new Date().toISOString(),\n monotonicMs: this.healthScope.monotonicMs(),\n priority: 'critical',\n resource: this.resource,\n correlation: this.healthCorrelation,\n data: {\n observerId: key,\n failureKind: 'contained',\n count: 1,\n error: { ...this.counters.lastFailure },\n },\n }, true)\n this.enqueue(event, true)\n } catch { /* health counters are the final protected path */ }\n }\n\n private notifyHealth(): void {\n const callback = this.options.onHealthChange\n if (callback === undefined) return\n try { callback(this.health()) } catch { /* emergency callback is separately contained */ }\n }\n}\n\n/** Create one Universal observation bus. Construction validates every durability claim. */\nexport function createObservability(options: ObservabilityOptions = {}): Observability {\n return new ObservationBus(options)\n}\n"],"mappings":"+cAkCA,MAgCM,EAA+D,CACnE,KAAM,EAAG,gBAAiB,EAAG,sBAAuB,CACtD,EACM,EAAqB,IAAI,IAAI,CACjC,YAAa,eAAgB,aAAc,eAAgB,cAC3D,YAAa,8BAA+B,8BAC5C,iCAAkC,4BACpC,CAAC,EACK,EAAuB,wCACvB,EAAmB,IAAI,IAAI,CAAC,OAAQ,WAAY,WAAY,MAAM,CAAC,EACnE,EAAa,IAAI,IAAI,CAAC,QAAS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