@kindgi/agents 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -0,0 +1,94 @@
1
+ import type { EvaluationResult } from '@kindgi/guardrails';
2
+ import type { Provenance } from '@kindgi/provenance';
3
+ import type { RunId } from '@kindgi/types';
4
+ import type { ConversationId, ConversationMessage, RetrievedFact } from '../types.js';
5
+ /**
6
+ * Public shape returned by `invokeAgent` on success. Extracted from
7
+ * `invoke.ts` into this module so handler code can import the type
8
+ * without pulling in the orchestration entrypoint (avoids circular
9
+ * deps).
10
+ */
11
+ export interface AgentTurnUsage {
12
+ readonly steps: number;
13
+ readonly promptTokens: number;
14
+ readonly completionTokens: number;
15
+ readonly totalCostUsd: number;
16
+ readonly durationMs: number;
17
+ }
18
+ /**
19
+ * Something about a completed turn its caller should know.
20
+ * `fallback-provider`: the turn ran on a fallback provider
21
+ * (`ProviderMetadata.fallback`, e.g. `dev-echo`) because no other
22
+ * registered provider satisfies the agent's capability.
23
+ */
24
+ export interface AgentTurnWarning {
25
+ readonly code: 'fallback-provider';
26
+ readonly message: string;
27
+ }
28
+ export interface AgentTurnResult {
29
+ /** The kernel run of this turn. */
30
+ readonly runId: RunId;
31
+ readonly conversationId: ConversationId;
32
+ readonly turnNumber: number;
33
+ readonly appended: readonly ConversationMessage[];
34
+ readonly response: ConversationMessage;
35
+ readonly retrieved: readonly RetrievedFact[];
36
+ readonly violations: readonly EvaluationResult[];
37
+ readonly usage: AgentTurnUsage;
38
+ readonly provider: {
39
+ readonly id: string;
40
+ readonly model: string;
41
+ };
42
+ /** Present when there is something to warn about (see `AgentTurnWarning`). */
43
+ readonly warnings?: readonly AgentTurnWarning[];
44
+ /**
45
+ * The parsed, schema-valid answer, when the agent declares `output`.
46
+ * `null` on a dry run (the model call is skipped, so there is no
47
+ * answer to validate).
48
+ */
49
+ readonly output?: unknown;
50
+ readonly provenance?: Provenance;
51
+ /**
52
+ * `true` when the turn was executed with `InvokeAgentInput.dryRun: true`.
53
+ * On dry runs: `appended` messages are synthetic (never persisted);
54
+ * no provenance is emitted; retrievals still ran for real (reads are
55
+ * side-effect-free); the model call was skipped and returned a fixed
56
+ * mock. Consumers filter by this to distinguish plan previews from
57
+ * executed turns.
58
+ */
59
+ readonly dryRun?: boolean;
60
+ /**
61
+ * Terminal state of the run backing this turn (park-and-resume).
62
+ * Absent = 'completed'. `'suspended'` = the run parked on a HITL waitpoint;
63
+ * `response`/`appended`/`usage` are empty placeholders until the
64
+ * waitpoint resolves and the run resumes to completion. Callers that
65
+ * render the final response should branch on this before reading
66
+ * `response.content`.
67
+ */
68
+ readonly status?: 'completed' | 'suspended';
69
+ }
70
+ /**
71
+ * What an agent step in a flow outputs — the authoring contract for the
72
+ * nodes after it. They read the typed answer as
73
+ * `nodeOutputs.<step>.output.<field>` and the answer's text as
74
+ * `nodeOutputs.<step>.text`.
75
+ */
76
+ export interface AgentStepOutput {
77
+ /** The parsed answer, when the agent declares `output`. */
78
+ readonly output?: unknown;
79
+ /** The final answer's text. */
80
+ readonly text: string;
81
+ /** The step's agent turn — a child run of the flow run. */
82
+ readonly runId: RunId;
83
+ readonly conversationId: ConversationId;
84
+ readonly usage: AgentTurnUsage;
85
+ /** Non-blocking guardrail findings on the answer. */
86
+ readonly violations: readonly {
87
+ readonly guardrailId: string;
88
+ readonly severity: string;
89
+ readonly action: string;
90
+ }[];
91
+ }
92
+ /** An agent step's output, from its turn's result. */
93
+ export declare function agentStepOutput(result: AgentTurnResult): AgentStepOutput;
94
+ //# sourceMappingURL=result-shape.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-shape.d.ts","sourceRoot":"","sources":["../../src/handlers/result-shape.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEtF;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,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2D;IAC3D,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,+BAA+B;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,2DAA2D;IAC3D,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,qDAAqD;IACrD,QAAQ,CAAC,UAAU,EAAE,SAAS;QAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;QAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;KACzB,EAAE,CAAC;CACL;AAED,sDAAsD;AACtD,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,GAAG,eAAe,CAcxE"}
@@ -0,0 +1,19 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ /** An agent step's output, from its turn's result. */
4
+ export function agentStepOutput(result) {
5
+ const content = result.response.content;
6
+ return {
7
+ ...(result.output !== undefined && { output: result.output }),
8
+ text: typeof content === 'string' ? content : JSON.stringify(content),
9
+ runId: result.runId,
10
+ conversationId: result.conversationId,
11
+ usage: result.usage,
12
+ violations: result.violations.map((v) => ({
13
+ guardrailId: v.guardrailId,
14
+ severity: v.severity,
15
+ action: v.action,
16
+ })),
17
+ };
18
+ }
19
+ //# sourceMappingURL=result-shape.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-shape.js","sourceRoot":"","sources":["../../src/handlers/result-shape.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAgGjC,sDAAsD;AACtD,MAAM,UAAU,eAAe,CAAC,MAAuB;IACrD,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;IACxC,OAAO;QACL,GAAG,CAAC,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;QAC7D,IAAI,EAAE,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;QACrE,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACxC,WAAW,EAAE,CAAC,CAAC,WAAgC;YAC/C,QAAQ,EAAE,CAAC,CAAC,QAAQ;YACpB,MAAM,EAAE,CAAC,CAAC,MAAM;SACjB,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { NodeHandler } from '@kindgi/handler';
2
+ import type { TurnContext } from './context.js';
3
+ /**
4
+ * Execute the agent's declared retrieval intents. Populates
5
+ * `ctx.retrieved` for downstream prompt building + emits
6
+ * `retrieval.completed`. Adds provenance nodes + edges when a builder
7
+ * is wired.
8
+ */
9
+ export declare function buildRunRetrievalsHandler(ctx: TurnContext): NodeHandler;
10
+ //# sourceMappingURL=run-retrievals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-retrievals.d.ts","sourceRoot":"","sources":["../../src/handlers/run-retrievals.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAKnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,WAAW,GAAG,WAAW,CA2DvE"}
@@ -0,0 +1,64 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ import { runRetrievals } from '../retrieval.js';
4
+ import { emitTurnEvent } from '../streaming.js';
5
+ import { throwAgentTurnFailure } from './errors.js';
6
+ /**
7
+ * Execute the agent's declared retrieval intents. Populates
8
+ * `ctx.retrieved` for downstream prompt building + emits
9
+ * `retrieval.completed`. Adds provenance nodes + edges when a builder
10
+ * is wired.
11
+ */
12
+ export function buildRunRetrievalsHandler(ctx) {
13
+ return async () => {
14
+ if (ctx.conversation === undefined || ctx.userMessage === undefined) {
15
+ throwAgentTurnFailure({
16
+ code: 'model-invocation-failed',
17
+ message: 'run-retrievals invoked before setup + persist-user-message completed',
18
+ cause: null,
19
+ });
20
+ }
21
+ const retrieved = await runRetrievals(ctx.input.agent, ctx.conversation, ctx.input.conversationId, ctx.input.userMessage, {
22
+ memory: ctx.bindings.memoryBinding,
23
+ ...(ctx.bindings.embeddingRegistry !== undefined && {
24
+ embeddingRegistry: ctx.bindings.embeddingRegistry,
25
+ }),
26
+ ...(ctx.bindings.embeddingModel !== undefined && {
27
+ embeddingModel: ctx.bindings.embeddingModel,
28
+ }),
29
+ });
30
+ if (retrieved.kind === 'err')
31
+ throwAgentTurnFailure(retrieved.error);
32
+ ctx.retrieved = retrieved.value;
33
+ await emitTurnEvent(ctx.bindings.onEvent, {
34
+ kind: 'retrieval.completed',
35
+ count: retrieved.value.length,
36
+ factIds: retrieved.value.map((r) => r.fact.id),
37
+ });
38
+ if (ctx.provenance !== undefined && ctx.userMessage !== undefined) {
39
+ for (const r of retrieved.value) {
40
+ ctx.provenance.addNode({
41
+ id: `retrieval:${r.fact.id}`,
42
+ kind: 'retrieval',
43
+ timestamp: ctx.userMessage.createdAt,
44
+ ...(r.fact.contentHash !== undefined && { contentHash: r.fact.contentHash }),
45
+ attributes: {
46
+ factId: r.fact.id,
47
+ factType: r.fact.type,
48
+ intentScope: r.intent.scope,
49
+ ...(r.score !== undefined && { score: r.score }),
50
+ },
51
+ });
52
+ ctx.provenance.addEdge({
53
+ from: `retrieval:${r.fact.id}`,
54
+ to: `input:${ctx.userMessage.sequence}`,
55
+ kind: 'influenced-by',
56
+ });
57
+ }
58
+ }
59
+ // The facts go in the journal: a resumed turn restores them from it
60
+ // (`rehydrateTurnContext`) rather than retrieving again.
61
+ return { count: retrieved.value.length, retrieved: retrieved.value };
62
+ };
63
+ }
64
+ //# sourceMappingURL=run-retrievals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-retrievals.js","sourceRoot":"","sources":["../../src/handlers/run-retrievals.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAIjC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGhD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,GAAgB;IACxD,OAAO,KAAK,IAAI,EAAE;QAChB,IAAI,GAAG,CAAC,YAAY,KAAK,SAAS,IAAI,GAAG,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACpE,qBAAqB,CAAC;gBACpB,IAAI,EAAE,yBAAyB;gBAC/B,OAAO,EAAE,sEAAsE;gBAC/E,KAAK,EAAE,IAAI;aACZ,CAAC,CAAC;QACL,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,aAAa,CACnC,GAAG,CAAC,KAAK,CAAC,KAAK,EACf,GAAG,CAAC,YAAY,EAChB,GAAG,CAAC,KAAK,CAAC,cAAc,EACxB,GAAG,CAAC,KAAK,CAAC,WAAW,EACrB;YACE,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,aAAa;YAClC,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,iBAAiB,KAAK,SAAS,IAAI;gBAClD,iBAAiB,EAAE,GAAG,CAAC,QAAQ,CAAC,iBAAiB;aAClD,CAAC;YACF,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,cAAc,KAAK,SAAS,IAAI;gBAC/C,cAAc,EA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,CAAC,CAAC;gBACH,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC;oBACrB,IAAI,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE;oBAC9B,EAAE,EAAE,SAAS,GAAG,CAAC,WAAW,CAAC,QAAQ,EAAE;oBACvC,IAAI,EAAE,eAAe;iBACtB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,oEAAoE;QACpE,yDAAyD;QACzD,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,KAAK,EAAE,CAAC;IACvE,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { NodeContext } from '@kindgi/handler';
2
+ import type { TurnContext } from './context.js';
3
+ export declare function writeRunSnapshot(ctx: TurnContext, kctx: NodeContext): Promise<void>;
4
+ //# sourceMappingURL=run-snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-snapshot.d.ts","sourceRoot":"","sources":["../../src/handlers/run-snapshot.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAsBzF"}
@@ -0,0 +1,26 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export async function writeRunSnapshot(ctx, kctx) {
4
+ // Snapshot write is best-effort: if it fails, the turn still proceeds.
5
+ // Resume paths will just get `run-snapshot-missing` and the caller
6
+ // knows to surface the run as unrecoverable. The alternative (throw
7
+ // and fail the turn) is worse — a snapshot-write hiccup shouldn't
8
+ // block a fresh turn from running. The RunSnapshotBinding impl must be
9
+ // idempotent under kernel replay (e.g. ON CONFLICT DO NOTHING on runId).
10
+ await ctx.bindings.runSnapshotBinding.write({
11
+ runId: kctx.runId,
12
+ tenantId: ctx.input.tenantId,
13
+ projectId: ctx.input.projectId,
14
+ agentId: ctx.input.agent.id,
15
+ agentVersion: ctx.input.agent.version,
16
+ conversationId: ctx.input.conversationId,
17
+ userMessage: ctx.input.userMessage,
18
+ ...(ctx.input.parameters !== undefined && { parameters: ctx.input.parameters }),
19
+ ...(ctx.input.input !== undefined && { input: ctx.input.input }),
20
+ ...(ctx.input.participantId !== undefined && { participantId: ctx.input.participantId }),
21
+ ...(ctx.input.dryRun === true && { dryRun: true }),
22
+ ...(ctx.input.principal !== undefined && { principal: ctx.input.principal }),
23
+ ...(ctx.input.authz !== undefined && { authz: ctx.input.authz }),
24
+ });
25
+ }
26
+ //# sourceMappingURL=run-snapshot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-snapshot.js","sourceRoot":"","sources":["../../src/handlers/run-snapshot.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAoBjC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,GAAgB,EAAE,IAAiB;IACxE,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpE,kEAAkE;IAClE,uEAAuE;IACvE,yEAAyE;IACzE,MAAM,GAAG,CAAC,QAAQ,CAAC,kBAAkB,CAAC,KAAK,CAAC;QAC1C,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,QAAQ;QAC5B,SAAS,EAAE,GAAG,CAAC,KAAK,CAAC,SAAS;QAC9B,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAC3B,YAAY,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO;QACrC,cAAc,EAAE,GAAG,CAAC,KAAK,CAAC,cAAc;QACxC,WAAW,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW;QAClC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,KAAK,SAAS,IAAI,EAAE,UAAU,EAAE,GAAG,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;QAC/E,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QAChE,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,KAAK,SAAS,IAAI,EAAE,aAAa,EAAE,GAAG,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACxF,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,KAAK,IAAI,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QAClD,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,EAAE,SAAS,EAAE,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QAC5E,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;KACjE,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { NodeHandler } from '@kindgi/handler';
2
+ import type { TurnContext } from './context.js';
3
+ /**
4
+ * The first node in the flow. Runs every precondition check in one
5
+ * gate so the run either commits to a full turn or fails fast before
6
+ * the user message is stored in the conversation (only the run
7
+ * snapshot is written first):
8
+ *
9
+ * 1. Load + validate conversation (open, not closed, matches agent version).
10
+ * 2. Session-level HITL gate (`conversationPolicy.hitl.afterTurns` /
11
+ * `hitlAfterTurns`).
12
+ * 3. Resolve declared guardrails against the guardrails bound for the run.
13
+ * 4. Resolve declared tools against the tenant's tool registry
14
+ * (`ToolRegistry.forTenant`).
15
+ * 5. Merge the tenant policy (bound policy + policy registry), then
16
+ * route the agent's first capability through the provider registry.
17
+ *
18
+ * Populates `ctx.conversation`, `ctx.guardrails`, `ctx.tools`,
19
+ * `ctx.tenantPolicy`, `ctx.provider` and `ctx.model` for downstream
20
+ * handlers. Emits `turn.started` on success. Any failure surfaces as an `AgentTurnFailure` — the run
21
+ * fails and `projectRunResult` translates it back into the caller's
22
+ * `InvokeAgentError`.
23
+ */
24
+ export declare function buildSetupHandler(ctx: TurnContext): NodeHandler;
25
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/handlers/setup.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAMnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAmChD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,WAAW,GAAG,WAAW,CAyM/D"}
@@ -0,0 +1,231 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ import { createHash } from 'node:crypto';
4
+ import { WaitpointCancelledError } from '@kindgi/handler';
5
+ import { evaluateSessionGate } from '../guardrails-gate.js';
6
+ import { emitTurnEvent } from '../streaming.js';
7
+ import { throwAgentTurnFailure } from './errors.js';
8
+ import { writeRunSnapshot } from './run-snapshot.js';
9
+ import { loadTurnConversation, resolveTurnEnvironment, resolveTurnHitlPolicy, } from './turn-environment.js';
10
+ /**
11
+ * Deterministic waitpoint token — must produce the same value on every
12
+ * flow replay so the kernel's `waitForToken(tokenId)` resolves against
13
+ * the correct suspended state. Not sensitive to time or approval id;
14
+ * driven only by (runId, gate scope, turnCount).
15
+ */
16
+ function computeSessionGateWaitToken(input) {
17
+ return createHash('sha256')
18
+ .update(`agent-turn:session-hitl-gate:${input.runId}:${input.turnCount}`)
19
+ .digest('hex')
20
+ .slice(0, 40);
21
+ }
22
+ /**
23
+ * The first node in the flow. Runs every precondition check in one
24
+ * gate so the run either commits to a full turn or fails fast before
25
+ * the user message is stored in the conversation (only the run
26
+ * snapshot is written first):
27
+ *
28
+ * 1. Load + validate conversation (open, not closed, matches agent version).
29
+ * 2. Session-level HITL gate (`conversationPolicy.hitl.afterTurns` /
30
+ * `hitlAfterTurns`).
31
+ * 3. Resolve declared guardrails against the guardrails bound for the run.
32
+ * 4. Resolve declared tools against the tenant's tool registry
33
+ * (`ToolRegistry.forTenant`).
34
+ * 5. Merge the tenant policy (bound policy + policy registry), then
35
+ * route the agent's first capability through the provider registry.
36
+ *
37
+ * Populates `ctx.conversation`, `ctx.guardrails`, `ctx.tools`,
38
+ * `ctx.tenantPolicy`, `ctx.provider` and `ctx.model` for downstream
39
+ * handlers. Emits `turn.started` on success. Any failure surfaces as an `AgentTurnFailure` — the run
40
+ * fails and `projectRunResult` translates it back into the caller's
41
+ * `InvokeAgentError`.
42
+ */
43
+ export function buildSetupHandler(ctx) {
44
+ return async (_input, kctx) => {
45
+ // Write the run's reconstruction snapshot on FIRST
46
+ // execution (idempotent via PK on runId). resumeAgentTurn(runId)
47
+ // reads this to rebuild the same InvokeAgentInput when a parked
48
+ // waitpoint resolves — kernel replay lands in an identical context.
49
+ // The binding write is tenant-scoped and idempotent on runId, so it
50
+ // is safe under handler replay.
51
+ await writeRunSnapshot(ctx, kctx);
52
+ // Create the provenance builder BEFORE the session-HITL
53
+ // gate so we can emit wait/resume nodes around the park boundary.
54
+ // The builder is fresh on every replay (kernel replays the flow
55
+ // from scratch); nodes emitted before the first suspend are
56
+ // discarded (persist-provenance runs only on run.completed). On the
57
+ // final replay, both wait AND resume nodes get emitted and
58
+ // persisted — the DAG shows the whole cycle.
59
+ if (ctx.bindings.provenance?.newBuilder !== undefined) {
60
+ ctx.provenance = ctx.bindings.provenance.newBuilder({
61
+ runId: kctx.runId,
62
+ tenantId: ctx.input.tenantId,
63
+ });
64
+ ctx.provenanceBindings = ctx.bindings.provenance;
65
+ }
66
+ const conversation = await loadTurnConversation(ctx);
67
+ // Session HITL gate — checked BEFORE tool/guardrail resolution so
68
+ // callers with a HITL block don't waste routing work.
69
+ //
70
+ // Park-and-resume: instead of failing the turn with
71
+ // `hitl-required`, we PARK the run on a kernel waitpoint. A reviewer's
72
+ // decision (via POST /v1/approvals/:id/complete) resolves the
73
+ // waitpoint; the kernel replays this handler; `waitForToken` returns
74
+ // the reviewer's decision object; the handler branches on it and
75
+ // continues (approve) or fails cleanly (reject / cancelled / timeout).
76
+ //
77
+ // Same run, same conversationId, same provenance record — the audit
78
+ // trail stays coherent across the human-in-the-loop cycle.
79
+ //
80
+ // Enqueue is idempotent on `waitTokenId` (see
81
+ // `HitlEnqueueInput.waitTokenId`) — safe under handler replay.
82
+ // The turn's approval rules — the agent's, held to the tenant's
83
+ // `hitl` policy — before the gate that may park on them.
84
+ const effectiveHitl = await resolveTurnHitlPolicy(ctx);
85
+ ctx.hitlPolicy = effectiveHitl;
86
+ const sessionGate = evaluateSessionGate({ ...(effectiveHitl.turn !== undefined && { afterTurns: effectiveHitl.turn.afterTurns }) }, conversation.turnCount);
87
+ if (sessionGate.kind === 'hitl-required') {
88
+ const waitTokenId = computeSessionGateWaitToken({
89
+ runId: kctx.runId,
90
+ turnCount: conversation.turnCount,
91
+ });
92
+ const timeoutMs = effectiveHitl.timeoutMs;
93
+ const expiresAt = new Date(Date.now() + timeoutMs).toISOString();
94
+ if (ctx.bindings.hitl?.enqueue !== undefined) {
95
+ try {
96
+ await ctx.bindings.hitl.enqueue({
97
+ tenantId: ctx.input.tenantId,
98
+ subjectKind: 'agent-turn:session-hitl-gate',
99
+ subjectRef: {
100
+ conversationId: ctx.input.conversationId,
101
+ agentId: ctx.input.agent.id,
102
+ agentVersion: ctx.input.agent.version,
103
+ turnCount: conversation.turnCount,
104
+ threshold: sessionGate.threshold,
105
+ },
106
+ requiredRole: effectiveHitl.defaultReviewerRole,
107
+ title: `HITL review required for ${ctx.input.agent.name}`,
108
+ description: sessionGate.reason,
109
+ waitTokenId,
110
+ provenanceRef: { runId: kctx.runId },
111
+ expiresAt: expiresAt,
112
+ });
113
+ }
114
+ catch {
115
+ // Failing sink must not affect turn outcome — swallow. The
116
+ // waitForToken below will still park; if no reviewer sees the
117
+ // approval row, the kernel timeout cancels the wait per policy.
118
+ }
119
+ }
120
+ // Provenance: emit `wait` node right before the park. On first
121
+ // execution (park), persist-provenance never runs so this node is
122
+ // lost — that's fine. On the FINAL replay after resume, this node
123
+ // AND the `resume` node below both emit and get persisted.
124
+ const waitNodeId = `session-hitl-gate-wait:${conversation.turnCount}`;
125
+ const resumeNodeId = `session-hitl-gate-resume:${conversation.turnCount}`;
126
+ if (ctx.provenance !== undefined) {
127
+ ctx.provenance.addNode({
128
+ id: waitNodeId,
129
+ kind: 'wait',
130
+ timestamp: new Date().toISOString(),
131
+ actor: `agent:${ctx.input.agent.id}`,
132
+ attributes: {
133
+ gate: 'session-hitl',
134
+ turnCount: conversation.turnCount,
135
+ threshold: sessionGate.threshold,
136
+ waitTokenId,
137
+ },
138
+ });
139
+ }
140
+ try {
141
+ const decision = await kctx.waitForToken(waitTokenId, {
142
+ timeoutMs,
143
+ });
144
+ // Post-resume: emit the resume node + resumed-from edge. Only
145
+ // runs on the REPLAY path — the first execution throws
146
+ // SuspensionSignal inside waitForToken and never gets here.
147
+ if (ctx.provenance !== undefined) {
148
+ ctx.provenance.addNode({
149
+ id: resumeNodeId,
150
+ kind: 'resume',
151
+ timestamp: new Date().toISOString(),
152
+ actor: `agent:${ctx.input.agent.id}`,
153
+ attributes: {
154
+ gate: 'session-hitl',
155
+ decision: decision.decided,
156
+ ...(decision.rationale !== undefined && { rationale: decision.rationale }),
157
+ },
158
+ });
159
+ ctx.provenance.addEdge({
160
+ from: waitNodeId,
161
+ to: resumeNodeId,
162
+ kind: 'resumed-from',
163
+ });
164
+ }
165
+ if (decision.decided === 'reject') {
166
+ throwAgentTurnFailure({
167
+ code: 'hitl-rejected',
168
+ message: `Reviewer rejected the session-HITL gate${decision.rationale !== undefined ? `: ${decision.rationale}` : ''}`,
169
+ ...(decision.rationale !== undefined && { rationale: decision.rationale }),
170
+ });
171
+ }
172
+ // decision.decided === 'approve' → fall through, turn proceeds
173
+ // normally through the rest of setup.
174
+ }
175
+ catch (cause) {
176
+ if (cause instanceof WaitpointCancelledError) {
177
+ // Emit resume node with cancelled attribute so the DAG still
178
+ // shows the resolution — even for terminal cancellations the
179
+ // flow reached the resume boundary before the failure.
180
+ if (ctx.provenance !== undefined) {
181
+ ctx.provenance.addNode({
182
+ id: resumeNodeId,
183
+ kind: 'resume',
184
+ timestamp: new Date().toISOString(),
185
+ actor: `agent:${ctx.input.agent.id}`,
186
+ attributes: {
187
+ gate: 'session-hitl',
188
+ decision: 'cancelled',
189
+ reason: cause.reason,
190
+ },
191
+ });
192
+ ctx.provenance.addEdge({
193
+ from: waitNodeId,
194
+ to: resumeNodeId,
195
+ kind: 'resumed-from',
196
+ });
197
+ }
198
+ throwAgentTurnFailure({
199
+ code: 'hitl-cancelled',
200
+ message: `Session-HITL gate cancelled: ${cause.reason}`,
201
+ reason: cause.reason,
202
+ });
203
+ }
204
+ // SuspensionSignal or anything else — let it propagate. The
205
+ // kernel executor's dispatch catch handles SuspensionSignal by
206
+ // suspending the run; other errors become step.failed.
207
+ throw cause;
208
+ }
209
+ }
210
+ const environment = await resolveTurnEnvironment(ctx);
211
+ // Provenance builder was created earlier (before the session-HITL
212
+ // gate) so wait/resume nodes could bracket the park boundary. Kept
213
+ // here as a documentation anchor — see the block above `getConversation`.
214
+ await emitTurnEvent(ctx.bindings.onEvent, {
215
+ kind: 'turn.started',
216
+ conversationId: ctx.input.conversationId,
217
+ turnNumber: conversation.turnCount + 1,
218
+ agentId: ctx.input.agent.id,
219
+ agentVersion: ctx.input.agent.version,
220
+ userMessage: ctx.input.userMessage,
221
+ });
222
+ // Kernel output — kept minimal + JSON-safe. Real state lives on ctx.
223
+ return {
224
+ turnNumber: conversation.turnCount + 1,
225
+ providerId: environment.providerId,
226
+ providerModel: environment.model,
227
+ toolCount: environment.toolCount,
228
+ };
229
+ };
230
+ }
231
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../src/handlers/setup.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGhD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAE/B;;;;;GAKG;AACH,SAAS,2BAA2B,CAAC,KAGpC;IACC,OAAO,UAAU,CAAC,QAAQ,CAAC;SACxB,MAAM,CAAC,gCAAgC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;SACxE,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAClB,CAAC;AAYD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAgB;IAChD,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;QAC5B,mDAAmD;QACnD,iEAAiE;QACjE,gEAAgE;QAChE,oEAAoE;QACpE,oEAAoE;QACpE,gCAAgC;QAChC,MAAM,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAElC,wDAAwD;QACxD,kEAAkE;QAClE,gEAAgE;QAChE,4DAA4D;QAC5D,oEAAoE;QACpE,2DAA2D;QAC3D,6CAA6C;QAC7C,IAAI,GAAG,CAAC,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D;gBACvD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,sBAAsB,CAAC,GAAG,CAAC,CAAC;QAEtD,kEAAkE;QAClE,mEAAmE;QACnE,0EAA0E;QAE1E,MAAM,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,EAAE;YACxC,IAAI,EAAE,cAAc;YACpB,cAAc,EAAE,GAAG,CAAC,KAAK,CAAC,cAAc;YACxC,UAAU,EAAE,YAAY,CAAC,SAAS,GAAG,CAAC;YACtC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;YAC3B,YAAY,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO;YACrC,WAAW,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW;SACnC,CAAC,CAAC;QAEH,qEAAqE;QACrE,OAAO;YACL,UAAU,EAAE,YAAY,CAAC,SAAS,GAAG,CAAC;YACtC,UAAU,EAAE,WAAW,CAAC,UAAU;YAClC,aAAa,EAAE,WAAW,CAAC,KAAK;YAChC,SAAS,EAAE,WAAW,CAAC,SAAS;SACjC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Typed agent output: reading the model's final answer as JSON and
3
+ * checking it against the agent's `output.schema`, and the repair
4
+ * message sent back when it doesn't fit.
5
+ *
6
+ * The repair loop lives in `budget-check`: an invalid answer with
7
+ * repairs left keeps the turn going, with the answer and a repair
8
+ * message appended to the conversation sent to the model. Repairs are
9
+ * counted from those messages, so a replayed turn counts the same.
10
+ */
11
+ import type { ModelMessage } from '@kindgi/capabilities';
12
+ import type { AgentOutputSpec } from '../types.js';
13
+ /** Default number of repair attempts. */
14
+ export declare const DEFAULT_MAX_REPAIRS = 1;
15
+ export type OutputCheck = {
16
+ readonly kind: 'ok';
17
+ readonly value: unknown;
18
+ } | {
19
+ readonly kind: 'invalid';
20
+ readonly errors: readonly string[];
21
+ };
22
+ /**
23
+ * The answer's text as JSON. Accepts a bare JSON value or one fenced
24
+ * as ```json … ``` (models often fence it).
25
+ */
26
+ export declare function parseJsonAnswer(content: unknown): OutputCheck;
27
+ /** Compiled once per turn — see `outputChecker`. */
28
+ export interface OutputChecker {
29
+ check(content: unknown): OutputCheck;
30
+ }
31
+ export declare function outputChecker(spec: AgentOutputSpec): OutputChecker;
32
+ /** Whether a message is one of this module's repair requests. */
33
+ export declare function isRepairMessage(m: ModelMessage): boolean;
34
+ /** How many repairs this turn has asked for so far. */
35
+ export declare function repairsSoFar(messages: readonly ModelMessage[]): number;
36
+ /** The message asking the model to fix its answer. */
37
+ export declare function repairMessage(spec: AgentOutputSpec, errors: readonly string[]): ModelMessage;
38
+ //# sourceMappingURL=structured-output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output.d.ts","sourceRoot":"","sources":["../../src/handlers/structured-output.ts"],"names":[],"mappings":"AAGA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,yCAAyC;AACzC,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAKrC,MAAM,MAAM,WAAW,GACnB;IAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GAChD;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAErE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,WAAW,CAgB7D;AAOD,oDAAoD;AACpD,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,WAAW,CAAC;CACtC;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,aAAa,CAmBlE;AAYD,iEAAiE;AACjE,wBAAgB,eAAe,CAAC,CAAC,EAAE,YAAY,GAAG,OAAO,CAExD;AAED,uDAAuD;AACvD,wBAAgB,YAAY,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAEtE;AAED,sDAAsD;AACtD,wBAAgB,aAAa,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,YAAY,CAa5F"}