melchizedek-agents 0.18.0 → 0.20.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 (293) hide show
  1. package/.env.example +12 -0
  2. package/CHANGELOG.md +1001 -0
  3. package/DOCUMENTATION.md +252 -65
  4. package/QUICKSTART.md +9 -6
  5. package/README.md +42 -4
  6. package/config/agents/examples/harness.yaml +3 -1
  7. package/config/agents/examples/model_zoo.yaml +10 -9
  8. package/config/agents/syndicateSchema.yaml +53 -16
  9. package/config/agents/templates/account_memory.yaml +2 -6
  10. package/config/agents/templates/case_desk.yaml +3 -9
  11. package/config/agents/templates/draft_review.yaml +3 -9
  12. package/config/agents/templates/intake_extractor.yaml +1 -3
  13. package/config/agents/templates/research_brief.yaml +3 -9
  14. package/config/agents/templates/research_desk.yaml +3 -9
  15. package/config/agents/templates/review_panel.yaml +4 -12
  16. package/config/agents/templates/support_triage.yaml +4 -12
  17. package/config/agents/templates/systems_operator.yaml +2 -6
  18. package/db/hardening.sql +7 -1
  19. package/db/migrations/0013_tool_credentials.sql +260 -0
  20. package/dist/lib/a2a/app.d.ts +70 -6
  21. package/dist/lib/a2a/app.js +107 -2
  22. package/dist/lib/a2a/executor.d.ts +20 -3
  23. package/dist/lib/a2a/executor.js +66 -7
  24. package/dist/lib/a2a/remoteAgent.d.ts +24 -9
  25. package/dist/lib/a2a/remoteAgent.js +31 -14
  26. package/dist/lib/adkPeer.d.ts +63 -0
  27. package/dist/lib/adkPeer.js +240 -0
  28. package/dist/lib/compile.d.ts +159 -30
  29. package/dist/lib/compile.js +215 -134
  30. package/dist/lib/compileAdk.d.ts +32 -0
  31. package/dist/lib/compileAdk.js +142 -0
  32. package/dist/lib/compileNative.d.ts +111 -0
  33. package/dist/lib/compileNative.js +278 -0
  34. package/dist/lib/config.d.ts +6 -5
  35. package/dist/lib/config.js +6 -5
  36. package/dist/lib/doctor.d.ts +28 -1
  37. package/dist/lib/doctor.js +64 -2
  38. package/dist/lib/index.d.ts +6 -1
  39. package/dist/lib/index.js +7 -1
  40. package/dist/lib/loadSyndicate.d.ts +18 -0
  41. package/dist/lib/memory/erase.d.ts +5 -3
  42. package/dist/lib/memory/erase.js +5 -2
  43. package/dist/lib/memory/namespace.d.ts +8 -1
  44. package/dist/lib/memory/namespace.js +12 -6
  45. package/dist/lib/memory/providers.js +2 -1
  46. package/dist/lib/memory/supabaseMemoryService.d.ts +37 -3
  47. package/dist/lib/memory/supabaseMemoryService.js +42 -2
  48. package/dist/lib/model.d.ts +47 -0
  49. package/dist/lib/model.js +37 -0
  50. package/dist/lib/models/adapterResolver.d.ts +115 -0
  51. package/dist/lib/models/adapterResolver.js +137 -0
  52. package/dist/lib/models/adkGeminiAdapter.d.ts +90 -0
  53. package/dist/lib/models/adkGeminiAdapter.js +369 -0
  54. package/dist/lib/models/adkShim.d.ts +111 -0
  55. package/dist/lib/models/adkShim.js +136 -0
  56. package/dist/lib/models/capabilities.d.ts +3 -0
  57. package/dist/lib/models/capabilities.js +33 -23
  58. package/dist/lib/models/chatCompletionsAdapter.d.ts +279 -0
  59. package/dist/lib/models/chatCompletionsAdapter.js +854 -0
  60. package/dist/lib/models/circuitBreaker.d.ts +42 -0
  61. package/dist/lib/models/circuitBreaker.js +70 -0
  62. package/dist/lib/models/claudeAdapter.d.ts +103 -0
  63. package/dist/lib/models/claudeAdapter.js +669 -0
  64. package/dist/lib/models/claudeLlm.d.ts +39 -62
  65. package/dist/lib/models/claudeLlm.js +45 -350
  66. package/dist/lib/models/claudeModels.d.ts +127 -0
  67. package/dist/lib/models/claudeModels.js +237 -0
  68. package/dist/lib/models/contract.d.ts +395 -0
  69. package/dist/lib/models/contract.js +39 -0
  70. package/dist/lib/models/endpoints.js +2 -1
  71. package/dist/lib/models/errorResponse.d.ts +50 -0
  72. package/dist/lib/models/errorResponse.js +48 -0
  73. package/dist/lib/models/fallback.d.ts +18 -11
  74. package/dist/lib/models/fallback.js +54 -43
  75. package/dist/lib/models/fallbackAdapter.d.ts +55 -0
  76. package/dist/lib/models/fallbackAdapter.js +62 -0
  77. package/dist/lib/models/gateway.js +2 -1
  78. package/dist/lib/models/gatewayAdapter.d.ts +51 -0
  79. package/dist/lib/models/gatewayAdapter.js +81 -0
  80. package/dist/lib/models/gatewayLlm.d.ts +12 -33
  81. package/dist/lib/models/gatewayLlm.js +16 -77
  82. package/dist/lib/models/geminiAdapter.d.ts +125 -0
  83. package/dist/lib/models/geminiAdapter.js +854 -0
  84. package/dist/lib/models/geminiState.d.ts +46 -0
  85. package/dist/lib/models/geminiState.js +51 -0
  86. package/dist/lib/models/genaiMapping.d.ts +283 -0
  87. package/dist/lib/models/genaiMapping.js +965 -0
  88. package/dist/lib/models/gptAdapter.d.ts +240 -0
  89. package/dist/lib/models/gptAdapter.js +804 -0
  90. package/dist/lib/models/gptLlm.d.ts +63 -123
  91. package/dist/lib/models/gptLlm.js +89 -603
  92. package/dist/lib/models/grokAdapter.d.ts +86 -0
  93. package/dist/lib/models/grokAdapter.js +142 -0
  94. package/dist/lib/models/grokLlm.d.ts +22 -45
  95. package/dist/lib/models/grokLlm.js +24 -69
  96. package/dist/lib/models/kimiAdapter.d.ts +157 -0
  97. package/dist/lib/models/kimiAdapter.js +203 -0
  98. package/dist/lib/models/kimiLlm.d.ts +15 -107
  99. package/dist/lib/models/kimiLlm.js +19 -155
  100. package/dist/lib/models/ollamaAdapter.d.ts +125 -0
  101. package/dist/lib/models/ollamaAdapter.js +155 -0
  102. package/dist/lib/models/ollamaLlm.d.ts +11 -107
  103. package/dist/lib/models/ollamaLlm.js +15 -153
  104. package/dist/lib/models/openAiCompatibleLlm.d.ts +73 -216
  105. package/dist/lib/models/openAiCompatibleLlm.js +109 -671
  106. package/dist/lib/models/providerState.d.ts +63 -0
  107. package/dist/lib/models/providerState.js +61 -0
  108. package/dist/lib/models/reasoning.d.ts +26 -0
  109. package/dist/lib/models/reasoning.js +59 -0
  110. package/dist/lib/models/registry.d.ts +62 -35
  111. package/dist/lib/models/registry.js +100 -124
  112. package/dist/lib/models/retry.d.ts +2 -1
  113. package/dist/lib/models/retry.js +3 -2
  114. package/dist/lib/models/schemaNormalize.d.ts +98 -0
  115. package/dist/lib/models/schemaNormalize.js +321 -1
  116. package/dist/lib/models/tracedGemini.d.ts +41 -0
  117. package/dist/lib/models/tracedGemini.js +98 -0
  118. package/dist/lib/models/urls.d.ts +11 -0
  119. package/dist/lib/models/urls.js +16 -0
  120. package/dist/lib/net/redirects.d.ts +21 -2
  121. package/dist/lib/net/redirects.js +11 -34
  122. package/dist/lib/observability/audit.d.ts +5 -1
  123. package/dist/lib/observability/lineage.d.ts +14 -0
  124. package/dist/lib/observability/lineage.js +33 -0
  125. package/dist/lib/observability/supabaseSpanExporter.d.ts +10 -4
  126. package/dist/lib/observability/supabaseSpanExporter.js +17 -9
  127. package/dist/lib/observability/tracer.d.ts +26 -8
  128. package/dist/lib/observability/tracer.js +43 -18
  129. package/dist/lib/runtime/adkMemoryBridge.d.ts +46 -0
  130. package/dist/lib/runtime/adkMemoryBridge.js +68 -0
  131. package/dist/lib/runtime/adkSessionBridge.d.ts +78 -0
  132. package/dist/lib/runtime/adkSessionBridge.js +176 -0
  133. package/dist/lib/runtime/approvals.d.ts +5 -0
  134. package/dist/lib/runtime/approvals.js +39 -8
  135. package/dist/lib/runtime/credentials.d.ts +61 -0
  136. package/dist/lib/runtime/credentials.js +67 -0
  137. package/dist/lib/runtime/events.d.ts +229 -0
  138. package/dist/lib/runtime/events.js +274 -0
  139. package/dist/lib/runtime/logging.d.ts +32 -0
  140. package/dist/lib/runtime/logging.js +55 -0
  141. package/dist/lib/runtime/memoryService.d.ts +72 -0
  142. package/dist/lib/runtime/memoryService.js +25 -0
  143. package/dist/lib/runtime/native/agentLoop.d.ts +209 -0
  144. package/dist/lib/runtime/native/agentLoop.js +705 -0
  145. package/dist/lib/runtime/native/compaction.d.ts +103 -0
  146. package/dist/lib/runtime/native/compaction.js +191 -0
  147. package/dist/lib/runtime/native/delegate.d.ts +151 -0
  148. package/dist/lib/runtime/native/delegate.js +256 -0
  149. package/dist/lib/runtime/native/history.d.ts +83 -0
  150. package/dist/lib/runtime/native/history.js +312 -0
  151. package/dist/lib/runtime/native/interrupts.d.ts +129 -0
  152. package/dist/lib/runtime/native/interrupts.js +310 -0
  153. package/dist/lib/runtime/native/request.d.ts +215 -0
  154. package/dist/lib/runtime/native/request.js +585 -0
  155. package/dist/lib/runtime/native/selfCorrection.d.ts +164 -0
  156. package/dist/lib/runtime/native/selfCorrection.js +327 -0
  157. package/dist/lib/runtime/native/step.d.ts +156 -0
  158. package/dist/lib/runtime/native/step.js +263 -0
  159. package/dist/lib/runtime/native/taskMode.d.ts +64 -0
  160. package/dist/lib/runtime/native/taskMode.js +126 -0
  161. package/dist/lib/runtime/native/telemetry.d.ts +75 -0
  162. package/dist/lib/runtime/native/telemetry.js +299 -0
  163. package/dist/lib/runtime/native/tempState.d.ts +31 -0
  164. package/dist/lib/runtime/native/tempState.js +56 -0
  165. package/dist/lib/runtime/nativeTurn.d.ts +86 -0
  166. package/dist/lib/runtime/nativeTurn.js +107 -0
  167. package/dist/lib/runtime/questions.d.ts +29 -7
  168. package/dist/lib/runtime/questions.js +47 -32
  169. package/dist/lib/runtime/runtimeFlag.d.ts +38 -0
  170. package/dist/lib/runtime/runtimeFlag.js +58 -0
  171. package/dist/lib/runtime/sessions.d.ts +166 -0
  172. package/dist/lib/runtime/sessions.js +201 -0
  173. package/dist/lib/runtime/syndicateTurn.d.ts +46 -5
  174. package/dist/lib/runtime/syndicateTurn.js +233 -36
  175. package/dist/lib/runtime/valueDepth.d.ts +23 -0
  176. package/dist/lib/runtime/valueDepth.js +41 -0
  177. package/dist/lib/session/supabaseSessionService.d.ts +65 -18
  178. package/dist/lib/session/supabaseSessionService.js +148 -105
  179. package/dist/lib/session/transcript.d.ts +69 -23
  180. package/dist/lib/session/transcript.js +105 -29
  181. package/dist/lib/skills.js +33 -7
  182. package/dist/lib/storage/postgres/credentialStore.d.ts +20 -0
  183. package/dist/lib/storage/postgres/credentialStore.js +82 -0
  184. package/dist/lib/storage/postgres/index.d.ts +12 -0
  185. package/dist/lib/storage/postgres/index.js +6 -1
  186. package/dist/lib/storage/postgres/sessionService.d.ts +44 -16
  187. package/dist/lib/storage/postgres/sessionService.js +128 -66
  188. package/dist/lib/syndicateSchema.d.ts +49 -0
  189. package/dist/lib/syndicateSchema.js +99 -9
  190. package/dist/lib/toolRegistry.d.ts +26 -2
  191. package/dist/lib/toolRegistry.js +73 -17
  192. package/dist/lib/tools/adkTool.d.ts +81 -0
  193. package/dist/lib/tools/adkTool.js +268 -0
  194. package/dist/lib/tools/auth.d.ts +118 -0
  195. package/dist/lib/tools/auth.js +89 -0
  196. package/dist/lib/tools/collectionsSearchTool.d.ts +8 -7
  197. package/dist/lib/tools/collectionsSearchTool.js +12 -27
  198. package/dist/lib/tools/credentialCipher.d.ts +58 -0
  199. package/dist/lib/tools/credentialCipher.js +116 -0
  200. package/dist/lib/tools/credentialStore.d.ts +77 -0
  201. package/dist/lib/tools/credentialStore.js +246 -0
  202. package/dist/lib/tools/examples.d.ts +43 -0
  203. package/dist/lib/tools/examples.js +62 -0
  204. package/dist/lib/tools/generateImageTool.d.ts +15 -6
  205. package/dist/lib/tools/generateImageTool.js +19 -29
  206. package/dist/lib/tools/inspectImageTool.d.ts +9 -6
  207. package/dist/lib/tools/inspectImageTool.js +13 -17
  208. package/dist/lib/tools/mcpToolFactory.d.ts +42 -1
  209. package/dist/lib/tools/mcpToolFactory.js +46 -47
  210. package/dist/lib/tools/memoryTools.d.ts +61 -0
  211. package/dist/lib/tools/memoryTools.js +119 -0
  212. package/dist/lib/tools/nativeTools.d.ts +38 -0
  213. package/dist/lib/tools/nativeTools.js +43 -0
  214. package/dist/lib/tools/oauthConsent.d.ts +181 -0
  215. package/dist/lib/tools/oauthConsent.js +330 -0
  216. package/dist/lib/tools/openapi/call.d.ts +108 -0
  217. package/dist/lib/tools/openapi/call.js +295 -0
  218. package/dist/lib/tools/openapi/parse.d.ts +147 -0
  219. package/dist/lib/tools/openapi/parse.js +570 -0
  220. package/dist/lib/tools/openapiTools.d.ts +25 -17
  221. package/dist/lib/tools/openapiTools.js +124 -121
  222. package/dist/lib/tools/scienceTools.d.ts +14 -14
  223. package/dist/lib/tools/skillToolset.d.ts +58 -87
  224. package/dist/lib/tools/skillToolset.js +61 -142
  225. package/dist/lib/tools/skills/env.d.ts +58 -0
  226. package/dist/lib/tools/skills/env.js +165 -0
  227. package/dist/lib/tools/skills/executor.d.ts +114 -0
  228. package/dist/lib/tools/skills/executor.js +331 -0
  229. package/dist/lib/tools/skills/frontmatter.d.ts +79 -0
  230. package/dist/lib/tools/skills/frontmatter.js +215 -0
  231. package/dist/lib/tools/skills/loader.d.ts +91 -0
  232. package/dist/lib/tools/skills/loader.js +257 -0
  233. package/dist/lib/tools/skills/tools.d.ts +187 -0
  234. package/dist/lib/tools/skills/tools.js +386 -0
  235. package/dist/lib/tools/taskTools.d.ts +15 -15
  236. package/dist/lib/tools/tool.d.ts +354 -0
  237. package/dist/lib/tools/tool.js +304 -0
  238. package/dist/lib/tools/toolContract.d.ts +89 -33
  239. package/dist/lib/tools/toolContract.js +104 -82
  240. package/dist/lib/tools/urlContextTool.d.ts +4 -1
  241. package/dist/lib/tools/urlContextTool.js +6 -2
  242. package/dist/lib/tools/webExtractTool.d.ts +3 -3
  243. package/dist/lib/tools/webExtractTool.js +2 -1
  244. package/dist/lib/tools/webSearchTool.d.ts +7 -10
  245. package/dist/lib/tools/webSearchTool.js +15 -60
  246. package/dist/lib/tools/wikiTools.d.ts +19 -19
  247. package/dist/lib/tools/wikiTools.js +13 -9
  248. package/dist/lib/tools/xApiSearchTool.d.ts +3 -3
  249. package/dist/lib/tools/xApiSearchTool.js +2 -1
  250. package/dist/lib/tools/xSearchTool.d.ts +8 -10
  251. package/dist/lib/tools/xSearchTool.js +12 -63
  252. package/dist/lib/tools/xaiSearchParams.d.ts +41 -0
  253. package/dist/lib/tools/xaiSearchParams.js +126 -0
  254. package/dist/lib/wiki/agentRun.d.ts +12 -0
  255. package/dist/lib/wiki/agentRun.js +74 -35
  256. package/dist/lib/wiki/entities.d.ts +12 -0
  257. package/dist/lib/wiki/entities.js +45 -3
  258. package/dist/lib/workflow/agentNode.d.ts +153 -0
  259. package/dist/lib/workflow/agentNode.js +365 -0
  260. package/dist/lib/workflow/graph.d.ts +178 -0
  261. package/dist/lib/workflow/graph.js +468 -0
  262. package/dist/lib/workflow/nodeEvents.d.ts +50 -0
  263. package/dist/lib/workflow/nodeEvents.js +101 -0
  264. package/dist/lib/workflow/pause.d.ts +122 -0
  265. package/dist/lib/workflow/pause.js +180 -0
  266. package/dist/lib/workflow/resume.d.ts +166 -0
  267. package/dist/lib/workflow/resume.js +441 -0
  268. package/dist/lib/workflow/route.d.ts +58 -0
  269. package/dist/lib/workflow/route.js +69 -0
  270. package/dist/lib/workflow/scheduler.d.ts +418 -0
  271. package/dist/lib/workflow/scheduler.js +756 -0
  272. package/dist/lib/workflow/toolNode.d.ts +127 -0
  273. package/dist/lib/workflow/toolNode.js +236 -0
  274. package/dist/lib/workflow/turn.d.ts +118 -0
  275. package/dist/lib/workflow/turn.js +216 -0
  276. package/dist/lib/workflow.d.ts +33 -11
  277. package/dist/lib/workflow.js +49 -27
  278. package/dist/lib/workflowConfig.d.ts +7 -2
  279. package/dist/lib/workflowConfig.js +7 -12
  280. package/dist/scripts/a2a_server.js +4 -3
  281. package/dist/scripts/assistant_worker.d.ts +2 -1
  282. package/dist/scripts/assistant_worker.js +9 -4
  283. package/dist/scripts/doctor.d.ts +3 -1
  284. package/dist/scripts/doctor.js +4 -2
  285. package/dist/scripts/syndicate_chat.js +19 -10
  286. package/package.json +9 -3
  287. package/skills/briefs/melchizedek-author.md +3 -2
  288. package/skills/briefs/melchizedek-models.md +13 -9
  289. package/skills/briefs/melchizedek.md +3 -3
  290. package/skills/melchizedek/SKILL.md +2 -1
  291. package/skills/melchizedek-author/SKILL.md +2 -1
  292. package/skills/melchizedek-author/assets/minimal.yaml +2 -0
  293. package/skills/melchizedek-models/SKILL.md +23 -6
@@ -0,0 +1,263 @@
1
+ /**
2
+ * lib/runtime/native/step.ts — one model step of the native loop: build the
3
+ * request, call the adapter under the turn's controls, and record the
4
+ * model's answer as the event ADK would have stored (ADR 0045, ADR 0066).
5
+ *
6
+ * WHY this file exists:
7
+ * On the ADK runtime one step is LlmAgent.runOneStepAsync: build the
8
+ * request, call the model through the shim (lib/models/adkShim.ts), turn
9
+ * each response into an event, and let the Runner store the ones that are
10
+ * not partial. The native loop does the same with no ADK in the path, and
11
+ * a session either runtime wrote must be one the other can continue, so
12
+ * each piece matches:
13
+ *
14
+ * - THE CALL'S CONTROLS (ADR 0053). The native loop is the adapter's
15
+ * caller, so it charges the turn and opens the llm.request span, through
16
+ * the same traceLlmGeneration call the shim makes, with the adapter's
17
+ * provider, the agent's model id and the request. The step budget, the
18
+ * token charge and the span's attributes are therefore the same on both
19
+ * runtimes. A turn that has stopped (cancel, deadline, the step limit)
20
+ * gets no call and no event: ADK checks the run's signal before the call
21
+ * and after each response and returns without an event, and the turn
22
+ * runner reports the stop from the turn's control. So does this step.
23
+ * - THE EVENT. Each response becomes ADK's event for it: created before
24
+ * the call with the run's id, the agent as author and the branch, and
25
+ * merged with the response as the shim maps it (modelResponseToLlmResponse),
26
+ * a fresh id for every response after the first. For a Gemini adapter
27
+ * that stands for ADK's own Gemini (standsForAdkGemini), the event has no
28
+ * turnComplete, since ADK's Gemini writes none (ADR 0100). A tool call with no id
29
+ * gets ADK's `adk-<uuid>`; a call to a long-running tool is listed in
30
+ * longRunningToolIds; a set_model_response call becomes its arguments as
31
+ * JSON text, ending the step (skipSummarization). An answer with no
32
+ * parts, no error and no usage makes no event.
33
+ * - SELF-CORRECTION (ADR 0075). With the caller's `correction`, the
34
+ * reflection tool is one of the step's tools, after the agent's, and
35
+ * each response passes through it first, as ADK's reflect-and-retry
36
+ * model plugin sees it: a retry may stand in its place, or the step may
37
+ * end on the plugin's UNKNOWN_ERROR event (lib/runtime/native/
38
+ * selfCorrection.ts). The request declares the tool only where ADK's
39
+ * model class would (declaresReflectionTool): never to a Gemini model
40
+ * ADK's own Gemini would serve, which sends no toolsDict (ADR 0097).
41
+ * On a Gemini adapter the reflection call stored in a response's place
42
+ * carries its signature, or Gemini 3's placeholder (reflectionSigning,
43
+ * ADR 0103), where ADK stores it unsigned.
44
+ * - A THROWN FAILURE. The contract forbids an adapter to throw, but a
45
+ * leaf that does (an ADK-era model class) is read as ADK reads it. With
46
+ * a `redirect`, a provider-side failure (errorDecision, lib/models/
47
+ * errorResponse.ts) is handed to it as a retryable failed final, so the
48
+ * fallback answers when nothing was produced yet (FallbackLlm). Any
49
+ * other thrown Error ends the step on ADK's error event for it
50
+ * (runAndHandleError): UNKNOWN_ERROR, or the code a JSON error message
51
+ * names, with the message, key-shaped text scrubbed. A throw that is
52
+ * not an Error, or one while the turn is stopping, is rethrown.
53
+ * - STORAGE. A final event is appended through the SessionService, which
54
+ * applies the store's own rules (trimming, state). A partial event is
55
+ * handed to the caller for streaming and stored nowhere.
56
+ *
57
+ * WHAT IT RETURNS: the request sent, the stored event, and the answer parsed
58
+ * into text, thinking (from the partials: a final never holds thinking) and
59
+ * tool calls with the ids as stored, and the tools the request declared.
60
+ * Running those calls, and looping, is lib/runtime/native/agentLoop.ts.
61
+ */
62
+ import { randomUUID } from 'node:crypto';
63
+ import { errorDecision, errorText } from '../../models/errorResponse.js';
64
+ import { contractModelResponse, modelResponseToLlmResponse } from '../../models/genaiMapping.js';
65
+ import { resolveAdapter } from '../../models/registry.js';
66
+ import { traceLlmGeneration } from '../../observability/tracer.js';
67
+ import { createTurnEvent, getFunctionCalls, newEventId } from '../events.js';
68
+ import { currentTurnControl, currentTurnSignal, stopCode, stopMessage } from '../turnControl.js';
69
+ import { toolOf } from '../../tools/tool.js';
70
+ import { ADK_CALL_ID_PREFIX } from './history.js';
71
+ import { SET_MODEL_RESPONSE, buildModelRequest } from './request.js';
72
+ import { declaresReflectionTool, reflectionSigning, standsForAdkGemini } from './selfCorrection.js';
73
+ export function eitherSignal(...candidates) {
74
+ const signals = [...new Set(candidates.filter((s) => s !== undefined))];
75
+ return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
76
+ }
77
+ /** The turn's stop, as the turn runner reports it; a cancel when the signal aborted outside a turn. */
78
+ /** The turn's stop, as a step reports it. */
79
+ export function stopOf() {
80
+ const reason = currentTurnControl()?.stopReason ?? 'canceled';
81
+ return { code: stopCode(reason), message: stopMessage(reason, currentTurnControl()) };
82
+ }
83
+ function isLongRunning(tool) {
84
+ const own = toolOf(tool);
85
+ if (own)
86
+ return own.longRunning === true;
87
+ return !!tool && typeof tool === 'object' && tool.isLongRunning === true;
88
+ }
89
+ /** ADK's postprocess: whether a response makes an event at all. */
90
+ function makesEvent(response) {
91
+ const usageOnly = !response.content && !!response.usageMetadata;
92
+ return !((!response.content || response.content.parts?.length === 0) && !response.errorCode && !response.interrupted && !usageOnly);
93
+ }
94
+ /** What ADK stores for a model call that threw: UNKNOWN_ERROR, or the code and message of a JSON error body. */
95
+ function thrownModelError(err) {
96
+ let code = 'UNKNOWN_ERROR';
97
+ let message = err.message;
98
+ try {
99
+ const body = JSON.parse(err.message);
100
+ if (body?.error) {
101
+ code = String(body.error.code || 'UNKNOWN_ERROR');
102
+ if (typeof body.error.message === 'string' && body.error.message)
103
+ message = body.error.message;
104
+ }
105
+ }
106
+ catch {
107
+ // Not JSON: the message as it is.
108
+ }
109
+ return { code, message: errorText(message) };
110
+ }
111
+ /**
112
+ * One model step for `agent`. Never throws for a failed call: the error is
113
+ * on the result and on the stored event, as on the ADK runtime, also when
114
+ * the adapter throws an Error, which the contract forbids. Throws when the
115
+ * request cannot be built (as ADK does).
116
+ */
117
+ export async function runModelStep(options) {
118
+ const { agent, session, sessions } = options;
119
+ const signal = eitherSignal(options.signal, currentTurnSignal());
120
+ const adapter = options.adapter ?? resolveAdapter(agent.model);
121
+ // ADK's plugin puts the reflection tool in the toolsDict alone: declared where the model class reads it, run either way.
122
+ const correctionTools = options.correction?.tools ?? [];
123
+ const declareCorrection = correctionTools.length > 0 && declaresReflectionTool(adapter);
124
+ const { request, tools } = await buildModelRequest(agent, {
125
+ session,
126
+ invocationId: options.invocationId,
127
+ ...(options.userContent ? { userContent: options.userContent } : {}),
128
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
129
+ ...(options.isolationScope !== undefined ? { isolationScope: options.isolationScope } : {}),
130
+ ...(options.root ? { root: options.root } : {}),
131
+ ...(options.memory ? { memory: options.memory } : {}),
132
+ ...(options.stateOverlay ? { stateOverlay: options.stateOverlay } : {}),
133
+ stream: options.stream ?? false,
134
+ ...(signal ? { signal } : {}),
135
+ ...(declareCorrection ? { extraTools: correctionTools } : {}),
136
+ ...(options.workflowScope ? { workflowScope: options.workflowScope } : {}),
137
+ });
138
+ if (!declareCorrection)
139
+ for (const tool of correctionTools)
140
+ tools.set(tool.name, tool);
141
+ if (options.model)
142
+ request.model = options.model;
143
+ const result = { request, text: '', thinking: '', toolCalls: [], longRunningToolIds: [], tools };
144
+ if (signal?.aborted)
145
+ return { ...result, stopped: stopOf() };
146
+ // The event ADK creates before the call; each response after the first gets a fresh id and time.
147
+ const base = createTurnEvent({ invocationId: options.invocationId, author: agent.name, branch: options.branch });
148
+ let next = { id: base.id, timestamp: base.timestamp };
149
+ // The tracer reads LlmResponses, as on the shim; the contract response each came from rides beside it.
150
+ const sources = new WeakMap();
151
+ // What the adapter itself threw, as opposed to the store or a callback.
152
+ let thrown;
153
+ // ADK's own Gemini writes no turnComplete, so its stand-in's events carry none (ADR 0100).
154
+ const adkGemini = standsForAdkGemini(adapter);
155
+ // How a reflection call stored in this adapter's place is signed (ADR 0103).
156
+ const signing = reflectionSigning(adapter, request.model);
157
+ async function* inner() {
158
+ try {
159
+ for await (const unchecked of adapter.generate(request)) {
160
+ // The answer held to the contract, as the shim's mapping holds it (contractModelResponse): the step reads and stores the same parts.
161
+ const response = contractModelResponse(unchecked);
162
+ const mapped = modelResponseToLlmResponse(response);
163
+ if (adkGemini)
164
+ delete mapped.turnComplete;
165
+ sources.set(mapped, response);
166
+ yield mapped;
167
+ }
168
+ }
169
+ catch (err) {
170
+ thrown = { error: err };
171
+ throw err;
172
+ }
173
+ }
174
+ let produced = false;
175
+ try {
176
+ return await readResponses();
177
+ }
178
+ catch (err) {
179
+ // An adapter that threw (see the header): FallbackLlm's catch.
180
+ if (thrown?.error !== err || signal?.aborted)
181
+ throw err;
182
+ const decision = errorDecision(err);
183
+ if (options.redirect && decision.retryable) {
184
+ const error = { code: 'PROVIDER_ERROR', message: errorText(err), retryable: true, ...(decision.status !== undefined ? { status: decision.status } : {}) };
185
+ const failed = { partial: false, parts: [], finishReason: 'error', error };
186
+ if (options.redirect(failed, produced))
187
+ return { ...result, response: failed, redirected: error };
188
+ }
189
+ if (!(err instanceof Error))
190
+ throw err;
191
+ // ADK's runAndHandleError: the step ends on an error event of its own.
192
+ const { code, message } = thrownModelError(err);
193
+ const event = createTurnEvent({ invocationId: options.invocationId, author: agent.name, errorCode: code, errorMessage: message });
194
+ options.beforeAppend?.(event);
195
+ const stored = await sessions.append(session, event);
196
+ return { ...result, event: stored, error: { code, message, retryable: false } };
197
+ }
198
+ async function readResponses() {
199
+ for await (const traced of traceLlmGeneration({ provider: adapter.provider, model: request.model, request }, inner())) {
200
+ if (signal?.aborted)
201
+ return { ...result, stopped: stopOf() };
202
+ const source = sources.get(traced);
203
+ if (!source) {
204
+ // A refusal the tracer made in place of the call: the turn has stopped.
205
+ return { ...result, stopped: { code: String(traced.errorCode), message: String(traced.errorMessage ?? '') } };
206
+ }
207
+ // Leaving the loop closes this call (and its span) before a fallback's opens.
208
+ if (!source.partial && source.error && options.redirect?.(source, produced))
209
+ return { ...result, response: source, redirected: source.error };
210
+ produced = true;
211
+ // Self-correction sees the response as ADK's afterModelCallback does: it may stand a retry in its place, or end the step.
212
+ // On Gemini the reflection call it stores is signed, so the next request does not 400 (ADR 0103).
213
+ const corrected = options.correction?.afterModel(traced, signing) ?? { response: traced, replaced: false };
214
+ if ('failed' in corrected) {
215
+ // ADK's runAndHandleError: a callback that threw ends the step on an error event of its own.
216
+ const { code, message } = corrected.failed;
217
+ const event = createTurnEvent({ invocationId: options.invocationId, author: agent.name, errorCode: code, errorMessage: message });
218
+ options.beforeAppend?.(event);
219
+ const stored = await sessions.append(session, event);
220
+ return { ...result, event: stored, ...(source.partial ? {} : { response: source }), error: { code, message, retryable: false } };
221
+ }
222
+ const llmResponse = corrected.response;
223
+ if (!makesEvent(llmResponse)) {
224
+ if (!source.partial)
225
+ result.response = source;
226
+ continue;
227
+ }
228
+ const event = createTurnEvent({ ...base, ...next, actions: base.actions, ...llmResponse });
229
+ next = { id: newEventId(), timestamp: Date.now() };
230
+ if (source.partial) {
231
+ for (const part of source.parts)
232
+ if (part.type === 'thinking')
233
+ result.thinking += part.text;
234
+ options.onPartial?.(event);
235
+ continue;
236
+ }
237
+ const calls = getFunctionCalls(event);
238
+ const setModelResponse = calls.find((c) => c.name === SET_MODEL_RESPONSE);
239
+ if (event.content && setModelResponse) {
240
+ event.content.parts = [{ text: JSON.stringify(setModelResponse.args) }];
241
+ event.actions.skipSummarization = true;
242
+ }
243
+ else if (calls.length > 0) {
244
+ for (const call of calls)
245
+ if (!call.id)
246
+ call.id = `${ADK_CALL_ID_PREFIX}${randomUUID()}`;
247
+ event.longRunningToolIds = [
248
+ ...new Set(calls.filter((c) => c.name && c.id && tools.has(c.name) && isLongRunning(tools.get(c.name))).map((c) => c.id)),
249
+ ];
250
+ }
251
+ options.beforeAppend?.(event);
252
+ const stored = await sessions.append(session, event);
253
+ result.event = stored;
254
+ result.response = source;
255
+ if (source.error && !corrected.replaced)
256
+ result.error = source.error;
257
+ result.text = (stored.content?.parts ?? []).filter((p) => !p.thought && typeof p.text === 'string').map((p) => p.text).join('');
258
+ result.toolCalls = getFunctionCalls(stored).map((c) => ({ type: 'toolCall', id: c.id, name: c.name ?? '', args: c.args ?? {} }));
259
+ result.longRunningToolIds = [...(stored.longRunningToolIds ?? [])];
260
+ }
261
+ return result;
262
+ }
263
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * lib/runtime/native/taskMode.ts — `mode: task` on the native loop: the
3
+ * finish_task tool, and how a task-mode node's run ends (ADR 0033, ADR 0081).
4
+ *
5
+ * WHY this file exists:
6
+ * On the ADK runtime `mode: task` is three things in ADK 2.2: LlmAgent
7
+ * adds its FinishTaskTool after the agent's own tools and never sets the
8
+ * output schema as the response schema; the tool declares the output
9
+ * schema as its parameters, adds a line to the instruction and answers
10
+ * "Task completed." (or an error naming the missing required keys); and
11
+ * a workflow node in task mode (ADK's runTaskMode) ends its run on that
12
+ * answer, the finish_task arguments its output. This file is those three
13
+ * for the native loop, word for word, so a session either runtime wrote
14
+ * holds the same events (tests/execution.test.ts).
15
+ *
16
+ * WHERE IT PLUGS IN:
17
+ * - lib/runtime/native/request.ts adds finishTaskTool(agent.outputSchema)
18
+ * after the agent's tools and before the caller's extra tools, as
19
+ * LlmAgent adds it after its own and before a plugin's;
20
+ * - lib/runtime/native/agentLoop.ts, when its context says the run is a
21
+ * task-mode node (`taskNode`), passes each event through
22
+ * taskNodeRun's `beforeStore` and ends the run when `output` is set.
23
+ * In a plain run (not a node) the loop goes on after finish_task's
24
+ * answer, as LlmAgent.runAsync does; the schema allows `mode: task` on
25
+ * workflow nodes only, so a validated syndicate never does that.
26
+ *
27
+ * QUIRKS KEPT FOR PARITY: the arguments are wrapped under `result` unless
28
+ * the schema's type is Gemini's `OBJECT` (ADK compares to Type.OBJECT, so a
29
+ * lowercase `object` is wrapped too), and only top-level `required` keys
30
+ * are checked. The arguments are the model's output: data, read by the next
31
+ * node, never instructions.
32
+ */
33
+ import type { Tool } from '../../tools/tool.ts';
34
+ import type { TurnEvent } from '../events.ts';
35
+ import type { NativeAgent } from './request.ts';
36
+ /** ADK's FINISH_TASK_TOOL_NAME. */
37
+ export declare const FINISH_TASK_TOOL_NAME = "finish_task";
38
+ /** ADK's FINISH_TASK_SUCCESS_RESULT: the tool's answer when the arguments carry every required key. */
39
+ export declare const FINISH_TASK_SUCCESS_RESULT = "Task completed.";
40
+ /** The line FinishTaskTool.processLlmRequest appends to the instruction. */
41
+ export declare const FINISH_TASK_INSTRUCTION = "Do NOT call `finish_task` prematurely. Use your available tools to fully complete every aspect of the task first. If the task is unclear, ask the user for clarification before proceeding. Once the task is fully complete, call `finish_task` by itself with no accompanying text output.";
42
+ /** A finish_task own Tool, with the extractor a task-mode node reads its output through. */
43
+ export interface FinishTaskTool extends Tool {
44
+ /** The node's output from a finish_task call's arguments: unwrapped from `result` when the schema is not an OBJECT. */
45
+ extractOutput(args: Record<string, unknown>): unknown;
46
+ }
47
+ /** ADK's FinishTaskTool for an agent's output schema, as an own Tool the native loop declares and runs. */
48
+ export declare function finishTaskTool(outputSchema?: Record<string, unknown>): FinishTaskTool;
49
+ /** One task-mode node's run: what the loop's task hook reads (ADK's runTaskMode). */
50
+ export interface TaskNodeRun {
51
+ /** Called on each event before it is stored: notes a finish_task call, and marks its successful answer as the node's output. */
52
+ beforeStore(event: TurnEvent): void;
53
+ /** True once finish_task answered with success: the run ends after that event is stored. */
54
+ readonly finished: boolean;
55
+ /** The node's output: the finish_task arguments, extracted. */
56
+ readonly output: unknown;
57
+ }
58
+ /**
59
+ * The task hook for a node run of `agent`: the latest finish_task call's
60
+ * arguments are held; the event that answers it with success gets
61
+ * `output` (the extracted arguments), `nodeInfo.messageAsOutput`, and the
62
+ * output under the agent's outputKey in its stateDelta, before it is stored.
63
+ */
64
+ export declare function taskNodeRun(agent: Pick<NativeAgent, 'outputSchema' | 'outputKey'>): TaskNodeRun;
@@ -0,0 +1,126 @@
1
+ /**
2
+ * lib/runtime/native/taskMode.ts — `mode: task` on the native loop: the
3
+ * finish_task tool, and how a task-mode node's run ends (ADR 0033, ADR 0081).
4
+ *
5
+ * WHY this file exists:
6
+ * On the ADK runtime `mode: task` is three things in ADK 2.2: LlmAgent
7
+ * adds its FinishTaskTool after the agent's own tools and never sets the
8
+ * output schema as the response schema; the tool declares the output
9
+ * schema as its parameters, adds a line to the instruction and answers
10
+ * "Task completed." (or an error naming the missing required keys); and
11
+ * a workflow node in task mode (ADK's runTaskMode) ends its run on that
12
+ * answer, the finish_task arguments its output. This file is those three
13
+ * for the native loop, word for word, so a session either runtime wrote
14
+ * holds the same events (tests/execution.test.ts).
15
+ *
16
+ * WHERE IT PLUGS IN:
17
+ * - lib/runtime/native/request.ts adds finishTaskTool(agent.outputSchema)
18
+ * after the agent's tools and before the caller's extra tools, as
19
+ * LlmAgent adds it after its own and before a plugin's;
20
+ * - lib/runtime/native/agentLoop.ts, when its context says the run is a
21
+ * task-mode node (`taskNode`), passes each event through
22
+ * taskNodeRun's `beforeStore` and ends the run when `output` is set.
23
+ * In a plain run (not a node) the loop goes on after finish_task's
24
+ * answer, as LlmAgent.runAsync does; the schema allows `mode: task` on
25
+ * workflow nodes only, so a validated syndicate never does that.
26
+ *
27
+ * QUIRKS KEPT FOR PARITY: the arguments are wrapped under `result` unless
28
+ * the schema's type is Gemini's `OBJECT` (ADK compares to Type.OBJECT, so a
29
+ * lowercase `object` is wrapped too), and only top-level `required` keys
30
+ * are checked. The arguments are the model's output: data, read by the next
31
+ * node, never instructions.
32
+ */
33
+ import { toContractJsonSchema } from '../../models/schemaNormalize.js';
34
+ import { getFunctionCalls, getFunctionResponses } from '../events.js';
35
+ /** ADK's FINISH_TASK_TOOL_NAME. */
36
+ export const FINISH_TASK_TOOL_NAME = 'finish_task';
37
+ /** ADK's FINISH_TASK_SUCCESS_RESULT: the tool's answer when the arguments carry every required key. */
38
+ export const FINISH_TASK_SUCCESS_RESULT = 'Task completed.';
39
+ const DESCRIPTION = 'Signal that this agent has completed its delegated task. Call this when you have finished your delegated task.';
40
+ const DESCRIPTION_WITH_SCHEMA = `${DESCRIPTION} Pass the required output data in the parameters.`;
41
+ /** The line FinishTaskTool.processLlmRequest appends to the instruction. */
42
+ export const FINISH_TASK_INSTRUCTION = 'Do NOT call `finish_task` prematurely. Use your available tools to fully complete every aspect of the task first. If the task is unclear, ask the user for clarification before proceeding. Once the task is fully complete, call `finish_task` by itself with no accompanying text output.';
43
+ /** ADK's DEFAULT_TASK_OUTPUT_SCHEMA, for an agent with no output schema. */
44
+ const DEFAULT_TASK_OUTPUT_SCHEMA = {
45
+ type: 'OBJECT',
46
+ properties: { result: { type: 'STRING', description: 'A brief summary of what the agent accomplished.' } },
47
+ required: ['result'],
48
+ };
49
+ /** The key the arguments are wrapped under, or undefined when the schema is Gemini's OBJECT (ADK's wrapperKey). */
50
+ function wrapperKeyOf(schema) {
51
+ return schema.type === 'OBJECT' ? undefined : 'result';
52
+ }
53
+ /** The required keys `value` lacks, as FinishTaskTool.missingRequiredKeys reads them. */
54
+ function missingRequiredKeys(schema, wrapperKey, value) {
55
+ if (wrapperKey)
56
+ return value === undefined || value === null ? [wrapperKey] : [];
57
+ const required = Array.isArray(schema.required) ? schema.required.filter((k) => typeof k === 'string') : [];
58
+ if (typeof value !== 'object' || value === null)
59
+ return required;
60
+ return required.filter((key) => value[key] === undefined);
61
+ }
62
+ /** ADK's FinishTaskTool for an agent's output schema, as an own Tool the native loop declares and runs. */
63
+ export function finishTaskTool(outputSchema) {
64
+ const schema = outputSchema ?? DEFAULT_TASK_OUTPUT_SCHEMA;
65
+ const wrapperKey = wrapperKeyOf(schema);
66
+ const description = outputSchema ? DESCRIPTION_WITH_SCHEMA : DESCRIPTION;
67
+ const parameters = wrapperKey ? { type: 'OBJECT', properties: { [wrapperKey]: schema }, required: [wrapperKey] } : schema;
68
+ return {
69
+ name: FINISH_TASK_TOOL_NAME,
70
+ declaration: () => ({ name: FINISH_TASK_TOOL_NAME, description, parameters: toContractJsonSchema(parameters) }),
71
+ instruction: async () => FINISH_TASK_INSTRUCTION,
72
+ execute: async (args) => {
73
+ const value = wrapperKey ? args[wrapperKey] : args;
74
+ const missing = missingRequiredKeys(schema, wrapperKey, value);
75
+ if (missing.length > 0) {
76
+ return {
77
+ error: `Invoking \`${FINISH_TASK_TOOL_NAME}()\` failed due to missing required parameters: ${missing.join(', ')}. You could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters with correct types.`,
78
+ };
79
+ }
80
+ return FINISH_TASK_SUCCESS_RESULT;
81
+ },
82
+ extractOutput: (args) => (wrapperKey ? args[wrapperKey] : args),
83
+ };
84
+ }
85
+ function isSuccess(event) {
86
+ return getFunctionResponses(event).some((r) => r.name === FINISH_TASK_TOOL_NAME && (r.response ?? {}).result === FINISH_TASK_SUCCESS_RESULT);
87
+ }
88
+ /**
89
+ * The task hook for a node run of `agent`: the latest finish_task call's
90
+ * arguments are held; the event that answers it with success gets
91
+ * `output` (the extracted arguments), `nodeInfo.messageAsOutput`, and the
92
+ * output under the agent's outputKey in its stateDelta, before it is stored.
93
+ */
94
+ export function taskNodeRun(agent) {
95
+ const tool = finishTaskTool(agent.outputSchema);
96
+ let pendingArgs;
97
+ let finished = false;
98
+ let output;
99
+ return {
100
+ beforeStore(event) {
101
+ if (finished || event.partial)
102
+ return;
103
+ const call = getFunctionCalls(event).find((c) => c.name === FINISH_TASK_TOOL_NAME);
104
+ if (call) {
105
+ pendingArgs = { ...(call.args ?? {}) };
106
+ return;
107
+ }
108
+ if (pendingArgs === undefined || !isSuccess(event))
109
+ return;
110
+ output = tool.extractOutput(pendingArgs);
111
+ event.output = output;
112
+ event.nodeInfo = { ...(event.nodeInfo ?? {}), messageAsOutput: true };
113
+ if (agent.outputKey && output !== undefined) {
114
+ const delta = (event.actions.stateDelta ??= {});
115
+ Object.defineProperty(delta, agent.outputKey, { value: output, writable: true, enumerable: true, configurable: true });
116
+ }
117
+ finished = true;
118
+ },
119
+ get finished() {
120
+ return finished;
121
+ },
122
+ get output() {
123
+ return output;
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * lib/runtime/native/telemetry.ts — the native loop's spans: one per agent
3
+ * run, one per model step, one per tool call (ADR 0076).
4
+ *
5
+ * WHY this file exists:
6
+ * The ledger (lib/observability/supabaseSpanExporter.ts) is a projection of
7
+ * a turn's spans. On the ADK runtime, ADK opens `invoke_agent <name>`
8
+ * around an agent's run, `call_llm` around each step's model call and
9
+ * `execute_tool <name>` around each tool call; the tracer reads them to
10
+ * attribute a model call to its agent and to sum tool time, and the
11
+ * exporter reads `call_llm` for the payload tier. A native run writes the
12
+ * same ledger rows because the loop opens the same three spans under the
13
+ * engine's own names and scope:
14
+ *
15
+ * agent.invoke <name> the agent's run (runAgentLoop), parent of the rest
16
+ * model.call one model step, parent of the step's llm.request
17
+ * span(s): two when a fallback model answers
18
+ * tool.execute <name> one tool call; a step's calls run side by side
19
+ *
20
+ * All three are in scope `melchizedek.runtime`, which the console exporter
21
+ * keeps quiet as it keeps ADK's (OTEL_CONSOLE_ALL_SPANS prints them).
22
+ *
23
+ * WHAT A SPAN CARRIES:
24
+ * gen_ai.* attributes as ADK sets them (operation, agent, conversation,
25
+ * tool name and call id, request model, usage, finish reason), and on
26
+ * model.call the provider the answering adapter names (`gen_ai.system`),
27
+ * where ADK's call_llm names its own scope. A model step that did not fail
28
+ * carries its payload as the engine holds it: `llm.payload.request` (the
29
+ * ModelRequest, its signal left out) and `llm.payload.response` (the
30
+ * adapter's final response). A failed step carries none: its llm.request
31
+ * span carries the failed call's payload, as on the ADK runtime, where a
32
+ * failed call_llm never ends. With TELEMETRY_PAYLOADS=off no payload is
33
+ * recorded at all. Tool spans carry no arguments and no results: the root
34
+ * span's ToolCall/ToolResponse events are where the ledger keeps those.
35
+ *
36
+ * The loop calls three hooks (agentLoop.ts): traceAgentInvocation around the
37
+ * whole run, traceModelCall around each step, traceToolCall around each call.
38
+ */
39
+ import type { TurnEvent, TurnFunctionCall, TurnPart } from '../events.ts';
40
+ import type { AgentLoopContext, AgentLoopEnd } from './agentLoop.ts';
41
+ import type { NativeAgent } from './request.ts';
42
+ import type { ModelStepResult } from './step.ts';
43
+ import type { NodeResult, TracedNode } from '../../workflow/scheduler.ts';
44
+ /** The agent's run as an `agent.invoke <name>` span, opened when the run starts. */
45
+ export declare function traceAgentInvocation(agent: Pick<NativeAgent, 'name' | 'description'>, ctx: Pick<AgentLoopContext, 'session' | 'invocationId'>, run: () => AsyncGenerator<TurnEvent, AgentLoopEnd>): AsyncGenerator<TurnEvent, AgentLoopEnd>;
46
+ /**
47
+ * One model step as a `model.call` span. `step` gets the loop's context with
48
+ * an `adapterFor` that notes the adapter it hands out, so the span names the
49
+ * provider that answered (the fallback's, when a fallback answered).
50
+ */
51
+ export declare function traceModelCall(agent: Pick<NativeAgent, 'name' | 'model'>, ctx: AgentLoopContext, step: (traced: AgentLoopContext) => AsyncGenerator<TurnEvent, ModelStepResult>): AsyncGenerator<TurnEvent, ModelStepResult>;
52
+ /** One tool call as a `tool.execute <name>` span, under the agent's. */
53
+ export declare function traceToolCall<O extends {
54
+ part?: TurnPart;
55
+ } | undefined>(call: TurnFunctionCall, tool: unknown, run: () => Promise<O>): Promise<O>;
56
+ /** The walk as a `workflow.invoke <name>` span; every node span opens under it. */
57
+ export declare function traceWorkflowInvocation<T>(workflow: {
58
+ name: string;
59
+ path: string;
60
+ }, ctx: {
61
+ sessionId: string;
62
+ invocationId: string;
63
+ }, run: () => Promise<T>): Promise<T>;
64
+ /**
65
+ * One node run as a `node.execute <name>` span (the scheduler's traceNode
66
+ * hook): every attempt of the run inside it, ending with ADK's status
67
+ * (`completed`, `waiting` when the run paused on a person, `failed`) and the
68
+ * attempts the run made.
69
+ */
70
+ export declare function traceNodeExecution(node: TracedNode, run: () => Promise<NodeResult>): Promise<NodeResult>;
71
+ /** A tool node's call as a `tool.execute <name>` span, under its node's (ToolNodeContext.traceCall). */
72
+ export declare function traceToolNodeCall<T>(call: {
73
+ id: string;
74
+ name: string;
75
+ }, tool: unknown, run: () => Promise<T>): Promise<T>;