@jangts/agent-core 0.1.0 → 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 (527) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +59 -0
  3. package/development/docs/api/reference.md +1907 -1874
  4. package/development/docs/api/support.md +27 -0
  5. package/development/docs/assets/agent-core-icon.png +0 -0
  6. package/development/docs/assets/agent-core-logo.png +0 -0
  7. package/development/docs/assets/character-agent-core.png +0 -0
  8. package/development/skills/agent-core-app/scripts/create-app.mjs +267 -70
  9. package/development/skills/agent-core-app/scripts/lib/knowledge.mjs +40 -15
  10. package/development/skills/agent-core-app/scripts/lib/source.mjs +30 -2
  11. package/development/skills/agent-core-app/scripts/plan.mjs +37 -12
  12. package/development/skills/agent-core-app/scripts/prepare-source.mjs +61 -10
  13. package/development/skills/agent-core-app/scripts/resources.mjs +45 -17
  14. package/development/skills/agent-core-app/scripts/validate-knowledge.mjs +18 -1
  15. package/development/skills/agent-core-app/templates/catalog.json +36 -22
  16. package/dist/cjs/capabilities/index.js +13 -0
  17. package/dist/cjs/capabilities/invocation.js +80 -10
  18. package/dist/cjs/capabilities/model.js +126 -13
  19. package/dist/cjs/capabilities/tool-runtime.js +64 -12
  20. package/dist/cjs/capabilities/tools.js +266 -31
  21. package/dist/cjs/context/assembly.js +46 -5
  22. package/dist/cjs/context/audit.js +31 -6
  23. package/dist/cjs/context/fragments.js +54 -11
  24. package/dist/cjs/context/index.js +12 -0
  25. package/dist/cjs/context/journal.js +84 -7
  26. package/dist/cjs/context/plan.js +30 -2
  27. package/dist/cjs/diagnostics/catalog.js +11 -3
  28. package/dist/cjs/diagnostics/index.js +149 -29
  29. package/dist/cjs/diagnostics/sub-flow.js +240 -40
  30. package/dist/cjs/errors.js +99 -17
  31. package/dist/cjs/execution/branch.js +20 -4
  32. package/dist/cjs/execution/engine.js +470 -56
  33. package/dist/cjs/execution/events.js +136 -18
  34. package/dist/cjs/execution/index.js +7 -0
  35. package/dist/cjs/execution/reporting.js +75 -6
  36. package/dist/cjs/execution/state.js +161 -22
  37. package/dist/cjs/execution/workflow.js +224 -32
  38. package/dist/cjs/index.js +18 -0
  39. package/dist/cjs/kits/aggregation.js +45 -3
  40. package/dist/cjs/kits/answering/batch.js +23 -4
  41. package/dist/cjs/kits/answering/check-result.js +31 -8
  42. package/dist/cjs/kits/answering/checks.js +24 -3
  43. package/dist/cjs/kits/answering/flow.js +192 -36
  44. package/dist/cjs/kits/answering/index.js +19 -1
  45. package/dist/cjs/kits/answering/tasks.js +88 -13
  46. package/dist/cjs/kits/artifacts.js +36 -4
  47. package/dist/cjs/kits/candidates.js +47 -5
  48. package/dist/cjs/kits/delivery.js +40 -5
  49. package/dist/cjs/kits/durable.js +155 -31
  50. package/dist/cjs/kits/evidence.js +66 -15
  51. package/dist/cjs/kits/family.js +152 -22
  52. package/dist/cjs/kits/index.js +12 -1
  53. package/dist/cjs/kits/inference.js +104 -16
  54. package/dist/cjs/kits/intents/catalog.js +67 -16
  55. package/dist/cjs/kits/intents/index.js +11 -0
  56. package/dist/cjs/kits/intents/registry.js +188 -43
  57. package/dist/cjs/kits/intents/scopes.js +215 -46
  58. package/dist/cjs/kits/interaction/command.js +140 -36
  59. package/dist/cjs/kits/interaction/commands.js +86 -11
  60. package/dist/cjs/kits/interaction/handlers.js +27 -10
  61. package/dist/cjs/kits/interaction/index.js +10 -0
  62. package/dist/cjs/kits/interaction/transfer.js +80 -14
  63. package/dist/cjs/kits/knowledge/catalog.js +62 -11
  64. package/dist/cjs/kits/knowledge/index.js +16 -1
  65. package/dist/cjs/kits/knowledge/publication.js +99 -23
  66. package/dist/cjs/kits/knowledge/sections.js +33 -4
  67. package/dist/cjs/kits/normalization.js +51 -7
  68. package/dist/cjs/kits/policies.js +79 -15
  69. package/dist/cjs/kits/presentation/events.js +54 -10
  70. package/dist/cjs/kits/presentation/index.js +24 -1
  71. package/dist/cjs/kits/presentation/outputs.js +176 -38
  72. package/dist/cjs/kits/presentation/templates.js +33 -5
  73. package/dist/cjs/kits/presentation/variants.js +31 -2
  74. package/dist/cjs/kits/projection.js +63 -8
  75. package/dist/cjs/kits/rank-fusion.js +27 -4
  76. package/dist/cjs/kits/reflection-log-source.js +89 -16
  77. package/dist/cjs/kits/reflection.js +234 -60
  78. package/dist/cjs/kits/retrieval.js +98 -18
  79. package/dist/cjs/kits/search.js +180 -27
  80. package/dist/cjs/kits/text-skills.js +104 -19
  81. package/dist/cjs/kits/tools.js +415 -74
  82. package/dist/cjs/kits/vector-search.js +50 -16
  83. package/dist/cjs/mock/node.js +7 -1
  84. package/dist/cjs/mock/web.js +7 -1
  85. package/dist/cjs/mock.js +7 -1
  86. package/dist/cjs/model/binding.js +68 -17
  87. package/dist/cjs/model/call-budget.js +45 -4
  88. package/dist/cjs/model/decision-retry.js +19 -1
  89. package/dist/cjs/model/defaults.js +27 -4
  90. package/dist/cjs/model/index.js +7 -0
  91. package/dist/cjs/model/interactions/arguments.js +36 -1
  92. package/dist/cjs/model/interactions/json-object.js +48 -12
  93. package/dist/cjs/model/interactions/native-functions.js +52 -10
  94. package/dist/cjs/model/message-diagnostics.js +17 -4
  95. package/dist/cjs/model/options.js +9 -1
  96. package/dist/cjs/model/preparation.js +86 -12
  97. package/dist/cjs/model/runner.js +413 -79
  98. package/dist/cjs/model/selection-transport.js +48 -8
  99. package/dist/cjs/model/settings.js +67 -13
  100. package/dist/cjs/model/token-budget.js +69 -11
  101. package/dist/cjs/model/transports.js +59 -6
  102. package/dist/cjs/structs/common.js +11 -0
  103. package/dist/cjs/structs/debug.js +34 -5
  104. package/dist/cjs/structs/errors.js +26 -1
  105. package/dist/cjs/structs/index.js +11 -1
  106. package/dist/cjs/structs/kits/durable.js +7 -0
  107. package/dist/cjs/structs/kits/family.js +1 -0
  108. package/dist/cjs/structs/kits/interaction.js +8 -1
  109. package/dist/cjs/structs/kits/knowledge-publication.js +1 -0
  110. package/dist/cjs/structs/kits/reflection.js +18 -3
  111. package/dist/cjs/structs/model/chat-provider.js +6 -0
  112. package/dist/cjs/structs/support/model/completion.js +2 -0
  113. package/dist/cjs/structs/support/model/messages.js +2 -0
  114. package/dist/cjs/support/capabilities.js +43 -6
  115. package/dist/cjs/support/context/assembly.js +88 -16
  116. package/dist/cjs/support/context/compression.js +48 -6
  117. package/dist/cjs/support/context/fragments.js +6 -0
  118. package/dist/cjs/support/context/history.js +36 -1
  119. package/dist/cjs/support/context/index.js +11 -0
  120. package/dist/cjs/support/context/nodes.js +164 -35
  121. package/dist/cjs/support/context/processing.js +319 -61
  122. package/dist/cjs/support/context/selection-policy.js +98 -21
  123. package/dist/cjs/support/context/selection.js +61 -10
  124. package/dist/cjs/support/context/snapshot.js +29 -7
  125. package/dist/cjs/support/context/strategies.js +120 -28
  126. package/dist/cjs/support/index.js +9 -1
  127. package/dist/cjs/support/model/capabilities.js +20 -1
  128. package/dist/cjs/support/model/chat-completions.js +92 -20
  129. package/dist/cjs/support/model/children.js +34 -6
  130. package/dist/cjs/support/model/compatible-provider.js +189 -59
  131. package/dist/cjs/support/model/completion/calls.js +61 -0
  132. package/dist/cjs/support/model/completion/default.js +32 -0
  133. package/dist/cjs/support/model/completion/index.js +28 -0
  134. package/dist/cjs/support/model/completion/session.js +102 -0
  135. package/dist/cjs/support/model/index.js +12 -0
  136. package/dist/cjs/support/model/interactions/index.js +12 -1
  137. package/dist/cjs/support/model/interactions/json-object.js +6 -0
  138. package/dist/cjs/support/model/interactions/native-functions.js +6 -0
  139. package/dist/cjs/support/model/observer.js +32 -6
  140. package/dist/cjs/support/model/preview-rules.js +66 -16
  141. package/dist/cjs/support/model/reply-preview.js +77 -17
  142. package/dist/cjs/support/model/stage-transport.js +33 -7
  143. package/dist/cjs/support/model/strategies.js +75 -14
  144. package/dist/cjs/support/model/transports.js +53 -11
  145. package/dist/cjs/support/registration.js +49 -7
  146. package/dist/cjs/support/schema.js +46 -4
  147. package/dist/cjs/support/stream-events.js +60 -8
  148. package/dist/cjs/support/tool-runtime.js +6 -0
  149. package/dist/cjs/support/tools.js +79 -10
  150. package/dist/cjs/support/transport/index.js +7 -0
  151. package/dist/cjs/support/transport/json.js +28 -4
  152. package/dist/cjs/support/transport/sse.js +25 -2
  153. package/dist/cjs/utils/break-observer.js +20 -2
  154. package/dist/cjs/utils/cancellation.js +77 -9
  155. package/dist/cjs/utils/catalog.js +19 -4
  156. package/dist/cjs/utils/debug.js +14 -2
  157. package/dist/cjs/utils/index.js +8 -0
  158. package/dist/cjs/utils/interaction-definition.js +26 -6
  159. package/dist/cjs/utils/invocation.js +42 -4
  160. package/dist/cjs/utils/model-protocol.js +20 -1
  161. package/dist/cjs/utils/object.js +16 -0
  162. package/dist/cjs/utils/observer.js +22 -2
  163. package/dist/cjs/utils/protocol-registry.js +47 -4
  164. package/dist/cjs/utils/query-key.js +21 -2
  165. package/dist/cjs/utils/registration.js +18 -2
  166. package/dist/cjs/utils/rules.js +39 -11
  167. package/dist/cjs/utils/schema-adapter.js +25 -2
  168. package/dist/cjs/utils/synchronous.js +64 -7
  169. package/dist/cjs/utils/text.js +15 -1
  170. package/dist/esm/capabilities/index.d.ts +13 -0
  171. package/dist/esm/capabilities/index.js +13 -0
  172. package/dist/esm/capabilities/invocation.d.ts +16 -2
  173. package/dist/esm/capabilities/invocation.js +80 -10
  174. package/dist/esm/capabilities/model.d.ts +68 -1
  175. package/dist/esm/capabilities/model.js +126 -13
  176. package/dist/esm/capabilities/tool-runtime.d.ts +11 -0
  177. package/dist/esm/capabilities/tool-runtime.js +64 -12
  178. package/dist/esm/capabilities/tools.d.ts +96 -3
  179. package/dist/esm/capabilities/tools.js +267 -32
  180. package/dist/esm/context/assembly.d.ts +13 -2
  181. package/dist/esm/context/assembly.js +46 -5
  182. package/dist/esm/context/audit.d.ts +23 -1
  183. package/dist/esm/context/audit.js +31 -6
  184. package/dist/esm/context/fragments.d.ts +37 -3
  185. package/dist/esm/context/fragments.js +54 -11
  186. package/dist/esm/context/index.d.ts +12 -0
  187. package/dist/esm/context/index.js +12 -0
  188. package/dist/esm/context/journal.d.ts +32 -1
  189. package/dist/esm/context/journal.js +84 -7
  190. package/dist/esm/context/plan.d.ts +11 -1
  191. package/dist/esm/context/plan.js +30 -2
  192. package/dist/esm/diagnostics/catalog.js +11 -3
  193. package/dist/esm/diagnostics/index.d.ts +30 -2
  194. package/dist/esm/diagnostics/index.js +149 -29
  195. package/dist/esm/diagnostics/sub-flow.d.ts +41 -3
  196. package/dist/esm/diagnostics/sub-flow.js +240 -40
  197. package/dist/esm/errors.d.ts +22 -2
  198. package/dist/esm/errors.js +99 -17
  199. package/dist/esm/execution/branch.d.ts +19 -1
  200. package/dist/esm/execution/branch.js +20 -4
  201. package/dist/esm/execution/engine.d.ts +291 -5
  202. package/dist/esm/execution/engine.js +471 -57
  203. package/dist/esm/execution/events.d.ts +16 -2
  204. package/dist/esm/execution/events.js +136 -18
  205. package/dist/esm/execution/index.d.ts +7 -0
  206. package/dist/esm/execution/index.js +7 -0
  207. package/dist/esm/execution/reporting.d.ts +49 -1
  208. package/dist/esm/execution/reporting.js +75 -6
  209. package/dist/esm/execution/state.d.ts +126 -10
  210. package/dist/esm/execution/state.js +161 -22
  211. package/dist/esm/execution/workflow.d.ts +121 -3
  212. package/dist/esm/execution/workflow.js +224 -32
  213. package/dist/esm/index.d.ts +17 -1
  214. package/dist/esm/index.js +18 -0
  215. package/dist/esm/kits/aggregation.d.ts +34 -2
  216. package/dist/esm/kits/aggregation.js +45 -3
  217. package/dist/esm/kits/answering/batch.d.ts +17 -0
  218. package/dist/esm/kits/answering/batch.js +23 -4
  219. package/dist/esm/kits/answering/check-result.d.ts +18 -1
  220. package/dist/esm/kits/answering/check-result.js +31 -8
  221. package/dist/esm/kits/answering/checks.d.ts +11 -0
  222. package/dist/esm/kits/answering/checks.js +24 -3
  223. package/dist/esm/kits/answering/flow.d.ts +25 -2
  224. package/dist/esm/kits/answering/flow.js +192 -36
  225. package/dist/esm/kits/answering/index.d.ts +12 -0
  226. package/dist/esm/kits/answering/index.js +19 -1
  227. package/dist/esm/kits/answering/tasks.d.ts +32 -1
  228. package/dist/esm/kits/answering/tasks.js +88 -13
  229. package/dist/esm/kits/artifacts.d.ts +11 -0
  230. package/dist/esm/kits/artifacts.js +36 -4
  231. package/dist/esm/kits/candidates.d.ts +23 -1
  232. package/dist/esm/kits/candidates.js +47 -5
  233. package/dist/esm/kits/delivery.d.ts +34 -0
  234. package/dist/esm/kits/delivery.js +40 -5
  235. package/dist/esm/kits/durable.d.ts +19 -0
  236. package/dist/esm/kits/durable.js +155 -31
  237. package/dist/esm/kits/evidence.d.ts +28 -5
  238. package/dist/esm/kits/evidence.js +66 -15
  239. package/dist/esm/kits/family.d.ts +17 -1
  240. package/dist/esm/kits/family.js +152 -22
  241. package/dist/esm/kits/index.d.ts +12 -1
  242. package/dist/esm/kits/index.js +12 -1
  243. package/dist/esm/kits/inference.d.ts +64 -0
  244. package/dist/esm/kits/inference.js +104 -16
  245. package/dist/esm/kits/intents/catalog.d.ts +13 -1
  246. package/dist/esm/kits/intents/catalog.js +67 -16
  247. package/dist/esm/kits/intents/index.d.ts +11 -0
  248. package/dist/esm/kits/intents/index.js +11 -0
  249. package/dist/esm/kits/intents/registry.d.ts +61 -3
  250. package/dist/esm/kits/intents/registry.js +188 -43
  251. package/dist/esm/kits/intents/scopes.d.ts +73 -3
  252. package/dist/esm/kits/intents/scopes.js +215 -46
  253. package/dist/esm/kits/interaction/command.d.ts +38 -4
  254. package/dist/esm/kits/interaction/command.js +140 -36
  255. package/dist/esm/kits/interaction/commands.d.ts +66 -2
  256. package/dist/esm/kits/interaction/commands.js +86 -11
  257. package/dist/esm/kits/interaction/handlers.d.ts +19 -2
  258. package/dist/esm/kits/interaction/handlers.js +27 -10
  259. package/dist/esm/kits/interaction/index.d.ts +10 -0
  260. package/dist/esm/kits/interaction/index.js +10 -0
  261. package/dist/esm/kits/interaction/transfer.d.ts +39 -2
  262. package/dist/esm/kits/interaction/transfer.js +80 -14
  263. package/dist/esm/kits/knowledge/catalog.d.ts +13 -0
  264. package/dist/esm/kits/knowledge/catalog.js +62 -11
  265. package/dist/esm/kits/knowledge/index.d.ts +11 -0
  266. package/dist/esm/kits/knowledge/index.js +16 -1
  267. package/dist/esm/kits/knowledge/publication.d.ts +15 -1
  268. package/dist/esm/kits/knowledge/publication.js +99 -23
  269. package/dist/esm/kits/knowledge/sections.d.ts +31 -1
  270. package/dist/esm/kits/knowledge/sections.js +33 -4
  271. package/dist/esm/kits/normalization.d.ts +25 -2
  272. package/dist/esm/kits/normalization.js +51 -7
  273. package/dist/esm/kits/policies.d.ts +26 -3
  274. package/dist/esm/kits/policies.js +79 -15
  275. package/dist/esm/kits/presentation/events.d.ts +51 -4
  276. package/dist/esm/kits/presentation/events.js +54 -10
  277. package/dist/esm/kits/presentation/index.d.ts +12 -0
  278. package/dist/esm/kits/presentation/index.js +25 -2
  279. package/dist/esm/kits/presentation/outputs.d.ts +30 -1
  280. package/dist/esm/kits/presentation/outputs.js +176 -38
  281. package/dist/esm/kits/presentation/templates.d.ts +32 -3
  282. package/dist/esm/kits/presentation/templates.js +33 -5
  283. package/dist/esm/kits/presentation/variants.d.ts +29 -0
  284. package/dist/esm/kits/presentation/variants.js +31 -2
  285. package/dist/esm/kits/projection.d.ts +42 -5
  286. package/dist/esm/kits/projection.js +63 -8
  287. package/dist/esm/kits/rank-fusion.d.ts +21 -1
  288. package/dist/esm/kits/rank-fusion.js +28 -5
  289. package/dist/esm/kits/reflection-log-source.d.ts +28 -1
  290. package/dist/esm/kits/reflection-log-source.js +89 -16
  291. package/dist/esm/kits/reflection.d.ts +17 -1
  292. package/dist/esm/kits/reflection.js +235 -61
  293. package/dist/esm/kits/retrieval.d.ts +18 -2
  294. package/dist/esm/kits/retrieval.js +98 -18
  295. package/dist/esm/kits/search.d.ts +56 -3
  296. package/dist/esm/kits/search.js +180 -27
  297. package/dist/esm/kits/text-skills.d.ts +16 -2
  298. package/dist/esm/kits/text-skills.js +104 -19
  299. package/dist/esm/kits/tools.d.ts +122 -2
  300. package/dist/esm/kits/tools.js +416 -74
  301. package/dist/esm/kits/vector-search.d.ts +47 -1
  302. package/dist/esm/kits/vector-search.js +51 -17
  303. package/dist/esm/mock/node.d.ts +7 -0
  304. package/dist/esm/mock/node.js +7 -1
  305. package/dist/esm/mock/web.d.ts +7 -0
  306. package/dist/esm/mock/web.js +7 -1
  307. package/dist/esm/mock.d.ts +7 -0
  308. package/dist/esm/mock.js +7 -1
  309. package/dist/esm/model/binding.d.ts +32 -3
  310. package/dist/esm/model/binding.js +68 -17
  311. package/dist/esm/model/call-budget.d.ts +30 -2
  312. package/dist/esm/model/call-budget.js +45 -4
  313. package/dist/esm/model/decision-retry.d.ts +10 -1
  314. package/dist/esm/model/decision-retry.js +19 -1
  315. package/dist/esm/model/defaults.d.ts +13 -2
  316. package/dist/esm/model/defaults.js +27 -4
  317. package/dist/esm/model/index.d.ts +7 -0
  318. package/dist/esm/model/index.js +7 -0
  319. package/dist/esm/model/interactions/arguments.d.ts +27 -0
  320. package/dist/esm/model/interactions/arguments.js +36 -1
  321. package/dist/esm/model/interactions/json-object.d.ts +7 -1
  322. package/dist/esm/model/interactions/json-object.js +48 -12
  323. package/dist/esm/model/interactions/native-functions.d.ts +6 -0
  324. package/dist/esm/model/interactions/native-functions.js +52 -10
  325. package/dist/esm/model/message-diagnostics.d.ts +17 -1
  326. package/dist/esm/model/message-diagnostics.js +17 -4
  327. package/dist/esm/model/options.d.ts +18 -1
  328. package/dist/esm/model/options.js +9 -1
  329. package/dist/esm/model/preparation.d.ts +30 -2
  330. package/dist/esm/model/preparation.js +86 -12
  331. package/dist/esm/model/runner.d.ts +129 -5
  332. package/dist/esm/model/runner.js +414 -80
  333. package/dist/esm/model/selection-transport.d.ts +14 -1
  334. package/dist/esm/model/selection-transport.js +48 -8
  335. package/dist/esm/model/settings.d.ts +11 -0
  336. package/dist/esm/model/settings.js +67 -13
  337. package/dist/esm/model/token-budget.d.ts +59 -1
  338. package/dist/esm/model/token-budget.js +69 -11
  339. package/dist/esm/model/transports.d.ts +20 -2
  340. package/dist/esm/model/transports.js +59 -6
  341. package/dist/esm/structs/capabilities/invocation.d.ts +36 -0
  342. package/dist/esm/structs/capabilities/model.d.ts +27 -0
  343. package/dist/esm/structs/capabilities/tools.d.ts +38 -0
  344. package/dist/esm/structs/common.d.ts +62 -2
  345. package/dist/esm/structs/common.js +11 -0
  346. package/dist/esm/structs/context/fragments.d.ts +28 -0
  347. package/dist/esm/structs/context/journal.d.ts +28 -3
  348. package/dist/esm/structs/context/processing.d.ts +11 -0
  349. package/dist/esm/structs/debug.d.ts +58 -1
  350. package/dist/esm/structs/debug.js +34 -5
  351. package/dist/esm/structs/diagnostics.d.ts +119 -1
  352. package/dist/esm/structs/errors.d.ts +42 -1
  353. package/dist/esm/structs/errors.js +26 -1
  354. package/dist/esm/structs/execution/engine.d.ts +24 -1
  355. package/dist/esm/structs/execution/events.d.ts +12 -0
  356. package/dist/esm/structs/execution/workflow.d.ts +71 -0
  357. package/dist/esm/structs/index.d.ts +11 -1
  358. package/dist/esm/structs/index.js +11 -1
  359. package/dist/esm/structs/invocation.d.ts +30 -0
  360. package/dist/esm/structs/kits/aggregation.d.ts +12 -0
  361. package/dist/esm/structs/kits/answering/checks.d.ts +11 -0
  362. package/dist/esm/structs/kits/answering/flow.d.ts +35 -1
  363. package/dist/esm/structs/kits/answering/state.d.ts +21 -0
  364. package/dist/esm/structs/kits/answering/tasks.d.ts +21 -0
  365. package/dist/esm/structs/kits/artifacts.d.ts +14 -0
  366. package/dist/esm/structs/kits/candidates.d.ts +19 -0
  367. package/dist/esm/structs/kits/delivery.d.ts +22 -0
  368. package/dist/esm/structs/kits/durable.d.ts +56 -3
  369. package/dist/esm/structs/kits/durable.js +7 -0
  370. package/dist/esm/structs/kits/evidence.d.ts +23 -0
  371. package/dist/esm/structs/kits/family.d.ts +49 -1
  372. package/dist/esm/structs/kits/family.js +1 -0
  373. package/dist/esm/structs/kits/intents/catalog.d.ts +26 -0
  374. package/dist/esm/structs/kits/intents/registry.d.ts +34 -0
  375. package/dist/esm/structs/kits/intents/scopes.d.ts +36 -1
  376. package/dist/esm/structs/kits/interaction.d.ts +64 -0
  377. package/dist/esm/structs/kits/interaction.js +8 -1
  378. package/dist/esm/structs/kits/knowledge-publication.d.ts +43 -1
  379. package/dist/esm/structs/kits/knowledge-publication.js +1 -0
  380. package/dist/esm/structs/kits/knowledge.d.ts +39 -2
  381. package/dist/esm/structs/kits/normalization.d.ts +15 -0
  382. package/dist/esm/structs/kits/policies.d.ts +25 -1
  383. package/dist/esm/structs/kits/presentation/events.d.ts +28 -4
  384. package/dist/esm/structs/kits/presentation/outputs.d.ts +38 -1
  385. package/dist/esm/structs/kits/presentation/templates.d.ts +15 -0
  386. package/dist/esm/structs/kits/projection.d.ts +21 -0
  387. package/dist/esm/structs/kits/reflection.d.ts +61 -2
  388. package/dist/esm/structs/kits/reflection.js +18 -3
  389. package/dist/esm/structs/kits/retrieval.d.ts +38 -0
  390. package/dist/esm/structs/kits/search.d.ts +22 -0
  391. package/dist/esm/structs/kits/text-skills.d.ts +36 -0
  392. package/dist/esm/structs/kits/tools.d.ts +87 -0
  393. package/dist/esm/structs/model/chat-provider.d.ts +24 -1
  394. package/dist/esm/structs/model/chat-provider.js +6 -0
  395. package/dist/esm/structs/model/interactions.d.ts +38 -0
  396. package/dist/esm/structs/model/messages.d.ts +30 -0
  397. package/dist/esm/structs/model/runtime.d.ts +104 -6
  398. package/dist/esm/structs/support/capabilities.d.ts +19 -2
  399. package/dist/esm/structs/support/context-processing.d.ts +88 -9
  400. package/dist/esm/structs/support/context.d.ts +29 -1
  401. package/dist/esm/structs/support/model/completion.d.ts +50 -0
  402. package/dist/esm/structs/support/model/completion.js +1 -0
  403. package/dist/esm/structs/support/model/interactions.d.ts +13 -1
  404. package/dist/esm/structs/support/model/messages.d.ts +52 -0
  405. package/dist/esm/structs/support/model/messages.js +1 -0
  406. package/dist/esm/structs/support/model/provider-observer.d.ts +22 -1
  407. package/dist/esm/structs/support/model/provider.d.ts +71 -6
  408. package/dist/esm/structs/support/registration.d.ts +13 -0
  409. package/dist/esm/structs/support/schema.d.ts +14 -0
  410. package/dist/esm/structs/support/tools.d.ts +28 -0
  411. package/dist/esm/structs/support/transport/json.d.ts +16 -0
  412. package/dist/esm/structs/support/transport/sse.d.ts +15 -0
  413. package/dist/esm/structs/utils/rules.d.ts +19 -0
  414. package/dist/esm/support/capabilities.d.ts +25 -2
  415. package/dist/esm/support/capabilities.js +43 -6
  416. package/dist/esm/support/context/assembly.d.ts +35 -4
  417. package/dist/esm/support/context/assembly.js +88 -16
  418. package/dist/esm/support/context/compression.d.ts +17 -1
  419. package/dist/esm/support/context/compression.js +48 -6
  420. package/dist/esm/support/context/fragments.d.ts +6 -0
  421. package/dist/esm/support/context/fragments.js +6 -0
  422. package/dist/esm/support/context/history.d.ts +43 -0
  423. package/dist/esm/support/context/history.js +36 -1
  424. package/dist/esm/support/context/index.d.ts +13 -2
  425. package/dist/esm/support/context/index.js +12 -1
  426. package/dist/esm/support/context/nodes.d.ts +49 -3
  427. package/dist/esm/support/context/nodes.js +165 -36
  428. package/dist/esm/support/context/processing.d.ts +145 -1
  429. package/dist/esm/support/context/processing.js +320 -62
  430. package/dist/esm/support/context/selection-policy.d.ts +42 -2
  431. package/dist/esm/support/context/selection-policy.js +98 -21
  432. package/dist/esm/support/context/selection.d.ts +14 -1
  433. package/dist/esm/support/context/selection.js +61 -10
  434. package/dist/esm/support/context/snapshot.d.ts +23 -1
  435. package/dist/esm/support/context/snapshot.js +29 -7
  436. package/dist/esm/support/context/strategies.d.ts +35 -2
  437. package/dist/esm/support/context/strategies.js +120 -28
  438. package/dist/esm/support/index.d.ts +9 -1
  439. package/dist/esm/support/index.js +9 -1
  440. package/dist/esm/support/model/capabilities.d.ts +10 -0
  441. package/dist/esm/support/model/capabilities.js +20 -1
  442. package/dist/esm/support/model/chat-completions.d.ts +44 -15
  443. package/dist/esm/support/model/chat-completions.js +92 -20
  444. package/dist/esm/support/model/children.d.ts +32 -2
  445. package/dist/esm/support/model/children.js +34 -6
  446. package/dist/esm/support/model/compatible-provider.d.ts +29 -3
  447. package/dist/esm/support/model/compatible-provider.js +190 -60
  448. package/dist/esm/support/model/completion/calls.d.ts +40 -0
  449. package/dist/esm/support/model/completion/calls.js +58 -0
  450. package/dist/esm/support/model/completion/default.d.ts +10 -0
  451. package/dist/esm/support/model/completion/default.js +29 -0
  452. package/dist/esm/support/model/completion/index.d.ts +10 -0
  453. package/dist/esm/support/model/completion/index.js +22 -0
  454. package/dist/esm/support/model/completion/session.d.ts +11 -0
  455. package/dist/esm/support/model/completion/session.js +99 -0
  456. package/dist/esm/support/model/index.d.ts +14 -0
  457. package/dist/esm/support/model/index.js +12 -0
  458. package/dist/esm/support/model/interactions/index.d.ts +1 -1
  459. package/dist/esm/support/model/interactions/index.js +12 -1
  460. package/dist/esm/support/model/interactions/json-object.d.ts +6 -0
  461. package/dist/esm/support/model/interactions/json-object.js +6 -0
  462. package/dist/esm/support/model/interactions/native-functions.d.ts +6 -0
  463. package/dist/esm/support/model/interactions/native-functions.js +6 -0
  464. package/dist/esm/support/model/observer.d.ts +25 -2
  465. package/dist/esm/support/model/observer.js +32 -6
  466. package/dist/esm/support/model/preview-rules.d.ts +20 -2
  467. package/dist/esm/support/model/preview-rules.js +66 -16
  468. package/dist/esm/support/model/reply-preview.d.ts +15 -1
  469. package/dist/esm/support/model/reply-preview.js +77 -17
  470. package/dist/esm/support/model/stage-transport.d.ts +9 -1
  471. package/dist/esm/support/model/stage-transport.js +33 -7
  472. package/dist/esm/support/model/strategies.d.ts +24 -2
  473. package/dist/esm/support/model/strategies.js +75 -14
  474. package/dist/esm/support/model/transports.d.ts +17 -1
  475. package/dist/esm/support/model/transports.js +53 -11
  476. package/dist/esm/support/registration.d.ts +20 -1
  477. package/dist/esm/support/registration.js +49 -7
  478. package/dist/esm/support/schema.d.ts +31 -1
  479. package/dist/esm/support/schema.js +46 -4
  480. package/dist/esm/support/stream-events.d.ts +22 -1
  481. package/dist/esm/support/stream-events.js +60 -8
  482. package/dist/esm/support/tool-runtime.d.ts +6 -0
  483. package/dist/esm/support/tool-runtime.js +6 -0
  484. package/dist/esm/support/tools.d.ts +22 -0
  485. package/dist/esm/support/tools.js +79 -10
  486. package/dist/esm/support/transport/index.d.ts +7 -0
  487. package/dist/esm/support/transport/index.js +7 -0
  488. package/dist/esm/support/transport/json.d.ts +29 -2
  489. package/dist/esm/support/transport/json.js +28 -4
  490. package/dist/esm/support/transport/sse.d.ts +31 -1
  491. package/dist/esm/support/transport/sse.js +25 -2
  492. package/dist/esm/types.d.ts +9 -1
  493. package/dist/esm/utils/break-observer.d.ts +27 -2
  494. package/dist/esm/utils/break-observer.js +20 -2
  495. package/dist/esm/utils/cancellation.d.ts +56 -5
  496. package/dist/esm/utils/cancellation.js +77 -9
  497. package/dist/esm/utils/catalog.d.ts +20 -1
  498. package/dist/esm/utils/catalog.js +19 -4
  499. package/dist/esm/utils/debug.d.ts +20 -1
  500. package/dist/esm/utils/debug.js +14 -2
  501. package/dist/esm/utils/index.d.ts +8 -0
  502. package/dist/esm/utils/index.js +8 -0
  503. package/dist/esm/utils/interaction-definition.d.ts +18 -1
  504. package/dist/esm/utils/interaction-definition.js +26 -6
  505. package/dist/esm/utils/invocation.d.ts +36 -1
  506. package/dist/esm/utils/invocation.js +42 -4
  507. package/dist/esm/utils/model-protocol.d.ts +8 -0
  508. package/dist/esm/utils/model-protocol.js +20 -1
  509. package/dist/esm/utils/object.d.ts +16 -0
  510. package/dist/esm/utils/object.js +16 -0
  511. package/dist/esm/utils/observer.d.ts +19 -1
  512. package/dist/esm/utils/observer.js +22 -2
  513. package/dist/esm/utils/protocol-registry.d.ts +38 -1
  514. package/dist/esm/utils/protocol-registry.js +47 -4
  515. package/dist/esm/utils/query-key.d.ts +11 -1
  516. package/dist/esm/utils/query-key.js +21 -2
  517. package/dist/esm/utils/registration.d.ts +34 -2
  518. package/dist/esm/utils/registration.js +18 -2
  519. package/dist/esm/utils/rules.d.ts +81 -4
  520. package/dist/esm/utils/rules.js +39 -11
  521. package/dist/esm/utils/schema-adapter.d.ts +12 -1
  522. package/dist/esm/utils/schema-adapter.js +25 -2
  523. package/dist/esm/utils/synchronous.d.ts +60 -4
  524. package/dist/esm/utils/synchronous.js +64 -7
  525. package/dist/esm/utils/text.d.ts +15 -1
  526. package/dist/esm/utils/text.js +15 -1
  527. package/package.json +23 -3
@@ -1,18 +1,45 @@
1
+ /**
2
+ * Core tool registry: the mechanism that turns registered tools into invoked tools.
3
+ *
4
+ * `ToolRegistry` owns identity, registration-time validation, cancellation, diagnostics,
5
+ * output parsing and success/failure bookkeeping. It deliberately knows nothing about
6
+ * visibility, authorization policy or domain metadata: those are App registrations, and
7
+ * `authorize` is called by the typed bridge in `tool-runtime.js`.
8
+ *
9
+ * `invoke` requires a synchronous tool; `invokeAsync` awaits thenables. Both reject an
10
+ * unknown tool and report through the ports bound at construction.
11
+ *
12
+ * Exports: `ToolRegistry`, `executeInvocation`, and the tool/invocation contracts.
13
+ */
1
14
  import { executionEvents } from '../execution/events.js';
2
- import { invocationId as nextInvocationId, invocationResult, toolInvocation } from '../utils/invocation.js';
15
+ import { invocationId as nextInvocationId, invocationResult, toolInvocation, } from '../utils/invocation.js';
3
16
  import { synchronous } from '../utils/synchronous.js';
4
17
  import { awaitWithSignal, combineSignals } from '../utils/cancellation.js';
5
18
  import { diagnosticError } from '../diagnostics/index.js';
6
19
  import { registrationData } from '../utils/registration.js';
7
20
  import { NodeReports } from '../execution/reporting.js';
8
- /** Mechanism only. Visibility, authorization, schemas and semantic metadata are host registrations. */
21
+ /**
22
+ * Registry mechanism only: visibility, authorization policy, schemas and semantic metadata
23
+ * are host registrations. A registry is mutable until sealed and keeps its own call log.
24
+ */
9
25
  export class ToolRegistry {
26
+ /** Insertion order is the declaration order and is preserved by every enumeration below. */
10
27
  tools = new Map();
28
+ /** Sealing is one-way: a running stage must not add tools to the registry it executes. */
11
29
  sealed = false;
30
+ /** In-memory execution facts for this registry's lifetime, one entry per completed call. */
12
31
  executionEvents = [];
13
- get events() { return Object.freeze([...this.executionEvents]); }
32
+ /** Frozen snapshot of the recorded execution facts. */
33
+ get events() {
34
+ return Object.freeze([...this.executionEvents]);
35
+ }
14
36
  diagnostics;
15
37
  ports;
38
+ /**
39
+ * @param options.execution Request-lifetime signal plus the diagnostics/observer source the
40
+ * registry starts from.
41
+ * @param options.errors Factories for the unknown-tool error and for failure codes.
42
+ */
16
43
  constructor({ execution, errors } = {}) {
17
44
  this.ports = {
18
45
  signal: execution?.signal,
@@ -22,42 +49,137 @@ export class ToolRegistry {
22
49
  };
23
50
  this.diagnostics = this.ports.diagnostics;
24
51
  }
25
- setDiagnostics(diagnostics) { this.diagnostics = diagnostics; }
52
+ /**
53
+ * Replace the diagnostics scope used by subsequent calls.
54
+ *
55
+ * Calls already in flight keep the scope they started with.
56
+ *
57
+ * @param diagnostics New diagnostics context, or undefined to stop emitting events.
58
+ */
59
+ setDiagnostics(diagnostics) {
60
+ this.diagnostics = diagnostics;
61
+ }
62
+ /**
63
+ * Register one executable tool.
64
+ *
65
+ * The stored entry is frozen and its parsers are bound to the tool, so later changes on the
66
+ * caller's object cannot alter validation or execution.
67
+ *
68
+ * @param tool Executable tool; `id` and `kind` must be non-empty, and the parse and execute
69
+ * handlers must all be functions.
70
+ * @returns This registry, for chaining.
71
+ * @throws Error when the registry is sealed or the id is already registered.
72
+ * @throws TypeError when the tool shape is invalid.
73
+ */
26
74
  register(tool) {
27
75
  if (this.sealed)
28
76
  throw new Error('Tool registry is sealed');
29
77
  const { id, kind, description, parseInput, parseOutput, execute, debugSteps } = tool;
30
- if (!id?.trim() || !kind?.trim() || ![parseInput, parseOutput, execute].every(value => typeof value === 'function'))
78
+ if (!id?.trim() ||
79
+ !kind?.trim() ||
80
+ ![parseInput, parseOutput, execute].every((value) => typeof value === 'function'))
31
81
  throw new TypeError('Invalid executable tool');
32
82
  if (this.tools.has(id))
33
83
  throw new Error(`Duplicate registered tool: ${id}`);
34
84
  const input = parseInput.bind(tool), output = parseOutput.bind(tool);
35
- this.tools.set(id, Object.freeze({ ...registrationData(tool, ['id', 'kind', 'description', 'parseInput', 'parseOutput', 'execute', 'debugSteps']), id, kind, description,
36
- debugSteps: debugSteps?.bind(tool), parseInput: input, parseOutput: output,
37
- execute: execute.bind(tool) }));
85
+ this.tools.set(id, Object.freeze({
86
+ ...registrationData(tool, [
87
+ 'id',
88
+ 'kind',
89
+ 'description',
90
+ 'parseInput',
91
+ 'parseOutput',
92
+ 'execute',
93
+ 'debugSteps',
94
+ ]),
95
+ id,
96
+ kind,
97
+ description,
98
+ debugSteps: debugSteps?.bind(tool),
99
+ parseInput: input,
100
+ parseOutput: output,
101
+ execute: execute.bind(tool),
102
+ }));
38
103
  return this;
39
104
  }
105
+ /**
106
+ * Invoke a registered tool synchronously.
107
+ *
108
+ * @param request Single request object carrying `toolId`, `input`, and optional signal and
109
+ * diagnostics. Exactly one argument is accepted; the arity check is runtime-enforced
110
+ * because callers may bypass the type system.
111
+ * @returns The tool result, with frozen invocation metadata.
112
+ * @throws TypeError when the request shape is wrong, the diagnostics belong to another run,
113
+ * or the tool returns a promise.
114
+ * @throws Error when the tool is unknown or the tool itself fails; the abort reason
115
+ * surfaces when the signal is cancelled.
116
+ */
40
117
  invoke(request) {
41
118
  const call = toolInvocation(request, arguments.length);
42
119
  return this.execute(call.toolId, call.input, false, call.diagnostics, call.signal);
43
120
  }
121
+ /**
122
+ * Invoke a registered tool and await its result.
123
+ *
124
+ * @param request Single request object, identical to `invoke`.
125
+ * @returns The tool result once the tool settles.
126
+ * @throws TypeError or Error under the same conditions as `invoke`; rejections from an
127
+ * asynchronous tool are propagated unchanged.
128
+ */
44
129
  async invokeAsync(request) {
45
130
  const call = toolInvocation(request, arguments.length);
46
- return await this.execute(call.toolId, call.input, true, call.diagnostics, call.signal);
131
+ return (await this.execute(call.toolId, call.input, true, call.diagnostics, call.signal));
47
132
  }
133
+ /**
134
+ * Run one call: validate, parse input, execute, parse output, then record the outcome.
135
+ *
136
+ * @param name Registered tool id.
137
+ * @param input Untrusted caller input, parsed before the tool sees it.
138
+ * @param asynchronous Whether promises returned by the tool are awaited.
139
+ * @param parentDiagnostics Scope the call is recorded under; defaults to the registry's.
140
+ * @param requestSignal Per-call signal, combined with the request-lifetime signal.
141
+ * @returns The frozen result on success; every failure path throws.
142
+ */
48
143
  execute(name, input, asynchronous, parentDiagnostics = this.diagnostics, requestSignal) {
49
- if (this.diagnostics?.identity?.runId && parentDiagnostics?.identity?.runId && this.diagnostics.identity.runId !== parentDiagnostics.identity.runId)
144
+ // A tool call stays inside the run that invoked it: mixing two diagnostic trees would
145
+ // produce records with two parents and break run-scoped correlation.
146
+ if (this.diagnostics?.identity?.runId &&
147
+ parentDiagnostics?.identity?.runId &&
148
+ this.diagnostics.identity.runId !== parentDiagnostics.identity.runId)
50
149
  throw new TypeError('Tool diagnostics must belong to the same run');
51
150
  const tool = this.tools.get(name);
52
151
  if (!tool)
53
152
  throw this.ports.unavailable?.(name) ?? new Error(`Tool is not registered: ${name}`);
153
+ // Either signal may cancel the call; combining them keeps both lifetimes effective.
54
154
  const signal = combineSignals(this.ports.signal, requestSignal);
55
155
  const invocationId = nextInvocationId();
56
- const diagnostics = parentDiagnostics?.child(invocationId, { invocationId, nodeRole: 'invocation', definitionKind: 'tool', definitionId: name, nodeId: name, nodeName: name, nodeKind: 'tool', nodeDescription: tool.description?.slice(0, 1024), stageId: undefined, definitionRevision: undefined });
156
+ const diagnostics = parentDiagnostics?.child(invocationId, {
157
+ invocationId,
158
+ nodeRole: 'invocation',
159
+ definitionKind: 'tool',
160
+ definitionId: name,
161
+ nodeId: name,
162
+ nodeName: name,
163
+ nodeKind: 'tool',
164
+ // Cap the persisted description so an App-supplied string cannot inflate every record.
165
+ nodeDescription: tool.description?.slice(0, 1024),
166
+ // Tool calls are not stage-scoped; explicit undefined clears inherited span fields.
167
+ stageId: undefined,
168
+ definitionRevision: undefined,
169
+ });
57
170
  const reports = new NodeReports(diagnostics, signal, 'tool.result');
58
- const reporting = { report: reports.report.bind(reports), createSubFlowLogger: reports.createSubFlowLogger.bind(reports) };
59
- diagnostics?.emit('tool.call', () => ({ toolId: name, invocationId, ...(diagnostics?.enabled('tool.call', 'content') ? { input } : {}) }));
171
+ const reporting = {
172
+ report: reports.report.bind(reports),
173
+ createSubFlowLogger: reports.createSubFlowLogger.bind(reports),
174
+ };
175
+ diagnostics?.emit('tool.call', () => ({
176
+ toolId: name,
177
+ invocationId,
178
+ ...(diagnostics?.enabled('tool.call', 'content') ? { input } : {}),
179
+ }));
60
180
  const started = Date.now();
181
+ // Track the phase for failure reports, so input or output parsing errors can be told
182
+ // apart from failures raised by the tool itself.
61
183
  let phase = 'input';
62
184
  const output = (value) => {
63
185
  signal.throwIfAborted();
@@ -71,28 +193,82 @@ export class ToolRegistry {
71
193
  let debug = reports.debug();
72
194
  if (tool.debugSteps && diagnostics?.enabled('tool.result', 'content')) {
73
195
  try {
74
- debug = reports.debug({ subs: synchronous(tool.debugSteps(result, reporting), 'Tool debug reports must be synchronous') });
196
+ debug = reports.debug({
197
+ subs: synchronous(tool.debugSteps(result, reporting), 'Tool debug reports must be synchronous'),
198
+ });
75
199
  }
76
200
  catch (error) {
77
- debug = { usedModel: reports.debug().usedModel, subSteps: () => { throw error; } };
201
+ // Debug material is optional evidence: it must not turn a successful tool call into
202
+ // a failure. Defer the error until a consumer actually asks for the sub-steps.
203
+ debug = {
204
+ usedModel: reports.debug().usedModel,
205
+ subSteps: () => {
206
+ throw error;
207
+ },
208
+ };
78
209
  }
79
210
  }
80
211
  signal.throwIfAborted();
81
212
  reports.close();
82
- diagnostics?.emit('tool.result', () => ({ toolId: name, invocationId, status: 'success', ...(diagnostics?.enabled('tool.result', 'content') ? { value: result } : {}), durationMs: Date.now() - started }), debug);
83
- this.executionEvents.push(Object.freeze({ ...diagnostics?.identity, toolId: name, invocationId, startedAtMs: started, kind: tool.kind, durationMs: Date.now() - started, status: 'success' }));
84
- return invocationResult(result, { ...diagnostics?.identity, invocationId, toolId: name, startedAtMs: started, durationMs: Date.now() - started, status: 'success' });
213
+ diagnostics?.emit('tool.result', () => ({
214
+ toolId: name,
215
+ invocationId,
216
+ status: 'success',
217
+ ...(diagnostics?.enabled('tool.result', 'content') ? { value: result } : {}),
218
+ durationMs: Date.now() - started,
219
+ }), debug);
220
+ // Kept locally as well as emitted, so a run summary does not require a log consumer.
221
+ this.executionEvents.push(Object.freeze({
222
+ ...diagnostics?.identity,
223
+ toolId: name,
224
+ invocationId,
225
+ startedAtMs: started,
226
+ kind: tool.kind,
227
+ durationMs: Date.now() - started,
228
+ status: 'success',
229
+ }));
230
+ return invocationResult(result, {
231
+ ...diagnostics?.identity,
232
+ invocationId,
233
+ toolId: name,
234
+ startedAtMs: started,
235
+ durationMs: Date.now() - started,
236
+ status: 'success',
237
+ });
85
238
  };
86
239
  const fail = (error) => {
87
240
  reports.close();
88
- diagnostics?.emit('rule.result', () => ({ tags: [name, phase], error: diagnosticError(error) }));
89
- diagnostics?.emit('tool.result', () => ({ toolId: name, invocationId, status: signal.aborted ? 'cancelled' : 'error', ...(diagnostics?.enabled('tool.result', 'content') ? { error: diagnosticError(error) } : {}), durationMs: Date.now() - started }), reports.debug());
241
+ // Rule-level record carries the failing phase, which the tool result does not.
242
+ diagnostics?.emit('rule.result', () => ({
243
+ tags: [name, phase],
244
+ error: diagnosticError(error),
245
+ }));
246
+ diagnostics?.emit('tool.result', () => ({
247
+ toolId: name,
248
+ invocationId,
249
+ status: signal.aborted ? 'cancelled' : 'error',
250
+ ...(diagnostics?.enabled('tool.result', 'content')
251
+ ? { error: diagnosticError(error) }
252
+ : {}),
253
+ durationMs: Date.now() - started,
254
+ }), reports.debug());
90
255
  let errorCode = signal.aborted ? 'CANCELLED' : 'TOOL_ERROR';
91
256
  try {
92
257
  errorCode = this.ports.errorCode?.(error) ?? errorCode;
93
258
  }
94
- catch { /* Error decoration cannot replace the original failure. */ }
95
- this.executionEvents.push(Object.freeze({ ...diagnostics?.identity, toolId: name, invocationId, startedAtMs: started, kind: tool.kind, durationMs: Date.now() - started, status: signal.aborted ? 'cancelled' : 'error', ...(errorCode ? { errorCode } : {}) }));
259
+ catch {
260
+ /* Error decoration cannot replace the original failure. */
261
+ }
262
+ this.executionEvents.push(Object.freeze({
263
+ ...diagnostics?.identity,
264
+ toolId: name,
265
+ invocationId,
266
+ startedAtMs: started,
267
+ kind: tool.kind,
268
+ durationMs: Date.now() - started,
269
+ status: signal.aborted ? 'cancelled' : 'error',
270
+ ...(errorCode ? { errorCode } : {}),
271
+ }));
96
272
  throw error;
97
273
  };
98
274
  try {
@@ -100,8 +276,16 @@ export class ToolRegistry {
100
276
  const parsed = synchronous(tool.parseInput(input), 'Tool input parsers must be synchronous');
101
277
  signal.throwIfAborted();
102
278
  phase = 'execute';
103
- const value = tool.execute(parsed, { mode: asynchronous ? 'async' : 'sync', invocationId, signal, diagnostics, ...reporting });
279
+ const value = tool.execute(parsed, {
280
+ mode: asynchronous ? 'async' : 'sync',
281
+ invocationId,
282
+ signal,
283
+ diagnostics,
284
+ ...reporting,
285
+ });
104
286
  if (asynchronous)
287
+ // Async completions are routed to `fail` explicitly, so bookkeeping runs exactly once
288
+ // whether the tool settles immediately or later.
105
289
  return awaitWithSignal(value, signal).then(output).then(succeed).catch(fail);
106
290
  return succeed(output(synchronous(value, 'Synchronous tools must not return a Promise')));
107
291
  }
@@ -109,19 +293,70 @@ export class ToolRegistry {
109
293
  return fail(error);
110
294
  }
111
295
  }
296
+ /**
297
+ * Register several tools.
298
+ *
299
+ * @param tools Executable tools applied in iteration order.
300
+ * @returns This registry, for chaining.
301
+ * @throws Error or TypeError under the same conditions as `register`.
302
+ */
112
303
  registerAll(tools) {
113
304
  for (const tool of tools)
114
305
  this.register(tool);
115
306
  return this;
116
307
  }
117
- get(name) { return this.tools.get(name); }
118
- get definitions() { return Object.freeze([...this.tools.values()]); }
119
- ids() { return Object.freeze([...this.tools.keys()]); }
120
- entries() { return this.tools.entries(); }
121
- require(id) { const tool = this.get(id); if (!tool)
122
- throw this.ports.unavailable?.(id) ?? new Error(`Tool is not registered: ${id}`); return tool; }
123
- has(name) { return this.tools.has(name); }
124
- values() { return this.tools.values(); }
125
- seal() { this.sealed = true; return this; }
308
+ /**
309
+ * @param name Tool id.
310
+ * @returns The registered tool, or undefined when absent.
311
+ */
312
+ get(name) {
313
+ return this.tools.get(name);
314
+ }
315
+ /** Frozen snapshot of the registered tools, in declaration order. */
316
+ get definitions() {
317
+ return Object.freeze([...this.tools.values()]);
318
+ }
319
+ /** Registered tool ids in declaration order. */
320
+ ids() {
321
+ return Object.freeze([...this.tools.keys()]);
322
+ }
323
+ /** Live iterator over `[id, tool]` pairs; it reflects only entries added before sealing. */
324
+ entries() {
325
+ return this.tools.entries();
326
+ }
327
+ /**
328
+ * @param id Tool id.
329
+ * @returns The registered tool.
330
+ * @throws Error when the tool is unknown; the App-supplied `unavailable` factory can
331
+ * replace the default message.
332
+ */
333
+ require(id) {
334
+ const tool = this.get(id);
335
+ if (!tool)
336
+ throw this.ports.unavailable?.(id) ?? new Error(`Tool is not registered: ${id}`);
337
+ return tool;
338
+ }
339
+ /**
340
+ * @param name Tool id.
341
+ * @returns Whether the id is registered in this registry.
342
+ */
343
+ has(name) {
344
+ return this.tools.has(name);
345
+ }
346
+ /** Live iterator over the registered tools. */
347
+ values() {
348
+ return this.tools.values();
349
+ }
350
+ /**
351
+ * Close the registry to further registration.
352
+ *
353
+ * Sealing is idempotent and does not affect existing tools.
354
+ *
355
+ * @returns This registry.
356
+ */
357
+ seal() {
358
+ this.sealed = true;
359
+ return this;
360
+ }
126
361
  }
127
362
  export { executeInvocation } from './invocation.js';
@@ -1,5 +1,16 @@
1
1
  import type { BuiltContext, ContextFragment } from '../structs/context/fragments.js';
2
- /** Metadata remains program-side. Data never becomes a system instruction. */
2
+ /**
3
+ * Build the model input from fragments.
4
+ *
5
+ * Metadata remains program-side: data never becomes a system instruction.
6
+ *
7
+ * @param fragments Fragments in carriage order; ids must be unique across the list.
8
+ * @param maxInputChars Total character budget for the resulting messages.
9
+ * @returns Messages, per-fragment usage and the measured input size.
10
+ * @throws Error when a fragment is invalid or duplicated, a user fragment carries a string
11
+ * value, or two user fragments declare the same field.
12
+ * @throws ValidationError when a fragment or the assembled input exceeds its budget.
13
+ */
3
14
  export declare function assembleFragments(fragments: ContextFragment[], maxInputChars: number): BuiltContext;
4
15
  export { commonPrefixLength } from '../utils/text.js';
5
- export type { ContextTrust, ContextLifetime, ContextFragment, ContextFragmentUsage, BuiltContext } from '../structs/context/fragments.js';
16
+ export type { ContextTrust, ContextLifetime, ContextFragment, ContextFragmentUsage, BuiltContext, } from '../structs/context/fragments.js';
@@ -1,8 +1,30 @@
1
+ /**
2
+ * Assemble validated fragments into the messages sent to the model.
3
+ *
4
+ * The order is fixed: system text first, then one user message carrying structured fields as
5
+ * JSON. Fragment metadata stays program-side in `fragmentUsage` and never becomes an
6
+ * instruction. The finished message list is measured against the overall budget, so a caller
7
+ * sees the same character count a transport will deliver.
8
+ *
9
+ * Exports: `assembleFragments`, plus a shared text helper and the fragment types.
10
+ */
1
11
  import { validateContextFragment, validateContextBudget } from './fragments.js';
2
12
  import { ValidationError } from '../structs/errors.js';
3
- /** Metadata remains program-side. Data never becomes a system instruction. */
13
+ /**
14
+ * Build the model input from fragments.
15
+ *
16
+ * Metadata remains program-side: data never becomes a system instruction.
17
+ *
18
+ * @param fragments Fragments in carriage order; ids must be unique across the list.
19
+ * @param maxInputChars Total character budget for the resulting messages.
20
+ * @returns Messages, per-fragment usage and the measured input size.
21
+ * @throws Error when a fragment is invalid or duplicated, a user fragment carries a string
22
+ * value, or two user fragments declare the same field.
23
+ * @throws ValidationError when a fragment or the assembled input exceeds its budget.
24
+ */
4
25
  export function assembleFragments(fragments, maxInputChars) {
5
26
  const ids = new Set();
27
+ // One merged object lets duplicate field names be rejected rather than silently overwritten.
6
28
  const fields = {};
7
29
  const system = [];
8
30
  const usage = [];
@@ -16,15 +38,34 @@ export function assembleFragments(fragments, maxInputChars) {
16
38
  for (const [key, value] of Object.entries(fragment.value)) {
17
39
  if (Object.hasOwn(fields, key))
18
40
  throw new Error(`Duplicate context field: ${key}`);
41
+ // defineProperty keeps names such as `__proto__` as own data instead of letting an
42
+ // assignment reach the object prototype.
19
43
  Object.defineProperty(fields, key, { value, enumerable: true });
20
44
  }
21
45
  }
22
- usage.push({ id: fragment.id, sourceId: fragment.sourceId, trust: fragment.trust, lifetime: fragment.lifetime,
23
- chars: serialized.length, maxChars: fragment.maxChars });
46
+ usage.push({
47
+ id: fragment.id,
48
+ sourceId: fragment.sourceId,
49
+ trust: fragment.trust,
50
+ lifetime: fragment.lifetime,
51
+ chars: serialized.length,
52
+ maxChars: fragment.maxChars,
53
+ });
24
54
  }
25
- const messages = [{ role: 'system', content: system.join('\n\n') }, { role: 'user', content: JSON.stringify(fields) }];
55
+ // Blank-line separation keeps independently declared instructions readable and attributable
56
+ // while still arriving as one system message.
57
+ const messages = [
58
+ { role: 'system', content: system.join('\n\n') },
59
+ { role: 'user', content: JSON.stringify(fields) },
60
+ ];
61
+ // Measured on the exact strings above, so the count matches what the transport will send.
26
62
  const inputChars = messages.reduce((sum, message) => sum + message.content.length, 0);
27
- validateContextBudget(inputChars, maxInputChars, () => new ValidationError([{ code: 'CONTEXT_BUDGET', message: `上下文超过${maxInputChars}字符;不截断原问题、约束与证据。` }]));
63
+ validateContextBudget(inputChars, maxInputChars, () => new ValidationError([
64
+ {
65
+ code: 'CONTEXT_BUDGET',
66
+ message: `上下文超过${maxInputChars}字符;不截断原问题、约束与证据。`,
67
+ },
68
+ ]));
28
69
  return { messages, fragmentUsage: usage, inputChars, maxInputChars };
29
70
  }
30
71
  export { commonPrefixLength } from '../utils/text.js';
@@ -1,3 +1,25 @@
1
+ /**
2
+ * Structural audit of context fragments before they are assembled.
3
+ *
4
+ * A plan may carry the trusted originals plus the fragments an App node produced. This check
5
+ * permits value rewrites for explicitly mutable fragments and rejects everything structural:
6
+ * added or removed fragments, changed trust, lifetime or budget, changed value type, changed
7
+ * field sets, and changes to system or instruction fragments.
8
+ *
9
+ * The guarantee is structural only. Whether a rewritten value is semantically faithful needs
10
+ * an App-side audit.
11
+ *
12
+ * Exports: `auditContextChange`.
13
+ */
1
14
  import type { ContextFragment } from '../structs/context/fragments.js';
2
- /** Structural audit only: semantic fidelity of a summary requires an application audit. */
15
+ /**
16
+ * Compare trusted originals with the fragments about to be assembled.
17
+ *
18
+ * @param original Fragments captured before any App-side processing.
19
+ * @param current Fragments that will actually be assembled; same length as `original`.
20
+ * @param mutable Ids explicitly allowed to change value. Everything else is protected.
21
+ * @returns Nothing; a clean audit has no side effect.
22
+ * @throws ValidationError when the fragment list, its metadata, the value type or the field
23
+ * set changed, or when a protected fragment was rewritten.
24
+ */
3
25
  export declare function auditContextChange(original: readonly ContextFragment[], current: readonly ContextFragment[], mutable: ReadonlySet<string>): void;
@@ -1,19 +1,44 @@
1
1
  import { ValidationError } from '../structs/errors.js';
2
2
  import { breakWhile } from '../utils/rules.js';
3
+ /** Single code for every violation, so consumers can classify audit failures uniformly. */
3
4
  const fail = (message) => new ValidationError([{ code: 'CONTEXT_POLICY', message }]);
4
- /** Structural audit only: semantic fidelity of a summary requires an application audit. */
5
+ /**
6
+ * Compare trusted originals with the fragments about to be assembled.
7
+ *
8
+ * @param original Fragments captured before any App-side processing.
9
+ * @param current Fragments that will actually be assembled; same length as `original`.
10
+ * @param mutable Ids explicitly allowed to change value. Everything else is protected.
11
+ * @returns Nothing; a clean audit has no side effect.
12
+ * @throws ValidationError when the fragment list, its metadata, the value type or the field
13
+ * set changed, or when a protected fragment was rewritten.
14
+ */
5
15
  export function auditContextChange(original, current, mutable) {
16
+ // Fragments may be rewritten in place but not added or removed: assembly and audit both
17
+ // assume the same positions describe the same fragment.
6
18
  breakWhile(original.length !== current.length, fail('Context fragments cannot be added or removed'));
7
19
  for (const [index, before] of original.entries()) {
8
20
  const after = current[index];
21
+ // Metadata and value are compared separately: only the value may be rewritten, and only
22
+ // for ids the plan explicitly allows.
9
23
  const { value: _before, ...beforeMetadata } = before;
10
24
  const { value: _after, ...afterMetadata } = after;
11
- breakWhile(Object.keys(beforeMetadata).length !== Object.keys(afterMetadata).length
12
- || Object.entries(beforeMetadata).some(([key, value]) => afterMetadata[key] !== value), fail('Context identity, trust and budgets must be preserved'));
25
+ breakWhile(Object.keys(beforeMetadata).length !== Object.keys(afterMetadata).length ||
26
+ Object.entries(beforeMetadata).some(([key, value]) => afterMetadata[key] !== value), fail('Context identity, trust and budgets must be preserved'));
27
+ // A type change would alter how the fragment is serialized, so it is rejected before any
28
+ // value comparison is attempted.
13
29
  breakWhile(typeof before.value !== typeof after.value, fail('Context value type must be preserved'));
30
+ // String comparison captures both values and their key order; a reordered rewrite counts
31
+ // as a change, which is the conservative direction for an audit.
14
32
  const changed = JSON.stringify(before.value) !== JSON.stringify(after.value);
15
- breakWhile(changed && (!mutable.has(before.id) || before.role === 'system' || before.trust === 'instruction'), fail(`Protected context changed: ${before.id}`));
16
- if (changed && typeof before.value === 'object' && typeof after.value === 'object')
17
- breakWhile(JSON.stringify(Object.keys(before.value).sort()) !== JSON.stringify(Object.keys(after.value).sort()), fail('Context fields must be preserved'));
33
+ breakWhile(changed &&
34
+ (!mutable.has(before.id) || before.role === 'system' || before.trust === 'instruction'), fail(`Protected context changed: ${before.id}`));
35
+ if (changed &&
36
+ before.value !== null &&
37
+ after.value !== null &&
38
+ typeof before.value === 'object' &&
39
+ typeof after.value === 'object')
40
+ // Only the field set is compared here; field order is not meaningful for context data.
41
+ breakWhile(JSON.stringify(Object.keys(before.value).sort()) !==
42
+ JSON.stringify(Object.keys(after.value).sort()), fail('Context fields must be preserved'));
18
43
  }
19
44
  }
@@ -1,7 +1,41 @@
1
+ /**
2
+ * Per-fragment validation and the shared input budget.
3
+ *
4
+ * A fragment is the only way text enters model context: it declares where it came from
5
+ * (`sourceId`), how far it may be trusted, its lifetime, and a hard character budget. These
6
+ * checks run before concatenation, so an oversized or mistrusted fragment fails instead of
7
+ * being silently truncated or promoted into an instruction.
8
+ *
9
+ * Exports: `validateContextFragment`, `validateContextBudget`, and a shared text helper.
10
+ */
1
11
  import type { ContextFragment } from '../structs/context/fragments.js';
2
- /** Validate one fragment before formatting. The shared set preserves registration order. */
12
+ /**
13
+ * Validate one fragment and return the text it contributes to the model input.
14
+ *
15
+ * @param fragment Declaration to check.
16
+ * @param ids Optional accumulator of ids already seen. Callers validating a batch pass the
17
+ * same set for every fragment so duplicates are detected across the whole input.
18
+ * @param checkBudget Whether this fragment's own `maxChars` is enforced. Disable only when the
19
+ * same serialized text has already been checked against the identical limit.
20
+ * @returns The exact text the fragment contributes: the value when it is a string, otherwise
21
+ * the JSON form used for structured fields.
22
+ * @throws Error when identity, trust, lifetime, role, the `maxChars` declaration or the value
23
+ * shape is invalid, or when untrusted content is declared as a system instruction.
24
+ * @throws ValidationError when the serialized text exceeds `maxChars`; text is never truncated.
25
+ */
3
26
  export declare function validateContextFragment(fragment: ContextFragment, ids?: Set<string>, checkBudget?: boolean): string;
4
- /** Core input-budget boundary; helpers may retain their existing error presentation. */
27
+ /**
28
+ * Enforce the character budget of the whole model input.
29
+ *
30
+ * @param inputChars Characters that will be sent; must be a non-negative safe integer.
31
+ * @param maxInputChars Budget limit. `Infinity` is accepted as an explicit "no limit", which
32
+ * is why it is allowed in place of a safe integer.
33
+ * @param exceeded Optional factory for the over-budget error. Support may pass one to keep its
34
+ * own message; Core otherwise raises a `CONTEXT_BUDGET` ValidationError.
35
+ * @returns Nothing.
36
+ * @throws TypeError when either count is not a non-negative integer.
37
+ * @throws Error when the budget is exceeded: the `exceeded` result, or a ValidationError.
38
+ */
5
39
  export declare function validateContextBudget(inputChars: number, maxInputChars: number, exceeded?: (limit: number) => Error): void;
6
40
  export { commonPrefixLength } from '../utils/text.js';
7
- export type { ContextTrust, ContextLifetime, ContextFragment, ContextFragmentUsage, BuiltContext } from '../structs/context/fragments.js';
41
+ export type { ContextTrust, ContextLifetime, ContextFragment, ContextFragmentUsage, BuiltContext, } from '../structs/context/fragments.js';