@kindgi/agents 0.0.0-bootstrap.0 → 0.1.1

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 (240) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +131 -2
  3. package/dist/agent-turn-flow.d.ts +57 -0
  4. package/dist/agent-turn-flow.d.ts.map +1 -0
  5. package/dist/agent-turn-flow.js +172 -0
  6. package/dist/agent-turn-flow.js.map +1 -0
  7. package/dist/conversation-binding.d.ts +111 -0
  8. package/dist/conversation-binding.d.ts.map +1 -0
  9. package/dist/conversation-binding.js +4 -0
  10. package/dist/conversation-binding.js.map +1 -0
  11. package/dist/define.d.ts +180 -0
  12. package/dist/define.d.ts.map +1 -0
  13. package/dist/define.js +361 -0
  14. package/dist/define.js.map +1 -0
  15. package/dist/errors.d.ts +62 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +4 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/guardrails-gate.d.ts +169 -0
  20. package/dist/guardrails-gate.d.ts.map +1 -0
  21. package/dist/guardrails-gate.js +202 -0
  22. package/dist/guardrails-gate.js.map +1 -0
  23. package/dist/handlers/budget-check.d.ts +22 -0
  24. package/dist/handlers/budget-check.d.ts.map +1 -0
  25. package/dist/handlers/budget-check.js +109 -0
  26. package/dist/handlers/budget-check.js.map +1 -0
  27. package/dist/handlers/build-initial-messages.d.ts +17 -0
  28. package/dist/handlers/build-initial-messages.d.ts.map +1 -0
  29. package/dist/handlers/build-initial-messages.js +86 -0
  30. package/dist/handlers/build-initial-messages.js.map +1 -0
  31. package/dist/handlers/compose-result.d.ts +10 -0
  32. package/dist/handlers/compose-result.d.ts.map +1 -0
  33. package/dist/handlers/compose-result.js +79 -0
  34. package/dist/handlers/compose-result.js.map +1 -0
  35. package/dist/handlers/constants.d.ts +8 -0
  36. package/dist/handlers/constants.d.ts.map +1 -0
  37. package/dist/handlers/constants.js +10 -0
  38. package/dist/handlers/constants.js.map +1 -0
  39. package/dist/handlers/context.d.ts +210 -0
  40. package/dist/handlers/context.d.ts.map +1 -0
  41. package/dist/handlers/context.js +4 -0
  42. package/dist/handlers/context.js.map +1 -0
  43. package/dist/handlers/dispatch-tools.d.ts +15 -0
  44. package/dist/handlers/dispatch-tools.d.ts.map +1 -0
  45. package/dist/handlers/dispatch-tools.js +511 -0
  46. package/dist/handlers/dispatch-tools.js.map +1 -0
  47. package/dist/handlers/errors.d.ts +133 -0
  48. package/dist/handlers/errors.d.ts.map +1 -0
  49. package/dist/handlers/errors.js +134 -0
  50. package/dist/handlers/errors.js.map +1 -0
  51. package/dist/handlers/evaluate-guardrails.d.ts +14 -0
  52. package/dist/handlers/evaluate-guardrails.d.ts.map +1 -0
  53. package/dist/handlers/evaluate-guardrails.js +128 -0
  54. package/dist/handlers/evaluate-guardrails.js.map +1 -0
  55. package/dist/handlers/final-iteration.d.ts +7 -0
  56. package/dist/handlers/final-iteration.d.ts.map +1 -0
  57. package/dist/handlers/final-iteration.js +26 -0
  58. package/dist/handlers/final-iteration.js.map +1 -0
  59. package/dist/handlers/index.d.ts +5 -0
  60. package/dist/handlers/index.d.ts.map +1 -0
  61. package/dist/handlers/index.js +41 -0
  62. package/dist/handlers/index.js.map +1 -0
  63. package/dist/handlers/model-call.d.ts +13 -0
  64. package/dist/handlers/model-call.d.ts.map +1 -0
  65. package/dist/handlers/model-call.js +136 -0
  66. package/dist/handlers/model-call.js.map +1 -0
  67. package/dist/handlers/persist-final-message.d.ts +14 -0
  68. package/dist/handlers/persist-final-message.d.ts.map +1 -0
  69. package/dist/handlers/persist-final-message.js +54 -0
  70. package/dist/handlers/persist-final-message.js.map +1 -0
  71. package/dist/handlers/persist-provenance.d.ts +12 -0
  72. package/dist/handlers/persist-provenance.d.ts.map +1 -0
  73. package/dist/handlers/persist-provenance.js +34 -0
  74. package/dist/handlers/persist-provenance.js.map +1 -0
  75. package/dist/handlers/persist-user-message.d.ts +15 -0
  76. package/dist/handlers/persist-user-message.d.ts.map +1 -0
  77. package/dist/handlers/persist-user-message.js +59 -0
  78. package/dist/handlers/persist-user-message.js.map +1 -0
  79. package/dist/handlers/public-types.d.ts +201 -0
  80. package/dist/handlers/public-types.d.ts.map +1 -0
  81. package/dist/handlers/public-types.js +4 -0
  82. package/dist/handlers/public-types.js.map +1 -0
  83. package/dist/handlers/rehydrate.d.ts +8 -0
  84. package/dist/handlers/rehydrate.d.ts.map +1 -0
  85. package/dist/handlers/rehydrate.js +94 -0
  86. package/dist/handlers/rehydrate.js.map +1 -0
  87. package/dist/handlers/render-prompt.d.ts +12 -0
  88. package/dist/handlers/render-prompt.d.ts.map +1 -0
  89. package/dist/handlers/render-prompt.js +41 -0
  90. package/dist/handlers/render-prompt.js.map +1 -0
  91. package/dist/handlers/resolve-tools.d.ts +10 -0
  92. package/dist/handlers/resolve-tools.d.ts.map +1 -0
  93. package/dist/handlers/resolve-tools.js +55 -0
  94. package/dist/handlers/resolve-tools.js.map +1 -0
  95. package/dist/handlers/result-shape.d.ts +94 -0
  96. package/dist/handlers/result-shape.d.ts.map +1 -0
  97. package/dist/handlers/result-shape.js +19 -0
  98. package/dist/handlers/result-shape.js.map +1 -0
  99. package/dist/handlers/run-retrievals.d.ts +10 -0
  100. package/dist/handlers/run-retrievals.d.ts.map +1 -0
  101. package/dist/handlers/run-retrievals.js +64 -0
  102. package/dist/handlers/run-retrievals.js.map +1 -0
  103. package/dist/handlers/run-snapshot.d.ts +4 -0
  104. package/dist/handlers/run-snapshot.d.ts.map +1 -0
  105. package/dist/handlers/run-snapshot.js +26 -0
  106. package/dist/handlers/run-snapshot.js.map +1 -0
  107. package/dist/handlers/setup.d.ts +25 -0
  108. package/dist/handlers/setup.d.ts.map +1 -0
  109. package/dist/handlers/setup.js +231 -0
  110. package/dist/handlers/setup.js.map +1 -0
  111. package/dist/handlers/structured-output.d.ts +38 -0
  112. package/dist/handlers/structured-output.d.ts.map +1 -0
  113. package/dist/handlers/structured-output.js +89 -0
  114. package/dist/handlers/structured-output.js.map +1 -0
  115. package/dist/handlers/tool-errors.d.ts +56 -0
  116. package/dist/handlers/tool-errors.d.ts.map +1 -0
  117. package/dist/handlers/tool-errors.js +73 -0
  118. package/dist/handlers/tool-errors.js.map +1 -0
  119. package/dist/handlers/tool-hitl.d.ts +45 -0
  120. package/dist/handlers/tool-hitl.d.ts.map +1 -0
  121. package/dist/handlers/tool-hitl.js +81 -0
  122. package/dist/handlers/tool-hitl.js.map +1 -0
  123. package/dist/handlers/turn-environment.d.ts +26 -0
  124. package/dist/handlers/turn-environment.d.ts.map +1 -0
  125. package/dist/handlers/turn-environment.js +154 -0
  126. package/dist/handlers/turn-environment.js.map +1 -0
  127. package/dist/hitl-policy.d.ts +45 -0
  128. package/dist/hitl-policy.d.ts.map +1 -0
  129. package/dist/hitl-policy.js +74 -0
  130. package/dist/hitl-policy.js.map +1 -0
  131. package/dist/index.d.ts +31 -0
  132. package/dist/index.d.ts.map +1 -0
  133. package/dist/index.js +19 -0
  134. package/dist/index.js.map +1 -0
  135. package/dist/invoke.d.ts +36 -0
  136. package/dist/invoke.d.ts.map +1 -0
  137. package/dist/invoke.js +228 -0
  138. package/dist/invoke.js.map +1 -0
  139. package/dist/migrations-dir.d.ts +11 -0
  140. package/dist/migrations-dir.d.ts.map +1 -0
  141. package/dist/migrations-dir.js +14 -0
  142. package/dist/migrations-dir.js.map +1 -0
  143. package/dist/project-run-result.d.ts +23 -0
  144. package/dist/project-run-result.d.ts.map +1 -0
  145. package/dist/project-run-result.js +116 -0
  146. package/dist/project-run-result.js.map +1 -0
  147. package/dist/prompt.d.ts +83 -0
  148. package/dist/prompt.d.ts.map +1 -0
  149. package/dist/prompt.js +119 -0
  150. package/dist/prompt.js.map +1 -0
  151. package/dist/provenance-emit.d.ts +44 -0
  152. package/dist/provenance-emit.d.ts.map +1 -0
  153. package/dist/provenance-emit.js +51 -0
  154. package/dist/provenance-emit.js.map +1 -0
  155. package/dist/registry.d.ts +38 -0
  156. package/dist/registry.d.ts.map +1 -0
  157. package/dist/registry.js +125 -0
  158. package/dist/registry.js.map +1 -0
  159. package/dist/retrieval.d.ts +47 -0
  160. package/dist/retrieval.d.ts.map +1 -0
  161. package/dist/retrieval.js +155 -0
  162. package/dist/retrieval.js.map +1 -0
  163. package/dist/run-snapshot-binding.d.ts +77 -0
  164. package/dist/run-snapshot-binding.d.ts.map +1 -0
  165. package/dist/run-snapshot-binding.js +4 -0
  166. package/dist/run-snapshot-binding.js.map +1 -0
  167. package/dist/schema.d.ts +497 -0
  168. package/dist/schema.d.ts.map +1 -0
  169. package/dist/schema.js +133 -0
  170. package/dist/schema.js.map +1 -0
  171. package/dist/streaming.d.ts +118 -0
  172. package/dist/streaming.d.ts.map +1 -0
  173. package/dist/streaming.js +17 -0
  174. package/dist/streaming.js.map +1 -0
  175. package/dist/tenant-policy.d.ts +16 -0
  176. package/dist/tenant-policy.d.ts.map +1 -0
  177. package/dist/tenant-policy.js +77 -0
  178. package/dist/tenant-policy.js.map +1 -0
  179. package/dist/types.d.ts +435 -0
  180. package/dist/types.d.ts.map +1 -0
  181. package/dist/types.js +4 -0
  182. package/dist/types.js.map +1 -0
  183. package/dist/versioning.d.ts +29 -0
  184. package/dist/versioning.d.ts.map +1 -0
  185. package/dist/versioning.js +58 -0
  186. package/dist/versioning.js.map +1 -0
  187. package/migrations/0000_sparkling_talkback.sql +18 -0
  188. package/migrations/0001_tired_warhawk.sql +16 -0
  189. package/migrations/0002_violet_ezekiel.sql +2 -0
  190. package/migrations/meta/0000_snapshot.json +172 -0
  191. package/migrations/meta/0001_snapshot.json +275 -0
  192. package/migrations/meta/0002_snapshot.json +287 -0
  193. package/migrations/meta/_journal.json +27 -0
  194. package/package.json +76 -4
  195. package/src/agent-turn-flow.ts +183 -0
  196. package/src/conversation-binding.ts +147 -0
  197. package/src/define.ts +572 -0
  198. package/src/errors.ts +80 -0
  199. package/src/guardrails-gate.ts +342 -0
  200. package/src/handlers/budget-check.ts +143 -0
  201. package/src/handlers/build-initial-messages.ts +103 -0
  202. package/src/handlers/compose-result.ts +90 -0
  203. package/src/handlers/constants.ts +10 -0
  204. package/src/handlers/context.ts +226 -0
  205. package/src/handlers/dispatch-tools.ts +633 -0
  206. package/src/handlers/errors.ts +282 -0
  207. package/src/handlers/evaluate-guardrails.ts +153 -0
  208. package/src/handlers/final-iteration.ts +30 -0
  209. package/src/handlers/index.ts +63 -0
  210. package/src/handlers/model-call.ts +151 -0
  211. package/src/handlers/persist-final-message.ts +67 -0
  212. package/src/handlers/persist-provenance.ts +39 -0
  213. package/src/handlers/persist-user-message.ts +70 -0
  214. package/src/handlers/public-types.ts +209 -0
  215. package/src/handlers/rehydrate.ts +161 -0
  216. package/src/handlers/render-prompt.ts +46 -0
  217. package/src/handlers/resolve-tools.ts +68 -0
  218. package/src/handlers/result-shape.ts +113 -0
  219. package/src/handlers/run-retrievals.ts +77 -0
  220. package/src/handlers/run-snapshot.ts +44 -0
  221. package/src/handlers/setup.ts +269 -0
  222. package/src/handlers/structured-output.ts +117 -0
  223. package/src/handlers/tool-errors.ts +122 -0
  224. package/src/handlers/tool-hitl.ts +126 -0
  225. package/src/handlers/turn-environment.ts +191 -0
  226. package/src/hitl-policy.ts +128 -0
  227. package/src/index.ts +154 -0
  228. package/src/invoke.ts +299 -0
  229. package/src/migrations-dir.ts +17 -0
  230. package/src/project-run-result.ts +131 -0
  231. package/src/prompt.ts +185 -0
  232. package/src/provenance-emit.ts +100 -0
  233. package/src/registry.ts +164 -0
  234. package/src/retrieval.ts +219 -0
  235. package/src/run-snapshot-binding.ts +87 -0
  236. package/src/schema.ts +154 -0
  237. package/src/streaming.ts +153 -0
  238. package/src/tenant-policy.ts +78 -0
  239. package/src/types.ts +453 -0
  240. package/src/versioning.ts +77 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kindgi Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # @kindgi/agents
1
+ # `@kindgi/agents`
2
2
 
3
- A placeholder. Releases come from https://github.com/kindgi/kindgi-sdk.
3
+ Agent definitions and the agent-turn executor for Kindgi. `defineAgent` validates a declarative agent (instructions template, required model capabilities, versioned tool references, retrieval intents, guardrail ids, budgets, conversation and HITL policy) into a plain, serializable `Agent`. `invokeAgent` runs one turn of a conversation as a run of a built-in flow. Storage, model providers, tools, and the flow runtime are all supplied through binding interfaces, which a runtime adapter implements.
4
+
5
+ ## Purpose
6
+
7
+ Keep an agent a piece of data that can be versioned, stored, and pinned by `{ id, version }`, and keep every side effect behind an interface. Because a turn is a journaled flow run, it can park on a human approval and resume later with the same run id, conversation, and provenance record.
8
+
9
+ ## Exports
10
+
11
+ - **Defining agents**
12
+ - **`defineAgent(spec: DefineAgentSpec)`** — returns `Result<Agent, InvalidAgentError>`, collecting every validation issue with a `path` and `message`. `DefineAgentSpec` has the fields of `Agent` except `preferredModel`, with `id` and `version` as plain strings.
13
+ - **`Agent`** — `id` (`AgentId`), `version` (exact semver), `name`, `description?`, `instructions` (a LiquidJS template), `parameters?` (`PromptParameter[]`), `capabilities` (`Capability[]` from [`@kindgi/capabilities`](../capabilities/); a turn routes on the first entry), `tools`, `retrieval`, `guardrails` (guardrail ids), `preferredProvider?`, `preferredModel?`, `conversationPolicy?`, `budget?`, `tags?`.
14
+ - **`ToolRef`** — `{ id, version }`, where `version` is an npm-style semver range (`'1.2.3'`, `'^1.2.3'`, `'~1.2.3'`, `'>=1.0.0 <2.0.0'`) resolved at run start against the tenant's tool registry (`ToolRegistry.forTenant`). Bare tool ids are rejected.
15
+ - **`RetrievalIntent`** — `types`, `scope` (`same-conversation`, `same-project`, `tenant`), `limit?` (default 10), `mode?` (`keyword`, `semantic`, `both`; omitted lists the latest facts of each type).
16
+ - **`ConversationPolicy`** — `historyLimit?` (prior messages loaded into the prompt), `autoCloseAfterInactiveSeconds?`, `hitlAfterTurns?`, and `hitl?`: a session gate (`afterTurns`), per-tool gates (`tools.default` and `tools.overrides` with modes `never_ask`, `ask_on_first_use`, `always_ask` and an optional `requiredRole`), `defaultReviewerRole`, and `timeoutMs`. Tool gates apply only when `hitl.tools` is set.
17
+ - **`TurnBudget`** — `maxSteps` (default 8), `maxCostUsd`, `maxWallMs` (default 120 000).
18
+ - **`PromptParameter`**, **`AgentId`**, **`ConversationId`** (re-exported from [`@kindgi/types`](../types/)).
19
+ - **`createAgentRegistry(seed?)`** — an in-memory **`AgentRegistry`** keyed by `(id, version)`: `register`, `get(id, version?)`, `getLatest`, `list`, `listVersions`, `unregister`.
20
+ - **Prompt rendering**
21
+ - **`renderInstructions(agent, context: RenderContext)`** — renders `instructions` in LiquidJS strict mode and returns `{ ok: true, value: RenderResult }` or `{ ok: false, error: PromptRenderError }`. A missing required parameter or unresolved variable is a `missing-parameter` error (`MissingParameterError`), never an empty string; other failures are `render-failure` (`RenderFailureError`). `RenderResult.context` holds every value the template saw.
22
+ - **`AUTO_INJECTED_VARS`** — `today`, `now`, `agent` (`id`, `name`, `version`), `conversation` (`id`, `turn`). These names are reserved and cannot be declared as parameters.
23
+ - **Running turns**
24
+ - **`invokeAgent(input: InvokeAgentInput, bindings: InvokeAgentBindings)`** — returns `Promise<Result<AgentTurnResult, InvokeAgentError>>`.
25
+ - `InvokeAgentInput` — `tenantId`, `projectId`, `agent`, `conversationId` (of a conversation opened with the same agent version), `userMessage`, and optional `parameters`, `participantId`, `abortSignal`, `dryRun` (no conversation, memory or provenance writes; the model call is skipped), `principal` and `authz` (when both are set, tool calls are authorized against the principal; see [`@kindgi/authz`](../authz/)).
26
+ - `InvokeAgentBindings` — `providerRegistry`, `toolRegistry` (the turn resolves tools on `toolRegistry.forTenant(tenantId)`, so it never sees another tenant's tools), `memoryBinding` (a `MemoryQueryBinding` from [`@kindgi/memory`](../memory/)), `conversationBinding`, `runSnapshotBinding`, and `runBinding` (a `RunBinding` from [`@kindgi/runtime`](../runtime/); optional in the type, required at call time); optionally `tenantPolicy`, `policyRegistry`, `embeddingRegistry`, `embeddingModel`, `onEvent`, `provenance`, `hitl`, `resolveSecret`, and the `GuardrailsBindings` fields (`guardrails`, `checks`, `compliance`). `tenantPolicy` and the policy derived from `policyRegistry` are merged so the result is at least as strict as each (allow lists intersect, deny lists union, the smaller cap wins); the merged policy governs model routing and the models llm-judge guardrails may use.
27
+ - `AgentTurnResult` — `conversationId`, `turnNumber`, `appended`, `response`, `retrieved`, `violations` (failed guardrails whose action is not `halt` — reported, not carried out), `usage` (`AgentTurnUsage`), `provider`, and optional `provenance`, `dryRun`, `status`. `status: 'suspended'` means the run parked on a HITL approval; the response fields are placeholders until it resumes.
28
+ - **`resumeAgentTurn(input: ResumeAgentTurnInput, bindings)`** — continues a suspended turn after its approval resolves. The caller passes the `Agent` at the version the run started with.
29
+ - It rebuilds the turn input from the run snapshot, and the turn's state from the run's journal and the conversation. That state is the environment `setup` resolved, routed to the same provider and model, plus the messages the turn stored, its retrieved facts and its usage.
30
+ - The turn goes on from the step it parked in. Calls that ran before the park keep their stored results.
31
+ - Provenance recorded before the park isn't rebuilt.
32
+ - Errors:
33
+ - `run-snapshot-missing` when no snapshot was stored;
34
+ - `run-journal-unavailable` when the journal can't be read;
35
+ - `capability-routing-failed` when the turn's provider or model is no longer registered or allowed.
36
+ - **`InvokeAgentError`** — the `AgentError` variants plus `UnresolvedToolError`, `tool-version-unresolvable`, `CapabilityRoutingError`, `ModelInvocationError`, `ToolInvocationError`, `BudgetExceededError` (`kind`: `steps` or `cost`), `AgentTurnAbortedError` (`reason`: `external`, or `timeout` when `maxWallMs` elapses), `HitlRequiredError`, `GuardrailViolationError`, `UnresolvedGuardrailError`, `TenantPolicyUnavailableError` (`code: 'tenant-policy-unavailable'`, with the `policyKind`: a tenant policy the turn must apply could not be evaluated, so the turn fails rather than run without it).
37
+ - **Streaming** — `bindings.onEvent` (`OnTurnEvent`, sync or async) receives each `TurnEvent`: `turn.started`, `retrieval.completed`, `model.call.started`, `model.call.completed`, `tool.started`, `tool.completed`, `tool.failed`, `agent.message`, `guardrail.violated`, `turn.completed`, `turn.failed`. Each has an exported type (`TurnStartedEvent`, `ToolStartedEvent`, …). Exceptions thrown by the handler are swallowed.
38
+ - **Turn flow**
39
+ - **`AGENT_TURN_FLOW`** — the [`@kindgi/flow`](../flow/) `Flow` every turn runs, with **`AGENT_TURN_FLOW_ID`** (`'agent.turn'`), **`AGENT_TURN_FLOW_VERSION`** (`'1.1.0'`), **`AGENT_TURN_LOOP_MAX_ITERATIONS`** (32), and one `*_NODE` constant per node id as it appears in run journals: `setup` → `render-prompt` → `persist-user-message` → `run-retrievals` → `build-initial-messages` → `agent-loop` (`model-call` → `dispatch-tools` → `budget-check`) → `evaluate-guardrails` → `persist-final-message` → `persist-provenance` → `compose-result`. Guardrails are evaluated once per turn, on the final response before it is stored; a failed check whose action is `halt` fails the turn with `guardrail-violation`, and the response is never written to the conversation. Failures with any other action (`log-only`, `retry`, `escalate`, `compensate`, or a custom action — guardrail kinds and actions are open strings) are reported in `violations` and as `guardrail.violated` events; the turn does not carry them out.
40
+ - Steps usable on their own: **`runRetrievals`** with **`RetrievalBindings`** and **`formatRetrievedForPrompt`** (`RetrievedFact` pairs a fact with the intent that fetched it); **`resolveGuardrails`**, **`buildRunTrace`**, **`evaluateGate`** (takes the turn's tenant policy, under which llm-judge guardrails route), **`categorizeOutcomes`**, **`evaluateSessionGate`** (`SessionGateResult`) with **`GuardrailsBindings`**; **`persistProvenance`** with **`ProvenanceBindings`** (`newBuilder`, `emit`, `emitBinding`, `keyProvider`).
41
+ - **`resolveEffectiveHitlPolicy({ tenant, agent })`** — returns an `EffectiveHitlPolicy`: framework defaults (24 h timeout, `standard` reviewer, `escalate` on timeout) overlaid with the agent's policy, then held to the tenant's `hitl` policy (`tenant`: a `HitlSpec` from [`@kindgi/policy-contract`](../policy-contract/), or `undefined`), which can only tighten: it caps the timeout, raises the reviewer role, and sets `toolFloors` — per tool, a gate is the stricter of the agent's and the tenant's. Each turn resolves it once, evaluating `hitl` through `policyRegistry`; an evaluation that throws fails the turn with `tenant-policy-unavailable`.
42
+ - **Bindings**, implemented by a runtime adapter
43
+ - **`ConversationBinding`** — `openConversation`, `getConversation`, `listConversations`, `listConversationsPage` (keyset pagination by `openedAt DESC, id DESC` with a `ConversationPageCursor`), `closeConversation`, `deleteConversation`, `appendMessage`, `readMessages`. Inputs: `OpenConversationInput`, `ListConversationsInput`, `ListConversationsPageInput`, `AppendMessageInput`, `ReadMessagesInput`; results: `Conversation`, `ConversationPage`, `ConversationMessage` (`MessageRole`: `user`, `agent`, `tool`, `system`).
44
+ - **`RunSnapshotBinding`** — `write(RunSnapshotWriteInput)` and `read(tenantId, runId)` of the `RunSnapshotRecord` that `resumeAgentTurn` needs. Writes must be idempotent per run id.
45
+ - **Postgres support** — Drizzle tables `agentConversations` and `agentRunSnapshots` with their row types (`AgentConversationRow`, `NewAgentConversationRow`, `AgentRunSnapshotRow`, `NewAgentRunSnapshotRow`), `AGENTS_TENANT_SCOPED_TABLES`, `AGENTS_MIGRATIONS_DIR` (absolute path to the bundled SQL migrations), and the `{ v, doc }` JSONB envelope helpers `wrap`, `unwrap`, `unwrapOrThrow`, `CURRENT_AGENTS_PAYLOAD_VERSION` with `EnvelopeError`, `MalformedEnvelopeError`, `UnsupportedPayloadVersionError`.
46
+ - **Errors** — **`AgentError`**: `InvalidAgentError`, `AgentNotFoundError`, `AgentAlreadyRegisteredError`, `AgentVersionMismatchError`, `ConversationNotFoundError`, `ConversationClosedError`, `InvalidMessageError`, `PersistenceError`. Every error carries a `code`.
47
+
48
+ ## Example
49
+
50
+ ```ts
51
+ import { defineAgent, invokeAgent } from '@kindgi/agents';
52
+ import type { InvokeAgentBindings } from '@kindgi/agents';
53
+ import type { ProjectId, TenantId } from '@kindgi/types';
54
+
55
+ const drafter = defineAgent({
56
+ id: 'acme.contract-drafter',
57
+ version: '1.0.0',
58
+ name: 'Contract Drafter',
59
+ instructions: 'You draft contract clauses for {{ firmName }}. Today is {{ today }}.',
60
+ parameters: [{ name: 'firmName', type: 'string' }],
61
+ capabilities: [{ needs: [{ feature: 'tool-use' }] }],
62
+ tools: [
63
+ { id: 'acme.clause-search', version: '^1.0.0' },
64
+ { id: 'acme.send-email', version: '~2.1.0' },
65
+ ],
66
+ retrieval: [{ types: ['acme.clause'], scope: 'same-project', mode: 'keyword', limit: 5 }],
67
+ guardrails: ['acme.no-pii'],
68
+ conversationPolicy: {
69
+ historyLimit: 20,
70
+ hitl: { tools: { overrides: { 'acme.send-email': 'always_ask' } } },
71
+ },
72
+ budget: { maxSteps: 6, maxCostUsd: 0.25, maxWallMs: 60_000 },
73
+ });
74
+ if (drafter.kind === 'err') throw new Error(JSON.stringify(drafter.error.issues));
75
+ const agent = drafter.value;
76
+
77
+ // `bindings` come from the runtime that hosts the agent, or from your own implementations.
78
+ export async function firstTurn(
79
+ bindings: InvokeAgentBindings,
80
+ tenantId: TenantId,
81
+ projectId: ProjectId,
82
+ userMessage: string,
83
+ ): Promise<string | undefined> {
84
+ const conversation = await bindings.conversationBinding.openConversation({
85
+ tenantId,
86
+ agentId: agent.id,
87
+ agentVersion: agent.version,
88
+ title: 'NDA for globex',
89
+ scope: { tenantId, projectId },
90
+ });
91
+ if (conversation.kind === 'err') throw new Error(conversation.error.message);
92
+
93
+ const result = await invokeAgent(
94
+ {
95
+ tenantId,
96
+ projectId,
97
+ agent,
98
+ conversationId: conversation.value.id,
99
+ userMessage,
100
+ parameters: { firmName: 'Acme LLP' },
101
+ },
102
+ {
103
+ ...bindings,
104
+ onEvent: (event) => {
105
+ if (event.kind === 'tool.started') console.log(`calling ${event.toolId}@${event.toolVersion}`);
106
+ },
107
+ },
108
+ );
109
+
110
+ if (result.kind === 'err') {
111
+ if (result.error.code === 'budget-exceeded') return `Stopped: ${result.error.kind} budget exceeded`;
112
+ throw new Error(`${result.error.code}: ${result.error.message}`);
113
+ }
114
+ if (result.value.status === 'suspended') return undefined; // waiting for a reviewer; see resumeAgentTurn
115
+ const { content } = result.value.response;
116
+ return typeof content === 'string' ? content : JSON.stringify(content);
117
+ }
118
+ ```
119
+
120
+ ## Non-goals
121
+
122
+ - **No storage or model access of its own.** Conversations, messages, run snapshots, memory, provenance, providers, tools, and flow execution all go through the bindings; the package ships Drizzle tables and migrations for Postgres implementations but never opens a database connection.
123
+ - **No tenancy in the agent registry.** `AgentRegistry` is a plain in-memory catalog; multi-tenant deployments keep one registry per tenant or layer isolation on top.
124
+ - **No moving a conversation to a new agent version.** A conversation stays pinned to the agent version it was opened with; invoking it with another version fails with `agent-version-mismatch`, and a closed conversation cannot be reopened.
125
+
126
+ ## Related
127
+
128
+ - [`@kindgi/sdk`](../sdk/) — re-exports `defineAgent`, `Agent`, and `DefineAgentSpec` from `@kindgi/sdk/define`.
129
+ - [`@kindgi/capabilities`](../capabilities/) — capability declarations and the router that picks a model for each turn.
130
+ - [`@kindgi/tools`](../tools/) and [`@kindgi/guardrails`](../guardrails/) — tool and check definitions referenced by `tools` and `guardrails`.
131
+ - [`@kindgi/memory`](../memory/) and [`@kindgi/provenance`](../provenance/) — the memory binding used for retrieval, and the provenance record built for each turn.
132
+ - [`@kindgi/flow`](../flow/) and [`@kindgi/runtime`](../runtime/) — the flow model and the `RunBinding` that executes the agent-turn flow.
@@ -0,0 +1,57 @@
1
+ import type { Flow } from '@kindgi/flow';
2
+ /**
3
+ * The versioned agent-turn flow. Every agent turn — regardless of which
4
+ * concrete `Agent` is being invoked — executes as a run of this flow
5
+ * against handlers that close over the specific agent + bindings + input.
6
+ *
7
+ * Shape (uses the kernel loop primitive for the model↔tool cycle):
8
+ *
9
+ * ```
10
+ * $start → setup → render-prompt → persist-user-message → run-retrievals
11
+ * → build-initial-messages → agent-loop (kernel loop node)
12
+ * → evaluate-guardrails → persist-final-message → persist-provenance
13
+ * → compose-result → $end
14
+ * ```
15
+ *
16
+ * Guardrails run on the final response before it is stored: a response
17
+ * a blocking guardrail rejects never reaches the conversation.
18
+ *
19
+ * `agent-loop` is a `while+after` (do-while) loop; its body is
20
+ * `$loop-start → model-call → dispatch-tools → budget-check → $loop-end`.
21
+ * Exit condition: `iterationOutput.finishedTurn === true`.
22
+ * `collectAllIterations: true` so post-loop nodes can aggregate every
23
+ * iteration's per-iteration usage + appended messages.
24
+ *
25
+ * Version-locked so historical runs pin to this shape; any
26
+ * change to the node set or body sub-flow bumps the version and
27
+ * `resumeRun` refuses to resume old runs against a new flow.
28
+ */
29
+ export declare const AGENT_TURN_FLOW_ID = "agent.turn";
30
+ export declare const AGENT_TURN_FLOW_VERSION = "1.1.0";
31
+ /**
32
+ * Safety cap for iterations. Per-agent `maxSteps` is enforced by the
33
+ * `budget-check` body node — this constant only bounds catastrophic
34
+ * runaway (model always requests a tool call, no budget-check, no
35
+ * agent config). Set high enough that no real agent will hit it.
36
+ */
37
+ export declare const AGENT_TURN_LOOP_MAX_ITERATIONS = 32;
38
+ export declare const SETUP_NODE = "setup";
39
+ export declare const RENDER_PROMPT_NODE = "render-prompt";
40
+ export declare const PERSIST_USER_MESSAGE_NODE = "persist-user-message";
41
+ export declare const RUN_RETRIEVALS_NODE = "run-retrievals";
42
+ export declare const BUILD_INITIAL_MESSAGES_NODE = "build-initial-messages";
43
+ export declare const AGENT_LOOP_NODE = "agent-loop";
44
+ export declare const PERSIST_FINAL_MESSAGE_NODE = "persist-final-message";
45
+ export declare const EVALUATE_GUARDRAILS_NODE = "evaluate-guardrails";
46
+ export declare const PERSIST_PROVENANCE_NODE = "persist-provenance";
47
+ export declare const COMPOSE_RESULT_NODE = "compose-result";
48
+ export declare const MODEL_CALL_NODE = "model-call";
49
+ export declare const DISPATCH_TOOLS_NODE = "dispatch-tools";
50
+ export declare const BUDGET_CHECK_NODE = "budget-check";
51
+ /**
52
+ * The compiled + validated flow. Cached — the loader is called once
53
+ * at module load. Throws on module load if the constant is malformed
54
+ * (should be caught by tests immediately).
55
+ */
56
+ export declare const AGENT_TURN_FLOW: Flow;
57
+ //# sourceMappingURL=agent-turn-flow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-turn-flow.d.ts","sourceRoot":"","sources":["../src/agent-turn-flow.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAGzC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,kBAAkB,eAAe,CAAC;AAC/C,eAAO,MAAM,uBAAuB,UAAU,CAAC;AAE/C;;;;;GAKG;AACH,eAAO,MAAM,8BAA8B,KAAK,CAAC;AAGjD,eAAO,MAAM,UAAU,UAAU,CAAC;AAClC,eAAO,MAAM,kBAAkB,kBAAkB,CAAC;AAClD,eAAO,MAAM,yBAAyB,yBAAyB,CAAC;AAChE,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AACpD,eAAO,MAAM,2BAA2B,2BAA2B,CAAC;AACpE,eAAO,MAAM,eAAe,eAAe,CAAC;AAC5C,eAAO,MAAM,0BAA0B,0BAA0B,CAAC;AAClE,eAAO,MAAM,wBAAwB,wBAAwB,CAAC;AAC9D,eAAO,MAAM,uBAAuB,uBAAuB,CAAC;AAC5D,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AAGpD,eAAO,MAAM,eAAe,eAAe,CAAC;AAC5C,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AACpD,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AA8GhD;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,IAQ1B,CAAC"}
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ import { loadFlow } from '@kindgi/flow';
4
+ /**
5
+ * The versioned agent-turn flow. Every agent turn — regardless of which
6
+ * concrete `Agent` is being invoked — executes as a run of this flow
7
+ * against handlers that close over the specific agent + bindings + input.
8
+ *
9
+ * Shape (uses the kernel loop primitive for the model↔tool cycle):
10
+ *
11
+ * ```
12
+ * $start → setup → render-prompt → persist-user-message → run-retrievals
13
+ * → build-initial-messages → agent-loop (kernel loop node)
14
+ * → evaluate-guardrails → persist-final-message → persist-provenance
15
+ * → compose-result → $end
16
+ * ```
17
+ *
18
+ * Guardrails run on the final response before it is stored: a response
19
+ * a blocking guardrail rejects never reaches the conversation.
20
+ *
21
+ * `agent-loop` is a `while+after` (do-while) loop; its body is
22
+ * `$loop-start → model-call → dispatch-tools → budget-check → $loop-end`.
23
+ * Exit condition: `iterationOutput.finishedTurn === true`.
24
+ * `collectAllIterations: true` so post-loop nodes can aggregate every
25
+ * iteration's per-iteration usage + appended messages.
26
+ *
27
+ * Version-locked so historical runs pin to this shape; any
28
+ * change to the node set or body sub-flow bumps the version and
29
+ * `resumeRun` refuses to resume old runs against a new flow.
30
+ */
31
+ export const AGENT_TURN_FLOW_ID = 'agent.turn';
32
+ export const AGENT_TURN_FLOW_VERSION = '1.1.0';
33
+ /**
34
+ * Safety cap for iterations. Per-agent `maxSteps` is enforced by the
35
+ * `budget-check` body node — this constant only bounds catastrophic
36
+ * runaway (model always requests a tool call, no budget-check, no
37
+ * agent config). Set high enough that no real agent will hit it.
38
+ */
39
+ export const AGENT_TURN_LOOP_MAX_ITERATIONS = 32;
40
+ // Outer node ids.
41
+ export const SETUP_NODE = 'setup';
42
+ export const RENDER_PROMPT_NODE = 'render-prompt';
43
+ export const PERSIST_USER_MESSAGE_NODE = 'persist-user-message';
44
+ export const RUN_RETRIEVALS_NODE = 'run-retrievals';
45
+ export const BUILD_INITIAL_MESSAGES_NODE = 'build-initial-messages';
46
+ export const AGENT_LOOP_NODE = 'agent-loop';
47
+ export const PERSIST_FINAL_MESSAGE_NODE = 'persist-final-message';
48
+ export const EVALUATE_GUARDRAILS_NODE = 'evaluate-guardrails';
49
+ export const PERSIST_PROVENANCE_NODE = 'persist-provenance';
50
+ export const COMPOSE_RESULT_NODE = 'compose-result';
51
+ // Loop body node ids.
52
+ export const MODEL_CALL_NODE = 'model-call';
53
+ export const DISPATCH_TOOLS_NODE = 'dispatch-tools';
54
+ export const BUDGET_CHECK_NODE = 'budget-check';
55
+ /**
56
+ * JSON Schema (draft 2020-12) for each iteration's `$loop-end` output.
57
+ * See `AgentTurnIterationOutput` in the handlers module for the TS
58
+ * mirror.
59
+ */
60
+ const iterationOutputSchema = {
61
+ type: 'object',
62
+ additionalProperties: false,
63
+ required: [
64
+ 'finishReason',
65
+ 'message',
66
+ 'iterationAppended',
67
+ 'iterationUsage',
68
+ 'provider',
69
+ 'finishedTurn',
70
+ 'nextMessages',
71
+ ],
72
+ properties: {
73
+ finishReason: {
74
+ type: 'string',
75
+ enum: ['stop', 'length', 'tool-use', 'content-filter', 'error'],
76
+ },
77
+ message: { type: 'object' },
78
+ iterationAppended: { type: 'array' },
79
+ iterationUsage: {
80
+ type: 'object',
81
+ additionalProperties: false,
82
+ required: ['promptTokens', 'completionTokens', 'costUsd'],
83
+ properties: {
84
+ promptTokens: { type: 'integer', minimum: 0 },
85
+ completionTokens: { type: 'integer', minimum: 0 },
86
+ costUsd: { type: 'number', minimum: 0 },
87
+ },
88
+ },
89
+ provider: {
90
+ type: 'object',
91
+ additionalProperties: false,
92
+ required: ['id', 'model'],
93
+ properties: {
94
+ id: { type: 'string' },
95
+ model: { type: 'string' },
96
+ },
97
+ },
98
+ finishedTurn: { type: 'boolean' },
99
+ nextMessages: { type: 'array' },
100
+ /** Populated when finishReason='error' from budget-check or dispatch failure. */
101
+ errorPayload: { type: 'object' },
102
+ },
103
+ };
104
+ const rawGraph = {
105
+ id: AGENT_TURN_FLOW_ID,
106
+ version: AGENT_TURN_FLOW_VERSION,
107
+ name: 'Agent turn',
108
+ description: 'Framework-grade agent turn execution. One run per turn. Model↔tool cycle uses the kernel loop primitive.',
109
+ nodes: [
110
+ { id: SETUP_NODE, kind: 'tool', ref: 'inline' },
111
+ { id: RENDER_PROMPT_NODE, kind: 'tool', ref: 'inline' },
112
+ { id: PERSIST_USER_MESSAGE_NODE, kind: 'tool', ref: 'inline' },
113
+ { id: RUN_RETRIEVALS_NODE, kind: 'tool', ref: 'inline' },
114
+ { id: BUILD_INITIAL_MESSAGES_NODE, kind: 'tool', ref: 'inline' },
115
+ {
116
+ id: AGENT_LOOP_NODE,
117
+ kind: 'loop',
118
+ loopKind: 'while',
119
+ evaluationTiming: 'after',
120
+ maxIterations: AGENT_TURN_LOOP_MAX_ITERATIONS,
121
+ exitCondition: {
122
+ op: 'truthy',
123
+ value: { path: 'iterationOutput.finishedTurn' },
124
+ },
125
+ outputSchema: iterationOutputSchema,
126
+ collectAllIterations: true,
127
+ body: {
128
+ nodes: [
129
+ { id: MODEL_CALL_NODE, kind: 'tool', ref: 'inline' },
130
+ { id: DISPATCH_TOOLS_NODE, kind: 'tool', ref: 'inline' },
131
+ { id: BUDGET_CHECK_NODE, kind: 'tool', ref: 'inline' },
132
+ ],
133
+ edges: [
134
+ { id: 'body-e1', from: '$loop-start', to: MODEL_CALL_NODE },
135
+ { id: 'body-e2', from: MODEL_CALL_NODE, to: DISPATCH_TOOLS_NODE },
136
+ { id: 'body-e3', from: DISPATCH_TOOLS_NODE, to: BUDGET_CHECK_NODE },
137
+ { id: 'body-e4', from: BUDGET_CHECK_NODE, to: '$loop-end' },
138
+ ],
139
+ },
140
+ },
141
+ { id: EVALUATE_GUARDRAILS_NODE, kind: 'tool', ref: 'inline' },
142
+ { id: PERSIST_FINAL_MESSAGE_NODE, kind: 'tool', ref: 'inline' },
143
+ { id: PERSIST_PROVENANCE_NODE, kind: 'tool', ref: 'inline' },
144
+ { id: COMPOSE_RESULT_NODE, kind: 'tool', ref: 'inline' },
145
+ ],
146
+ edges: [
147
+ { id: 'e0', from: '$start', to: SETUP_NODE },
148
+ { id: 'e1', from: SETUP_NODE, to: RENDER_PROMPT_NODE },
149
+ { id: 'e2', from: RENDER_PROMPT_NODE, to: PERSIST_USER_MESSAGE_NODE },
150
+ { id: 'e3', from: PERSIST_USER_MESSAGE_NODE, to: RUN_RETRIEVALS_NODE },
151
+ { id: 'e4', from: RUN_RETRIEVALS_NODE, to: BUILD_INITIAL_MESSAGES_NODE },
152
+ { id: 'e5', from: BUILD_INITIAL_MESSAGES_NODE, to: AGENT_LOOP_NODE },
153
+ { id: 'e6', from: AGENT_LOOP_NODE, to: EVALUATE_GUARDRAILS_NODE },
154
+ { id: 'e7', from: EVALUATE_GUARDRAILS_NODE, to: PERSIST_FINAL_MESSAGE_NODE },
155
+ { id: 'e8', from: PERSIST_FINAL_MESSAGE_NODE, to: PERSIST_PROVENANCE_NODE },
156
+ { id: 'e9', from: PERSIST_PROVENANCE_NODE, to: COMPOSE_RESULT_NODE },
157
+ { id: 'e10', from: COMPOSE_RESULT_NODE, to: '$end' },
158
+ ],
159
+ };
160
+ /**
161
+ * The compiled + validated flow. Cached — the loader is called once
162
+ * at module load. Throws on module load if the constant is malformed
163
+ * (should be caught by tests immediately).
164
+ */
165
+ export const AGENT_TURN_FLOW = (() => {
166
+ const r = loadFlow(rawGraph);
167
+ if (r.kind === 'err') {
168
+ throw new Error(`AGENT_TURN_FLOW failed to load — this is a bug in agent-turn-flow.ts: ${JSON.stringify(r.error)}`);
169
+ }
170
+ return r.value;
171
+ })();
172
+ //# sourceMappingURL=agent-turn-flow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-turn-flow.js","sourceRoot":"","sources":["../src/agent-turn-flow.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAGjC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AAC/C,MAAM,CAAC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAEjD,kBAAkB;AAClB,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC;AAClC,MAAM,CAAC,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAClD,MAAM,CAAC,MAAM,yBAAyB,GAAG,sBAAsB,CA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