@jangts/agent-core 0.1.1 → 0.2.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 (523) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/development/docs/api/reference.md +1907 -1874
  3. package/development/docs/api/support.md +27 -0
  4. package/development/skills/agent-core-app/scripts/create-app.mjs +267 -70
  5. package/development/skills/agent-core-app/scripts/lib/knowledge.mjs +40 -15
  6. package/development/skills/agent-core-app/scripts/lib/source.mjs +30 -2
  7. package/development/skills/agent-core-app/scripts/plan.mjs +37 -12
  8. package/development/skills/agent-core-app/scripts/prepare-source.mjs +61 -10
  9. package/development/skills/agent-core-app/scripts/resources.mjs +45 -17
  10. package/development/skills/agent-core-app/scripts/validate-knowledge.mjs +18 -1
  11. package/development/skills/agent-core-app/templates/catalog.json +36 -22
  12. package/dist/cjs/capabilities/index.js +13 -0
  13. package/dist/cjs/capabilities/invocation.js +80 -10
  14. package/dist/cjs/capabilities/model.js +126 -13
  15. package/dist/cjs/capabilities/tool-runtime.js +64 -12
  16. package/dist/cjs/capabilities/tools.js +266 -31
  17. package/dist/cjs/context/assembly.js +46 -5
  18. package/dist/cjs/context/audit.js +31 -6
  19. package/dist/cjs/context/fragments.js +54 -11
  20. package/dist/cjs/context/index.js +12 -0
  21. package/dist/cjs/context/journal.js +84 -7
  22. package/dist/cjs/context/plan.js +30 -2
  23. package/dist/cjs/diagnostics/catalog.js +11 -3
  24. package/dist/cjs/diagnostics/index.js +149 -29
  25. package/dist/cjs/diagnostics/sub-flow.js +240 -40
  26. package/dist/cjs/errors.js +99 -17
  27. package/dist/cjs/execution/branch.js +20 -4
  28. package/dist/cjs/execution/engine.js +470 -56
  29. package/dist/cjs/execution/events.js +136 -18
  30. package/dist/cjs/execution/index.js +7 -0
  31. package/dist/cjs/execution/reporting.js +75 -6
  32. package/dist/cjs/execution/state.js +161 -22
  33. package/dist/cjs/execution/workflow.js +224 -32
  34. package/dist/cjs/index.js +18 -0
  35. package/dist/cjs/kits/aggregation.js +45 -3
  36. package/dist/cjs/kits/answering/batch.js +23 -4
  37. package/dist/cjs/kits/answering/check-result.js +31 -8
  38. package/dist/cjs/kits/answering/checks.js +24 -3
  39. package/dist/cjs/kits/answering/flow.js +192 -36
  40. package/dist/cjs/kits/answering/index.js +19 -1
  41. package/dist/cjs/kits/answering/tasks.js +88 -13
  42. package/dist/cjs/kits/artifacts.js +36 -4
  43. package/dist/cjs/kits/candidates.js +47 -5
  44. package/dist/cjs/kits/delivery.js +40 -5
  45. package/dist/cjs/kits/durable.js +155 -31
  46. package/dist/cjs/kits/evidence.js +66 -15
  47. package/dist/cjs/kits/family.js +152 -22
  48. package/dist/cjs/kits/index.js +12 -1
  49. package/dist/cjs/kits/inference.js +104 -16
  50. package/dist/cjs/kits/intents/catalog.js +67 -16
  51. package/dist/cjs/kits/intents/index.js +11 -0
  52. package/dist/cjs/kits/intents/registry.js +188 -43
  53. package/dist/cjs/kits/intents/scopes.js +215 -46
  54. package/dist/cjs/kits/interaction/command.js +140 -36
  55. package/dist/cjs/kits/interaction/commands.js +86 -11
  56. package/dist/cjs/kits/interaction/handlers.js +27 -10
  57. package/dist/cjs/kits/interaction/index.js +10 -0
  58. package/dist/cjs/kits/interaction/transfer.js +80 -14
  59. package/dist/cjs/kits/knowledge/catalog.js +62 -11
  60. package/dist/cjs/kits/knowledge/index.js +16 -1
  61. package/dist/cjs/kits/knowledge/publication.js +99 -23
  62. package/dist/cjs/kits/knowledge/sections.js +33 -4
  63. package/dist/cjs/kits/normalization.js +51 -7
  64. package/dist/cjs/kits/policies.js +79 -15
  65. package/dist/cjs/kits/presentation/events.js +54 -10
  66. package/dist/cjs/kits/presentation/index.js +24 -1
  67. package/dist/cjs/kits/presentation/outputs.js +176 -38
  68. package/dist/cjs/kits/presentation/templates.js +33 -5
  69. package/dist/cjs/kits/presentation/variants.js +31 -2
  70. package/dist/cjs/kits/projection.js +63 -8
  71. package/dist/cjs/kits/rank-fusion.js +27 -4
  72. package/dist/cjs/kits/reflection-log-source.js +89 -16
  73. package/dist/cjs/kits/reflection.js +234 -60
  74. package/dist/cjs/kits/retrieval.js +98 -18
  75. package/dist/cjs/kits/search.js +180 -27
  76. package/dist/cjs/kits/text-skills.js +104 -19
  77. package/dist/cjs/kits/tools.js +415 -74
  78. package/dist/cjs/kits/vector-search.js +50 -16
  79. package/dist/cjs/mock/node.js +7 -1
  80. package/dist/cjs/mock/web.js +7 -1
  81. package/dist/cjs/mock.js +7 -1
  82. package/dist/cjs/model/binding.js +68 -17
  83. package/dist/cjs/model/call-budget.js +45 -4
  84. package/dist/cjs/model/decision-retry.js +19 -1
  85. package/dist/cjs/model/defaults.js +27 -4
  86. package/dist/cjs/model/index.js +7 -0
  87. package/dist/cjs/model/interactions/arguments.js +36 -1
  88. package/dist/cjs/model/interactions/json-object.js +48 -12
  89. package/dist/cjs/model/interactions/native-functions.js +52 -10
  90. package/dist/cjs/model/message-diagnostics.js +17 -4
  91. package/dist/cjs/model/options.js +9 -1
  92. package/dist/cjs/model/preparation.js +86 -12
  93. package/dist/cjs/model/runner.js +413 -79
  94. package/dist/cjs/model/selection-transport.js +48 -8
  95. package/dist/cjs/model/settings.js +67 -13
  96. package/dist/cjs/model/token-budget.js +69 -11
  97. package/dist/cjs/model/transports.js +59 -6
  98. package/dist/cjs/structs/common.js +11 -0
  99. package/dist/cjs/structs/debug.js +34 -5
  100. package/dist/cjs/structs/errors.js +26 -1
  101. package/dist/cjs/structs/index.js +11 -1
  102. package/dist/cjs/structs/kits/durable.js +7 -0
  103. package/dist/cjs/structs/kits/family.js +1 -0
  104. package/dist/cjs/structs/kits/interaction.js +8 -1
  105. package/dist/cjs/structs/kits/knowledge-publication.js +1 -0
  106. package/dist/cjs/structs/kits/reflection.js +18 -3
  107. package/dist/cjs/structs/model/chat-provider.js +6 -0
  108. package/dist/cjs/structs/support/model/completion.js +2 -0
  109. package/dist/cjs/structs/support/model/messages.js +2 -0
  110. package/dist/cjs/support/capabilities.js +43 -6
  111. package/dist/cjs/support/context/assembly.js +88 -16
  112. package/dist/cjs/support/context/compression.js +48 -6
  113. package/dist/cjs/support/context/fragments.js +6 -0
  114. package/dist/cjs/support/context/history.js +36 -1
  115. package/dist/cjs/support/context/index.js +11 -0
  116. package/dist/cjs/support/context/nodes.js +164 -35
  117. package/dist/cjs/support/context/processing.js +319 -61
  118. package/dist/cjs/support/context/selection-policy.js +98 -21
  119. package/dist/cjs/support/context/selection.js +61 -10
  120. package/dist/cjs/support/context/snapshot.js +29 -7
  121. package/dist/cjs/support/context/strategies.js +120 -28
  122. package/dist/cjs/support/index.js +9 -1
  123. package/dist/cjs/support/model/capabilities.js +20 -1
  124. package/dist/cjs/support/model/chat-completions.js +92 -20
  125. package/dist/cjs/support/model/children.js +34 -6
  126. package/dist/cjs/support/model/compatible-provider.js +189 -59
  127. package/dist/cjs/support/model/completion/calls.js +61 -0
  128. package/dist/cjs/support/model/completion/default.js +32 -0
  129. package/dist/cjs/support/model/completion/index.js +28 -0
  130. package/dist/cjs/support/model/completion/session.js +102 -0
  131. package/dist/cjs/support/model/index.js +12 -0
  132. package/dist/cjs/support/model/interactions/index.js +12 -1
  133. package/dist/cjs/support/model/interactions/json-object.js +6 -0
  134. package/dist/cjs/support/model/interactions/native-functions.js +6 -0
  135. package/dist/cjs/support/model/observer.js +32 -6
  136. package/dist/cjs/support/model/preview-rules.js +66 -16
  137. package/dist/cjs/support/model/reply-preview.js +77 -17
  138. package/dist/cjs/support/model/stage-transport.js +33 -7
  139. package/dist/cjs/support/model/strategies.js +75 -14
  140. package/dist/cjs/support/model/transports.js +53 -11
  141. package/dist/cjs/support/registration.js +49 -7
  142. package/dist/cjs/support/schema.js +46 -4
  143. package/dist/cjs/support/stream-events.js +60 -8
  144. package/dist/cjs/support/tool-runtime.js +6 -0
  145. package/dist/cjs/support/tools.js +79 -10
  146. package/dist/cjs/support/transport/index.js +7 -0
  147. package/dist/cjs/support/transport/json.js +28 -4
  148. package/dist/cjs/support/transport/sse.js +25 -2
  149. package/dist/cjs/utils/break-observer.js +20 -2
  150. package/dist/cjs/utils/cancellation.js +77 -9
  151. package/dist/cjs/utils/catalog.js +19 -4
  152. package/dist/cjs/utils/debug.js +14 -2
  153. package/dist/cjs/utils/index.js +8 -0
  154. package/dist/cjs/utils/interaction-definition.js +26 -6
  155. package/dist/cjs/utils/invocation.js +42 -4
  156. package/dist/cjs/utils/model-protocol.js +20 -1
  157. package/dist/cjs/utils/object.js +16 -0
  158. package/dist/cjs/utils/observer.js +22 -2
  159. package/dist/cjs/utils/protocol-registry.js +47 -4
  160. package/dist/cjs/utils/query-key.js +21 -2
  161. package/dist/cjs/utils/registration.js +18 -2
  162. package/dist/cjs/utils/rules.js +39 -11
  163. package/dist/cjs/utils/schema-adapter.js +25 -2
  164. package/dist/cjs/utils/synchronous.js +64 -7
  165. package/dist/cjs/utils/text.js +15 -1
  166. package/dist/esm/capabilities/index.d.ts +13 -0
  167. package/dist/esm/capabilities/index.js +13 -0
  168. package/dist/esm/capabilities/invocation.d.ts +16 -2
  169. package/dist/esm/capabilities/invocation.js +80 -10
  170. package/dist/esm/capabilities/model.d.ts +68 -1
  171. package/dist/esm/capabilities/model.js +126 -13
  172. package/dist/esm/capabilities/tool-runtime.d.ts +11 -0
  173. package/dist/esm/capabilities/tool-runtime.js +64 -12
  174. package/dist/esm/capabilities/tools.d.ts +96 -3
  175. package/dist/esm/capabilities/tools.js +267 -32
  176. package/dist/esm/context/assembly.d.ts +13 -2
  177. package/dist/esm/context/assembly.js +46 -5
  178. package/dist/esm/context/audit.d.ts +23 -1
  179. package/dist/esm/context/audit.js +31 -6
  180. package/dist/esm/context/fragments.d.ts +37 -3
  181. package/dist/esm/context/fragments.js +54 -11
  182. package/dist/esm/context/index.d.ts +12 -0
  183. package/dist/esm/context/index.js +12 -0
  184. package/dist/esm/context/journal.d.ts +32 -1
  185. package/dist/esm/context/journal.js +84 -7
  186. package/dist/esm/context/plan.d.ts +11 -1
  187. package/dist/esm/context/plan.js +30 -2
  188. package/dist/esm/diagnostics/catalog.js +11 -3
  189. package/dist/esm/diagnostics/index.d.ts +30 -2
  190. package/dist/esm/diagnostics/index.js +149 -29
  191. package/dist/esm/diagnostics/sub-flow.d.ts +41 -3
  192. package/dist/esm/diagnostics/sub-flow.js +240 -40
  193. package/dist/esm/errors.d.ts +22 -2
  194. package/dist/esm/errors.js +99 -17
  195. package/dist/esm/execution/branch.d.ts +19 -1
  196. package/dist/esm/execution/branch.js +20 -4
  197. package/dist/esm/execution/engine.d.ts +291 -5
  198. package/dist/esm/execution/engine.js +471 -57
  199. package/dist/esm/execution/events.d.ts +16 -2
  200. package/dist/esm/execution/events.js +136 -18
  201. package/dist/esm/execution/index.d.ts +7 -0
  202. package/dist/esm/execution/index.js +7 -0
  203. package/dist/esm/execution/reporting.d.ts +49 -1
  204. package/dist/esm/execution/reporting.js +75 -6
  205. package/dist/esm/execution/state.d.ts +126 -10
  206. package/dist/esm/execution/state.js +161 -22
  207. package/dist/esm/execution/workflow.d.ts +121 -3
  208. package/dist/esm/execution/workflow.js +224 -32
  209. package/dist/esm/index.d.ts +17 -1
  210. package/dist/esm/index.js +18 -0
  211. package/dist/esm/kits/aggregation.d.ts +34 -2
  212. package/dist/esm/kits/aggregation.js +45 -3
  213. package/dist/esm/kits/answering/batch.d.ts +17 -0
  214. package/dist/esm/kits/answering/batch.js +23 -4
  215. package/dist/esm/kits/answering/check-result.d.ts +18 -1
  216. package/dist/esm/kits/answering/check-result.js +31 -8
  217. package/dist/esm/kits/answering/checks.d.ts +11 -0
  218. package/dist/esm/kits/answering/checks.js +24 -3
  219. package/dist/esm/kits/answering/flow.d.ts +25 -2
  220. package/dist/esm/kits/answering/flow.js +192 -36
  221. package/dist/esm/kits/answering/index.d.ts +12 -0
  222. package/dist/esm/kits/answering/index.js +19 -1
  223. package/dist/esm/kits/answering/tasks.d.ts +32 -1
  224. package/dist/esm/kits/answering/tasks.js +88 -13
  225. package/dist/esm/kits/artifacts.d.ts +11 -0
  226. package/dist/esm/kits/artifacts.js +36 -4
  227. package/dist/esm/kits/candidates.d.ts +23 -1
  228. package/dist/esm/kits/candidates.js +47 -5
  229. package/dist/esm/kits/delivery.d.ts +34 -0
  230. package/dist/esm/kits/delivery.js +40 -5
  231. package/dist/esm/kits/durable.d.ts +19 -0
  232. package/dist/esm/kits/durable.js +155 -31
  233. package/dist/esm/kits/evidence.d.ts +28 -5
  234. package/dist/esm/kits/evidence.js +66 -15
  235. package/dist/esm/kits/family.d.ts +17 -1
  236. package/dist/esm/kits/family.js +152 -22
  237. package/dist/esm/kits/index.d.ts +12 -1
  238. package/dist/esm/kits/index.js +12 -1
  239. package/dist/esm/kits/inference.d.ts +64 -0
  240. package/dist/esm/kits/inference.js +104 -16
  241. package/dist/esm/kits/intents/catalog.d.ts +13 -1
  242. package/dist/esm/kits/intents/catalog.js +67 -16
  243. package/dist/esm/kits/intents/index.d.ts +11 -0
  244. package/dist/esm/kits/intents/index.js +11 -0
  245. package/dist/esm/kits/intents/registry.d.ts +61 -3
  246. package/dist/esm/kits/intents/registry.js +188 -43
  247. package/dist/esm/kits/intents/scopes.d.ts +73 -3
  248. package/dist/esm/kits/intents/scopes.js +215 -46
  249. package/dist/esm/kits/interaction/command.d.ts +38 -4
  250. package/dist/esm/kits/interaction/command.js +140 -36
  251. package/dist/esm/kits/interaction/commands.d.ts +66 -2
  252. package/dist/esm/kits/interaction/commands.js +86 -11
  253. package/dist/esm/kits/interaction/handlers.d.ts +19 -2
  254. package/dist/esm/kits/interaction/handlers.js +27 -10
  255. package/dist/esm/kits/interaction/index.d.ts +10 -0
  256. package/dist/esm/kits/interaction/index.js +10 -0
  257. package/dist/esm/kits/interaction/transfer.d.ts +39 -2
  258. package/dist/esm/kits/interaction/transfer.js +80 -14
  259. package/dist/esm/kits/knowledge/catalog.d.ts +13 -0
  260. package/dist/esm/kits/knowledge/catalog.js +62 -11
  261. package/dist/esm/kits/knowledge/index.d.ts +11 -0
  262. package/dist/esm/kits/knowledge/index.js +16 -1
  263. package/dist/esm/kits/knowledge/publication.d.ts +15 -1
  264. package/dist/esm/kits/knowledge/publication.js +99 -23
  265. package/dist/esm/kits/knowledge/sections.d.ts +31 -1
  266. package/dist/esm/kits/knowledge/sections.js +33 -4
  267. package/dist/esm/kits/normalization.d.ts +25 -2
  268. package/dist/esm/kits/normalization.js +51 -7
  269. package/dist/esm/kits/policies.d.ts +26 -3
  270. package/dist/esm/kits/policies.js +79 -15
  271. package/dist/esm/kits/presentation/events.d.ts +51 -4
  272. package/dist/esm/kits/presentation/events.js +54 -10
  273. package/dist/esm/kits/presentation/index.d.ts +12 -0
  274. package/dist/esm/kits/presentation/index.js +25 -2
  275. package/dist/esm/kits/presentation/outputs.d.ts +30 -1
  276. package/dist/esm/kits/presentation/outputs.js +176 -38
  277. package/dist/esm/kits/presentation/templates.d.ts +32 -3
  278. package/dist/esm/kits/presentation/templates.js +33 -5
  279. package/dist/esm/kits/presentation/variants.d.ts +29 -0
  280. package/dist/esm/kits/presentation/variants.js +31 -2
  281. package/dist/esm/kits/projection.d.ts +42 -5
  282. package/dist/esm/kits/projection.js +63 -8
  283. package/dist/esm/kits/rank-fusion.d.ts +21 -1
  284. package/dist/esm/kits/rank-fusion.js +28 -5
  285. package/dist/esm/kits/reflection-log-source.d.ts +28 -1
  286. package/dist/esm/kits/reflection-log-source.js +89 -16
  287. package/dist/esm/kits/reflection.d.ts +17 -1
  288. package/dist/esm/kits/reflection.js +235 -61
  289. package/dist/esm/kits/retrieval.d.ts +18 -2
  290. package/dist/esm/kits/retrieval.js +98 -18
  291. package/dist/esm/kits/search.d.ts +56 -3
  292. package/dist/esm/kits/search.js +180 -27
  293. package/dist/esm/kits/text-skills.d.ts +16 -2
  294. package/dist/esm/kits/text-skills.js +104 -19
  295. package/dist/esm/kits/tools.d.ts +122 -2
  296. package/dist/esm/kits/tools.js +416 -74
  297. package/dist/esm/kits/vector-search.d.ts +47 -1
  298. package/dist/esm/kits/vector-search.js +51 -17
  299. package/dist/esm/mock/node.d.ts +7 -0
  300. package/dist/esm/mock/node.js +7 -1
  301. package/dist/esm/mock/web.d.ts +7 -0
  302. package/dist/esm/mock/web.js +7 -1
  303. package/dist/esm/mock.d.ts +7 -0
  304. package/dist/esm/mock.js +7 -1
  305. package/dist/esm/model/binding.d.ts +32 -3
  306. package/dist/esm/model/binding.js +68 -17
  307. package/dist/esm/model/call-budget.d.ts +30 -2
  308. package/dist/esm/model/call-budget.js +45 -4
  309. package/dist/esm/model/decision-retry.d.ts +10 -1
  310. package/dist/esm/model/decision-retry.js +19 -1
  311. package/dist/esm/model/defaults.d.ts +13 -2
  312. package/dist/esm/model/defaults.js +27 -4
  313. package/dist/esm/model/index.d.ts +7 -0
  314. package/dist/esm/model/index.js +7 -0
  315. package/dist/esm/model/interactions/arguments.d.ts +27 -0
  316. package/dist/esm/model/interactions/arguments.js +36 -1
  317. package/dist/esm/model/interactions/json-object.d.ts +7 -1
  318. package/dist/esm/model/interactions/json-object.js +48 -12
  319. package/dist/esm/model/interactions/native-functions.d.ts +6 -0
  320. package/dist/esm/model/interactions/native-functions.js +52 -10
  321. package/dist/esm/model/message-diagnostics.d.ts +17 -1
  322. package/dist/esm/model/message-diagnostics.js +17 -4
  323. package/dist/esm/model/options.d.ts +18 -1
  324. package/dist/esm/model/options.js +9 -1
  325. package/dist/esm/model/preparation.d.ts +30 -2
  326. package/dist/esm/model/preparation.js +86 -12
  327. package/dist/esm/model/runner.d.ts +129 -5
  328. package/dist/esm/model/runner.js +414 -80
  329. package/dist/esm/model/selection-transport.d.ts +14 -1
  330. package/dist/esm/model/selection-transport.js +48 -8
  331. package/dist/esm/model/settings.d.ts +11 -0
  332. package/dist/esm/model/settings.js +67 -13
  333. package/dist/esm/model/token-budget.d.ts +59 -1
  334. package/dist/esm/model/token-budget.js +69 -11
  335. package/dist/esm/model/transports.d.ts +20 -2
  336. package/dist/esm/model/transports.js +59 -6
  337. package/dist/esm/structs/capabilities/invocation.d.ts +36 -0
  338. package/dist/esm/structs/capabilities/model.d.ts +27 -0
  339. package/dist/esm/structs/capabilities/tools.d.ts +38 -0
  340. package/dist/esm/structs/common.d.ts +62 -2
  341. package/dist/esm/structs/common.js +11 -0
  342. package/dist/esm/structs/context/fragments.d.ts +28 -0
  343. package/dist/esm/structs/context/journal.d.ts +28 -3
  344. package/dist/esm/structs/context/processing.d.ts +11 -0
  345. package/dist/esm/structs/debug.d.ts +58 -1
  346. package/dist/esm/structs/debug.js +34 -5
  347. package/dist/esm/structs/diagnostics.d.ts +119 -1
  348. package/dist/esm/structs/errors.d.ts +42 -1
  349. package/dist/esm/structs/errors.js +26 -1
  350. package/dist/esm/structs/execution/engine.d.ts +24 -1
  351. package/dist/esm/structs/execution/events.d.ts +12 -0
  352. package/dist/esm/structs/execution/workflow.d.ts +71 -0
  353. package/dist/esm/structs/index.d.ts +11 -1
  354. package/dist/esm/structs/index.js +11 -1
  355. package/dist/esm/structs/invocation.d.ts +30 -0
  356. package/dist/esm/structs/kits/aggregation.d.ts +12 -0
  357. package/dist/esm/structs/kits/answering/checks.d.ts +11 -0
  358. package/dist/esm/structs/kits/answering/flow.d.ts +35 -1
  359. package/dist/esm/structs/kits/answering/state.d.ts +21 -0
  360. package/dist/esm/structs/kits/answering/tasks.d.ts +21 -0
  361. package/dist/esm/structs/kits/artifacts.d.ts +14 -0
  362. package/dist/esm/structs/kits/candidates.d.ts +19 -0
  363. package/dist/esm/structs/kits/delivery.d.ts +22 -0
  364. package/dist/esm/structs/kits/durable.d.ts +56 -3
  365. package/dist/esm/structs/kits/durable.js +7 -0
  366. package/dist/esm/structs/kits/evidence.d.ts +23 -0
  367. package/dist/esm/structs/kits/family.d.ts +49 -1
  368. package/dist/esm/structs/kits/family.js +1 -0
  369. package/dist/esm/structs/kits/intents/catalog.d.ts +26 -0
  370. package/dist/esm/structs/kits/intents/registry.d.ts +34 -0
  371. package/dist/esm/structs/kits/intents/scopes.d.ts +36 -1
  372. package/dist/esm/structs/kits/interaction.d.ts +64 -0
  373. package/dist/esm/structs/kits/interaction.js +8 -1
  374. package/dist/esm/structs/kits/knowledge-publication.d.ts +43 -1
  375. package/dist/esm/structs/kits/knowledge-publication.js +1 -0
  376. package/dist/esm/structs/kits/knowledge.d.ts +39 -2
  377. package/dist/esm/structs/kits/normalization.d.ts +15 -0
  378. package/dist/esm/structs/kits/policies.d.ts +25 -1
  379. package/dist/esm/structs/kits/presentation/events.d.ts +28 -4
  380. package/dist/esm/structs/kits/presentation/outputs.d.ts +38 -1
  381. package/dist/esm/structs/kits/presentation/templates.d.ts +15 -0
  382. package/dist/esm/structs/kits/projection.d.ts +21 -0
  383. package/dist/esm/structs/kits/reflection.d.ts +61 -2
  384. package/dist/esm/structs/kits/reflection.js +18 -3
  385. package/dist/esm/structs/kits/retrieval.d.ts +38 -0
  386. package/dist/esm/structs/kits/search.d.ts +22 -0
  387. package/dist/esm/structs/kits/text-skills.d.ts +36 -0
  388. package/dist/esm/structs/kits/tools.d.ts +87 -0
  389. package/dist/esm/structs/model/chat-provider.d.ts +24 -1
  390. package/dist/esm/structs/model/chat-provider.js +6 -0
  391. package/dist/esm/structs/model/interactions.d.ts +38 -0
  392. package/dist/esm/structs/model/messages.d.ts +30 -0
  393. package/dist/esm/structs/model/runtime.d.ts +104 -6
  394. package/dist/esm/structs/support/capabilities.d.ts +19 -2
  395. package/dist/esm/structs/support/context-processing.d.ts +88 -9
  396. package/dist/esm/structs/support/context.d.ts +29 -1
  397. package/dist/esm/structs/support/model/completion.d.ts +50 -0
  398. package/dist/esm/structs/support/model/completion.js +1 -0
  399. package/dist/esm/structs/support/model/interactions.d.ts +13 -1
  400. package/dist/esm/structs/support/model/messages.d.ts +52 -0
  401. package/dist/esm/structs/support/model/messages.js +1 -0
  402. package/dist/esm/structs/support/model/provider-observer.d.ts +22 -1
  403. package/dist/esm/structs/support/model/provider.d.ts +71 -6
  404. package/dist/esm/structs/support/registration.d.ts +13 -0
  405. package/dist/esm/structs/support/schema.d.ts +14 -0
  406. package/dist/esm/structs/support/tools.d.ts +28 -0
  407. package/dist/esm/structs/support/transport/json.d.ts +16 -0
  408. package/dist/esm/structs/support/transport/sse.d.ts +15 -0
  409. package/dist/esm/structs/utils/rules.d.ts +19 -0
  410. package/dist/esm/support/capabilities.d.ts +25 -2
  411. package/dist/esm/support/capabilities.js +43 -6
  412. package/dist/esm/support/context/assembly.d.ts +35 -4
  413. package/dist/esm/support/context/assembly.js +88 -16
  414. package/dist/esm/support/context/compression.d.ts +17 -1
  415. package/dist/esm/support/context/compression.js +48 -6
  416. package/dist/esm/support/context/fragments.d.ts +6 -0
  417. package/dist/esm/support/context/fragments.js +6 -0
  418. package/dist/esm/support/context/history.d.ts +43 -0
  419. package/dist/esm/support/context/history.js +36 -1
  420. package/dist/esm/support/context/index.d.ts +13 -2
  421. package/dist/esm/support/context/index.js +12 -1
  422. package/dist/esm/support/context/nodes.d.ts +49 -3
  423. package/dist/esm/support/context/nodes.js +165 -36
  424. package/dist/esm/support/context/processing.d.ts +145 -1
  425. package/dist/esm/support/context/processing.js +320 -62
  426. package/dist/esm/support/context/selection-policy.d.ts +42 -2
  427. package/dist/esm/support/context/selection-policy.js +98 -21
  428. package/dist/esm/support/context/selection.d.ts +14 -1
  429. package/dist/esm/support/context/selection.js +61 -10
  430. package/dist/esm/support/context/snapshot.d.ts +23 -1
  431. package/dist/esm/support/context/snapshot.js +29 -7
  432. package/dist/esm/support/context/strategies.d.ts +35 -2
  433. package/dist/esm/support/context/strategies.js +120 -28
  434. package/dist/esm/support/index.d.ts +9 -1
  435. package/dist/esm/support/index.js +9 -1
  436. package/dist/esm/support/model/capabilities.d.ts +10 -0
  437. package/dist/esm/support/model/capabilities.js +20 -1
  438. package/dist/esm/support/model/chat-completions.d.ts +44 -15
  439. package/dist/esm/support/model/chat-completions.js +92 -20
  440. package/dist/esm/support/model/children.d.ts +32 -2
  441. package/dist/esm/support/model/children.js +34 -6
  442. package/dist/esm/support/model/compatible-provider.d.ts +29 -3
  443. package/dist/esm/support/model/compatible-provider.js +190 -60
  444. package/dist/esm/support/model/completion/calls.d.ts +40 -0
  445. package/dist/esm/support/model/completion/calls.js +58 -0
  446. package/dist/esm/support/model/completion/default.d.ts +10 -0
  447. package/dist/esm/support/model/completion/default.js +29 -0
  448. package/dist/esm/support/model/completion/index.d.ts +10 -0
  449. package/dist/esm/support/model/completion/index.js +22 -0
  450. package/dist/esm/support/model/completion/session.d.ts +11 -0
  451. package/dist/esm/support/model/completion/session.js +99 -0
  452. package/dist/esm/support/model/index.d.ts +14 -0
  453. package/dist/esm/support/model/index.js +12 -0
  454. package/dist/esm/support/model/interactions/index.d.ts +1 -1
  455. package/dist/esm/support/model/interactions/index.js +12 -1
  456. package/dist/esm/support/model/interactions/json-object.d.ts +6 -0
  457. package/dist/esm/support/model/interactions/json-object.js +6 -0
  458. package/dist/esm/support/model/interactions/native-functions.d.ts +6 -0
  459. package/dist/esm/support/model/interactions/native-functions.js +6 -0
  460. package/dist/esm/support/model/observer.d.ts +25 -2
  461. package/dist/esm/support/model/observer.js +32 -6
  462. package/dist/esm/support/model/preview-rules.d.ts +20 -2
  463. package/dist/esm/support/model/preview-rules.js +66 -16
  464. package/dist/esm/support/model/reply-preview.d.ts +15 -1
  465. package/dist/esm/support/model/reply-preview.js +77 -17
  466. package/dist/esm/support/model/stage-transport.d.ts +9 -1
  467. package/dist/esm/support/model/stage-transport.js +33 -7
  468. package/dist/esm/support/model/strategies.d.ts +24 -2
  469. package/dist/esm/support/model/strategies.js +75 -14
  470. package/dist/esm/support/model/transports.d.ts +17 -1
  471. package/dist/esm/support/model/transports.js +53 -11
  472. package/dist/esm/support/registration.d.ts +20 -1
  473. package/dist/esm/support/registration.js +49 -7
  474. package/dist/esm/support/schema.d.ts +31 -1
  475. package/dist/esm/support/schema.js +46 -4
  476. package/dist/esm/support/stream-events.d.ts +22 -1
  477. package/dist/esm/support/stream-events.js +60 -8
  478. package/dist/esm/support/tool-runtime.d.ts +6 -0
  479. package/dist/esm/support/tool-runtime.js +6 -0
  480. package/dist/esm/support/tools.d.ts +22 -0
  481. package/dist/esm/support/tools.js +79 -10
  482. package/dist/esm/support/transport/index.d.ts +7 -0
  483. package/dist/esm/support/transport/index.js +7 -0
  484. package/dist/esm/support/transport/json.d.ts +29 -2
  485. package/dist/esm/support/transport/json.js +28 -4
  486. package/dist/esm/support/transport/sse.d.ts +31 -1
  487. package/dist/esm/support/transport/sse.js +25 -2
  488. package/dist/esm/types.d.ts +9 -1
  489. package/dist/esm/utils/break-observer.d.ts +27 -2
  490. package/dist/esm/utils/break-observer.js +20 -2
  491. package/dist/esm/utils/cancellation.d.ts +56 -5
  492. package/dist/esm/utils/cancellation.js +77 -9
  493. package/dist/esm/utils/catalog.d.ts +20 -1
  494. package/dist/esm/utils/catalog.js +19 -4
  495. package/dist/esm/utils/debug.d.ts +20 -1
  496. package/dist/esm/utils/debug.js +14 -2
  497. package/dist/esm/utils/index.d.ts +8 -0
  498. package/dist/esm/utils/index.js +8 -0
  499. package/dist/esm/utils/interaction-definition.d.ts +18 -1
  500. package/dist/esm/utils/interaction-definition.js +26 -6
  501. package/dist/esm/utils/invocation.d.ts +36 -1
  502. package/dist/esm/utils/invocation.js +42 -4
  503. package/dist/esm/utils/model-protocol.d.ts +8 -0
  504. package/dist/esm/utils/model-protocol.js +20 -1
  505. package/dist/esm/utils/object.d.ts +16 -0
  506. package/dist/esm/utils/object.js +16 -0
  507. package/dist/esm/utils/observer.d.ts +19 -1
  508. package/dist/esm/utils/observer.js +22 -2
  509. package/dist/esm/utils/protocol-registry.d.ts +38 -1
  510. package/dist/esm/utils/protocol-registry.js +47 -4
  511. package/dist/esm/utils/query-key.d.ts +11 -1
  512. package/dist/esm/utils/query-key.js +21 -2
  513. package/dist/esm/utils/registration.d.ts +34 -2
  514. package/dist/esm/utils/registration.js +18 -2
  515. package/dist/esm/utils/rules.d.ts +81 -4
  516. package/dist/esm/utils/rules.js +39 -11
  517. package/dist/esm/utils/schema-adapter.d.ts +12 -1
  518. package/dist/esm/utils/schema-adapter.js +25 -2
  519. package/dist/esm/utils/synchronous.d.ts +60 -4
  520. package/dist/esm/utils/synchronous.js +64 -7
  521. package/dist/esm/utils/text.d.ts +15 -1
  522. package/dist/esm/utils/text.js +15 -1
  523. package/package.json +3 -2
@@ -1,28 +1,71 @@
1
1
  import { ValidationError } from '../structs/errors.js';
2
2
  import { breakWhile } from '../utils/rules.js';
3
- /** Validate one fragment before formatting. The shared set preserves registration order. */
3
+ /**
4
+ * Validate one fragment and return the text it contributes to the model input.
5
+ *
6
+ * @param fragment Declaration to check.
7
+ * @param ids Optional accumulator of ids already seen. Callers validating a batch pass the
8
+ * same set for every fragment so duplicates are detected across the whole input.
9
+ * @param checkBudget Whether this fragment's own `maxChars` is enforced. Disable only when the
10
+ * same serialized text has already been checked against the identical limit.
11
+ * @returns The exact text the fragment contributes: the value when it is a string, otherwise
12
+ * the JSON form used for structured fields.
13
+ * @throws Error when identity, trust, lifetime, role, the `maxChars` declaration or the value
14
+ * shape is invalid, or when untrusted content is declared as a system instruction.
15
+ * @throws ValidationError when the serialized text exceeds `maxChars`; text is never truncated.
16
+ */
4
17
  export function validateContextFragment(fragment, ids = new Set(), checkBudget = true) {
5
- if (!/^[a-z][a-zA-Z0-9:._-]*$/.test(fragment.id) || ids.has(fragment.id) || !fragment.sourceId
6
- || !['instruction', 'server', 'user', 'tool'].includes(fragment.trust)
7
- || !['configuration', 'turn', 'step'].includes(fragment.lifetime) || !['system', 'user'].includes(fragment.role)
8
- || !Number.isSafeInteger(fragment.maxChars) || fragment.maxChars < 1)
18
+ // Ids are stable keys in usage records and protected-context errors, so they start with a
19
+ // lowercase letter and admit only characters that are safe in both positions.
20
+ if (!/^[a-z][a-zA-Z0-9:._-]*$/.test(fragment.id) ||
21
+ ids.has(fragment.id) ||
22
+ !fragment.sourceId ||
23
+ !['instruction', 'server', 'user', 'tool'].includes(fragment.trust) ||
24
+ !['configuration', 'turn', 'step'].includes(fragment.lifetime) ||
25
+ !['system', 'user'].includes(fragment.role) ||
26
+ !Number.isSafeInteger(fragment.maxChars) ||
27
+ fragment.maxChars < 1)
9
28
  throw new Error('Invalid context fragment');
29
+ // Consumed before the later checks: a failed fragment must not leave its id reusable by a
30
+ // retry through the same accumulator.
10
31
  ids.add(fragment.id);
11
- if (fragment.role === 'system' && (fragment.trust === 'user' || fragment.trust === 'tool' || typeof fragment.value !== 'string'))
32
+ if (fragment.role === 'system' &&
33
+ (fragment.trust === 'user' || fragment.trust === 'tool' || typeof fragment.value !== 'string'))
12
34
  throw new Error('Untrusted context cannot become a system instruction');
13
- if (typeof fragment.value !== 'string' && (!fragment.value || typeof fragment.value !== 'object' || Array.isArray(fragment.value)))
35
+ if (typeof fragment.value !== 'string' &&
36
+ (!fragment.value || typeof fragment.value !== 'object' || Array.isArray(fragment.value)))
14
37
  throw new Error('Invalid context value');
38
+ // Structured values are measured as the JSON text that will be sent, so the declared budget
39
+ // describes the payload rather than the in-memory object.
15
40
  const serialized = typeof fragment.value === 'string' ? fragment.value : JSON.stringify(fragment.value);
16
41
  if (checkBudget && serialized.length > fragment.maxChars)
17
- throw new ValidationError([{ code: 'CONTEXT_BUDGET', message: `上下文片段 ${fragment.id} 超过预算;不截断原问题、约束与证据。` }]);
42
+ throw new ValidationError([
43
+ {
44
+ code: 'CONTEXT_BUDGET',
45
+ message: `上下文片段 ${fragment.id} 超过预算;不截断原问题、约束与证据。`,
46
+ },
47
+ ]);
18
48
  return serialized;
19
49
  }
20
- /** Core input-budget boundary; helpers may retain their existing error presentation. */
50
+ /**
51
+ * Enforce the character budget of the whole model input.
52
+ *
53
+ * @param inputChars Characters that will be sent; must be a non-negative safe integer.
54
+ * @param maxInputChars Budget limit. `Infinity` is accepted as an explicit "no limit", which
55
+ * is why it is allowed in place of a safe integer.
56
+ * @param exceeded Optional factory for the over-budget error. Support may pass one to keep its
57
+ * own message; Core otherwise raises a `CONTEXT_BUDGET` ValidationError.
58
+ * @returns Nothing.
59
+ * @throws TypeError when either count is not a non-negative integer.
60
+ * @throws Error when the budget is exceeded: the `exceeded` result, or a ValidationError.
61
+ */
21
62
  export function validateContextBudget(inputChars, maxInputChars, exceeded) {
22
63
  breakWhile(!Number.isSafeInteger(inputChars) || inputChars < 0, () => new TypeError('Invalid context input size'));
23
64
  breakWhile(maxInputChars !== Infinity && (!Number.isSafeInteger(maxInputChars) || maxInputChars < 0), () => new TypeError('Invalid context budget'));
24
65
  if (inputChars > maxInputChars)
25
- throw exceeded?.(maxInputChars)
26
- ?? new ValidationError([{ code: 'CONTEXT_BUDGET', message: `Model input exceeds ${maxInputChars} characters` }]);
66
+ throw (exceeded?.(maxInputChars) ??
67
+ new ValidationError([
68
+ { code: 'CONTEXT_BUDGET', message: `Model input exceeds ${maxInputChars} characters` },
69
+ ]));
27
70
  }
28
71
  export { commonPrefixLength } from '../utils/text.js';
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Context surface: fragment trust, per-fragment budgets, message assembly, structural audit,
3
+ * the request-local journal and plan assembly.
4
+ *
5
+ * Core owns the guarantees here. A fragment declares its trust, lifetime and character
6
+ * budget in one place; assembly validates those declarations and refuses to truncate;
7
+ * auditing rejects structural change to protected fragments. Selection, ordering, compression
8
+ * and model choice remain App-side nodes that run before this boundary.
9
+ *
10
+ * Exports: `assembleFragments`, `assembleContextPlan`, `ContextJournal`, the fragment helpers,
11
+ * and the evidence Kit helpers consumed alongside assembled context.
12
+ */
1
13
  export * from './fragments.js';
2
14
  export { assembleFragments } from './assembly.js';
3
15
  export * from './journal.js';
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Context surface: fragment trust, per-fragment budgets, message assembly, structural audit,
3
+ * the request-local journal and plan assembly.
4
+ *
5
+ * Core owns the guarantees here. A fragment declares its trust, lifetime and character
6
+ * budget in one place; assembly validates those declarations and refuses to truncate;
7
+ * auditing rejects structural change to protected fragments. Selection, ordering, compression
8
+ * and model choice remain App-side nodes that run before this boundary.
9
+ *
10
+ * Exports: `assembleFragments`, `assembleContextPlan`, `ContextJournal`, the fragment helpers,
11
+ * and the evidence Kit helpers consumed alongside assembled context.
12
+ */
1
13
  export * from './fragments.js';
2
14
  export { assembleFragments } from './assembly.js';
3
15
  export * from './journal.js';
@@ -3,16 +3,47 @@ import type { ToolJournal, ToolJournalStart, ToolJournalFinish } from '../struct
3
3
  import type { ContextRecord } from '../structs/context/journal.js';
4
4
  /** Request-local context projection of execution receipts; not a separate persistent log store. */
5
5
  export declare class ContextJournal implements ToolJournal {
6
+ /** Append-only: `producerSequence` is derived from this length, so order is never rewritten. */
6
7
  private readonly records;
8
+ /** Duplicate invocation ids are rejected instead of overwriting earlier history. */
7
9
  private readonly invocationIds;
10
+ /** Open tool calls, so a result can only close a call that actually started. */
8
11
  private readonly toolCalls;
9
- model({ stageId, value, invocation }: {
12
+ /**
13
+ * Record one model-produced value.
14
+ *
15
+ * @param options.stageId Stage that produced the value.
16
+ * @param options.value Value to record; deep-cloned on write.
17
+ * @param options.invocation Execution identity whose `invocationId` must not be in the journal.
18
+ * @returns Nothing.
19
+ * @throws Error when the invocation id was already recorded.
20
+ */
21
+ model({ stageId, value, invocation, }: {
10
22
  stageId: string;
11
23
  value: unknown;
12
24
  invocation: InvocationMetadata;
13
25
  }): void;
26
+ /**
27
+ * Open a tool call.
28
+ *
29
+ * @param request Tool id, input and optional invocation metadata. A supplied invocation id is
30
+ * kept so Core records and the journal share one identity; otherwise a new id is generated.
31
+ * @returns The invocation id that must be used to finish the call.
32
+ * @throws Error when a call with that id is already recorded.
33
+ */
14
34
  beginTool({ toolId, input, invocation }: ToolJournalStart): string;
35
+ /**
36
+ * Close an open tool call with its outcome.
37
+ *
38
+ * @param request Invocation id, terminal status and result value; the value is cloned into
39
+ * the record.
40
+ * @returns Nothing.
41
+ * @throws Error when the call is unknown or was already finished.
42
+ */
15
43
  finishTool({ invocationId, status, value }: ToolJournalFinish): void;
44
+ /**
45
+ * @returns A detached copy of every record, safe for the caller to mutate.
46
+ */
16
47
  snapshot(): readonly ContextRecord[];
17
48
  }
18
49
  export type { ContextRecord } from '../structs/context/journal.js';
@@ -1,35 +1,112 @@
1
+ /**
2
+ * Request-local journal of context-relevant execution receipts.
3
+ *
4
+ * It records what was produced (model values, tool inputs) and what came back (tool results),
5
+ * each stamped with a monotonic producer sequence so a snapshot replays in order. Values are
6
+ * deep-cloned on write and on read: a caller mutating its own object cannot retroactively
7
+ * change recorded history, and a snapshot is not a live window into the journal.
8
+ *
9
+ * This is a projection, not a persistent log store; storage and retention belong to the App.
10
+ *
11
+ * Exports: `ContextJournal` and the `ContextRecord` type.
12
+ */
1
13
  import { invocationId as nextInvocationId } from '../utils/invocation.js';
2
14
  /** Request-local context projection of execution receipts; not a separate persistent log store. */
3
15
  export class ContextJournal {
16
+ /** Append-only: `producerSequence` is derived from this length, so order is never rewritten. */
4
17
  records = [];
18
+ /** Duplicate invocation ids are rejected instead of overwriting earlier history. */
5
19
  invocationIds = new Set();
20
+ /** Open tool calls, so a result can only close a call that actually started. */
6
21
  toolCalls = new Map();
7
- model({ stageId, value, invocation }) {
22
+ /**
23
+ * Record one model-produced value.
24
+ *
25
+ * @param options.stageId Stage that produced the value.
26
+ * @param options.value Value to record; deep-cloned on write.
27
+ * @param options.invocation Execution identity whose `invocationId` must not be in the journal.
28
+ * @returns Nothing.
29
+ * @throws Error when the invocation id was already recorded.
30
+ */
31
+ model({ stageId, value, invocation, }) {
8
32
  if (this.invocationIds.has(invocation.invocationId))
9
33
  throw new Error('Duplicate journal invocation');
10
- this.records.push({ ...invocation, producerSequence: this.records.length + 1, occurredAtMs: Date.now(), type: 'model', stageId, value: structuredClone(value) });
34
+ this.records.push({
35
+ ...invocation,
36
+ // Derived from the append position, so the sequence stays gap-free without a counter.
37
+ producerSequence: this.records.length + 1,
38
+ occurredAtMs: Date.now(),
39
+ type: 'model',
40
+ stageId,
41
+ value: structuredClone(value),
42
+ });
11
43
  this.invocationIds.add(invocation.invocationId);
12
44
  }
45
+ /**
46
+ * Open a tool call.
47
+ *
48
+ * @param request Tool id, input and optional invocation metadata. A supplied invocation id is
49
+ * kept so Core records and the journal share one identity; otherwise a new id is generated.
50
+ * @returns The invocation id that must be used to finish the call.
51
+ * @throws Error when a call with that id is already recorded.
52
+ */
13
53
  beginTool({ toolId, input, invocation }) {
14
54
  const invocationId = invocation?.invocationId ?? nextInvocationId();
15
55
  if (this.invocationIds.has(invocationId))
16
56
  throw new Error('Duplicate journal invocation');
17
- const record = { ...invocation, invocationId, startedAtMs: invocation?.startedAtMs ?? Date.now(), durationMs: 0, producerSequence: this.records.length + 1, occurredAtMs: Date.now(), type: 'tool', toolId, input: structuredClone(input) };
57
+ const record = {
58
+ ...invocation,
59
+ invocationId,
60
+ startedAtMs: invocation?.startedAtMs ?? Date.now(),
61
+ durationMs: 0,
62
+ producerSequence: this.records.length + 1,
63
+ occurredAtMs: Date.now(),
64
+ type: 'tool',
65
+ toolId,
66
+ input: structuredClone(input),
67
+ };
18
68
  this.records.push(record);
19
69
  this.invocationIds.add(invocationId);
20
70
  this.toolCalls.set(invocationId, { record, finished: false });
21
71
  return invocationId;
22
72
  }
73
+ /**
74
+ * Close an open tool call with its outcome.
75
+ *
76
+ * @param request Invocation id, terminal status and result value; the value is cloned into
77
+ * the record.
78
+ * @returns Nothing.
79
+ * @throws Error when the call is unknown or was already finished.
80
+ */
23
81
  finishTool({ invocationId, status, value }) {
24
82
  const entry = this.toolCalls.get(invocationId);
25
83
  if (!entry || entry.finished)
26
84
  throw new Error('Invalid tool receipt');
27
85
  const call = entry.record;
28
86
  const occurredAtMs = Date.now();
29
- this.records.push({ invocationId, runId: call.runId, spanId: call.spanId, parentSpanId: call.parentSpanId, parentInvocationId: call.parentInvocationId,
30
- startedAtMs: call.startedAtMs, durationMs: occurredAtMs - call.startedAtMs,
31
- producerSequence: this.records.length + 1, occurredAtMs, type: 'tool-result', toolId: call.toolId, status, value: structuredClone(value) });
87
+ this.records.push({
88
+ invocationId,
89
+ runId: call.runId,
90
+ spanId: call.spanId,
91
+ parentSpanId: call.parentSpanId,
92
+ parentInvocationId: call.parentInvocationId,
93
+ startedAtMs: call.startedAtMs,
94
+ durationMs: occurredAtMs - call.startedAtMs,
95
+ producerSequence: this.records.length + 1,
96
+ occurredAtMs,
97
+ type: 'tool-result',
98
+ toolId: call.toolId,
99
+ status,
100
+ value: structuredClone(value),
101
+ });
102
+ // Kept after finishing, so a repeated finish is rejected instead of appending a second
103
+ // result for the same call.
32
104
  entry.finished = true;
33
105
  }
34
- snapshot() { return structuredClone(this.records); }
106
+ /**
107
+ * @returns A detached copy of every record, safe for the caller to mutate.
108
+ */
109
+ snapshot() {
110
+ return structuredClone(this.records);
111
+ }
35
112
  }
@@ -1,4 +1,14 @@
1
1
  import type { ContextPlan } from '../structs/context/processing.js';
2
2
  import type { BuiltContext } from '../structs/context/fragments.js';
3
- /** Generic input assembly only. Reduction, grouping and model selection are App-side nodes. */
3
+ /**
4
+ * Build the model input for a context plan.
5
+ *
6
+ * @param plan Fragments, their budget, optional protected user messages, and the optional
7
+ * originals/allow-list used for the structural audit.
8
+ * @returns The assembled context, including appended user messages and the final character
9
+ * count that was checked against the budget.
10
+ * @throws ValidationError when the audit fails, a fragment is invalid or over its budget, or
11
+ * the combined input exceeds the budget.
12
+ * @throws Error when an additional message is not a user message.
13
+ */
4
14
  export declare function assembleContextPlan(plan: ContextPlan): BuiltContext;
@@ -1,15 +1,43 @@
1
+ /**
2
+ * Assembly of a `ContextPlan`: the Core-side step between App context processing and the
3
+ * model input budget.
4
+ *
5
+ * A plan may carry trusted originals and an explicit mutation allow-list; when it does, the
6
+ * current fragments are audited before assembly. Assembly itself only validates, merges and
7
+ * measures. Reduction, grouping and model selection happen in App-side nodes before this
8
+ * point.
9
+ *
10
+ * Exports: `assembleContextPlan`.
11
+ */
1
12
  import { auditContextChange } from './audit.js';
2
13
  import { breakWhile } from '../utils/rules.js';
3
14
  import { assembleFragments } from './assembly.js';
4
15
  import { validateContextBudget } from './fragments.js';
5
- /** Generic input assembly only. Reduction, grouping and model selection are App-side nodes. */
16
+ /**
17
+ * Build the model input for a context plan.
18
+ *
19
+ * @param plan Fragments, their budget, optional protected user messages, and the optional
20
+ * originals/allow-list used for the structural audit.
21
+ * @returns The assembled context, including appended user messages and the final character
22
+ * count that was checked against the budget.
23
+ * @throws ValidationError when the audit fails, a fragment is invalid or over its budget, or
24
+ * the combined input exceeds the budget.
25
+ * @throws Error when an additional message is not a user message.
26
+ */
6
27
  export function assembleContextPlan(plan) {
28
+ // Audit first: a structural violation must surface as a policy error rather than be masked
29
+ // by a later budget or field-merge failure on fragments the plan did not allow to change.
7
30
  if (plan.originalFragments)
8
31
  auditContextChange(plan.originalFragments, plan.fragments, new Set(plan.mutableFragmentIds ?? []));
9
32
  const context = assembleFragments([...plan.fragments], plan.maxInputChars);
33
+ // Detach caller-owned messages: the built context must not change if the plan object is
34
+ // reused or mutated after assembly.
10
35
  const additional = structuredClone([...(plan.additionalMessages ?? [])]);
11
- breakWhile(additional.some(message => message.role !== 'user' || typeof message.content !== 'string'), 'Additional context must be user messages');
36
+ // Only user messages may be appended: the system instruction is fixed by the fragments above.
37
+ breakWhile(additional.some((message) => message.role !== 'user' || typeof message.content !== 'string'), 'Additional context must be user messages');
12
38
  context.messages.push(...additional);
39
+ // The per-fragment budget already passed; this re-check covers the appended messages, which
40
+ // are outside every fragment's limit.
13
41
  context.inputChars += additional.reduce((sum, message) => sum + message.content.length, 0);
14
42
  validateContextBudget(context.inputChars, context.maxInputChars);
15
43
  return context;
@@ -1,7 +1,15 @@
1
1
  export const coreEventCatalog = {
2
- 'node.progress': 'metadata', 'model.start': 'metadata',
3
- 'model.binding': 'metadata', 'model.prepare': 'content', 'model.output': 'content', 'model.parsed': 'content', 'model.end': 'metadata',
2
+ 'node.progress': 'metadata',
3
+ 'model.start': 'metadata',
4
+ 'model.binding': 'metadata',
5
+ 'model.prepare': 'content',
6
+ 'model.output': 'content',
7
+ 'model.parsed': 'content',
8
+ 'model.end': 'metadata',
4
9
  'runtime.rejected': 'metadata',
5
- 'loop.event': 'metadata', 'workflow.event': 'metadata', 'tool.call': 'metadata', 'tool.result': 'metadata',
10
+ 'loop.event': 'metadata',
11
+ 'workflow.event': 'metadata',
12
+ 'tool.call': 'metadata',
13
+ 'tool.result': 'metadata',
6
14
  'rule.result': 'metadata',
7
15
  };
@@ -3,8 +3,36 @@ export * from '../structs/diagnostics.js';
3
3
  export * from './catalog.js';
4
4
  export type * from '../structs/debug.js';
5
5
  export { reportedStepStatusCatalog, reportedStepStatuses } from '../structs/debug.js';
6
- /** Configure the optional log consumer of the shared execution fact source. */
6
+ /**
7
+ * Configure the optional log consumer of the shared execution fact source.
8
+ *
9
+ * @param options.output Log consumer. Without it, events are still observable but not persisted.
10
+ * @param options.observe Live observer applied to this scope and every child scope.
11
+ * @param options.runId Run identity; a random id is generated when omitted.
12
+ * @param options.spanId Root span id; defaults to `run`.
13
+ * @returns A diagnostic context whose children share the run, sequence and consumers.
14
+ */
7
15
  export declare function createDiagnostics(options?: CreateDiagnosticsOptions): DiagnosticContext;
16
+ /**
17
+ * Convert a thrown value into a plain record suitable as a log payload.
18
+ *
19
+ * @param error Any thrown value. Non-Errors are reported as `NonError` with their string form
20
+ * and no issue details.
21
+ * @returns A record with name, message, stack, code, issues and whatever boundary metadata was
22
+ * recorded. It never throws: an uninspectable value becomes `UninspectableError`.
23
+ */
8
24
  export declare function diagnosticError(error: unknown): Record<string, unknown>;
9
- /** Validate the current envelope and return a detached record without interpreting payloads. */
25
+ /**
26
+ * Validate a persisted diagnostic record and return a detached copy.
27
+ *
28
+ * Persisted data is untrusted, so the envelope version, event type, identity, ordering and the
29
+ * bounded sub-step shape are checked; the payload itself is not interpreted. The copy is deep
30
+ * cloned, so a store cannot hand back a record that later shares structure with the caller.
31
+ *
32
+ * @param input Candidate record, typically parsed JSON from a log store.
33
+ * @returns A normalized record with `subSteps`, `subStepsDropped` and `subStepsTruncated`
34
+ * defaulted.
35
+ * @throws TypeError when the envelope, identity, node role or reported steps are invalid.
36
+ * @throws RangeError when a reported payload is too large or too deeply nested.
37
+ */
10
38
  export declare function normalizeDiagnosticEvent(input: unknown): import('../structs/diagnostics.js').CoreDiagnosticRecord;
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Core diagnostics surface: one execution fact source shared by live observers and an optional
3
+ * log consumer.
4
+ *
5
+ * `createDiagnostics` configures the consumer, `diagnosticError` turns an arbitrary thrown value
6
+ * into a loggable record, and `normalizeDiagnosticEvent` re-validates a persisted record before
7
+ * it is trusted. Payload visibility comes from the event catalog, and a failing consumer never
8
+ * changes execution.
9
+ *
10
+ * Exports: the factory and helpers above, the event catalog, and the diagnostic types.
11
+ */
1
12
  import { createEventScope } from '../execution/events.js';
2
13
  import { reportedStepStatuses } from '../structs/debug.js';
3
14
  import { getErrorInfo } from '../errors.js';
@@ -7,10 +18,26 @@ import { breakWhile } from '../utils/rules.js';
7
18
  export * from '../structs/diagnostics.js';
8
19
  export * from './catalog.js';
9
20
  export { reportedStepStatusCatalog, reportedStepStatuses } from '../structs/debug.js';
10
- /** Configure the optional log consumer of the shared execution fact source. */
21
+ /**
22
+ * Configure the optional log consumer of the shared execution fact source.
23
+ *
24
+ * @param options.output Log consumer. Without it, events are still observable but not persisted.
25
+ * @param options.observe Live observer applied to this scope and every child scope.
26
+ * @param options.runId Run identity; a random id is generated when omitted.
27
+ * @param options.spanId Root span id; defaults to `run`.
28
+ * @returns A diagnostic context whose children share the run, sequence and consumers.
29
+ */
11
30
  export function createDiagnostics(options = {}) {
12
31
  return createEventScope(options);
13
32
  }
33
+ /**
34
+ * Convert a thrown value into a plain record suitable as a log payload.
35
+ *
36
+ * @param error Any thrown value. Non-Errors are reported as `NonError` with their string form
37
+ * and no issue details.
38
+ * @returns A record with name, message, stack, code, issues and whatever boundary metadata was
39
+ * recorded. It never throws: an uninspectable value becomes `UninspectableError`.
40
+ */
14
41
  export function diagnosticError(error) {
15
42
  const info = getErrorInfo(error);
16
43
  let detail;
@@ -18,43 +45,96 @@ export function diagnosticError(error) {
18
45
  if (!(error instanceof Error))
19
46
  return { name: 'NonError', message: String(error) };
20
47
  const { name, message, stack, code } = error;
21
- detail = { name, message, stack, code: code ?? (info.code === 'UNKNOWN_ERROR' ? undefined : info.code) };
48
+ detail = {
49
+ name,
50
+ message,
51
+ stack,
52
+ code: code ?? (info.code === 'UNKNOWN_ERROR' ? undefined : info.code),
53
+ };
22
54
  }
23
55
  catch {
24
- detail = { name: 'UninspectableError', message: 'Error details unavailable', code: info.code === 'UNKNOWN_ERROR' ? undefined : info.code };
56
+ detail = {
57
+ name: 'UninspectableError',
58
+ message: 'Error details unavailable',
59
+ code: info.code === 'UNKNOWN_ERROR' ? undefined : info.code,
60
+ };
25
61
  }
26
- return { ...detail, issues: info.issues,
62
+ return {
63
+ ...detail,
64
+ issues: info.issues,
27
65
  ...(info.stageId === undefined ? {} : { stageId: info.stageId }),
28
- ...(info.isRetryable === undefined ? {} : { isRetryable: info.isRetryable }) };
66
+ ...(info.isRetryable === undefined ? {} : { isRetryable: info.isRetryable }),
67
+ };
29
68
  }
30
- /** Validate the current envelope and return a detached record without interpreting payloads. */
69
+ /**
70
+ * Validate a persisted diagnostic record and return a detached copy.
71
+ *
72
+ * Persisted data is untrusted, so the envelope version, event type, identity, ordering and the
73
+ * bounded sub-step shape are checked; the payload itself is not interpreted. The copy is deep
74
+ * cloned, so a store cannot hand back a record that later shares structure with the caller.
75
+ *
76
+ * @param input Candidate record, typically parsed JSON from a log store.
77
+ * @returns A normalized record with `subSteps`, `subStepsDropped` and `subStepsTruncated`
78
+ * defaulted.
79
+ * @throws TypeError when the envelope, identity, node role or reported steps are invalid.
80
+ * @throws RangeError when a reported payload is too large or too deeply nested.
81
+ */
31
82
  export function normalizeDiagnosticEvent(input) {
32
83
  if (!input || typeof input !== 'object')
33
84
  throw new TypeError('Invalid diagnostic record');
34
85
  const raw = input;
86
+ // The version gates the whole layout: an older record may use different fields, so it is
87
+ // rejected instead of best-effort coerced.
35
88
  if (raw.version !== 2)
36
89
  throw new TypeError('Unsupported diagnostic version');
37
90
  const { type, producerSequence, occurredAtMs } = raw;
38
- if (typeof type !== 'string' || !Object.hasOwn(coreEventCatalog, type) || typeof raw.runId !== 'string' || !raw.runId
39
- || typeof raw.spanId !== 'string' || !raw.spanId || !Number.isSafeInteger(producerSequence) || Number(producerSequence) < 1
40
- || typeof occurredAtMs !== 'number' || !Number.isFinite(occurredAtMs) || !Object.hasOwn(raw, 'payload'))
91
+ if (typeof type !== 'string' ||
92
+ !Object.hasOwn(coreEventCatalog, type) ||
93
+ typeof raw.runId !== 'string' ||
94
+ !raw.runId ||
95
+ typeof raw.spanId !== 'string' ||
96
+ !raw.spanId ||
97
+ !Number.isSafeInteger(producerSequence) ||
98
+ Number(producerSequence) < 1 ||
99
+ typeof occurredAtMs !== 'number' ||
100
+ !Number.isFinite(occurredAtMs) ||
101
+ !Object.hasOwn(raw, 'payload'))
41
102
  throw new TypeError('Invalid diagnostic envelope');
42
103
  const { eventId } = raw;
43
104
  if (typeof eventId !== 'string' || !eventId)
44
105
  throw new TypeError('Invalid diagnostic event identity');
45
106
  const steps = raw.subSteps ?? [];
46
- if (!Array.isArray(steps) || steps.length > 256 || new Set(steps.map(step => step?.stepId)).size !== steps.length
47
- || steps.some(step => !step || step.origin !== 'reported' || typeof step.stepId !== 'string' || !step.stepId.trim()
48
- || typeof step.name !== 'string' || typeof step.kind !== 'string' || !Number.isSafeInteger(step.sequence) || step.sequence < 1
49
- || (step.status !== undefined && !reportedStepStatuses.includes(step.status))
50
- || ['parentStepId', 'relatedDefinitionId', 'caseId', 'summary'].some(key => step[key] !== undefined && typeof step[key] !== 'string')
51
- || (step.usedModel !== undefined && typeof step.usedModel !== 'boolean')
52
- || (step.revision !== undefined && (!Number.isSafeInteger(step.revision) || step.revision < 1 || !Number.isFinite(step.createdAtMs)))
53
- || ['createdAtMs', 'startedAtMs', 'endedAtMs'].some(key => step[key] !== undefined && (typeof step[key] !== 'number' || !Number.isFinite(step[key]) || step[key] < 0))
54
- || (step.nextStepIds !== undefined && (!Array.isArray(step.nextStepIds) || step.nextStepIds.some((id) => typeof id !== 'string'))))
55
- || (raw.subStepsDropped !== undefined && (!Number.isSafeInteger(raw.subStepsDropped) || Number(raw.subStepsDropped) < 0))
56
- || (raw.subStepsTruncated !== undefined && typeof raw.subStepsTruncated !== 'boolean'))
107
+ // The count and size bounds match what the sub-flow logger enforces, so a record produced by
108
+ // Core can never be rejected here; only hand-edited or foreign records can.
109
+ if (!Array.isArray(steps) ||
110
+ steps.length > 256 ||
111
+ new Set(steps.map((step) => step?.stepId)).size !== steps.length ||
112
+ steps.some((step) => !step ||
113
+ step.origin !== 'reported' ||
114
+ typeof step.stepId !== 'string' ||
115
+ !step.stepId.trim() ||
116
+ typeof step.name !== 'string' ||
117
+ typeof step.kind !== 'string' ||
118
+ !Number.isSafeInteger(step.sequence) ||
119
+ step.sequence < 1 ||
120
+ (step.status !== undefined && !reportedStepStatuses.includes(step.status)) ||
121
+ ['parentStepId', 'relatedDefinitionId', 'caseId', 'summary'].some((key) => step[key] !== undefined && typeof step[key] !== 'string') ||
122
+ (step.usedModel !== undefined && typeof step.usedModel !== 'boolean') ||
123
+ (step.revision !== undefined &&
124
+ (!Number.isSafeInteger(step.revision) ||
125
+ step.revision < 1 ||
126
+ !Number.isFinite(step.createdAtMs))) ||
127
+ ['createdAtMs', 'startedAtMs', 'endedAtMs'].some((key) => step[key] !== undefined &&
128
+ (typeof step[key] !== 'number' || !Number.isFinite(step[key]) || step[key] < 0)) ||
129
+ (step.nextStepIds !== undefined &&
130
+ (!Array.isArray(step.nextStepIds) ||
131
+ step.nextStepIds.some((id) => typeof id !== 'string')))) ||
132
+ (raw.subStepsDropped !== undefined &&
133
+ (!Number.isSafeInteger(raw.subStepsDropped) || Number(raw.subStepsDropped) < 0)) ||
134
+ (raw.subStepsTruncated !== undefined && typeof raw.subStepsTruncated !== 'boolean'))
57
135
  throw new TypeError('Invalid reported diagnostic steps');
136
+ // Structural check only: the returned snapshot is discarded because the clone below already
137
+ // produces the detached copy kept by the normalized record.
58
138
  for (const step of steps)
59
139
  if (step.payload !== undefined)
60
140
  payloadSnapshot(step.payload);
@@ -62,19 +142,59 @@ export function normalizeDiagnosticEvent(input) {
62
142
  breakWhile(raw.usedModel !== undefined && typeof raw.usedModel !== 'boolean', () => new TypeError('Invalid reported model use'));
63
143
  if (type === 'node.progress') {
64
144
  const progress = raw.payload?.subStep;
65
- breakWhile(progress !== undefined && (!progress || !['write', 'fix'].includes(progress.operation) || typeof progress.stepId !== 'string' || !progress.stepId
66
- || !Number.isSafeInteger(progress.sequence) || progress.sequence < 1 || !Number.isSafeInteger(progress.revision) || progress.revision < 1
67
- || !Number.isFinite(progress.createdAtMs) || progress.createdAtMs < 0 || !reportedStepStatuses.includes(progress.status)
68
- || (progress.usedModel !== undefined && typeof progress.usedModel !== 'boolean')), () => new TypeError('Invalid reported sub-step progress'));
145
+ breakWhile(progress !== undefined &&
146
+ (!progress ||
147
+ !['write', 'fix'].includes(progress.operation) ||
148
+ typeof progress.stepId !== 'string' ||
149
+ !progress.stepId ||
150
+ !Number.isSafeInteger(progress.sequence) ||
151
+ progress.sequence < 1 ||
152
+ !Number.isSafeInteger(progress.revision) ||
153
+ progress.revision < 1 ||
154
+ !Number.isFinite(progress.createdAtMs) ||
155
+ progress.createdAtMs < 0 ||
156
+ !reportedStepStatuses.includes(progress.status) ||
157
+ (progress.usedModel !== undefined && typeof progress.usedModel !== 'boolean')), () => new TypeError('Invalid reported sub-step progress'));
69
158
  }
70
- for (const key of ['parentSpanId', 'invocationId', 'parentInvocationId', 'workflowInvocationId', 'workflowNodeId', 'agentId', 'branchId', 'agentVersionId', 'parentBranchId', 'parentAgentVersionId', 'forkPointId', 'definitionId', 'definitionKind', 'definitionRevision', 'nodeId', 'nodeName', 'nodeKind', 'nodeDescription', 'stageId', 'modelId']) {
159
+ for (const key of [
160
+ 'parentSpanId',
161
+ 'invocationId',
162
+ 'parentInvocationId',
163
+ 'workflowInvocationId',
164
+ 'workflowNodeId',
165
+ 'agentId',
166
+ 'branchId',
167
+ 'agentVersionId',
168
+ 'parentBranchId',
169
+ 'parentAgentVersionId',
170
+ 'forkPointId',
171
+ 'definitionId',
172
+ 'definitionKind',
173
+ 'definitionRevision',
174
+ 'nodeId',
175
+ 'nodeName',
176
+ 'nodeKind',
177
+ 'nodeDescription',
178
+ 'stageId',
179
+ 'modelId',
180
+ ]) {
71
181
  if (raw[key] !== undefined && typeof raw[key] !== 'string')
72
182
  throw new TypeError('Invalid diagnostic identity');
73
183
  }
74
- if (raw.nodeRole !== undefined && !['workflow-node', 'workflow-boundary', 'invocation', 'loop-step'].includes(String(raw.nodeRole)))
184
+ if (raw.nodeRole !== undefined &&
185
+ !['workflow-node', 'workflow-boundary', 'invocation', 'loop-step'].includes(String(raw.nodeRole)))
75
186
  throw new TypeError('Invalid diagnostic node role');
187
+ // Detached copy: the caller's object may be reused, frozen or backed by a store buffer.
76
188
  const copy = structuredClone(raw);
77
- return { ...copy, version: 2, eventId, type, producerSequence, occurredAtMs,
78
- subSteps: copy.subSteps ?? [], subStepsDropped: copy.subStepsDropped ?? 0,
79
- subStepsTruncated: copy.subStepsTruncated ?? false };
189
+ return {
190
+ ...copy,
191
+ version: 2,
192
+ eventId,
193
+ type,
194
+ producerSequence,
195
+ occurredAtMs,
196
+ subSteps: copy.subSteps ?? [],
197
+ subStepsDropped: copy.subStepsDropped ?? 0,
198
+ subStepsTruncated: copy.subStepsTruncated ?? false,
199
+ };
80
200
  }